-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
673 lines (572 loc) · 25.2 KB
/
script.js
File metadata and controls
673 lines (572 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/**
* Main Calendar Application
* Uses modular services for holidays and prompt contract calculations
*/
// Constants
const CALENDAR_YEAR_RANGE = 1; // Years before and after current year to display
const SCROLL_DELAY = 100; // Delay in ms for scroll animations
const BAR_RENDER_DELAY = 10; // Delay in ms for bar rendering after DOM update
const BAR_SPACING = 22; // Vertical spacing between stacked bars in pixels
const BAR_MARGIN = 4; // Margin from cell border for bars in pixels
const ARROW_WIDTH = 10; // Width of arrow elements in pixels
// Global service instances
let holidayService;
let promptContracts;
let selectedDate = null;
let holidays = null;
let currentYear = new Date().getFullYear();
/**
* Initialize services
*/
async function initializeServices() {
// Initialize holiday service
holidayService = new HolidayService();
await holidayService.initialize();
// Initialize prompt contracts calculator
promptContracts = new PromptContracts(holidayService);
}
/**
* Helper function to format date key
*/
function formatDateKey(date) {
if (!promptContracts) {
// Fallback if services not initialized yet
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
return promptContracts.formatDateKey(date);
}
/**
* Helper functions for calendar rendering
*/
function isWeekend(date) {
return promptContracts.isWeekend(date);
}
function isPublicHoliday(date, holidays) {
return promptContracts.isPublicHoliday(date, holidays);
}
function isBusinessDay(date, holidays) {
return promptContracts.isBusinessDay(date, holidays);
}
function getNextBusinessDay(date, holidays) {
return promptContracts.getNextBusinessDay(date, holidays);
}
/**
* ICIS Prompt Contract Calculations (delegate to promptContracts)
*/
function getDayAhead(reportDate, holidays) {
return promptContracts.getDayAhead(reportDate, holidays);
}
function getWeekend(reportDate, holidays) {
return promptContracts.getWeekend(reportDate, holidays);
}
function getWDNW(reportDate, holidays) {
return promptContracts.getWDNW(reportDate, holidays);
}
function getBOM(reportDate, holidays) {
return promptContracts.getBOM(reportDate, holidays);
}
/**
* Convert a date range [startDate, endDate] to an array of all dates in the range (inclusive)
*/
function dateRangeToArray([startDate, endDate]) {
const dates = [];
const current = new Date(startDate);
const end = new Date(endDate);
while (current <= end) {
dates.push(new Date(current));
current.setDate(current.getDate() + 1);
}
return dates;
}
// Theme management
function initTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
updateThemeIcon(savedTheme);
}
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateThemeIcon(newTheme);
}
function updateThemeIcon(theme) {
const themeIcon = document.querySelector('.theme-icon');
if (themeIcon) {
themeIcon.textContent = theme === 'dark' ? '☀️' : '🌙';
}
}
// Modal management
function initModal() {
const modal = document.getElementById('modal');
const aboutLink = document.getElementById('about-link');
const modalClose = document.getElementById('modal-close');
aboutLink.addEventListener('click', (e) => {
e.preventDefault();
modal.classList.add('show');
});
modalClose.addEventListener('click', () => {
modal.classList.remove('show');
});
modal.addEventListener('click', (e) => {
if (e.target === modal) {
modal.classList.remove('show');
}
});
// Close on Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && modal.classList.contains('show')) {
modal.classList.remove('show');
}
});
}
// Calendar generation
let referenceDateInputHandler = null;
async function initializeCalendar() {
// Ensure services are initialized
if (!holidayService || !promptContracts) {
await initializeServices();
}
const now = new Date();
const startYear = currentYear - CALENDAR_YEAR_RANGE;
const endYear = currentYear + CALENDAR_YEAR_RANGE;
holidays = holidayService.getHolidays(startYear, endYear);
// Set initial selected date to today or next business day
// Create a new Date object to avoid mutation issues
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
selectedDate = new Date(today);
if (!isBusinessDay(selectedDate, holidays)) {
selectedDate = getNextBusinessDay(selectedDate, holidays);
}
// Set reference date input - only add event listener once
const referenceDateInput = document.getElementById('reference-date');
referenceDateInput.value = formatDateInput(selectedDate);
// Remove existing listener if it exists to prevent duplicates
if (referenceDateInputHandler) {
referenceDateInput.removeEventListener('change', referenceDateInputHandler);
}
// Create and store the handler
referenceDateInputHandler = (e) => {
const newDate = new Date(e.target.value);
if (!isNaN(newDate.getTime())) {
// Create a new Date object to avoid mutation
let candidateDate = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate());
// If the selected date is not a business day, skip to the next business day
if (!isBusinessDay(candidateDate, holidays)) {
candidateDate = getNextBusinessDay(candidateDate, holidays);
// Update the input field to show the corrected date
e.target.value = formatDateInput(candidateDate);
}
selectedDate = candidateDate;
renderCalendar();
// Scroll to selected date
setTimeout(() => {
scrollToDate(selectedDate);
}, SCROLL_DELAY);
}
};
referenceDateInput.addEventListener('change', referenceDateInputHandler);
// Ensure selectedDate is properly set before rendering
// Use a small delay to ensure DOM is ready and all state is set
setTimeout(() => {
renderCalendar();
// Scroll to selected date on initial load
setTimeout(() => {
scrollToDate(selectedDate);
}, SCROLL_DELAY);
}, 0);
}
function scrollToDate(date) {
const dateKey = formatDateKey(date);
const dayElement = document.querySelector(`[data-date="${dateKey}"]`);
if (dayElement) {
dayElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
function formatDateInput(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function formatDateDisplay(date) {
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return `${date.getDate()} ${months[date.getMonth()]}`;
}
function renderCalendar() {
// Validate that selectedDate and holidays are available
if (!selectedDate || !holidays) {
console.warn('renderCalendar: selectedDate or holidays not available');
return;
}
const calendarGrid = document.getElementById('calendar-grid');
if (!calendarGrid) {
console.warn('renderCalendar: calendar-grid element not found');
return;
}
calendarGrid.innerHTML = '';
// Add day headers (only once at the top)
const dayHeaders = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
dayHeaders.forEach(day => {
const header = document.createElement('div');
header.className = 'day-header';
header.textContent = day;
calendarGrid.appendChild(header);
});
// Calculate date range (last year to next year)
const startYear = currentYear - CALENDAR_YEAR_RANGE;
const endYear = currentYear + CALENDAR_YEAR_RANGE;
const startDate = new Date(startYear, 0, 1);
const endDate = new Date(endYear, 11, 31);
// Find first Monday before or on start date
let currentDate = new Date(startDate);
while (currentDate.getDay() !== 1) {
currentDate.setDate(currentDate.getDate() - 1);
}
// Get all dates in range
const allDates = [];
while (currentDate <= endDate) {
allDates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
// Calculate prompt contracts for selected date
// Ensure we're using a fresh copy of selectedDate to avoid mutation issues
const reportDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate());
const contracts = promptContracts.getAllContracts(reportDate, holidays);
const dayAheadRange = contracts.dayAhead;
const weekendRange = contracts.weekend;
const wdnwRange = contracts.wdnw;
const bomRange = contracts.bom;
// Convert ranges to date arrays
const dayAheadDays = dateRangeToArray(dayAheadRange);
const weekendDays = dateRangeToArray(weekendRange);
const wdnwDays = dateRangeToArray(wdnwRange);
const bomDays = dateRangeToArray(bomRange);
// Create sets for quick lookup
const dayAheadSet = new Set(dayAheadDays.map(d => formatDateKey(d)));
const weekendSet = new Set(weekendDays.map(d => formatDateKey(d)));
const wdnwSet = new Set(wdnwDays.map(d => formatDateKey(d)));
const bomSet = new Set(bomDays.map(d => formatDateKey(d)));
// Render calendar days
allDates.forEach(date => {
const dayElement = document.createElement('div');
dayElement.className = 'calendar-day';
const dateKey = formatDateKey(date);
dayElement.setAttribute('data-date', dateKey);
// Check if date is in current year range (not other month, but might be outside current year)
const isWeekendDay = isWeekend(date);
const isHoliday = isPublicHoliday(date, holidays);
const isActive = formatDateKey(date) === formatDateKey(selectedDate);
// Check if date is a business day (for selection)
const isBusiness = isBusinessDay(date, holidays);
if (!isBusiness) {
dayElement.classList.add('non-business');
}
if (isWeekendDay) {
dayElement.classList.add('weekend');
}
if (isHoliday) {
dayElement.classList.add('public-holiday');
}
if (isActive) {
dayElement.classList.add('active');
}
// Day number with month label for first day of month
const dayNumber = document.createElement('div');
dayNumber.className = 'day-number';
if (date.getDate() === 1) {
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
dayNumber.textContent = `1 ${monthNames[date.getMonth()]} ${date.getFullYear()}`;
} else {
dayNumber.textContent = date.getDate();
}
dayElement.appendChild(dayNumber);
// Day label (for holidays)
if (isHoliday) {
const dayLabel = document.createElement('div');
dayLabel.className = 'day-label';
dayLabel.textContent = holidays.get(dateKey);
dayElement.appendChild(dayLabel);
}
// Store contract info for continuous bar rendering
dayElement.setAttribute('data-da', dayAheadSet.has(dateKey) ? '1' : '0');
dayElement.setAttribute('data-weekend', weekendSet.has(dateKey) ? '1' : '0');
dayElement.setAttribute('data-wdnw', wdnwSet.has(dateKey) ? '1' : '0');
dayElement.setAttribute('data-bom', bomSet.has(dateKey) ? '1' : '0');
// Click handler - only allow selection of business days
if (isBusiness) {
dayElement.addEventListener('click', () => {
// Create a new Date object to avoid mutation
selectedDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
const referenceDateInput = document.getElementById('reference-date');
if (referenceDateInput) {
referenceDateInput.value = formatDateInput(selectedDate);
}
renderCalendar();
// Scroll to selected date
setTimeout(() => {
scrollToDate(selectedDate);
}, SCROLL_DELAY);
});
} else {
dayElement.style.cursor = 'not-allowed';
}
calendarGrid.appendChild(dayElement);
});
// Render continuous bars for prompt contracts
renderContinuousBars(allDates, dayAheadDays, weekendDays, wdnwDays, bomDays);
}
// Helper function to find consecutive date ranges
function findConsecutiveRanges(dates) {
if (dates.length === 0) return [];
const sortedDates = [...dates].sort((a, b) => a - b);
const ranges = [];
let start = sortedDates[0];
let end = sortedDates[0];
for (let i = 1; i < sortedDates.length; i++) {
const current = new Date(sortedDates[i]);
const prev = new Date(sortedDates[i - 1]);
const daysDiff = (current - prev) / (1000 * 60 * 60 * 24);
if (daysDiff === 1) {
end = current;
} else {
ranges.push({ start: new Date(start), end: new Date(end) });
start = current;
end = current;
}
}
ranges.push({ start: new Date(start), end: new Date(end) });
return ranges;
}
function renderContinuousBars(allDates, dayAhead, weekendDays, wdnwDays, bomDays) {
// Wait for DOM to update, then calculate positions
setTimeout(() => {
const calendarGrid = document.getElementById('calendar-grid');
const calendarContainer = calendarGrid.parentElement;
// Remove existing container
const existingContainer = document.getElementById('prompt-bars-container');
if (existingContainer) {
existingContainer.remove();
}
// Create container for continuous bars
const barsContainer = document.createElement('div');
barsContainer.id = 'prompt-bars-container';
barsContainer.className = 'prompt-bars-container';
calendarContainer.appendChild(barsContainer);
// Calculate grid cell dimensions
const firstDay = document.querySelector('.calendar-day');
if (!firstDay) return;
const header = document.querySelector('.day-header');
const headerHeight = header ? header.offsetHeight : 0;
const cellWidth = firstDay.offsetWidth;
const cellHeight = firstDay.offsetHeight;
const gridGap = 1; // gap between cells
// Create date to index mapping
const dateToIndex = new Map();
allDates.forEach((date, index) => {
dateToIndex.set(formatDateKey(date), index);
});
// Collect all bar segments with their types and lengths
const allBars = [];
// DA bar (single day)
if (dayAhead.length > 0) {
const daIndex = dateToIndex.get(formatDateKey(dayAhead[0]));
if (daIndex !== undefined) {
allBars.push({ type: 'da', label: 'DA', startIndex: daIndex, endIndex: daIndex, length: 1 });
}
}
// Weekend bars
const weekendRanges = findConsecutiveRanges(weekendDays);
weekendRanges.forEach((range) => {
const startKey = formatDateKey(range.start);
const endKey = formatDateKey(range.end);
const startIndex = dateToIndex.get(startKey);
const endIndex = dateToIndex.get(endKey);
if (startIndex !== undefined && endIndex !== undefined) {
allBars.push({ type: 'weekend', label: 'WKND', startIndex, endIndex, length: endIndex - startIndex + 1 });
}
});
// WDNW bars
const wdnwRanges = findConsecutiveRanges(wdnwDays);
wdnwRanges.forEach((range) => {
const startKey = formatDateKey(range.start);
const endKey = formatDateKey(range.end);
const startIndex = dateToIndex.get(startKey);
const endIndex = dateToIndex.get(endKey);
if (startIndex !== undefined && endIndex !== undefined) {
allBars.push({ type: 'wdnw', label: 'WDNW', startIndex, endIndex, length: endIndex - startIndex + 1 });
}
});
// BOM bars
const bomRanges = findConsecutiveRanges(bomDays);
bomRanges.forEach((range) => {
const startKey = formatDateKey(range.start);
const endKey = formatDateKey(range.end);
const startIndex = dateToIndex.get(startKey);
const endIndex = dateToIndex.get(endKey);
if (startIndex !== undefined && endIndex !== undefined) {
allBars.push({ type: 'bom', label: 'BOM', startIndex, endIndex, length: endIndex - startIndex + 1 });
}
});
// Sort bars by length (longest first) for stacking - longer bars go on bottom
allBars.sort((a, b) => b.length - a.length);
// Group bars by overlapping dates to determine stacking levels
const barLevels = assignBarLevels(allBars);
// Render bars with proper stacking
// Longer bars (lower indices) go on bottom, shorter bars (higher indices) go on top
allBars.forEach((bar, idx) => {
const level = barLevels.get(idx);
const startCol = bar.startIndex % 7;
const startRow = Math.floor(bar.startIndex / 7) + 1;
const endCol = bar.endIndex % 7;
const endRow = Math.floor(bar.endIndex / 7) + 1;
// Show label on all bars - when overlapping, shorter bars (higher level) are on top
// Always show label unless there's a longer bar overlapping at the same level
const overlappingLongerBar = allBars.find((otherBar, otherIdx) =>
otherIdx < idx && // Longer bars come first (sorted by length)
barLevels.get(otherIdx) === level &&
!(bar.endIndex < otherBar.startIndex || bar.startIndex > otherBar.endIndex)
);
const showLabel = !overlappingLongerBar || level > 0;
// Check if bar spans multiple weeks
if (startRow !== endRow) {
// Multi-week bar - create segments with arrows
createMultiWeekBar(bar, startCol, startRow, endCol, endRow, cellWidth, cellHeight, gridGap, headerHeight, level, barsContainer, allDates, showLabel);
} else {
// Single week bar
const span = bar.endIndex - bar.startIndex + 1;
const barElement = createContinuousBar(bar.type, showLabel ? bar.label : '', startCol, startRow, span, cellWidth, cellHeight, gridGap, headerHeight, level);
barsContainer.appendChild(barElement);
}
});
}, BAR_RENDER_DELAY);
}
function assignBarLevels(bars) {
const levels = new Map();
const occupiedRanges = [];
// Sort by start index for proper level assignment
const sortedBars = bars.map((bar, idx) => ({ bar, idx })).sort((a, b) => a.bar.startIndex - b.bar.startIndex);
sortedBars.forEach(({ bar, idx }) => {
let level = 0;
// Find the lowest level that doesn't overlap with existing bars on that level
for (let l = 0; l < 10; l++) {
const hasOverlap = occupiedRanges.some(range =>
range.level === l &&
!(bar.endIndex < range.startIndex || bar.startIndex > range.endIndex)
);
if (!hasOverlap) {
level = l;
break;
}
}
levels.set(idx, level);
occupiedRanges.push({ startIndex: bar.startIndex, endIndex: bar.endIndex, level });
});
return levels;
}
function createMultiWeekBar(bar, startCol, startRow, endCol, endRow, cellWidth, cellHeight, gridGap, headerHeight, level, container, allDates, showLabel = true) {
const margin = BAR_MARGIN;
const barSpacing = BAR_SPACING;
// Calculate positions
const baseTop = headerHeight + (startRow - 1) * (cellHeight + gridGap) + cellHeight - 28;
const top = baseTop - (level * barSpacing);
// First week segment (from start to end of week)
const firstWeekEndCol = 6; // Sunday
const firstWeekLeft = startCol * (cellWidth + gridGap) + margin;
const firstWeekWidth = (firstWeekEndCol - startCol + 1) * (cellWidth + gridGap) - gridGap - (margin * 2);
const firstSegment = document.createElement('div');
firstSegment.className = `continuous-bar ${bar.type} bar-segment arrow-end`;
if (showLabel) {
firstSegment.textContent = bar.label;
}
firstSegment.style.left = `${firstWeekLeft}px`;
firstSegment.style.top = `${top}px`;
firstSegment.style.width = `${firstWeekWidth}px`;
// Left side rounded, right side has arrow (beveled via CSS corner properties)
// Only set border-radius on left side to avoid overriding arrow styling
firstSegment.style.borderTopLeftRadius = '4px';
firstSegment.style.borderBottomLeftRadius = '4px';
container.appendChild(firstSegment);
// Middle weeks (if any) - show label on each week
for (let row = startRow + 1; row < endRow; row++) {
const weekLeft = 0;
const weekWidth = 7 * (cellWidth + gridGap) - gridGap;
const weekTop = headerHeight + (row - 1) * (cellHeight + gridGap) + cellHeight - 28 - (level * barSpacing);
// Full week segment with label - has arrows on both ends (continues from previous and to next week)
const weekSegment = document.createElement('div');
weekSegment.className = `continuous-bar ${bar.type} bar-segment arrow-both`;
if (showLabel) {
weekSegment.textContent = bar.label;
}
weekSegment.style.left = `${margin}px`;
weekSegment.style.top = `${weekTop}px`;
weekSegment.style.width = `${weekWidth - (margin * 2)}px`;
container.appendChild(weekSegment);
}
// Last week segment (from start of week to end)
if (endRow > startRow) {
const lastWeekLeft = 0;
const lastWeekFullWidth = (endCol + 1) * (cellWidth + gridGap) - gridGap - margin;
const lastWeekTop = headerHeight + (endRow - 1) * (cellHeight + gridGap) + cellHeight - 28 - (level * barSpacing);
// Last segment with label - has arrow on left (where it continues from), rounded on right
const lastSegment = document.createElement('div');
lastSegment.className = `continuous-bar ${bar.type} bar-segment arrow-start`;
if (showLabel) {
lastSegment.textContent = bar.label;
}
lastSegment.style.left = `${margin}px`;
lastSegment.style.top = `${lastWeekTop}px`;
lastSegment.style.width = `${lastWeekFullWidth - margin}px`;
// Left side has arrow (beveled via CSS corner properties), right side rounded
// Only set border-radius on right side to avoid overriding arrow styling
lastSegment.style.borderTopRightRadius = '4px';
lastSegment.style.borderBottomRightRadius = '4px';
container.appendChild(lastSegment);
}
}
function createContinuousBar(type, label, startCol, startRow, span, cellWidth, cellHeight, gridGap, headerHeight, level = 0) {
const bar = document.createElement('div');
bar.className = `continuous-bar ${type}`;
if (label) {
bar.textContent = label;
}
const margin = BAR_MARGIN;
const barSpacing = BAR_SPACING;
// Calculate position and width
const left = startCol * (cellWidth + gridGap) + margin;
const top = headerHeight + (startRow - 1) * (cellHeight + gridGap) + cellHeight - 28 - (level * barSpacing);
const width = span * (cellWidth + gridGap) - gridGap - (margin * 2);
bar.style.left = `${left}px`;
bar.style.top = `${top}px`;
bar.style.width = `${width}px`;
return bar;
}
// Initialize on load
document.addEventListener('DOMContentLoaded', async () => {
// Initialize theme
initTheme();
// Initialize services first
await initializeServices();
// Theme toggle
const themeToggle = document.getElementById('theme-toggle');
if (themeToggle) {
themeToggle.addEventListener('click', toggleTheme);
}
// Initialize modal
initModal();
// Initialize calendar
await initializeCalendar();
// Update year range annually
setInterval(async () => {
const newYear = new Date().getFullYear();
if (newYear !== currentYear) {
currentYear = newYear;
await initializeCalendar();
}
}, 86400000); // Check daily
});