Calendar/src/managers/GridManager.ts

529 lines
18 KiB
TypeScript
Raw Normal View History

2025-08-07 00:15:44 +02:00
// Grid structure management - Simple CSS Grid Implementation with Strategy Pattern
import { eventBus } from '../core/EventBus';
import { calendarConfig } from '../core/CalendarConfig';
import { EventTypes } from '../constants/EventTypes';
import { StateEvents } from '../types/CalendarState';
import { DateUtils } from '../utils/DateUtils';
2025-08-07 00:15:44 +02:00
import { ResourceCalendarData } from '../types/CalendarTypes';
import { CalendarTypeFactory } from '../factories/CalendarTypeFactory';
import { HeaderRenderContext } from '../renderers/HeaderRenderer';
import { ColumnRenderContext } from '../renderers/ColumnRenderer';
/**
* Grid position interface
*/
interface GridPosition {
minutes: number;
time: string;
y: number;
}
/**
2025-08-07 00:15:44 +02:00
* Manages the calendar grid structure using simple CSS Grid with Strategy Pattern
*/
export class GridManager {
private container: HTMLElement | null = null;
2025-07-25 23:31:25 +02:00
private grid: HTMLElement | null = null;
private currentWeek: Date | null = null;
2025-08-04 23:55:04 +02:00
private allDayEvents: any[] = []; // Store all-day events for current week
2025-08-07 00:15:44 +02:00
private resourceData: ResourceCalendarData | null = null; // Store resource data for resource calendar
constructor() {
console.log('🏗️ GridManager: Constructor called');
this.init();
}
private init(): void {
this.findElements();
this.subscribeToEvents();
2025-07-25 23:31:25 +02:00
// Set initial current week to today if not set
if (!this.currentWeek) {
this.currentWeek = this.getWeekStart(new Date());
console.log('GridManager: Set initial currentWeek to', this.currentWeek);
// Don't render immediately - wait for proper initialization event
console.log('GridManager: Waiting for initialization complete before rendering');
2025-07-25 23:31:25 +02:00
}
}
private getWeekStart(date: Date): Date {
2025-08-02 23:59:52 +02:00
// Use DateUtils for consistent week calculation (Sunday = 0)
return DateUtils.getWeekStart(date, 0);
}
private findElements(): void {
2025-07-25 23:31:25 +02:00
this.grid = document.querySelector('swp-calendar-container');
2025-08-09 01:16:04 +02:00
console.log('GridManager: findElements called, found swp-calendar-container:', !!this.grid);
}
private subscribeToEvents(): void {
2025-08-09 01:16:04 +02:00
// State-driven events removed - render() is now called directly by CalendarManager
// Re-render grid on config changes
eventBus.on(EventTypes.CONFIG_UPDATE, (e: Event) => {
const detail = (e as CustomEvent).detail;
2025-08-05 21:56:06 +02:00
if (['dayStartHour', 'dayEndHour', 'hourHeight', 'view', 'weekDays', 'fitToWidth'].includes(detail.key)) {
this.render();
}
});
2025-08-07 00:15:44 +02:00
// Re-render on calendar type change
eventBus.on(EventTypes.CALENDAR_TYPE_CHANGED, () => {
this.render();
});
// Re-render on view change
eventBus.on(EventTypes.VIEW_CHANGE, () => {
this.render();
});
// Re-render on period change
eventBus.on(EventTypes.PERIOD_CHANGE, (e: Event) => {
const detail = (e as CustomEvent).detail;
this.currentWeek = detail.week;
2025-07-25 23:31:25 +02:00
this.render();
});
// Handle week changes from NavigationManager
eventBus.on(EventTypes.WEEK_CHANGED, (e: Event) => {
const detail = (e as CustomEvent).detail;
this.currentWeek = detail.weekStart;
this.render();
});
2025-08-04 23:55:04 +02:00
// Handle events loaded
eventBus.on(EventTypes.EVENTS_LOADED, (e: Event) => {
const detail = (e as CustomEvent).detail;
this.updateAllDayEvents(detail.events);
});
// Handle data loaded for resource mode
eventBus.on(StateEvents.DATA_LOADED, (e: Event) => {
2025-08-07 00:15:44 +02:00
const detail = (e as CustomEvent).detail;
console.log(`GridManager: Received DATA_LOADED`);
2025-08-07 00:15:44 +02:00
if (detail.data && detail.data.calendarMode === 'resource') {
// Resource data will be passed in the state event
// For now just update grid styles
this.updateGridStyles();
2025-08-07 00:15:44 +02:00
}
});
// Handle grid clicks
this.setupGridInteractions();
}
/**
* Set resource data for resource calendar mode
*/
public setResourceData(resourceData: ResourceCalendarData | null): void {
this.resourceData = resourceData;
console.log('GridManager: Set resource data:', resourceData ? `${resourceData.resources.length} resources` : 'null');
}
/**
2025-08-09 01:16:04 +02:00
* Render the complete grid structure - now returns Promise for direct calls
*/
2025-08-09 01:16:04 +02:00
async render(): Promise<void> {
if (!this.grid) {
console.warn('GridManager: render() called but this.grid is null, re-finding elements');
this.findElements();
if (!this.grid) {
throw new Error('GridManager: swp-calendar-container not found, cannot render');
}
}
2025-07-25 23:31:25 +02:00
2025-08-09 01:16:04 +02:00
console.log('GridManager: Starting render with grid element:', this.grid);
2025-07-25 23:31:25 +02:00
this.updateGridStyles();
this.renderGrid();
const columnCount = this.getColumnCount();
2025-08-09 01:16:04 +02:00
console.log(`GridManager: Render complete - created ${columnCount} columns`);
// Emit GRID_RENDERED event to trigger event rendering
const weekEnd = this.currentWeek ? new Date(this.currentWeek.getTime() + 6 * 24 * 60 * 60 * 1000) : null;
eventBus.emit(EventTypes.GRID_RENDERED, {
container: this.grid,
currentWeek: this.currentWeek,
startDate: this.currentWeek,
endDate: weekEnd,
columnCount: columnCount
});
}
/**
* Get current column count based on calendar mode
*/
private getColumnCount(): number {
const calendarType = calendarConfig.getCalendarMode();
if (calendarType === 'resource' && this.resourceData) {
return this.resourceData.resources.length;
} else if (calendarType === 'date') {
const dateSettings = calendarConfig.getDateViewSettings();
switch (dateSettings.period) {
case 'day': return 1;
case 'week': return dateSettings.weekDays;
case 'month': return 7;
default: return dateSettings.weekDays;
}
}
return 7; // Default
}
/**
2025-07-25 23:31:25 +02:00
* Render the complete grid using POC structure
*/
2025-07-25 23:31:25 +02:00
private renderGrid(): void {
console.log('GridManager: renderGrid called', {
hasGrid: !!this.grid,
hasCurrentWeek: !!this.currentWeek,
currentWeek: this.currentWeek
});
if (!this.grid || !this.currentWeek) {
console.warn('GridManager: Cannot render - missing grid or currentWeek');
return;
}
// Only clear and rebuild if grid is empty (first render)
if (this.grid.children.length === 0) {
console.log('GridManager: First render - creating grid structure');
// Create POC structure: header-spacer + time-axis + grid-container
this.createHeaderSpacer();
this.createTimeAxis();
this.createGridContainer();
} else {
console.log('GridManager: Re-render - updating existing structure');
// Just update the calendar header for all-day events
this.updateCalendarHeader();
}
2025-07-25 23:31:25 +02:00
console.log('GridManager: Grid rendered successfully with POC structure');
}
/**
* Create header spacer to align time axis with week content
*/
private createHeaderSpacer(): void {
if (!this.grid) return;
const headerSpacer = document.createElement('swp-header-spacer');
this.grid.appendChild(headerSpacer);
}
/**
* Create time axis (positioned beside grid container) like in POC
*/
2025-07-25 23:31:25 +02:00
private createTimeAxis(): void {
if (!this.grid) return;
2025-07-25 23:31:25 +02:00
const timeAxis = document.createElement('swp-time-axis');
const timeAxisContent = document.createElement('swp-time-axis-content');
const gridSettings = calendarConfig.getGridSettings();
const startHour = gridSettings.dayStartHour;
const endHour = gridSettings.dayEndHour;
console.log('GridManager: Creating time axis - startHour:', startHour, 'endHour:', endHour);
for (let hour = startHour; hour < endHour; hour++) {
2025-07-25 23:31:25 +02:00
const marker = document.createElement('swp-hour-marker');
const period = hour >= 12 ? 'PM' : 'AM';
const displayHour = hour > 12 ? hour - 12 : (hour === 0 ? 12 : hour);
marker.textContent = `${displayHour} ${period}`;
timeAxisContent.appendChild(marker);
}
2025-07-25 23:31:25 +02:00
timeAxis.appendChild(timeAxisContent);
2025-07-25 23:31:25 +02:00
this.grid.appendChild(timeAxis);
}
/**
* Create grid container with header and scrollable content using Strategy Pattern
*/
private createGridContainer(): void {
2025-07-25 23:31:25 +02:00
if (!this.grid || !this.currentWeek) return;
const gridContainer = document.createElement('swp-grid-container');
// Create calendar header using Strategy Pattern
const calendarHeader = document.createElement('swp-calendar-header');
this.renderCalendarHeader(calendarHeader);
gridContainer.appendChild(calendarHeader);
2025-07-25 23:31:25 +02:00
// Create scrollable content
const scrollableContent = document.createElement('swp-scrollable-content');
const timeGrid = document.createElement('swp-time-grid');
2025-07-25 23:31:25 +02:00
// Add grid lines
const gridLines = document.createElement('swp-grid-lines');
timeGrid.appendChild(gridLines);
// Create column container using Strategy Pattern
const columnContainer = document.createElement('swp-day-columns');
this.renderColumnContainer(columnContainer);
timeGrid.appendChild(columnContainer);
2025-07-25 23:31:25 +02:00
scrollableContent.appendChild(timeGrid);
gridContainer.appendChild(scrollableContent);
2025-07-25 23:31:25 +02:00
this.grid.appendChild(gridContainer);
2025-07-25 23:31:25 +02:00
}
/**
* Render calendar header using Strategy Pattern
*/
private renderCalendarHeader(calendarHeader: HTMLElement): void {
2025-08-07 00:15:44 +02:00
if (!this.currentWeek) return;
const calendarType = calendarConfig.getCalendarMode();
2025-08-07 00:15:44 +02:00
const headerRenderer = CalendarTypeFactory.getHeaderRenderer(calendarType);
const context: HeaderRenderContext = {
currentWeek: this.currentWeek,
config: calendarConfig,
allDayEvents: this.allDayEvents,
resourceData: this.resourceData
};
headerRenderer.render(calendarHeader, context);
2025-08-07 00:15:44 +02:00
// Update spacer heights based on all-day events
this.updateSpacerHeights();
}
2025-07-25 23:31:25 +02:00
/**
* Render column container using Strategy Pattern
2025-07-25 23:31:25 +02:00
*/
private renderColumnContainer(columnContainer: HTMLElement): void {
2025-07-25 23:31:25 +02:00
if (!this.currentWeek) return;
console.log('GridManager: renderColumnContainer called');
const calendarType = calendarConfig.getCalendarMode();
2025-08-07 00:15:44 +02:00
const columnRenderer = CalendarTypeFactory.getColumnRenderer(calendarType);
const context: ColumnRenderContext = {
currentWeek: this.currentWeek,
config: calendarConfig,
resourceData: this.resourceData
};
2025-08-04 23:22:31 +02:00
columnRenderer.render(columnContainer, context);
2025-08-04 23:22:31 +02:00
}
/**
* Update only the calendar header (for all-day events) without rebuilding entire grid
*/
private updateCalendarHeader(): void {
if (!this.grid || !this.currentWeek) return;
const calendarHeader = this.grid.querySelector('swp-calendar-header');
if (!calendarHeader) return;
2025-08-07 00:15:44 +02:00
// Clear existing content
calendarHeader.innerHTML = '';
2025-08-07 00:15:44 +02:00
// Re-render headers using Strategy Pattern
this.renderCalendarHeader(calendarHeader as HTMLElement);
}
2025-08-04 23:55:04 +02:00
/**
* Update all-day events data and re-render if needed
*/
private updateAllDayEvents(events: any[]): void {
if (!this.currentWeek) return;
// Filter all-day events for current week
const weekStart = this.currentWeek;
const weekEnd = new Date(weekStart);
weekEnd.setDate(weekStart.getDate() + 6);
this.allDayEvents = events.filter(event => {
if (!event.allDay) return false;
const eventDate = new Date(event.start);
return eventDate >= weekStart && eventDate <= weekEnd;
});
console.log('GridManager: Updated all-day events:', this.allDayEvents.length);
// Update only the calendar header if grid is already rendered
2025-08-04 23:55:04 +02:00
if (this.grid && this.grid.children.length > 0) {
this.updateCalendarHeader();
2025-08-04 23:55:04 +02:00
}
}
2025-08-04 23:22:31 +02:00
/**
* Update spacer heights based on all-day events presence
*/
private updateSpacerHeights(): void {
2025-08-05 00:17:17 +02:00
const allDayEventCount = 1;
const eventHeight = 26; // Height per all-day event in pixels
const padding = 0; // Top/bottom padding
2025-08-04 23:55:04 +02:00
const allDayHeight = allDayEventCount > 0 ? (allDayEventCount * eventHeight) + padding : 0;
2025-08-04 23:22:31 +02:00
// Set CSS variable for dynamic spacer height
document.documentElement.style.setProperty('--all-day-row-height', `${allDayHeight}px`);
2025-08-04 23:55:04 +02:00
console.log('GridManager: Updated --all-day-row-height to', `${allDayHeight}px`, 'for', allDayEventCount, 'events');
}
/**
* Update grid CSS variables
*/
private updateGridStyles(): void {
const root = document.documentElement;
const gridSettings = calendarConfig.getGridSettings();
2025-08-05 21:56:06 +02:00
const calendar = document.querySelector('swp-calendar') as HTMLElement;
const calendarType = calendarConfig.getCalendarMode();
// Set CSS variables
root.style.setProperty('--hour-height', `${gridSettings.hourHeight}px`);
root.style.setProperty('--minute-height', `${gridSettings.hourHeight / 60}px`);
root.style.setProperty('--snap-interval', gridSettings.snapInterval.toString());
root.style.setProperty('--day-start-hour', gridSettings.dayStartHour.toString());
root.style.setProperty('--day-end-hour', gridSettings.dayEndHour.toString());
root.style.setProperty('--work-start-hour', gridSettings.workStartHour.toString());
root.style.setProperty('--work-end-hour', gridSettings.workEndHour.toString());
2025-08-05 21:56:06 +02:00
2025-08-07 00:15:44 +02:00
// Set number of columns based on calendar type
let columnCount = 7; // Default for date mode
if (calendarType === 'resource' && this.resourceData) {
columnCount = this.resourceData.resources.length;
} else if (calendarType === 'date') {
const dateSettings = calendarConfig.getDateViewSettings();
// Calculate columns based on view type - business logic moved from config
switch (dateSettings.period) {
case 'day':
columnCount = 1;
break;
case 'week':
columnCount = dateSettings.weekDays;
break;
case 'month':
columnCount = 7;
break;
default:
columnCount = dateSettings.weekDays;
}
2025-08-07 00:15:44 +02:00
}
root.style.setProperty('--grid-columns', columnCount.toString());
2025-08-05 21:56:06 +02:00
// Set day column min width based on fitToWidth setting
if (gridSettings.fitToWidth) {
2025-08-05 21:56:06 +02:00
root.style.setProperty('--day-column-min-width', '50px'); // Small min-width allows columns to fit available space
} else {
root.style.setProperty('--day-column-min-width', '250px'); // Default min-width for horizontal scroll mode
}
// Set fitToWidth data attribute for CSS targeting
if (calendar) {
calendar.setAttribute('data-fit-to-width', gridSettings.fitToWidth.toString());
2025-08-05 21:56:06 +02:00
}
2025-08-07 00:15:44 +02:00
console.log('GridManager: Updated grid styles with', columnCount, 'columns for', calendarType, 'calendar');
}
/**
2025-07-25 23:31:25 +02:00
* Setup grid interaction handlers for POC structure
*/
private setupGridInteractions(): void {
2025-07-25 23:31:25 +02:00
if (!this.grid) return;
2025-08-07 00:15:44 +02:00
// Click handler for day columns (works for both date and resource columns)
2025-07-25 23:31:25 +02:00
this.grid.addEventListener('click', (e: MouseEvent) => {
// Ignore if clicking on an event
if ((e.target as Element).closest('swp-event')) return;
2025-08-07 00:15:44 +02:00
const dayColumn = (e.target as Element).closest('swp-day-column, swp-resource-column') as HTMLElement;
2025-07-25 23:31:25 +02:00
if (!dayColumn) return;
2025-07-25 23:31:25 +02:00
const position = this.getClickPosition(e, dayColumn);
eventBus.emit(EventTypes.GRID_CLICK, {
2025-07-25 23:31:25 +02:00
date: (dayColumn as any).dataset.date,
2025-08-07 00:15:44 +02:00
resource: (dayColumn as any).dataset.resource,
employeeId: (dayColumn as any).dataset.employeeId,
time: position.time,
2025-07-26 00:00:03 +02:00
minutes: position.minutes
});
});
2025-07-25 23:31:25 +02:00
// Double click handler for day columns
this.grid.addEventListener('dblclick', (e: MouseEvent) => {
// Ignore if clicking on an event
if ((e.target as Element).closest('swp-event')) return;
2025-08-07 00:15:44 +02:00
const dayColumn = (e.target as Element).closest('swp-day-column, swp-resource-column') as HTMLElement;
2025-07-25 23:31:25 +02:00
if (!dayColumn) return;
2025-07-25 23:31:25 +02:00
const position = this.getClickPosition(e, dayColumn);
eventBus.emit(EventTypes.GRID_DBLCLICK, {
2025-07-25 23:31:25 +02:00
date: (dayColumn as any).dataset.date,
2025-08-07 00:15:44 +02:00
resource: (dayColumn as any).dataset.resource,
employeeId: (dayColumn as any).dataset.employeeId,
time: position.time,
2025-07-26 00:00:03 +02:00
minutes: position.minutes
});
});
}
/**
2025-07-25 23:31:25 +02:00
* Get click position in day column (POC structure)
*/
2025-07-25 23:31:25 +02:00
private getClickPosition(event: MouseEvent, dayColumn: HTMLElement): GridPosition {
const rect = dayColumn.getBoundingClientRect();
const y = event.clientY - rect.top;
const gridSettings = calendarConfig.getGridSettings();
const hourHeight = gridSettings.hourHeight;
2025-07-25 23:31:25 +02:00
const minuteHeight = hourHeight / 60;
const snapInterval = gridSettings.snapInterval;
const dayStartHour = gridSettings.dayStartHour;
2025-07-25 23:31:25 +02:00
// Calculate total minutes from day start
let totalMinutes = Math.floor(y / minuteHeight);
// Snap to interval
2025-07-25 23:31:25 +02:00
totalMinutes = Math.round(totalMinutes / snapInterval) * snapInterval;
// Add day start offset
2025-07-25 23:31:25 +02:00
totalMinutes += dayStartHour * 60;
return {
minutes: totalMinutes,
time: this.minutesToTime(totalMinutes),
2025-07-25 23:31:25 +02:00
y: y
};
}
2025-07-25 23:31:25 +02:00
/**
* Scroll to specific hour
*/
scrollToHour(hour: number): void {
if (!this.grid) return;
const gridSettings = calendarConfig.getGridSettings();
const hourHeight = gridSettings.hourHeight;
const dayStartHour = gridSettings.dayStartHour;
2025-07-25 23:31:25 +02:00
const headerHeight = 80; // Header row height
const scrollTop = headerHeight + ((hour - dayStartHour) * hourHeight);
this.grid.scrollTop = scrollTop;
}
/**
* Utility methods
*/
private minutesToTime(totalMinutes: number): string {
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
const period = hours >= 12 ? 'PM' : 'AM';
const displayHour = hours > 12 ? hours - 12 : (hours === 0 ? 12 : hours);
return `${displayHour}:${minutes.toString().padStart(2, '0')} ${period}`;
}
}