Major refactorering to get a hold on all these events
This commit is contained in:
parent
2a766cf685
commit
59b3c64c55
18 changed files with 1901 additions and 357 deletions
|
|
@ -2,14 +2,17 @@ import { EventBus } from '../core/EventBus.js';
|
|||
import { EventTypes } from '../constants/EventTypes.js';
|
||||
import { CalendarConfig } from '../core/CalendarConfig.js';
|
||||
import { CalendarEvent, CalendarView, IEventBus } from '../types/CalendarTypes.js';
|
||||
import { CalendarStateManager } from './CalendarStateManager.js';
|
||||
import { StateEvents } from '../types/CalendarState.js';
|
||||
|
||||
/**
|
||||
* CalendarManager - Hovedkoordinator for alle calendar managers
|
||||
* Håndterer initialisering, koordinering og kommunikation mellem alle managers
|
||||
* CalendarManager - Main coordinator for all calendar managers
|
||||
* Now delegates initialization to CalendarStateManager for better coordination
|
||||
*/
|
||||
export class CalendarManager {
|
||||
private eventBus: IEventBus;
|
||||
private config: CalendarConfig;
|
||||
private stateManager: CalendarStateManager;
|
||||
private currentView: CalendarView = 'week';
|
||||
private currentDate: Date = new Date();
|
||||
private isInitialized: boolean = false;
|
||||
|
|
@ -17,40 +20,37 @@ export class CalendarManager {
|
|||
constructor(eventBus: IEventBus, config: CalendarConfig) {
|
||||
this.eventBus = eventBus;
|
||||
this.config = config;
|
||||
this.stateManager = new CalendarStateManager();
|
||||
this.setupEventListeners();
|
||||
console.log('📋 CalendarManager: Created with state management');
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialiser calendar systemet
|
||||
* Initialize calendar system using state-driven approach
|
||||
*/
|
||||
public initialize(): void {
|
||||
public async initialize(): Promise<void> {
|
||||
if (this.isInitialized) {
|
||||
console.warn('CalendarManager is already initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Initializing CalendarManager...');
|
||||
console.log('🚀 CalendarManager: Starting state-driven initialization');
|
||||
|
||||
// Emit initialization event
|
||||
this.eventBus.emit(EventTypes.CALENDAR_INITIALIZING, {
|
||||
view: this.currentView,
|
||||
date: this.currentDate,
|
||||
config: this.config
|
||||
});
|
||||
|
||||
// Set initial view and date
|
||||
this.setView(this.currentView);
|
||||
this.setCurrentDate(this.currentDate);
|
||||
|
||||
this.isInitialized = true;
|
||||
|
||||
// Emit initialization complete event
|
||||
this.eventBus.emit(EventTypes.CALENDAR_INITIALIZED, {
|
||||
view: this.currentView,
|
||||
date: this.currentDate
|
||||
});
|
||||
|
||||
console.log('CalendarManager initialized successfully');
|
||||
try {
|
||||
// Delegate to StateManager for coordinated initialization
|
||||
await this.stateManager.initialize();
|
||||
|
||||
// Set initial view and date after successful initialization
|
||||
this.setView(this.currentView);
|
||||
this.setCurrentDate(this.currentDate);
|
||||
|
||||
this.isInitialized = true;
|
||||
console.log('✅ CalendarManager: Initialization complete');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ CalendarManager initialization failed:', error);
|
||||
throw error; // Let the caller handle the error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -139,7 +139,28 @@ export class CalendarManager {
|
|||
* Check om calendar er initialiseret
|
||||
*/
|
||||
public isCalendarInitialized(): boolean {
|
||||
return this.isInitialized;
|
||||
return this.isInitialized && this.stateManager.isReady();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current calendar state
|
||||
*/
|
||||
public getCurrentState(): string {
|
||||
return this.stateManager.getCurrentState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get state manager for advanced operations
|
||||
*/
|
||||
public getStateManager(): CalendarStateManager {
|
||||
return this.stateManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get initialization report for debugging
|
||||
*/
|
||||
public getInitializationReport(): any {
|
||||
return this.stateManager.getInitializationReport();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
471
src/managers/CalendarStateManager.ts
Normal file
471
src/managers/CalendarStateManager.ts
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
// Calendar state management and coordination
|
||||
|
||||
import { eventBus } from '../core/EventBus';
|
||||
import { calendarConfig } from '../core/CalendarConfig';
|
||||
import {
|
||||
CalendarState,
|
||||
StateEvents,
|
||||
CalendarEvent,
|
||||
StateChangeEvent,
|
||||
ErrorEvent,
|
||||
VALID_STATE_TRANSITIONS,
|
||||
InitializationPhase,
|
||||
STATE_TO_PHASE
|
||||
} from '../types/CalendarState';
|
||||
|
||||
/**
|
||||
* Central coordinator for calendar initialization and state management
|
||||
* Ensures proper sequencing and eliminates race conditions
|
||||
*/
|
||||
export class CalendarStateManager {
|
||||
private currentState: CalendarState = CalendarState.UNINITIALIZED;
|
||||
private stateHistory: Array<{ state: CalendarState; timestamp: number }> = [];
|
||||
private initializationStartTime: number = 0;
|
||||
private phaseTimings: Map<InitializationPhase, { start: number; end?: number }> = new Map();
|
||||
|
||||
constructor() {
|
||||
console.log('📋 CalendarStateManager: Created');
|
||||
this.recordStateChange(CalendarState.UNINITIALIZED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current calendar state
|
||||
*/
|
||||
getCurrentState(): CalendarState {
|
||||
return this.currentState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if calendar is in ready state
|
||||
*/
|
||||
isReady(): boolean {
|
||||
return this.currentState === CalendarState.READY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current initialization phase
|
||||
*/
|
||||
getCurrentPhase(): InitializationPhase {
|
||||
return STATE_TO_PHASE[this.currentState];
|
||||
}
|
||||
|
||||
/**
|
||||
* Main initialization method - coordinates all calendar setup
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
console.log('🚀 CalendarStateManager: Starting calendar initialization');
|
||||
this.initializationStartTime = Date.now();
|
||||
|
||||
try {
|
||||
// Phase 1: Configuration loading (blocks everything else)
|
||||
await this.executeConfigurationPhase();
|
||||
|
||||
// Phase 2: Parallel data loading and DOM structure setup
|
||||
await this.executeDataAndDOMPhase();
|
||||
|
||||
// Phase 3: Event rendering (requires both data and DOM)
|
||||
await this.executeEventRenderingPhase();
|
||||
|
||||
// Phase 4: Finalization
|
||||
await this.executeFinalizationPhase();
|
||||
|
||||
const totalTime = Date.now() - this.initializationStartTime;
|
||||
console.log(`🎊 Calendar initialization complete in ${totalTime}ms`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Calendar initialization failed:', error);
|
||||
await this.handleInitializationError(error as Error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 1: Configuration Loading
|
||||
* Must complete before any other operations
|
||||
*/
|
||||
private async executeConfigurationPhase(): Promise<void> {
|
||||
console.log('📖 Phase 1: Configuration Loading');
|
||||
await this.transitionTo(CalendarState.INITIALIZING);
|
||||
|
||||
this.startPhase(InitializationPhase.CONFIGURATION);
|
||||
|
||||
// Emit config loading started
|
||||
this.emitEvent(StateEvents.CONFIG_LOADING_STARTED, 'CalendarStateManager', {
|
||||
configSource: 'URL and DOM attributes'
|
||||
});
|
||||
|
||||
// Configuration is already loaded in CalendarConfig constructor
|
||||
// but we validate and emit the completion event
|
||||
const configValid = this.validateConfiguration();
|
||||
|
||||
if (!configValid) {
|
||||
throw new Error('Invalid calendar configuration');
|
||||
}
|
||||
|
||||
this.emitEvent(StateEvents.CONFIG_LOADED, 'CalendarStateManager', {
|
||||
calendarMode: calendarConfig.getCalendarMode(),
|
||||
dateViewSettings: calendarConfig.getDateViewSettings(),
|
||||
gridSettings: calendarConfig.getGridSettings()
|
||||
});
|
||||
|
||||
await this.transitionTo(CalendarState.CONFIG_LOADED);
|
||||
this.endPhase(InitializationPhase.CONFIGURATION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 2: Parallel Data Loading and DOM Setup
|
||||
* These can run concurrently to improve performance
|
||||
*/
|
||||
private async executeDataAndDOMPhase(): Promise<void> {
|
||||
console.log('📊 Phase 2: Data Loading and DOM Setup (Parallel)');
|
||||
this.startPhase(InitializationPhase.DATA_AND_DOM);
|
||||
|
||||
// Start both data loading and rendering setup in parallel
|
||||
const dataPromise = this.coordinateDataLoading();
|
||||
const domPromise = this.coordinateDOMSetup();
|
||||
|
||||
// Wait for both to complete
|
||||
await Promise.all([dataPromise, domPromise]);
|
||||
|
||||
this.endPhase(InitializationPhase.DATA_AND_DOM);
|
||||
}
|
||||
|
||||
/**
|
||||
* Coordinate data loading process
|
||||
*/
|
||||
private async coordinateDataLoading(): Promise<void> {
|
||||
await this.transitionTo(CalendarState.DATA_LOADING);
|
||||
|
||||
this.emitEvent(StateEvents.DATA_LOADING_STARTED, 'CalendarStateManager', {
|
||||
mode: calendarConfig.getCalendarMode(),
|
||||
period: this.getCurrentPeriod()
|
||||
});
|
||||
|
||||
// EventManager will respond to DATA_LOADING_STARTED and load data
|
||||
// We wait for its DATA_LOADED response
|
||||
await this.waitForEvent(StateEvents.DATA_LOADED, 10000);
|
||||
|
||||
await this.transitionTo(CalendarState.DATA_LOADED);
|
||||
console.log('✅ Data loading phase complete');
|
||||
}
|
||||
|
||||
/**
|
||||
* Coordinate DOM structure setup
|
||||
*/
|
||||
private async coordinateDOMSetup(): Promise<void> {
|
||||
await this.transitionTo(CalendarState.RENDERING);
|
||||
|
||||
this.emitEvent(StateEvents.RENDERING_STARTED, 'CalendarStateManager', {
|
||||
phase: 'DOM structure setup'
|
||||
});
|
||||
|
||||
// GridManager will respond to RENDERING_STARTED and create DOM structure
|
||||
// We wait for its GRID_RENDERED response
|
||||
await this.waitForEvent(StateEvents.GRID_RENDERED, 5000);
|
||||
|
||||
await this.transitionTo(CalendarState.RENDERED);
|
||||
console.log('✅ DOM setup phase complete');
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 3: Event Rendering
|
||||
* Requires both data and DOM to be ready
|
||||
*/
|
||||
private async executeEventRenderingPhase(): Promise<void> {
|
||||
console.log('🎨 Phase 3: Event Rendering');
|
||||
this.startPhase(InitializationPhase.EVENT_RENDERING);
|
||||
|
||||
// Both data and DOM are ready, trigger event rendering
|
||||
// EventRenderer will wait for both GRID_RENDERED and DATA_LOADED
|
||||
|
||||
// Wait for events to be rendered
|
||||
await this.waitForEvent(StateEvents.EVENTS_RENDERED, 3000);
|
||||
|
||||
this.emitEvent(StateEvents.RENDERING_COMPLETE, 'CalendarStateManager', {
|
||||
phase: 'Event rendering complete'
|
||||
});
|
||||
|
||||
this.endPhase(InitializationPhase.EVENT_RENDERING);
|
||||
console.log('✅ Event rendering phase complete');
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 4: Finalization
|
||||
* System is ready for user interaction
|
||||
*/
|
||||
private async executeFinalizationPhase(): Promise<void> {
|
||||
console.log('🏁 Phase 4: Finalization');
|
||||
this.startPhase(InitializationPhase.FINALIZATION);
|
||||
|
||||
await this.transitionTo(CalendarState.READY);
|
||||
|
||||
const totalTime = Date.now() - this.initializationStartTime;
|
||||
|
||||
this.emitEvent(StateEvents.CALENDAR_READY, 'CalendarStateManager', {
|
||||
initializationTime: totalTime,
|
||||
finalState: this.currentState,
|
||||
phaseTimings: this.getPhaseTimings()
|
||||
});
|
||||
|
||||
this.endPhase(InitializationPhase.FINALIZATION);
|
||||
console.log(`🎉 Calendar is ready! Total initialization time: ${totalTime}ms`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transition to a new state with validation
|
||||
*/
|
||||
private async transitionTo(newState: CalendarState): Promise<void> {
|
||||
if (!this.isValidTransition(this.currentState, newState)) {
|
||||
const error = new Error(`Invalid state transition: ${this.currentState} → ${newState}`);
|
||||
await this.handleInitializationError(error);
|
||||
return;
|
||||
}
|
||||
|
||||
const oldState = this.currentState;
|
||||
this.currentState = newState;
|
||||
this.recordStateChange(newState);
|
||||
|
||||
// Emit state change event
|
||||
const stateChangeEvent: StateChangeEvent = {
|
||||
type: StateEvents.CALENDAR_STATE_CHANGED,
|
||||
component: 'CalendarStateManager',
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
from: oldState,
|
||||
to: newState,
|
||||
transitionValid: true
|
||||
},
|
||||
metadata: {
|
||||
phase: STATE_TO_PHASE[newState]
|
||||
}
|
||||
};
|
||||
|
||||
eventBus.emit(StateEvents.CALENDAR_STATE_CHANGED, stateChangeEvent);
|
||||
console.log(`📍 State: ${oldState} → ${newState} [${STATE_TO_PHASE[newState]}]`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate state transition
|
||||
*/
|
||||
private isValidTransition(from: CalendarState, to: CalendarState): boolean {
|
||||
const allowedTransitions = VALID_STATE_TRANSITIONS[from] || [];
|
||||
return allowedTransitions.includes(to);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle initialization errors with recovery attempts
|
||||
*/
|
||||
private async handleInitializationError(error: Error): Promise<void> {
|
||||
console.error('💥 Initialization error:', error);
|
||||
|
||||
const errorEvent: ErrorEvent = {
|
||||
type: StateEvents.CALENDAR_ERROR,
|
||||
component: 'CalendarStateManager',
|
||||
error,
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
failedComponent: 'CalendarStateManager',
|
||||
currentState: this.currentState,
|
||||
canRecover: this.canRecoverFromError(error)
|
||||
}
|
||||
};
|
||||
|
||||
eventBus.emit(StateEvents.CALENDAR_ERROR, errorEvent);
|
||||
|
||||
// Attempt recovery if possible
|
||||
if (this.canRecoverFromError(error)) {
|
||||
await this.attemptRecovery(error);
|
||||
} else {
|
||||
await this.transitionTo(CalendarState.ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to recover from errors
|
||||
*/
|
||||
private async attemptRecovery(error: Error): Promise<void> {
|
||||
console.log('🔧 Attempting error recovery...');
|
||||
|
||||
this.emitEvent(StateEvents.RECOVERY_ATTEMPTED, 'CalendarStateManager', {
|
||||
error: error.message,
|
||||
currentState: this.currentState
|
||||
});
|
||||
|
||||
try {
|
||||
// Simple recovery strategy: try to continue from a stable state
|
||||
if (this.currentState === CalendarState.DATA_LOADING) {
|
||||
// Retry data loading
|
||||
await this.coordinateDataLoading();
|
||||
} else if (this.currentState === CalendarState.RENDERING) {
|
||||
// Retry DOM setup
|
||||
await this.coordinateDOMSetup();
|
||||
}
|
||||
|
||||
this.emitEvent(StateEvents.RECOVERY_SUCCESS, 'CalendarStateManager', {
|
||||
recoveredFrom: error.message
|
||||
});
|
||||
|
||||
} catch (recoveryError) {
|
||||
console.error('❌ Recovery failed:', recoveryError);
|
||||
|
||||
this.emitEvent(StateEvents.RECOVERY_FAILED, 'CalendarStateManager', {
|
||||
originalError: error.message,
|
||||
recoveryError: (recoveryError as Error).message
|
||||
});
|
||||
|
||||
await this.transitionTo(CalendarState.ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if error is recoverable
|
||||
*/
|
||||
private canRecoverFromError(error: Error): boolean {
|
||||
// Simple recovery logic - can be extended
|
||||
const recoverableErrors = [
|
||||
'timeout',
|
||||
'network',
|
||||
'dom not ready',
|
||||
'data loading failed'
|
||||
];
|
||||
|
||||
return recoverableErrors.some(pattern =>
|
||||
error.message.toLowerCase().includes(pattern)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate calendar configuration
|
||||
*/
|
||||
private validateConfiguration(): boolean {
|
||||
try {
|
||||
const mode = calendarConfig.getCalendarMode();
|
||||
const gridSettings = calendarConfig.getGridSettings();
|
||||
|
||||
// Basic validation
|
||||
if (!mode || !['date', 'resource'].includes(mode)) {
|
||||
console.error('Invalid calendar mode:', mode);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!gridSettings.hourHeight || gridSettings.hourHeight < 20) {
|
||||
console.error('Invalid hour height:', gridSettings.hourHeight);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Configuration validation failed:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current period for data loading
|
||||
*/
|
||||
private getCurrentPeriod(): { start: string; end: string } {
|
||||
const currentDate = calendarConfig.getSelectedDate() || new Date();
|
||||
const mode = calendarConfig.getCalendarMode();
|
||||
|
||||
if (mode === 'date') {
|
||||
const dateSettings = calendarConfig.getDateViewSettings();
|
||||
|
||||
if (dateSettings.period === 'week') {
|
||||
const weekStart = new Date(currentDate);
|
||||
weekStart.setDate(currentDate.getDate() - currentDate.getDay());
|
||||
const weekEnd = new Date(weekStart);
|
||||
weekEnd.setDate(weekStart.getDate() + 6);
|
||||
|
||||
return {
|
||||
start: weekStart.toISOString().split('T')[0],
|
||||
end: weekEnd.toISOString().split('T')[0]
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Default to current day
|
||||
return {
|
||||
start: currentDate.toISOString().split('T')[0],
|
||||
end: currentDate.toISOString().split('T')[0]
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility methods
|
||||
*/
|
||||
private recordStateChange(state: CalendarState): void {
|
||||
this.stateHistory.push({
|
||||
state,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
}
|
||||
|
||||
private startPhase(phase: InitializationPhase): void {
|
||||
this.phaseTimings.set(phase, { start: Date.now() });
|
||||
}
|
||||
|
||||
private endPhase(phase: InitializationPhase): void {
|
||||
const timing = this.phaseTimings.get(phase);
|
||||
if (timing) {
|
||||
timing.end = Date.now();
|
||||
console.log(`⏱️ ${phase} completed in ${timing.end - timing.start}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
private getPhaseTimings(): Record<string, number> {
|
||||
const timings: Record<string, number> = {};
|
||||
|
||||
this.phaseTimings.forEach((timing, phase) => {
|
||||
if (timing.start && timing.end) {
|
||||
timings[phase] = timing.end - timing.start;
|
||||
}
|
||||
});
|
||||
|
||||
return timings;
|
||||
}
|
||||
|
||||
private emitEvent(type: string, component: string, data?: any): void {
|
||||
const event: CalendarEvent = {
|
||||
type,
|
||||
component,
|
||||
timestamp: Date.now(),
|
||||
data,
|
||||
metadata: {
|
||||
phase: this.getCurrentPhase()
|
||||
}
|
||||
};
|
||||
|
||||
eventBus.emit(type, event);
|
||||
}
|
||||
|
||||
private async waitForEvent(eventType: string, timeout: number = 5000): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
reject(new Error(`Timeout waiting for event: ${eventType}`));
|
||||
}, timeout);
|
||||
|
||||
const handler = (event: Event) => {
|
||||
clearTimeout(timer);
|
||||
resolve((event as CustomEvent).detail);
|
||||
eventBus.off(eventType, handler);
|
||||
};
|
||||
|
||||
eventBus.on(eventType, handler);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug methods
|
||||
*/
|
||||
getStateHistory(): Array<{ state: CalendarState; timestamp: number }> {
|
||||
return [...this.stateHistory];
|
||||
}
|
||||
|
||||
getInitializationReport(): any {
|
||||
return {
|
||||
currentState: this.currentState,
|
||||
totalTime: Date.now() - this.initializationStartTime,
|
||||
phaseTimings: this.getPhaseTimings(),
|
||||
stateHistory: this.stateHistory
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -2,14 +2,14 @@
|
|||
|
||||
import { eventBus } from '../core/EventBus';
|
||||
import { EventTypes } from '../constants/EventTypes';
|
||||
import { CalendarEvent, EventData, Period, EventType } from '../types/CalendarTypes';
|
||||
import { CalendarEvent, EventData, Period } from '../types/CalendarTypes';
|
||||
|
||||
/**
|
||||
* Event creation data interface
|
||||
*/
|
||||
interface EventCreateData {
|
||||
title: string;
|
||||
type: EventType;
|
||||
type: string;
|
||||
start: string;
|
||||
end: string;
|
||||
allDay: boolean;
|
||||
|
|
@ -67,7 +67,7 @@ export class DataManager {
|
|||
* Fetch events for a specific period
|
||||
*/
|
||||
async fetchEventsForPeriod(period: Period): Promise<EventData> {
|
||||
const cacheKey = `${period.start}-${period.end}-${period.view}`;
|
||||
const cacheKey = `${period.start}-${period.end}`;
|
||||
|
||||
// Check cache first
|
||||
if (this.cache.has(cacheKey)) {
|
||||
|
|
@ -90,8 +90,7 @@ export class DataManager {
|
|||
// Real API call
|
||||
const params = new URLSearchParams({
|
||||
start: period.start,
|
||||
end: period.end,
|
||||
view: period.view
|
||||
end: period.end
|
||||
});
|
||||
|
||||
const response = await fetch(`${this.baseUrl}?${params}`);
|
||||
|
|
@ -275,8 +274,8 @@ export class DataManager {
|
|||
*/
|
||||
private getMockData(period: Period): EventData {
|
||||
const events: CalendarEvent[] = [];
|
||||
const types: EventType[] = ['meeting', 'meal', 'work', 'milestone'];
|
||||
const titles: Record<EventType, string[]> = {
|
||||
const types: string[] = ['meeting', 'meal', 'work', 'milestone'];
|
||||
const titles: Record<string, string[]> = {
|
||||
meeting: ['Team Standup', 'Client Meeting', 'Project Review', 'Sprint Planning', 'Design Review'],
|
||||
meal: ['Breakfast', 'Lunch', 'Coffee Break', 'Dinner'],
|
||||
work: ['Deep Work Session', 'Code Review', 'Documentation', 'Testing'],
|
||||
|
|
@ -296,7 +295,7 @@ export class DataManager {
|
|||
if (isWeekend) {
|
||||
// Maybe one or two events on weekends
|
||||
if (Math.random() > 0.7) {
|
||||
const type: EventType = 'meal';
|
||||
const type: string = 'meal';
|
||||
const title = titles[type][Math.floor(Math.random() * titles[type].length)];
|
||||
const hour = 12 + Math.floor(Math.random() * 4);
|
||||
|
||||
|
|
@ -358,10 +357,11 @@ export class DataManager {
|
|||
}
|
||||
}
|
||||
|
||||
// Add a multi-day event
|
||||
if (period.view === 'week') {
|
||||
// Add a multi-day event if period spans multiple days
|
||||
const daysDiff = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
|
||||
if (daysDiff > 1) {
|
||||
const midWeek = new Date(startDate);
|
||||
midWeek.setDate(midWeek.getDate() + 2);
|
||||
midWeek.setDate(midWeek.getDate() + Math.min(2, daysDiff - 1));
|
||||
|
||||
events.push({
|
||||
id: `evt-${events.length + 1}`,
|
||||
|
|
@ -379,7 +379,6 @@ export class DataManager {
|
|||
meta: {
|
||||
start: period.start,
|
||||
end: period.end,
|
||||
view: period.view,
|
||||
total: events.length
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { EventBus } from '../core/EventBus';
|
||||
import { IEventBus, CalendarEvent, ResourceCalendarData } from '../types/CalendarTypes';
|
||||
import { EventTypes } from '../constants/EventTypes';
|
||||
import { StateEvents } from '../types/CalendarState';
|
||||
import { calendarConfig } from '../core/CalendarConfig';
|
||||
|
||||
/**
|
||||
|
|
@ -15,33 +16,54 @@ export class EventManager {
|
|||
console.log('EventManager: Constructor called');
|
||||
this.eventBus = eventBus;
|
||||
this.setupEventListeners();
|
||||
console.log('EventManager: About to call loadMockData()');
|
||||
this.loadMockData().then(() => {
|
||||
console.log('EventManager: loadMockData() completed, syncing events');
|
||||
// Data loaded, sync events after loading
|
||||
this.syncEvents();
|
||||
}).catch(error => {
|
||||
console.error('EventManager: loadMockData() failed:', error);
|
||||
});
|
||||
console.log('EventManager: Waiting for CALENDAR_INITIALIZED before loading data');
|
||||
}
|
||||
|
||||
private setupEventListeners(): void {
|
||||
this.eventBus.on(EventTypes.CALENDAR_INITIALIZED, () => {
|
||||
this.syncEvents();
|
||||
// Listen for state-driven data loading request
|
||||
this.eventBus.on(StateEvents.DATA_LOADING_STARTED, (e: Event) => {
|
||||
const detail = (e as CustomEvent).detail;
|
||||
console.log('EventManager: Received DATA_LOADING_STARTED, starting data load');
|
||||
|
||||
this.loadMockData().then(() => {
|
||||
console.log('EventManager: loadMockData() completed, emitting DATA_LOADED');
|
||||
// Emit state-driven data loaded event
|
||||
this.eventBus.emit(StateEvents.DATA_LOADED, {
|
||||
type: StateEvents.DATA_LOADED,
|
||||
component: 'EventManager',
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
eventCount: this.events.length,
|
||||
calendarMode: calendarConfig.getCalendarMode(),
|
||||
period: detail.data?.period || { start: '', end: '' },
|
||||
events: this.events // Include actual events for EventRenderer
|
||||
},
|
||||
metadata: {
|
||||
phase: 'data-loading'
|
||||
}
|
||||
});
|
||||
}).catch(error => {
|
||||
console.error('EventManager: loadMockData() failed:', error);
|
||||
this.eventBus.emit(StateEvents.DATA_FAILED, {
|
||||
type: StateEvents.DATA_FAILED,
|
||||
component: 'EventManager',
|
||||
timestamp: Date.now(),
|
||||
error,
|
||||
metadata: {
|
||||
phase: 'data-loading'
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
this.eventBus.on(EventTypes.DATE_CHANGED, () => {
|
||||
this.syncEvents();
|
||||
});
|
||||
|
||||
this.eventBus.on(EventTypes.VIEW_RENDERED, () => {
|
||||
this.syncEvents();
|
||||
});
|
||||
// Legacy event listeners removed - data is now managed via state-driven events only
|
||||
|
||||
}
|
||||
|
||||
private async loadMockData(): Promise<void> {
|
||||
try {
|
||||
const calendarType = calendarConfig.getCalendarType();
|
||||
const calendarType = calendarConfig.getCalendarMode();
|
||||
let jsonFile: string;
|
||||
|
||||
console.log(`EventManager: Calendar type detected: '${calendarType}'`);
|
||||
|
|
@ -59,43 +81,41 @@ export class EventManager {
|
|||
throw new Error(`Failed to load mock events: ${response.status}`);
|
||||
}
|
||||
|
||||
if (calendarType === 'resource') {
|
||||
const resourceData: ResourceCalendarData = await response.json();
|
||||
// Flatten events from all resources and add resource metadata
|
||||
this.events = resourceData.resources.flatMap(resource =>
|
||||
resource.events.map(event => ({
|
||||
...event,
|
||||
resourceName: resource.name,
|
||||
resourceDisplayName: resource.displayName,
|
||||
resourceEmployeeId: resource.employeeId
|
||||
}))
|
||||
);
|
||||
console.log(`EventManager: Loaded ${this.events.length} events from ${resourceData.resources.length} resources`);
|
||||
|
||||
// Emit resource data for GridManager
|
||||
this.eventBus.emit(EventTypes.RESOURCE_DATA_LOADED, {
|
||||
resourceData: resourceData
|
||||
});
|
||||
} else {
|
||||
this.events = await response.json();
|
||||
console.log(`EventManager: Loaded ${this.events.length} date calendar events`);
|
||||
}
|
||||
const data = await response.json();
|
||||
console.log(`EventManager: Loaded data for ${calendarType} calendar`);
|
||||
|
||||
console.log('EventManager: First event:', this.events[0]);
|
||||
console.log('EventManager: Last event:', this.events[this.events.length - 1]);
|
||||
// Remove legacy double emission - data is sent via StateEvents.DATA_LOADED only
|
||||
|
||||
// Process data for internal use
|
||||
this.processCalendarData(calendarType, data);
|
||||
} catch (error) {
|
||||
console.error('EventManager: Failed to load mock events:', error);
|
||||
this.events = []; // Fallback to empty array
|
||||
}
|
||||
}
|
||||
|
||||
private syncEvents(): void {
|
||||
// Emit events for rendering
|
||||
this.eventBus.emit(EventTypes.EVENTS_LOADED, {
|
||||
events: this.events
|
||||
});
|
||||
private processCalendarData(calendarType: string, data: any): void {
|
||||
if (calendarType === 'resource') {
|
||||
const resourceData = data as ResourceCalendarData;
|
||||
this.events = resourceData.resources.flatMap(resource =>
|
||||
resource.events.map(event => ({
|
||||
...event,
|
||||
resourceName: resource.name,
|
||||
resourceDisplayName: resource.displayName,
|
||||
resourceEmployeeId: resource.employeeId
|
||||
}))
|
||||
);
|
||||
console.log(`EventManager: Processed ${this.events.length} events from ${resourceData.resources.length} resources`);
|
||||
} else {
|
||||
this.events = data as CalendarEvent[];
|
||||
console.log(`EventManager: Processed ${this.events.length} date events`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`EventManager: Synced ${this.events.length} events`);
|
||||
private syncEvents(): void {
|
||||
// Events are now synced via StateEvents.DATA_LOADED during initialization
|
||||
// This method maintained for internal state management only
|
||||
console.log(`EventManager: Internal sync - ${this.events.length} events in memory`);
|
||||
}
|
||||
|
||||
public getEvents(): CalendarEvent[] {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { EventBus } from '../core/EventBus';
|
||||
import { IEventBus, CalendarEvent } from '../types/CalendarTypes';
|
||||
import { EventTypes } from '../constants/EventTypes';
|
||||
import { StateEvents } from '../types/CalendarState';
|
||||
import { calendarConfig } from '../core/CalendarConfig';
|
||||
import { CalendarTypeFactory } from '../factories/CalendarTypeFactory';
|
||||
|
||||
|
|
@ -11,30 +12,36 @@ import { CalendarTypeFactory } from '../factories/CalendarTypeFactory';
|
|||
export class EventRenderer {
|
||||
private eventBus: IEventBus;
|
||||
private pendingEvents: CalendarEvent[] = [];
|
||||
private dataReady: boolean = false;
|
||||
private gridReady: boolean = false;
|
||||
|
||||
constructor(eventBus: IEventBus) {
|
||||
this.eventBus = eventBus;
|
||||
this.setupEventListeners();
|
||||
|
||||
// Initialize the factory (if not already done)
|
||||
CalendarTypeFactory.initialize();
|
||||
}
|
||||
|
||||
private setupEventListeners(): void {
|
||||
this.eventBus.on(EventTypes.EVENTS_LOADED, (event: Event) => {
|
||||
// Listen for state-driven data loaded event
|
||||
this.eventBus.on(StateEvents.DATA_LOADED, (event: Event) => {
|
||||
const customEvent = event as CustomEvent;
|
||||
const { events } = customEvent.detail;
|
||||
console.log('EventRenderer: Received EVENTS_LOADED with', events.length, 'events');
|
||||
// Store events but don't render yet - wait for grid to be ready
|
||||
this.pendingEvents = events;
|
||||
// Events are in customEvent.detail (direct from StateEvent payload)
|
||||
const eventCount = customEvent.detail.data?.eventCount || 0;
|
||||
const events = customEvent.detail.data?.events || [];
|
||||
console.log('EventRenderer: Received DATA_LOADED with', eventCount, 'events');
|
||||
this.pendingEvents = events; // Store the actual events
|
||||
this.dataReady = true;
|
||||
this.tryRenderEvents();
|
||||
});
|
||||
|
||||
this.eventBus.on(EventTypes.GRID_RENDERED, () => {
|
||||
// Grid is ready, now we can render events
|
||||
// Listen for state-driven grid rendered event
|
||||
this.eventBus.on(StateEvents.GRID_RENDERED, (event: Event) => {
|
||||
const customEvent = event as CustomEvent;
|
||||
console.log('EventRenderer: Received GRID_RENDERED');
|
||||
this.gridReady = true;
|
||||
this.tryRenderEvents();
|
||||
});
|
||||
|
||||
|
||||
this.eventBus.on(EventTypes.VIEW_RENDERED, () => {
|
||||
// Clear existing events when view changes
|
||||
this.clearEvents();
|
||||
|
|
@ -48,20 +55,50 @@ export class EventRenderer {
|
|||
}
|
||||
|
||||
private tryRenderEvents(): void {
|
||||
// Only render if we have both events and appropriate columns are ready
|
||||
console.log('EventRenderer: tryRenderEvents called, pending events:', this.pendingEvents.length);
|
||||
// Only render if we have both data and grid ready
|
||||
console.log('EventRenderer: tryRenderEvents called', {
|
||||
dataReady: this.dataReady,
|
||||
gridReady: this.gridReady,
|
||||
pendingEvents: this.pendingEvents.length
|
||||
});
|
||||
|
||||
if (!this.dataReady || !this.gridReady) {
|
||||
console.log('EventRenderer: Waiting - data ready:', this.dataReady, 'grid ready:', this.gridReady);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.pendingEvents.length > 0) {
|
||||
const calendarType = calendarConfig.getCalendarType();
|
||||
const calendarType = calendarConfig.getCalendarMode();
|
||||
let columnsSelector = calendarType === 'resource' ? 'swp-resource-column' : 'swp-day-column';
|
||||
const columns = document.querySelectorAll(columnsSelector);
|
||||
|
||||
console.log(`EventRenderer: Found ${columns.length} ${columnsSelector} elements for ${calendarType} calendar`);
|
||||
|
||||
if (columns.length > 0) {
|
||||
console.log('🎨 EventRenderer: Both data and grid ready, rendering events!');
|
||||
const eventCount = this.pendingEvents.length;
|
||||
this.renderEvents(this.pendingEvents);
|
||||
this.pendingEvents = []; // Clear pending events after rendering
|
||||
|
||||
// Emit events rendered event
|
||||
this.eventBus.emit(StateEvents.EVENTS_RENDERED, {
|
||||
type: StateEvents.EVENTS_RENDERED,
|
||||
component: 'EventRenderer',
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
eventCount,
|
||||
calendarMode: calendarType,
|
||||
renderMethod: 'state-driven'
|
||||
},
|
||||
metadata: {
|
||||
phase: 'event-rendering'
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.log('EventRenderer: Grid not ready yet, columns not found');
|
||||
}
|
||||
} else {
|
||||
console.log('EventRenderer: No pending events to render');
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -69,7 +106,7 @@ export class EventRenderer {
|
|||
console.log('EventRenderer: renderEvents called with', events.length, 'events');
|
||||
|
||||
// Get the appropriate event renderer strategy
|
||||
const calendarType = calendarConfig.getCalendarType();
|
||||
const calendarType = calendarConfig.getCalendarMode();
|
||||
const eventRenderer = CalendarTypeFactory.getEventRenderer(calendarType);
|
||||
|
||||
console.log(`EventRenderer: Using ${calendarType} event renderer strategy`);
|
||||
|
|
@ -84,7 +121,7 @@ export class EventRenderer {
|
|||
}
|
||||
|
||||
private clearEvents(): void {
|
||||
const calendarType = calendarConfig.getCalendarType();
|
||||
const calendarType = calendarConfig.getCalendarMode();
|
||||
const eventRenderer = CalendarTypeFactory.getEventRenderer(calendarType);
|
||||
eventRenderer.clearEvents();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
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';
|
||||
import { ResourceCalendarData } from '../types/CalendarTypes';
|
||||
import { CalendarTypeFactory } from '../factories/CalendarTypeFactory';
|
||||
|
|
@ -29,13 +30,11 @@ export class GridManager {
|
|||
private resourceData: ResourceCalendarData | null = null; // Store resource data for resource calendar
|
||||
|
||||
constructor() {
|
||||
console.log('🏗️ GridManager: Constructor called');
|
||||
this.init();
|
||||
}
|
||||
|
||||
private init(): void {
|
||||
// Initialize the factory
|
||||
CalendarTypeFactory.initialize();
|
||||
|
||||
this.findElements();
|
||||
this.subscribeToEvents();
|
||||
|
||||
|
|
@ -43,8 +42,8 @@ export class GridManager {
|
|||
if (!this.currentWeek) {
|
||||
this.currentWeek = this.getWeekStart(new Date());
|
||||
console.log('GridManager: Set initial currentWeek to', this.currentWeek);
|
||||
// Render initial grid
|
||||
this.render();
|
||||
// Don't render immediately - wait for proper initialization event
|
||||
console.log('GridManager: Waiting for initialization complete before rendering');
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -58,6 +57,13 @@ export class GridManager {
|
|||
}
|
||||
|
||||
private subscribeToEvents(): void {
|
||||
// Listen for state-driven rendering start event
|
||||
eventBus.on(StateEvents.RENDERING_STARTED, (e: Event) => {
|
||||
const detail = (e as CustomEvent).detail;
|
||||
console.log('GridManager: Received RENDERING_STARTED, starting DOM structure setup');
|
||||
this.render();
|
||||
});
|
||||
|
||||
// Re-render grid on config changes
|
||||
eventBus.on(EventTypes.CONFIG_UPDATE, (e: Event) => {
|
||||
const detail = (e as CustomEvent).detail;
|
||||
|
|
@ -96,18 +102,15 @@ export class GridManager {
|
|||
this.updateAllDayEvents(detail.events);
|
||||
});
|
||||
|
||||
// Handle resource data loaded
|
||||
eventBus.on(EventTypes.RESOURCE_DATA_LOADED, (e: Event) => {
|
||||
// Handle data loaded for resource mode
|
||||
eventBus.on(StateEvents.DATA_LOADED, (e: Event) => {
|
||||
const detail = (e as CustomEvent).detail;
|
||||
this.resourceData = detail.resourceData;
|
||||
console.log(`GridManager: Received resource data for ${this.resourceData!.resources.length} resources`);
|
||||
console.log(`GridManager: Received DATA_LOADED`);
|
||||
|
||||
// Update grid styles with new column count immediately
|
||||
this.updateGridStyles();
|
||||
|
||||
// Re-render if grid is already rendered
|
||||
if (this.grid && this.grid.children.length > 0) {
|
||||
this.render();
|
||||
if (detail.data && detail.data.calendarMode === 'resource') {
|
||||
// Resource data will be passed in the state event
|
||||
// For now just update grid styles
|
||||
this.updateGridStyles();
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -124,12 +127,54 @@ export class GridManager {
|
|||
this.updateGridStyles();
|
||||
this.renderGrid();
|
||||
|
||||
// Emit grid rendered event
|
||||
// Emit state-driven grid rendered event
|
||||
const columnCount = this.getColumnCount();
|
||||
console.log('GridManager: Emitting GRID_RENDERED event');
|
||||
eventBus.emit(EventTypes.GRID_RENDERED);
|
||||
|
||||
eventBus.emit(StateEvents.GRID_RENDERED, {
|
||||
type: StateEvents.GRID_RENDERED,
|
||||
component: 'GridManager',
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
columnCount,
|
||||
gridMode: calendarConfig.getCalendarMode(),
|
||||
domElementsCreated: [
|
||||
'swp-header-spacer',
|
||||
'swp-time-axis',
|
||||
'swp-grid-container',
|
||||
'swp-calendar-header',
|
||||
'swp-scrollable-content'
|
||||
]
|
||||
},
|
||||
metadata: {
|
||||
phase: 'rendering'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('GridManager: GRID_RENDERED event emitted');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the complete grid using POC structure
|
||||
*/
|
||||
|
|
@ -148,10 +193,10 @@ export class GridManager {
|
|||
// 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 + week-container + right-column + bottom spacers
|
||||
// Create POC structure: header-spacer + time-axis + grid-container
|
||||
this.createHeaderSpacer();
|
||||
this.createTimeAxis();
|
||||
this.createWeekContainer();
|
||||
this.createGridContainer();
|
||||
} else {
|
||||
console.log('GridManager: Re-render - updating existing structure');
|
||||
// Just update the calendar header for all-day events
|
||||
|
|
@ -172,15 +217,16 @@ export class GridManager {
|
|||
}
|
||||
|
||||
/**
|
||||
* Create time axis (positioned beside week container) like in POC
|
||||
* Create time axis (positioned beside grid container) like in POC
|
||||
*/
|
||||
private createTimeAxis(): void {
|
||||
if (!this.grid) return;
|
||||
|
||||
const timeAxis = document.createElement('swp-time-axis');
|
||||
const timeAxisContent = document.createElement('swp-time-axis-content');
|
||||
const startHour = calendarConfig.get('dayStartHour');
|
||||
const endHour = calendarConfig.get('dayEndHour');
|
||||
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++) {
|
||||
|
|
@ -196,17 +242,17 @@ export class GridManager {
|
|||
}
|
||||
|
||||
/**
|
||||
* Create week container with header and scrollable content using Strategy Pattern
|
||||
* Create grid container with header and scrollable content using Strategy Pattern
|
||||
*/
|
||||
private createWeekContainer(): void {
|
||||
private createGridContainer(): void {
|
||||
if (!this.grid || !this.currentWeek) return;
|
||||
|
||||
const weekContainer = document.createElement('swp-grid-container');
|
||||
const gridContainer = document.createElement('swp-grid-container');
|
||||
|
||||
// Create calendar header using Strategy Pattern
|
||||
const calendarHeader = document.createElement('swp-calendar-header');
|
||||
this.renderCalendarHeader(calendarHeader);
|
||||
weekContainer.appendChild(calendarHeader);
|
||||
gridContainer.appendChild(calendarHeader);
|
||||
|
||||
// Create scrollable content
|
||||
const scrollableContent = document.createElement('swp-scrollable-content');
|
||||
|
|
@ -222,9 +268,9 @@ export class GridManager {
|
|||
timeGrid.appendChild(columnContainer);
|
||||
|
||||
scrollableContent.appendChild(timeGrid);
|
||||
weekContainer.appendChild(scrollableContent);
|
||||
gridContainer.appendChild(scrollableContent);
|
||||
|
||||
this.grid.appendChild(weekContainer);
|
||||
this.grid.appendChild(gridContainer);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -233,7 +279,7 @@ export class GridManager {
|
|||
private renderCalendarHeader(calendarHeader: HTMLElement): void {
|
||||
if (!this.currentWeek) return;
|
||||
|
||||
const calendarType = calendarConfig.getCalendarType();
|
||||
const calendarType = calendarConfig.getCalendarMode();
|
||||
const headerRenderer = CalendarTypeFactory.getHeaderRenderer(calendarType);
|
||||
|
||||
const context: HeaderRenderContext = {
|
||||
|
|
@ -256,7 +302,7 @@ export class GridManager {
|
|||
if (!this.currentWeek) return;
|
||||
|
||||
console.log('GridManager: renderColumnContainer called');
|
||||
const calendarType = calendarConfig.getCalendarType();
|
||||
const calendarType = calendarConfig.getCalendarMode();
|
||||
const columnRenderer = CalendarTypeFactory.getColumnRenderer(calendarType);
|
||||
|
||||
const context: ColumnRenderContext = {
|
||||
|
|
@ -330,30 +376,44 @@ export class GridManager {
|
|||
*/
|
||||
private updateGridStyles(): void {
|
||||
const root = document.documentElement;
|
||||
const config = calendarConfig.getAll();
|
||||
const gridSettings = calendarConfig.getGridSettings();
|
||||
const calendar = document.querySelector('swp-calendar') as HTMLElement;
|
||||
const calendarType = calendarConfig.getCalendarType();
|
||||
const calendarType = calendarConfig.getCalendarMode();
|
||||
|
||||
// Set CSS variables
|
||||
root.style.setProperty('--hour-height', `${config.hourHeight}px`);
|
||||
root.style.setProperty('--minute-height', `${config.hourHeight / 60}px`);
|
||||
root.style.setProperty('--snap-interval', config.snapInterval.toString());
|
||||
root.style.setProperty('--day-start-hour', config.dayStartHour.toString());
|
||||
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());
|
||||
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());
|
||||
|
||||
// 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') {
|
||||
columnCount = config.weekDays;
|
||||
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;
|
||||
}
|
||||
}
|
||||
root.style.setProperty('--grid-columns', columnCount.toString());
|
||||
|
||||
// Set day column min width based on fitToWidth setting
|
||||
if (config.fitToWidth) {
|
||||
if (gridSettings.fitToWidth) {
|
||||
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
|
||||
|
|
@ -361,7 +421,7 @@ export class GridManager {
|
|||
|
||||
// Set fitToWidth data attribute for CSS targeting
|
||||
if (calendar) {
|
||||
calendar.setAttribute('data-fit-to-width', config.fitToWidth.toString());
|
||||
calendar.setAttribute('data-fit-to-width', gridSettings.fitToWidth.toString());
|
||||
}
|
||||
|
||||
console.log('GridManager: Updated grid styles with', columnCount, 'columns for', calendarType, 'calendar');
|
||||
|
|
@ -419,10 +479,11 @@ export class GridManager {
|
|||
const rect = dayColumn.getBoundingClientRect();
|
||||
const y = event.clientY - rect.top;
|
||||
|
||||
const hourHeight = calendarConfig.get('hourHeight');
|
||||
const gridSettings = calendarConfig.getGridSettings();
|
||||
const hourHeight = gridSettings.hourHeight;
|
||||
const minuteHeight = hourHeight / 60;
|
||||
const snapInterval = calendarConfig.get('snapInterval');
|
||||
const dayStartHour = calendarConfig.get('dayStartHour');
|
||||
const snapInterval = gridSettings.snapInterval;
|
||||
const dayStartHour = gridSettings.dayStartHour;
|
||||
|
||||
// Calculate total minutes from day start
|
||||
let totalMinutes = Math.floor(y / minuteHeight);
|
||||
|
|
@ -446,8 +507,9 @@ export class GridManager {
|
|||
scrollToHour(hour: number): void {
|
||||
if (!this.grid) return;
|
||||
|
||||
const hourHeight = calendarConfig.get('hourHeight');
|
||||
const dayStartHour = calendarConfig.get('dayStartHour');
|
||||
const gridSettings = calendarConfig.getGridSettings();
|
||||
const hourHeight = gridSettings.hourHeight;
|
||||
const dayStartHour = gridSettings.dayStartHour;
|
||||
const headerHeight = 80; // Header row height
|
||||
const scrollTop = headerHeight + ((hour - dayStartHour) * hourHeight);
|
||||
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ export class NavigationManager {
|
|||
private animationQueue: number = 0;
|
||||
|
||||
constructor(eventBus: IEventBus) {
|
||||
console.log('🧭 NavigationManager: Constructor called');
|
||||
this.eventBus = eventBus;
|
||||
this.currentWeek = DateUtils.getWeekStart(new Date(), 0); // Sunday start like POC
|
||||
this.targetWeek = new Date(this.currentWeek);
|
||||
|
|
@ -21,10 +22,17 @@ export class NavigationManager {
|
|||
|
||||
private init(): void {
|
||||
this.setupEventListeners();
|
||||
this.updateWeekInfo();
|
||||
// Don't update week info immediately - wait for DOM to be ready
|
||||
console.log('NavigationManager: Waiting for CALENDAR_INITIALIZED before updating DOM');
|
||||
}
|
||||
|
||||
private setupEventListeners(): void {
|
||||
// Initial DOM update when calendar is initialized
|
||||
this.eventBus.on(EventTypes.CALENDAR_INITIALIZED, () => {
|
||||
console.log('NavigationManager: Received CALENDAR_INITIALIZED, updating week info');
|
||||
this.updateWeekInfo();
|
||||
});
|
||||
|
||||
// Listen for navigation button clicks
|
||||
document.addEventListener('click', (e) => {
|
||||
const target = e.target as HTMLElement;
|
||||
|
|
@ -157,10 +165,16 @@ export class NavigationManager {
|
|||
|
||||
if (weekNumberElement) {
|
||||
weekNumberElement.textContent = `Week ${weekNumber}`;
|
||||
console.log('NavigationManager: Updated week number:', `Week ${weekNumber}`);
|
||||
} else {
|
||||
console.warn('NavigationManager: swp-week-number element not found in DOM');
|
||||
}
|
||||
|
||||
if (dateRangeElement) {
|
||||
dateRangeElement.textContent = dateRange;
|
||||
console.log('NavigationManager: Updated date range:', dateRange);
|
||||
} else {
|
||||
console.warn('NavigationManager: swp-date-range element not found in DOM');
|
||||
}
|
||||
|
||||
// Notify other managers about week info update
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
import { eventBus } from '../core/EventBus';
|
||||
import { calendarConfig } from '../core/CalendarConfig';
|
||||
import { EventTypes } from '../constants/EventTypes';
|
||||
import { StateEvents } from '../types/CalendarState';
|
||||
|
||||
/**
|
||||
* Manages scrolling functionality for the calendar using native scrollbars
|
||||
|
|
@ -15,6 +16,7 @@ export class ScrollManager {
|
|||
private resizeObserver: ResizeObserver | null = null;
|
||||
|
||||
constructor() {
|
||||
console.log('📜 ScrollManager: Constructor called');
|
||||
this.init();
|
||||
}
|
||||
|
||||
|
|
@ -24,10 +26,20 @@ export class ScrollManager {
|
|||
|
||||
private subscribeToEvents(): void {
|
||||
// Initialize scroll when grid is rendered
|
||||
eventBus.on(EventTypes.GRID_RENDERED, () => {
|
||||
eventBus.on(StateEvents.GRID_RENDERED, () => {
|
||||
console.log('ScrollManager: Received GRID_RENDERED event');
|
||||
this.setupScrolling();
|
||||
});
|
||||
|
||||
// Add safety check - if grid is already rendered when ScrollManager initializes
|
||||
// This prevents race condition where GridManager renders before ScrollManager subscribes
|
||||
//setTimeout(() => {
|
||||
// const existingGrid = document.querySelector('swp-calendar-container');
|
||||
// if (existingGrid && existingGrid.children.length > 0) {
|
||||
// console.log('ScrollManager: Grid already exists, setting up scrolling');
|
||||
// this.setupScrolling();
|
||||
// }
|
||||
//}, 0);
|
||||
|
||||
// Handle window resize
|
||||
window.addEventListener('resize', () => {
|
||||
|
|
@ -35,8 +47,8 @@ export class ScrollManager {
|
|||
});
|
||||
|
||||
// Handle config updates for scrollbar styling
|
||||
eventBus.on(EventTypes.CONFIG_UPDATE, (event: CustomEvent) => {
|
||||
const { key } = event.detail;
|
||||
eventBus.on(EventTypes.CONFIG_UPDATE, (event: Event) => {
|
||||
const { key } = (event as CustomEvent).detail;
|
||||
if (key.startsWith('scrollbar')) {
|
||||
this.applyScrollbarStyling();
|
||||
}
|
||||
|
|
@ -131,8 +143,9 @@ export class ScrollManager {
|
|||
* Scroll to specific hour
|
||||
*/
|
||||
scrollToHour(hour: number): void {
|
||||
const hourHeight = calendarConfig.get('hourHeight');
|
||||
const dayStartHour = calendarConfig.get('dayStartHour');
|
||||
const gridSettings = calendarConfig.getGridSettings();
|
||||
const hourHeight = gridSettings.hourHeight;
|
||||
const dayStartHour = gridSettings.dayStartHour;
|
||||
const scrollTop = (hour - dayStartHour) * hourHeight;
|
||||
|
||||
this.scrollTo(scrollTop);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue