This commit is contained in:
Janus Knudsen 2025-07-25 23:31:25 +02:00
parent b443649ced
commit 42c418e961
7 changed files with 349 additions and 659 deletions

View file

@ -1,4 +1,4 @@
// Grid structure management
// Grid structure management - Simple CSS Grid Implementation
import { eventBus } from '../core/EventBus';
import { calendarConfig } from '../core/CalendarConfig';
@ -15,15 +15,11 @@ interface GridPosition {
}
/**
* Manages the calendar grid structure
* Manages the calendar grid structure using simple CSS Grid
*/
export class GridManager {
private container: HTMLElement | null = null;
private timeAxis: HTMLElement | null = null;
private weekHeader: HTMLElement | null = null;
private timeGrid: HTMLElement | null = null;
private dayColumns: HTMLElement | null = null;
private scrollableContent: HTMLElement | null = null;
private grid: HTMLElement | null = null;
private currentWeek: Date | null = null;
constructor() {
@ -33,15 +29,27 @@ export class GridManager {
private init(): void {
this.findElements();
this.subscribeToEvents();
this.setupScrollSync();
// 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);
// Render initial grid
this.render();
}
}
private getWeekStart(date: Date): Date {
const weekStart = new Date(date);
const day = weekStart.getDay();
const diff = weekStart.getDate() - day; // Sunday is 0
weekStart.setDate(diff);
weekStart.setHours(0, 0, 0, 0);
return weekStart;
}
private findElements(): void {
this.container = document.querySelector('swp-calendar-container');
this.timeAxis = document.querySelector('swp-time-axis');
this.weekHeader = document.querySelector('swp-week-header');
this.timeGrid = document.querySelector('swp-time-grid');
this.scrollableContent = document.querySelector('swp-scrollable-content');
this.grid = document.querySelector('swp-calendar-container');
}
private subscribeToEvents(): void {
@ -62,7 +70,7 @@ export class GridManager {
eventBus.on(EventTypes.PERIOD_CHANGE, (e: Event) => {
const detail = (e as CustomEvent).detail;
this.currentWeek = detail.week;
this.renderHeaders();
this.render();
});
// Handle week changes from NavigationManager
@ -72,12 +80,6 @@ export class GridManager {
this.render();
});
// Handle new week container creation
eventBus.on(EventTypes.WEEK_CONTAINER_CREATED, (e: Event) => {
const detail = (e as CustomEvent).detail;
this.renderGridForContainer(detail.container, detail.weekStart);
});
// Handle grid clicks
this.setupGridInteractions();
}
@ -86,129 +88,158 @@ export class GridManager {
* Render the complete grid structure
*/
render(): void {
this.renderTimeAxis();
this.renderHeaders();
if (!this.grid) return;
this.updateGridStyles();
this.renderGrid();
this.renderGridLines();
// Emit grid rendered event
eventBus.emit(EventTypes.GRID_RENDERED);
}
/**
* Render time axis (left side hours)
*/
private renderTimeAxis(): void {
if (!this.timeAxis) return;
const startHour = calendarConfig.get('dayStartHour');
const endHour = calendarConfig.get('dayEndHour');
this.timeAxis.innerHTML = '';
for (let hour = startHour; hour <= endHour; hour++) {
const marker = document.createElement('swp-hour-marker');
marker.textContent = this.formatHour(hour);
(marker as any).dataset.hour = hour;
this.timeAxis.appendChild(marker);
}
}
/**
* Render week headers
*/
private renderHeaders(): void {
if (!this.weekHeader || !this.currentWeek) return;
const view = calendarConfig.get('view');
const weekDays = calendarConfig.get('weekDays');
this.weekHeader.innerHTML = '';
if (view === 'week') {
const dates = this.getWeekDates(this.currentWeek);
const daysToShow = dates.slice(0, weekDays);
daysToShow.forEach((date, index) => {
const header = document.createElement('swp-day-header');
header.innerHTML = `
<swp-day-name>${this.getDayName(date)}</swp-day-name>
<swp-day-date>${date.getDate()}</swp-day-date>
`;
(header as any).dataset.date = this.formatDate(date);
(header as any).dataset.dayIndex = index;
// Mark today
if (this.isToday(date)) {
(header as any).dataset.today = 'true';
}
this.weekHeader!.appendChild(header);
});
}
}
/**
* Render the main grid structure
* Render the complete grid using POC structure
*/
private renderGrid(): void {
if (!this.timeGrid) return;
// Clear existing columns
let dayColumns = this.timeGrid.querySelector('swp-day-columns');
if (!dayColumns) {
dayColumns = document.createElement('swp-day-columns');
this.timeGrid.appendChild(dayColumns);
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;
}
// Clear existing grid and rebuild POC structure
this.grid.innerHTML = '';
dayColumns.innerHTML = '';
// Create POC structure: time-axis + week-container
this.createTimeAxis();
this.createWeekContainer();
const view = calendarConfig.get('view');
const columnsCount = view === 'week' ? calendarConfig.get('weekDays') : 1;
console.log('GridManager: Grid rendered successfully with POC structure');
}
/**
* Create time axis (left column) like in POC
*/
private createTimeAxis(): void {
if (!this.grid) return;
const timeAxis = document.createElement('swp-time-axis');
const startHour = calendarConfig.get('dayStartHour');
const endHour = calendarConfig.get('dayEndHour');
for (let hour = startHour; hour <= endHour; hour++) {
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}`;
timeAxis.appendChild(marker);
}
this.grid.appendChild(timeAxis);
}
/**
* Create week container with header and scrollable content like in POC
*/
private createWeekContainer(): void {
if (!this.grid || !this.currentWeek) return;
const weekContainer = document.createElement('swp-week-container');
// Create columns
for (let i = 0; i < columnsCount; i++) {
const column = document.createElement('swp-day-column');
(column as any).dataset.columnIndex = i;
if (this.currentWeek) {
const dates = this.getWeekDates(this.currentWeek);
if (dates[i]) {
(column as any).dataset.date = this.formatDate(dates[i]);
}
// Create week header
const weekHeader = document.createElement('swp-week-header');
this.renderWeekHeaders(weekHeader);
weekContainer.appendChild(weekHeader);
// Create scrollable content
const scrollableContent = document.createElement('swp-scrollable-content');
const timeGrid = document.createElement('swp-time-grid');
// Add grid lines
const gridLines = document.createElement('swp-grid-lines');
timeGrid.appendChild(gridLines);
// Create day columns
const dayColumns = document.createElement('swp-day-columns');
this.renderDayColumns(dayColumns);
timeGrid.appendChild(dayColumns);
scrollableContent.appendChild(timeGrid);
weekContainer.appendChild(scrollableContent);
this.grid.appendChild(weekContainer);
}
/**
* Render week headers like in POC
*/
private renderWeekHeaders(weekHeader: HTMLElement): void {
if (!this.currentWeek) return;
const dates = this.getWeekDates(this.currentWeek);
const weekDays = calendarConfig.get('weekDays');
const daysToShow = dates.slice(0, weekDays);
daysToShow.forEach((date) => {
const header = document.createElement('swp-day-header');
if (this.isToday(date)) {
(header as any).dataset.today = 'true';
}
// Add events container
header.innerHTML = `
<swp-day-name>${this.getDayName(date)}</swp-day-name>
<swp-day-date>${date.getDate()}</swp-day-date>
`;
(header as any).dataset.date = this.formatDate(date);
weekHeader.appendChild(header);
});
}
/**
* Render day columns like in POC
*/
private renderDayColumns(dayColumns: HTMLElement): void {
console.log('GridManager: renderDayColumns called');
if (!this.currentWeek) {
console.log('GridManager: No currentWeek, returning');
return;
}
const dates = this.getWeekDates(this.currentWeek);
const weekDays = calendarConfig.get('weekDays');
const daysToShow = dates.slice(0, weekDays);
console.log('GridManager: About to render', daysToShow.length, 'day columns');
daysToShow.forEach((date, dayIndex) => {
const column = document.createElement('swp-day-column');
(column as any).dataset.date = this.formatDate(date);
(column as any).dataset.dayIndex = dayIndex.toString();
console.log(`GridManager: Creating day column ${dayIndex} for date ${this.formatDate(date)}`);
// Add dummy content to force column width (temporary test)
const dummyContent = document.createElement('div');
dummyContent.style.height = '20px';
dummyContent.style.width = '100%';
dummyContent.style.backgroundColor = 'red';
dummyContent.style.color = 'white';
dummyContent.style.fontSize = '12px';
dummyContent.style.textAlign = 'center';
dummyContent.textContent = `Day ${dayIndex + 1}`;
column.appendChild(dummyContent);
const eventsLayer = document.createElement('swp-events-layer');
column.appendChild(eventsLayer);
dayColumns.appendChild(column);
}
this.dayColumns = dayColumns as HTMLElement;
this.updateGridStyles();
}
/**
* Render grid lines
*/
private renderGridLines(): void {
if (!this.timeGrid) return;
let gridLines = this.timeGrid.querySelector('swp-grid-lines');
if (!gridLines) {
gridLines = document.createElement('swp-grid-lines');
this.timeGrid.insertBefore(gridLines, this.timeGrid.firstChild);
}
const totalHours = calendarConfig.totalHours;
const hourHeight = calendarConfig.get('hourHeight');
// Set CSS variables
this.timeGrid.style.setProperty('--total-hours', totalHours.toString());
this.timeGrid.style.setProperty('--hour-height', `${hourHeight}px`);
// Grid lines are handled by CSS
});
}
/**
@ -226,84 +257,93 @@ export class GridManager {
root.style.setProperty('--day-end-hour', config.dayEndHour.toString());
root.style.setProperty('--work-start-hour', config.workStartHour.toString());
root.style.setProperty('--work-end-hour', config.workEndHour.toString());
// Set grid height
const totalHeight = calendarConfig.totalHours * config.hourHeight;
if (this.timeGrid) {
this.timeGrid.style.height = `${totalHeight}px`;
}
}
/**
* Setup grid interaction handlers
* Setup grid interaction handlers for POC structure
*/
private setupGridInteractions(): void {
if (!this.timeGrid) return;
if (!this.grid) return;
// Click handler
this.timeGrid.addEventListener('click', (e: MouseEvent) => {
// Click handler for day columns
this.grid.addEventListener('click', (e: MouseEvent) => {
// Ignore if clicking on an event
if ((e.target as Element).closest('swp-event')) return;
const column = (e.target as Element).closest('swp-day-column') as HTMLElement;
if (!column) return;
const dayColumn = (e.target as Element).closest('swp-day-column') as HTMLElement;
if (!dayColumn) return;
const position = this.getClickPosition(e, column);
const position = this.getClickPosition(e, dayColumn);
eventBus.emit(EventTypes.GRID_CLICK, {
date: (column as any).dataset.date,
date: (dayColumn as any).dataset.date,
time: position.time,
minutes: position.minutes,
columnIndex: parseInt((column as any).dataset.columnIndex)
dayIndex: parseInt((dayColumn as any).dataset.dayIndex)
});
});
// Double click handler
this.timeGrid.addEventListener('dblclick', (e: MouseEvent) => {
// 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;
const column = (e.target as Element).closest('swp-day-column') as HTMLElement;
if (!column) return;
const dayColumn = (e.target as Element).closest('swp-day-column') as HTMLElement;
if (!dayColumn) return;
const position = this.getClickPosition(e, column);
const position = this.getClickPosition(e, dayColumn);
eventBus.emit(EventTypes.GRID_DBLCLICK, {
date: (column as any).dataset.date,
date: (dayColumn as any).dataset.date,
time: position.time,
minutes: position.minutes,
columnIndex: parseInt((column as any).dataset.columnIndex)
dayIndex: parseInt((dayColumn as any).dataset.dayIndex)
});
});
}
/**
* Get click position in grid
* Get click position in day column (POC structure)
*/
private getClickPosition(event: MouseEvent, column: HTMLElement): GridPosition {
const rect = column.getBoundingClientRect();
const y = event.clientY - rect.top + (this.scrollableContent?.scrollTop || 0);
private getClickPosition(event: MouseEvent, dayColumn: HTMLElement): GridPosition {
const rect = dayColumn.getBoundingClientRect();
const y = event.clientY - rect.top;
const minuteHeight = calendarConfig.minuteHeight;
const hourHeight = calendarConfig.get('hourHeight');
const minuteHeight = hourHeight / 60;
const snapInterval = calendarConfig.get('snapInterval');
const dayStartHour = calendarConfig.get('dayStartHour');
// Calculate minutes from start of day
let minutes = Math.floor(y / minuteHeight);
// Calculate total minutes from day start
let totalMinutes = Math.floor(y / minuteHeight);
// Snap to interval
minutes = Math.round(minutes / snapInterval) * snapInterval;
totalMinutes = Math.round(totalMinutes / snapInterval) * snapInterval;
// Add day start offset
const totalMinutes = (dayStartHour * 60) + minutes;
totalMinutes += dayStartHour * 60;
return {
minutes: totalMinutes,
time: this.minutesToTime(totalMinutes),
y: minutes * minuteHeight
y: y
};
}
/**
* Scroll to specific hour
*/
scrollToHour(hour: number): void {
if (!this.grid) return;
const hourHeight = calendarConfig.get('hourHeight');
const dayStartHour = calendarConfig.get('dayStartHour');
const headerHeight = 80; // Header row height
const scrollTop = headerHeight + ((hour - dayStartHour) * hourHeight);
this.grid.scrollTop = scrollTop;
}
/**
* Utility methods
*/
@ -346,241 +386,4 @@ export class GridManager {
return `${displayHour}:${minutes.toString().padStart(2, '0')} ${period}`;
}
/**
* Scroll to specific hour
*/
scrollToHour(hour: number): void {
if (!this.scrollableContent) return;
const hourHeight = calendarConfig.get('hourHeight');
const dayStartHour = calendarConfig.get('dayStartHour');
const scrollTop = (hour - dayStartHour) * hourHeight;
this.scrollableContent.scrollTop = scrollTop;
}
/**
* Render grid for a specific container (used during navigation transitions)
*/
private renderGridForContainer(container: HTMLElement, weekStart: Date): void {
// Find the week header and scrollable content within this container
const weekHeader = container.querySelector('swp-week-header');
const scrollableContent = container.querySelector('swp-scrollable-content');
const timeGrid = container.querySelector('swp-time-grid');
if (!weekHeader || !scrollableContent || !timeGrid) {
console.warn('GridManager: Required elements not found in container');
return;
}
// Render week header for this container
this.renderWeekHeaderForContainer(weekHeader as HTMLElement, weekStart);
// Render grid content for this container - pass weekStart
this.renderGridForSpecificContainer(container, weekStart);
this.renderGridLinesForContainer(timeGrid as HTMLElement);
this.setupGridInteractionsForContainer(container);
// Setup scroll sync for this new container
this.setupScrollSyncForContainer(scrollableContent as HTMLElement);
}
/**
* Render week header for a specific container
*/
private renderWeekHeaderForContainer(weekHeader: HTMLElement, weekStart: Date): void {
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
weekHeader.innerHTML = '';
for (let i = 0; i < 7; i++) {
const date = new Date(weekStart);
date.setDate(date.getDate() + i);
const header = document.createElement('swp-day-header');
if (this.isToday(date)) {
(header as any).dataset.today = 'true';
}
header.innerHTML = `
<swp-day-name>${days[date.getDay()]}</swp-day-name>
<swp-day-date>${date.getDate()}</swp-day-date>
`;
(header as any).dataset.date = this.formatDate(date);
weekHeader.appendChild(header);
}
}
/**
* Render grid structure for a specific container
*/
private renderGridForSpecificContainer(container: HTMLElement, weekStart?: Date): void {
const timeGrid = container.querySelector('swp-time-grid');
if (!timeGrid) {
console.warn('GridManager: No time-grid found in container');
return;
}
// Use the weekStart parameter or fall back to currentWeek
const targetWeek = weekStart || this.currentWeek;
if (!targetWeek) {
console.warn('GridManager: No target week available');
return;
}
// Clear existing columns
let dayColumns = timeGrid.querySelector('swp-day-columns');
if (!dayColumns) {
dayColumns = document.createElement('swp-day-columns');
timeGrid.appendChild(dayColumns);
}
dayColumns.innerHTML = '';
const view = calendarConfig.get('view');
const columnsCount = view === 'week' ? calendarConfig.get('weekDays') : 1;
// Create columns using the target week
for (let i = 0; i < columnsCount; i++) {
const column = document.createElement('swp-day-column');
(column as any).dataset.columnIndex = i;
const dates = this.getWeekDates(targetWeek);
if (dates[i]) {
(column as any).dataset.date = this.formatDate(dates[i]);
}
// Add events container
const eventsLayer = document.createElement('swp-events-layer');
column.appendChild(eventsLayer);
dayColumns.appendChild(column);
}
// Update grid styles for this container
const totalHeight = calendarConfig.totalHours * calendarConfig.get('hourHeight');
(timeGrid as HTMLElement).style.height = `${totalHeight}px`;
}
/**
* Render grid lines for a specific time grid
*/
private renderGridLinesForContainer(timeGrid: HTMLElement): void {
let gridLines = timeGrid.querySelector('swp-grid-lines');
if (!gridLines) {
gridLines = document.createElement('swp-grid-lines');
timeGrid.insertBefore(gridLines, timeGrid.firstChild);
}
const totalHours = calendarConfig.totalHours;
const hourHeight = calendarConfig.get('hourHeight');
// Set CSS variables
timeGrid.style.setProperty('--total-hours', totalHours.toString());
timeGrid.style.setProperty('--hour-height', `${hourHeight}px`);
}
/**
* Setup grid interactions for a specific container
*/
private setupGridInteractionsForContainer(container: HTMLElement): void {
const timeGrid = container.querySelector('swp-time-grid');
if (!timeGrid) return;
// Click handler
timeGrid.addEventListener('click', (e: Event) => {
const mouseEvent = e as MouseEvent;
// Ignore if clicking on an event
if ((mouseEvent.target as Element).closest('swp-event')) return;
const column = (mouseEvent.target as Element).closest('swp-day-column') as HTMLElement;
if (!column) return;
const position = this.getClickPositionForContainer(mouseEvent, column, container);
eventBus.emit(EventTypes.GRID_CLICK, {
date: (column as any).dataset.date,
time: position.time,
minutes: position.minutes,
columnIndex: parseInt((column as any).dataset.columnIndex)
});
});
// Double click handler
timeGrid.addEventListener('dblclick', (e: Event) => {
const mouseEvent = e as MouseEvent;
// Ignore if clicking on an event
if ((mouseEvent.target as Element).closest('swp-event')) return;
const column = (mouseEvent.target as Element).closest('swp-day-column') as HTMLElement;
if (!column) return;
const position = this.getClickPositionForContainer(mouseEvent, column, container);
eventBus.emit(EventTypes.GRID_DBLCLICK, {
date: (column as any).dataset.date,
time: position.time,
minutes: position.minutes,
columnIndex: parseInt((column as any).dataset.columnIndex)
});
});
}
/**
* Get click position for a specific container
*/
private getClickPositionForContainer(event: MouseEvent, column: HTMLElement, container: HTMLElement): GridPosition {
const rect = column.getBoundingClientRect();
const scrollableContent = container.querySelector('swp-scrollable-content') as HTMLElement;
const y = event.clientY - rect.top + (scrollableContent?.scrollTop || 0);
const minuteHeight = calendarConfig.minuteHeight;
const snapInterval = calendarConfig.get('snapInterval');
const dayStartHour = calendarConfig.get('dayStartHour');
// Calculate minutes from start of day
let minutes = Math.floor(y / minuteHeight);
// Snap to interval
minutes = Math.round(minutes / snapInterval) * snapInterval;
// Add day start offset
const totalMinutes = (dayStartHour * 60) + minutes;
return {
minutes: totalMinutes,
time: this.minutesToTime(totalMinutes),
y: minutes * minuteHeight
};
}
/**
* Setup scroll synchronization between time-axis and scrollable content
*/
private setupScrollSync(): void {
if (!this.scrollableContent || !this.timeAxis) return;
// Sync time-axis scroll with scrollable content
this.scrollableContent.addEventListener('scroll', () => {
if (this.timeAxis) {
this.timeAxis.scrollTop = this.scrollableContent!.scrollTop;
}
});
}
/**
* Setup scroll synchronization for a specific container's scrollable content
*/
private setupScrollSyncForContainer(scrollableContent: HTMLElement): void {
if (!this.timeAxis) return;
// Sync time-axis scroll with this container's scrollable content
scrollableContent.addEventListener('scroll', () => {
if (this.timeAxis) {
this.timeAxis.scrollTop = scrollableContent.scrollTop;
}
});
}
}