Improves all-day event drag and drop

Handles dragging of both timed events (converting to all-day) and existing all-day events to different days.

Refactors all-day height recalculation to support animated transitions for a smoother user experience when all-day event counts change.

Uses event delegation for header mouseover detection.

Updates ScrollManager to listen for header height changes.
This commit is contained in:
Janus Knudsen 2025-08-25 21:20:51 +02:00
parent 6ede297bb5
commit f2763ad826
6 changed files with 186 additions and 48 deletions

View file

@ -78,18 +78,26 @@ export class ColumnDetector {
document.body.addEventListener('mousedown', this.handleMouseDown.bind(this)); document.body.addEventListener('mousedown', this.handleMouseDown.bind(this));
document.body.addEventListener('mouseup', this.handleMouseUp.bind(this)); document.body.addEventListener('mouseup', this.handleMouseUp.bind(this));
// Listen for header mouseover events // Listen for header mouseover events (both day-headers and all-day-containers)
eventBus.on('header:mouseover', (event) => { eventBus.on('header:mouseover', (event) => {
const { dayHeader, headerRenderer } = (event as CustomEvent).detail; const { element, targetDate, headerRenderer } = (event as CustomEvent).detail;
if (this.isMouseDown && this.draggedClone) {
console.log('Dragging clone over header - expanding and converting to all-day');
headerRenderer.addToAllDay(dayHeader);
// Convert clone to all-day format immediately if (this.isMouseDown && this.draggedClone && targetDate) {
const targetDate = dayHeader.dataset.date; // Scenario 1: Timed event being dragged to header - convert to all-day
if (targetDate) { if (this.draggedClone.tagName === 'SWP-EVENT') {
console.log('Converting timed event to all-day for date:', targetDate);
headerRenderer.addToAllDay(element);
this.convertToAllDayPreview(targetDate); this.convertToAllDayPreview(targetDate);
} }
// Scenario 2: All-day event being moved to different day
else if (this.draggedClone.tagName === 'SWP-ALLDAY-EVENT') {
const currentDate = this.draggedClone.parentElement?.getAttribute('data-date');
if (currentDate !== targetDate) {
console.log('Moving all-day event from', currentDate, 'to', targetDate);
this.moveAllDayToNewDate(targetDate);
}
}
} }
}); });
} }
@ -442,56 +450,63 @@ export class ColumnDetector {
this.transformCloneToAllDay(this.draggedClone, targetDate); this.transformCloneToAllDay(this.draggedClone, targetDate);
// No need to recalculate height - addToAllDay already handles this // No need to recalculate height - addToAllDay already handles this
console.log(`Converted clone to all-day preview for date: ${targetDate}`);
} }
/** /**
* Transform clone from timed event to all-day event format * Transform clone from timed event to all-day event format
*/ */
private transformCloneToAllDay(clone: HTMLElement, targetDate: string): void { private transformCloneToAllDay(clone: HTMLElement, targetDate: string): void {
console.log('transformCloneToAllDay called with:', { clone, targetDate });
const calendarHeader = document.querySelector('swp-calendar-header'); const calendarHeader = document.querySelector('swp-calendar-header');
if (!calendarHeader) { if (!calendarHeader) return;
console.error('No calendar header found');
return;
}
// Find or create all-day container for target date // Find or create all-day container for target date
const container = this.findOrCreateAllDayContainer(calendarHeader as HTMLElement, targetDate); const container = this.findOrCreateAllDayContainer(calendarHeader as HTMLElement, targetDate);
if (!container) { if (!container) return;
console.error('No container found/created');
return;
}
// Extract title from original clone (remove time info) // Extract title from original clone (remove time info)
const titleElement = clone.querySelector('swp-event-title'); const titleElement = clone.querySelector('swp-event-title');
const eventTitle = titleElement ? titleElement.textContent || 'Untitled Event' : 'Untitled Event'; const eventTitle = titleElement ? titleElement.textContent || 'Untitled Event' : 'Untitled Event';
console.log('Creating all-day event with title:', eventTitle);
// Create new all-day event element // Create new all-day event element
const allDayEvent = document.createElement('swp-allday-event'); const allDayEvent = document.createElement('swp-allday-event');
allDayEvent.setAttribute('data-event-id', clone.dataset.eventId || ''); allDayEvent.setAttribute('data-event-id', clone.dataset.eventId || '');
allDayEvent.setAttribute('data-type', clone.dataset.type || 'work'); allDayEvent.setAttribute('data-type', clone.dataset.type || 'work');
allDayEvent.textContent = eventTitle; allDayEvent.textContent = eventTitle;
console.log('All-day event created:', allDayEvent);
// Remove the original clone from its current parent // Remove the original clone from its current parent
if (clone.parentElement) { if (clone.parentElement) {
console.log('Removing original clone from parent:', clone.parentElement);
clone.parentElement.removeChild(clone); clone.parentElement.removeChild(clone);
} }
// Add new all-day event to container // Add new all-day event to container
container.appendChild(allDayEvent); container.appendChild(allDayEvent);
console.log('All-day event added to container:', container);
// Update reference to point to new element // Update reference to point to new element
this.draggedClone = allDayEvent; this.draggedClone = allDayEvent;
console.log(`Transformed clone to all-day event in container for date: ${targetDate}`); // Recalculate height after adding new all-day event
this.recalculateAllDayHeight();
}
/**
* Move all-day event to a new date container
*/
private moveAllDayToNewDate(targetDate: string): void {
if (!this.draggedClone) return;
const calendarHeader = document.querySelector('swp-calendar-header');
if (!calendarHeader) return;
// Find or create container for new date
const newContainer = this.findOrCreateAllDayContainer(calendarHeader as HTMLElement, targetDate);
// Move the dragged clone to new container
if (newContainer && this.draggedClone.parentElement !== newContainer) {
newContainer.appendChild(this.draggedClone);
// Recalculate height after moving
this.recalculateAllDayHeight();
}
} }
/** /**
@ -528,13 +543,87 @@ export class ColumnDetector {
(container as HTMLElement).style.gridRow = '2'; // All-day row (container as HTMLElement).style.gridRow = '2'; // All-day row
calendarHeader.appendChild(container); calendarHeader.appendChild(container);
console.log(`Created new all-day container for column ${columnIndex}, date: ${targetDate}`);
} }
return container as HTMLElement; return container as HTMLElement;
} }
/**
* Recalculate all-day row height based on maximum events in any container
*/
private recalculateAllDayHeight(): void {
const calendarHeader = document.querySelector('swp-calendar-header') as HTMLElement;
if (!calendarHeader) return;
// Find all all-day containers
const allDayContainers = calendarHeader.querySelectorAll('swp-allday-container');
let maxStackHeight = 0;
// Count events in each container to find maximum
allDayContainers.forEach(container => {
const eventCount = container.querySelectorAll('swp-allday-event').length;
if (eventCount > maxStackHeight) {
maxStackHeight = eventCount;
}
});
// Calculate new height using same formula as EventRenderer
const calculatedHeight = maxStackHeight > 0
? (maxStackHeight * ALL_DAY_CONSTANTS.EVENT_HEIGHT) +
((maxStackHeight - 1) * ALL_DAY_CONSTANTS.EVENT_GAP) +
ALL_DAY_CONSTANTS.CONTAINER_PADDING
: ALL_DAY_CONSTANTS.SINGLE_ROW_HEIGHT; // Keep minimum height
// Get current heights for animation
const root = document.documentElement;
const headerHeight = parseInt(getComputedStyle(root).getPropertyValue('--header-height'));
const currentAllDayHeight = parseInt(getComputedStyle(root).getPropertyValue('--all-day-row-height') || '0');
const currentTotalHeight = headerHeight + currentAllDayHeight;
const targetTotalHeight = headerHeight + calculatedHeight;
// Only animate if height actually changes
if (currentAllDayHeight !== calculatedHeight) {
// Find header spacer
const headerSpacer = document.querySelector('swp-header-spacer') as HTMLElement;
// Animate both header and spacer simultaneously
const animations = [
calendarHeader.animate([
{ height: `${currentTotalHeight}px` },
{ height: `${targetTotalHeight}px` }
], {
duration: 150,
easing: 'ease-out',
fill: 'forwards'
})
];
if (headerSpacer) {
animations.push(
headerSpacer.animate([
{ height: `${currentTotalHeight}px` },
{ height: `${targetTotalHeight}px` }
], {
duration: 150,
easing: 'ease-out',
fill: 'forwards'
})
);
}
// Wait for all animations to finish before setting CSS variable
Promise.all(animations.map(anim => anim.finished)).then(() => {
root.style.setProperty('--all-day-row-height', `${calculatedHeight}px`);
// Notify ScrollManager about header height change
eventBus.emit('header:height-changed');
});
console.log(`Animated all-day height: ${currentAllDayHeight}px → ${calculatedHeight}px (max stack: ${maxStackHeight})`);
}
}
public destroy(): void { public destroy(): void {
this.stopAutoScroll(); this.stopAutoScroll();
document.body.removeEventListener('mousemove', this.handleMouseMove.bind(this)); document.body.removeEventListener('mousemove', this.handleMouseMove.bind(this));

View file

@ -36,6 +36,10 @@ export class ScrollManager {
this.setupScrolling(); this.setupScrolling();
}); });
// Handle all-day row height changes
eventBus.on('header:height-changed', () => {
this.updateScrollableHeight();
});
// Handle window resize // Handle window resize
window.addEventListener('resize', () => { window.addEventListener('resize', () => {

View file

@ -186,17 +186,10 @@ export abstract class BaseEventRenderer implements EventRendererStrategy {
? (maxStackHeight * ALL_DAY_CONSTANTS.EVENT_HEIGHT) + ((maxStackHeight - 1) * ALL_DAY_CONSTANTS.EVENT_GAP) + ALL_DAY_CONSTANTS.CONTAINER_PADDING ? (maxStackHeight * ALL_DAY_CONSTANTS.EVENT_HEIGHT) + ((maxStackHeight - 1) * ALL_DAY_CONSTANTS.EVENT_GAP) + ALL_DAY_CONSTANTS.CONTAINER_PADDING
: 0; // No height if no events : 0; // No height if no events
// Set CSS variable for row height // Only set CSS variable - header-spacer height is handled by CSS calc()
const root = document.documentElement; const root = document.documentElement;
root.style.setProperty('--all-day-row-height', `${calculatedHeight}px`); root.style.setProperty('--all-day-row-height', `${calculatedHeight}px`);
// Also update header-spacer height
const headerSpacer = container.querySelector('swp-header-spacer');
if (headerSpacer) {
const headerHeight = parseInt(getComputedStyle(root).getPropertyValue('--header-height') || '80');
(headerSpacer as HTMLElement).style.height = `${headerHeight + calculatedHeight}px`;
}
console.log(`BaseEventRenderer: Set all-day row height to ${calculatedHeight}px (max stack: ${maxStackHeight})`); console.log(`BaseEventRenderer: Set all-day row height to ${calculatedHeight}px (max stack: ${maxStackHeight})`);
} }

View file

@ -135,12 +135,30 @@ export class GridRenderer {
headerRenderer.render(calendarHeader, context); headerRenderer.render(calendarHeader, context);
// Add mouseover listeners on day headers for drag detection // Use event delegation for mouseover detection on entire header
const dayHeaders = calendarHeader.querySelectorAll('swp-day-header'); calendarHeader.addEventListener('mouseover', (event) => {
dayHeaders.forEach(dayHeader => { const target = event.target as HTMLElement;
dayHeader.addEventListener('mouseover', () => {
eventBus.emit('header:mouseover', { dayHeader, headerRenderer }); // Check what was hovered - could be day-header OR all-day-container
const dayHeader = target.closest('swp-day-header');
const allDayContainer = target.closest('swp-allday-container');
if (dayHeader || allDayContainer) {
const hoveredElement = dayHeader || allDayContainer;
const targetDate = (hoveredElement as HTMLElement).dataset.date;
console.log('GridRenderer: Detected hover over:', {
elementType: dayHeader ? 'day-header' : 'all-day-container',
targetDate,
element: hoveredElement
}); });
eventBus.emit('header:mouseover', {
element: hoveredElement,
targetDate,
headerRenderer
});
}
}); });
} }
@ -179,7 +197,7 @@ export class GridRenderer {
// Clear existing content // Clear existing content
calendarHeader.innerHTML = ''; calendarHeader.innerHTML = '';
// Re-render headers using Strategy Pattern // Re-render headers using Strategy Pattern - this will also re-attach the event listener
this.renderCalendarHeader(calendarHeader as HTMLElement, currentWeek, resourceData); this.renderCalendarHeader(calendarHeader as HTMLElement, currentWeek, resourceData);
} }
} }

View file

@ -1,6 +1,7 @@
// Header rendering strategy interface and implementations // Header rendering strategy interface and implementations
import { CalendarConfig, ALL_DAY_CONSTANTS } from '../core/CalendarConfig'; import { CalendarConfig, ALL_DAY_CONSTANTS } from '../core/CalendarConfig';
import { eventBus } from '../core/EventBus';
import { ResourceCalendarData } from '../types/CalendarTypes'; import { ResourceCalendarData } from '../types/CalendarTypes';
import { DateCalculator } from '../utils/DateCalculator'; import { DateCalculator } from '../utils/DateCalculator';
@ -37,7 +38,7 @@ export abstract class BaseHeaderRenderer implements HeaderRenderer {
private animateHeaderExpansion(calendarHeader: HTMLElement): void { private animateHeaderExpansion(calendarHeader: HTMLElement): void {
const root = document.documentElement; const root = document.documentElement;
const currentHeaderHeight = parseInt(getComputedStyle(root).getPropertyValue('--header-height') || '80'); const currentHeaderHeight = parseInt(getComputedStyle(root).getPropertyValue('--header-height'));
const targetHeight = currentHeaderHeight + ALL_DAY_CONSTANTS.SINGLE_ROW_HEIGHT; const targetHeight = currentHeaderHeight + ALL_DAY_CONSTANTS.SINGLE_ROW_HEIGHT;
// Find header spacer // Find header spacer
@ -49,7 +50,7 @@ export abstract class BaseHeaderRenderer implements HeaderRenderer {
{ height: `${currentHeaderHeight}px` }, { height: `${currentHeaderHeight}px` },
{ height: `${targetHeight}px` } { height: `${targetHeight}px` }
], { ], {
duration: 300, duration: 150,
easing: 'ease-out', easing: 'ease-out',
fill: 'forwards' fill: 'forwards'
}) })
@ -61,7 +62,7 @@ export abstract class BaseHeaderRenderer implements HeaderRenderer {
{ height: `${currentHeaderHeight}px` }, { height: `${currentHeaderHeight}px` },
{ height: `${targetHeight}px` } { height: `${targetHeight}px` }
], { ], {
duration: 300, duration: 150,
easing: 'ease-out', easing: 'ease-out',
fill: 'forwards' fill: 'forwards'
}) })
@ -72,8 +73,41 @@ export abstract class BaseHeaderRenderer implements HeaderRenderer {
Promise.all(animations.map(anim => anim.finished)).then(() => { Promise.all(animations.map(anim => anim.finished)).then(() => {
// Set the CSS variable after animation // Set the CSS variable after animation
root.style.setProperty('--all-day-row-height', `${ALL_DAY_CONSTANTS.SINGLE_ROW_HEIGHT}px`); root.style.setProperty('--all-day-row-height', `${ALL_DAY_CONSTANTS.SINGLE_ROW_HEIGHT}px`);
// Create empty all-day containers after animation
this.createEmptyAllDayContainers(calendarHeader);
// Notify ScrollManager about header height change
eventBus.emit('header:height-changed');
}); });
} }
private createEmptyAllDayContainers(calendarHeader: HTMLElement): void {
const dayHeaders = calendarHeader.querySelectorAll('swp-day-header');
dayHeaders.forEach((dayHeader, index) => {
const date = (dayHeader as HTMLElement).dataset.date;
if (!date) return;
const columnIndex = index + 1; // 1-based grid index
const containerKey = `${columnIndex}-1`;
// Check if container already exists
let container = calendarHeader.querySelector(`swp-allday-container[data-container-key="${containerKey}"]`);
if (!container) {
// Create empty container
container = document.createElement('swp-allday-container');
container.setAttribute('data-container-key', containerKey);
container.setAttribute('data-date', date);
(container as HTMLElement).style.gridColumn = `${columnIndex}`;
(container as HTMLElement).style.gridRow = '2';
calendarHeader.appendChild(container);
}
});
console.log('Created empty all-day containers for all days');
}
} }
/** /**

View file

@ -56,7 +56,7 @@ swp-header-spacer {
border-bottom: 1px solid var(--color-border); border-bottom: 1px solid var(--color-border);
z-index: 5; /* Higher than time-axis to cover it when scrolling */ z-index: 5; /* Higher than time-axis to cover it when scrolling */
position: relative; position: relative;
transition: height 300ms ease; /* Smooth height transitions */ transition: height 150ms ease; /* Smooth height transitions */
} }
@ -151,7 +151,7 @@ swp-calendar-header {
top: 0; top: 0;
z-index: 3; /* Lower than header-spacer so it slides under during horizontal scroll */ z-index: 3; /* Lower than header-spacer so it slides under during horizontal scroll */
height: calc(var(--header-height) + var(--all-day-row-height)); /* Same calculation as spacers */ height: calc(var(--header-height) + var(--all-day-row-height)); /* Same calculation as spacers */
transition: height 0.3s ease; transition: height 150ms ease;
/* Force scrollbar to appear for alignment */ /* Force scrollbar to appear for alignment */
overflow-y: scroll; overflow-y: scroll;