-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2042 lines (1737 loc) · 77.2 KB
/
script.js
File metadata and controls
2042 lines (1737 loc) · 77.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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Presentation Timer Application
// ============================
// This application displays a presentation timer that shows:
// - Current time
// - Current section name
// - Time remaining in current section
// - Timeline of all sections with color-coded status indicators
// - Buttons to adjust section times (+/-)
// Global Variables
// ----------------
// presentationData: Stores the parsed YAML data
let presentationData = null;
// Track previous section for change detection
let previousSectionName = null;
// Wake lock reference
let wakeLock = null;
// Key for storing presentation data in localStorage
const STORAGE_KEY = 'presentationTimerConfig';
/**
* Parses a time string in HH:MM:SS format to a Date object
* Handles day rollover when times cross midnight
* @param {string} timeString - Time string in format "HH:MM:SS"
* @param {Date} [referenceDate] - Reference date to compare against for day rollover detection
* @returns {Date} - Date object with today's date and the specified time
*/
function parseTime(timeString, referenceDate = null) {
try {
if (typeof timeString !== 'string') {
throw new Error('Time string must be a string');
}
const timeParts = timeString.split(':');
if (timeParts.length !== 3) {
throw new Error('Time format must be HH:MM:SS');
}
const hours = parseInt(timeParts[0], 10);
const minutes = parseInt(timeParts[1], 10);
const seconds = parseInt(timeParts[2], 10);
if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
throw new Error('Invalid time components');
}
if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59 || seconds < 0 || seconds > 59) {
throw new Error('Time components out of range');
}
// Create date object with today's date and specified time
const now = new Date();
const date = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes, seconds);
// If we have a reference date, check if we need to add a day
if (referenceDate && referenceDate instanceof Date) {
// If this time appears to be earlier than the reference time,
// it likely means we've crossed midnight and should be the next day
if (date.getTime() < referenceDate.getTime()) {
date.setDate(date.getDate() + 1);
}
}
return date;
} catch (error) {
console.error('Error parsing time:', error);
throw error;
}
}
/**
* Formats a Date object as HH:MM:SS string (24-hour format for internal use)
* @param {Date} date - Date object to format
* @returns {string} - Time string in format "HH:MM:SS"
*/
function formatTime(date) {
try {
if (!(date instanceof Date)) {
throw new Error('Invalid date object');
}
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
} catch (error) {
console.error('Error formatting time:', error);
throw error;
}
}
/**
* Formats a Date object as HH:MM:SS AM/PM string for display
* @param {Date} date - Date object to format
* @returns {string} - Time string in format "HH:MM:SS AM/PM"
*/
function formatTimeDisplay(date) {
return date.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: true
});
}
/**
* Determines the status of a section based on current time
* @param {Date} currentTime - Current time
* @param {Date} startTime - Section start time
* @param {Date} endTime - Section end time
* @returns {string} - Status color ('red', 'yellow', or 'green')
*/
function getTimeStatus(currentTime, startTime, endTime) {
const now = currentTime.getTime();
const end = endTime.getTime();
const fiveMinutesBefore = end - (5 * 60 * 1000);
if (now > end) {
return 'red';
} else if (now >= fiveMinutesBefore) {
return 'yellow';
} else {
return 'green';
}
}
/**
* Formats a duration in MM:SS format
* @param {number} duration - Duration in milliseconds
* @returns {string} - Duration string in format "MM:SS"
*/
function formatDuration(duration) {
const minutes = Math.floor(duration / 60000);
const seconds = Math.floor((duration % 60000) / 1000);
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
/**
* Parses YAML text into presentation data object with validation
* @param {string} yamlText - Raw YAML text to parse
* @returns {Object} - Parsed and validated presentation data
* @throws {Error} If the YAML data is invalid or missing required fields
*/
function parseYAMLData(yamlText) {
// Parse YAML using our simple parser
const lines = yamlText.split('\n');
const data = { title: "", sections: [] };
let inSections = false;
// Parse the YAML content
lines.forEach((line, index) => {
const originalLine = line;
line = line.trim();
console.log(`Line ${index}: "${originalLine}" -> "${line}"`);
if (line === '' || line.startsWith('#')) return;
if (line.startsWith('title:')) {
data.title = line.substring(6).trim().replace(/['"]+/g, '');
console.log('Parsed title:', data.title);
} else if (line.startsWith('start_time:')) {
data.start_time = line.substring(11).trim().replace(/['"]+/g, '');
console.log('Parsed start time:', data.start_time);
} else if (line === 'sections:') {
inSections = true;
console.log('Found sections');
} else if (inSections && line.startsWith('- name:')) {
const name = line.substring(7).trim().replace(/['"]+/g, '');
const section = { name: name };
data.sections.push(section);
console.log('Added section:', name);
} else if (inSections && data.sections.length > 0) {
const lastSection = data.sections[data.sections.length - 1];
if (line.startsWith('duration:')) {
const duration = parseInt(line.substring(9).trim());
lastSection.duration = duration;
console.log(`Set duration for ${lastSection.name}:`, duration, 'minutes');
}
}
});
console.log('Parsed YAML data:', data);
// Set default values if missing
if (!data.title) {
console.log('No title found in YAML, using default');
data.title = 'Presentation Timer';
}
if (!data.start_time) {
console.log('No start_time found in YAML, using current time');
const now = new Date();
data.start_time = formatTime(now);
}
if (data.sections.length === 0) {
throw new Error('No sections found in YAML file');
}
// Validate sections and calculate times
let currentTime = parseTime(data.start_time);
data.sections.forEach((section, index) => {
if (!section.name) {
throw new Error(`Section ${index} missing name`);
}
if (typeof section.duration === 'undefined') {
throw new Error(`Section "${section.name}" missing duration`);
}
// Set start time
section.start = formatTime(currentTime);
// Calculate end time by adding duration in minutes
const endTime = parseTime(formatTime(currentTime), currentTime);
endTime.setMinutes(endTime.getMinutes() + section.duration);
section.end = formatTime(endTime);
console.log(`Calculated times for ${section.name}: ${section.start} - ${section.end} (${section.duration} min)`);
// Move current time to end of this section for next section's start
currentTime = endTime;
});
return data;
}
/**
* Loads presentation data from YAML file or returns default data if not available
* @returns {Promise<Object>} - Parsed and validated presentation data or default data
*/
async function loadPresentationData() {
try {
console.log('Loading YAML file...');
const response = await fetch('presentation_times.yaml');
if (!response.ok) {
if (response.status === 404) {
console.log('YAML file not found, using default data');
return {
title: 'Presentation Timer',
start_time: formatTime(new Date()),
sections: []
};
}
throw new Error(`HTTP error! status: ${response.status}`);
}
const text = await response.text();
console.log('YAML content loaded');
// Parse and validate the YAML data
return parseYAMLData(text);
} catch (error) {
console.error('Error loading YAML file:', error);
if (error.message.includes('Failed to fetch')) {
console.log('Using default data due to fetch error');
return {
title: 'Presentation Timer',
start_time: formatTime(new Date()),
sections: []
};
}
throw new Error(`Failed to load presentation data: ${error.message}`);
}
}
/**
* Recalculates section times based on a new start time
* @param {string} newStartTime - New start time in HH:MM:SS format
*/
function recalculateTimesFromStart(newStartTime) {
if (!presentationData || !presentationData.sections) {
console.error('No presentation data available for recalculation');
return;
}
try {
console.log('Recalculating times from new start time:', newStartTime);
// Update the start time
presentationData.start_time = newStartTime;
// Recalculate all section times
let currentTime = parseTime(newStartTime);
presentationData.sections.forEach((section) => {
// Set start time
section.start = formatTime(currentTime);
// Calculate end time by adding duration in minutes
const endTime = parseTime(formatTime(currentTime), currentTime);
endTime.setMinutes(endTime.getMinutes() + section.duration);
section.end = formatTime(endTime);
// Move current time to end of this section for next section's start
currentTime = endTime;
});
console.log('All section times recalculated successfully');
// Force update the timeline display immediately
updateTimelineDisplay();
} catch (error) {
console.error('Error recalculating times:', error);
}
}
/**
* Updates just the timeline display (extracted for reuse)
*/
function updateTimelineDisplay() {
try {
const currentTime = new Date();
const timeline = document.getElementById('timeline');
const nextSectionElement = document.getElementById('next-section');
if (!presentationData) return;
// Get current section to highlight it
const currentSection = getCurrentSection(currentTime);
const currentSectionName = currentSection ? currentSection.name : null;
const currentSectionIndex = currentSection ? presentationData.sections.findIndex(s => s.name === currentSectionName) : -1;
// Update next section display for landscape mode
if (nextSectionElement) {
let nextSection = null;
if (currentSectionIndex !== -1 && currentSectionIndex < presentationData.sections.length - 1) {
// Get the next section after current one
nextSection = presentationData.sections[currentSectionIndex + 1];
} else if (currentSectionIndex === -1 && presentationData.sections.length > 0) {
// If no current section or before presentation starts, show first section
nextSection = presentationData.sections[0];
}
if (nextSection) {
nextSectionElement.textContent = `${nextSection.name} (${nextSection.duration}m)`;
} else {
nextSectionElement.textContent = "End of presentation";
}
}
// Check if we need to update the timeline at all
const existingItems = timeline.querySelectorAll('.timeline-item');
const needsFullRebuild = existingItems.length !== presentationData.sections.length;
// Track which input has focus (if any)
const focusedInput = document.activeElement;
let focusedIndex = -1;
let focusedValue = '';
if (focusedInput && focusedInput.classList.contains('duration-input')) {
focusedIndex = parseInt(focusedInput.closest('.timeline-item').id.replace('section-', ''));
focusedValue = focusedInput.value;
}
// Only rebuild if necessary
if (needsFullRebuild) {
timeline.innerHTML = '';
presentationData.sections.forEach((section, index) => {
createTimelineItem(section, index, currentSectionIndex, currentTime);
});
} else {
// Just update the existing items
presentationData.sections.forEach((section, index) => {
updateTimelineItem(section, index, currentSectionIndex, currentTime, timeline);
});
}
// Restore focus if needed
if (focusedIndex >= 0 && focusedIndex < presentationData.sections.length) {
const input = document.querySelector(`#section-${focusedIndex} .duration-input`);
if (input) {
input.focus();
if (input.value !== focusedValue) {
input.value = focusedValue;
}
}
}
// Auto-scroll to current section if it changed
if (currentSectionName !== previousSectionName) {
console.log('Section changed from', previousSectionName, 'to', currentSectionName);
scrollToCurrentSection(currentSectionIndex);
previousSectionName = currentSectionName;
}
} catch (error) {
console.error('Error updating timeline display:', error);
}
}
/**
* Creates a new timeline item
*/
function createTimelineItem(section, index, currentSectionIndex, currentTime) {
try {
const timeline = document.getElementById('timeline');
if (!timeline) return;
// Use the presentation start time as reference for day rollover detection
const presentationStartTime = parseTime(presentationData.start_time);
const startTime = parseTime(section.start, presentationStartTime);
const endTime = parseTime(section.end, startTime);
const status = getTimeStatus(currentTime, startTime, endTime);
const item = document.createElement('div');
item.className = 'timeline-item';
item.id = `section-${index}`;
// Highlight current section using index for unique identification
if (index === currentSectionIndex) {
item.classList.add('current-section');
}
// Section name (left column)
const sectionName = document.createElement('div');
sectionName.className = 'section-name';
// For responsive design, include duration in parentheses on small screens
const isResponsiveMode = window.matchMedia('(max-width: 768px), (max-height: 600px) and (orientation: landscape)').matches;
sectionName.textContent = isResponsiveMode ?
`${section.name} (${section.duration}m)` :
section.name;
// Duration input (middle column)
const durationContainer = document.createElement('div');
durationContainer.className = 'duration-container';
const durationInput = document.createElement('input');
durationInput.type = 'number';
durationInput.className = 'duration-input';
durationInput.value = section.duration;
durationInput.min = '1';
durationInput.max = '999';
durationInput.dataset.index = index;
durationInput.addEventListener('change', (event) => {
updateSectionDuration(parseInt(event.target.dataset.index), parseInt(event.target.value));
});
const durationLabel = document.createElement('span');
durationLabel.className = 'duration-label';
durationLabel.textContent = ' min';
durationContainer.appendChild(durationInput);
durationContainer.appendChild(durationLabel);
// Time range (right column)
const timeBox = document.createElement('div');
timeBox.className = `time-box ${status}`;
timeBox.textContent = `${formatTimeDisplay(startTime)} - ${formatTimeDisplay(endTime)}`;
// Add all three columns to the item
item.appendChild(sectionName);
item.appendChild(durationContainer);
item.appendChild(timeBox);
timeline.appendChild(item);
} catch (error) {
console.error('Error creating timeline item:', error);
}
}
/**
* Updates an existing timeline item
*/
function updateTimelineItem(section, index, currentSectionIndex, currentTime, timeline) {
try {
const item = document.getElementById(`section-${index}`);
if (!item) {
createTimelineItem(section, index, currentSectionName, currentTime);
return;
}
// Update current section highlighting using index for unique identification
if (index === currentSectionIndex) {
item.classList.add('current-section');
} else {
item.classList.remove('current-section');
}
// Only update the time box if needed (skip the input to preserve focus)
const timeBox = item.querySelector('.time-box');
if (timeBox) {
const presentationStartTime = parseTime(presentationData.start_time);
const startTime = parseTime(section.start, presentationStartTime);
const endTime = parseTime(section.end, startTime);
const status = getTimeStatus(currentTime, startTime, endTime);
timeBox.className = `time-box ${status}`;
timeBox.textContent = `${formatTimeDisplay(startTime)} - ${formatTimeDisplay(endTime)}`;
}
} catch (error) {
console.error('Error updating timeline item:', error);
}
}
/**
* Updates a specific section's duration and recalculates all times
* @param {number} sectionIndex - Index of the section to update
* @param {number} newDuration - New duration in minutes
*/
function updateSectionDuration(sectionIndex, newDuration) {
if (!presentationData || !presentationData.sections) {
console.error('No presentation data available');
return;
}
if (sectionIndex < 0 || sectionIndex >= presentationData.sections.length) {
console.error('Invalid section index:', sectionIndex);
return;
}
if (!newDuration || newDuration < 1) {
console.error('Invalid duration:', newDuration);
return;
}
try {
console.log(`Updating ${presentationData.sections[sectionIndex].name} duration from ${presentationData.sections[sectionIndex].duration} to ${newDuration} minutes`);
// Update the section duration
presentationData.sections[sectionIndex].duration = newDuration;
// Recalculate all times from the start
recalculateTimesFromStart(presentationData.start_time);
// Update display
updateDisplay();
console.log('Section duration updated successfully');
} catch (error) {
console.error('Error updating section duration:', error);
}
}
/**
* Updates the display with current time, section status, and timeline
*/
function updateDisplay() {
try {
if (!presentationData) {
console.error('No presentation data available');
return;
}
const currentTime = new Date();
// Update current time display
const currentTimeElement = document.getElementById('current-time');
if (currentTimeElement) {
currentTimeElement.textContent = formatTimeDisplay(currentTime);
}
// Check if we have any sections
if (!presentationData.sections || presentationData.sections.length === 0) {
const currentSectionNameElement = document.getElementById('current-section-name');
const timeRemainingElement = document.getElementById('time-remaining');
if (currentSectionNameElement) {
currentSectionNameElement.textContent = 'No presentation data loaded';
currentSectionNameElement.className = '';
}
if (timeRemainingElement) {
timeRemainingElement.textContent = '00:00';
// Don't modify classes if we're in narrow screen mode
if (!isNarrowScreen() || isLandscapeSmallScreen()) {
timeRemainingElement.className = '';
}
}
// Clear the timeline
const timeline = document.getElementById('timeline');
if (timeline) {
timeline.innerHTML = `
<div class="no-sections">
<p>No timer configuration found. Please import a configuration file using the "Import Settings" button. </p>
<p>Or <a href="sample-config.yaml" download="presentation-timer-config.yaml" class="download-link">download a sample configuration file</a> to get started.</p>
</div>`;
}
return;
}
const currentSection = getCurrentSection(currentTime);
// Update current section name and timer
const currentSectionNameElement = document.getElementById('current-section-name');
const currentSectionDurationElement = document.getElementById('current-section-duration');
const timeRemainingElement = document.getElementById('time-remaining');
// Check if presentation hasn't started yet
const presentationStartTime = parseTime(presentationData.start_time);
const currentTimeMs = currentTime.getTime();
const startTimeMs = presentationStartTime.getTime();
if (currentTimeMs < startTimeMs) {
// Before presentation starts - show countdown to start
if (currentSectionNameElement) {
currentSectionNameElement.textContent = 'Time Until Start';
currentSectionNameElement.className = 'time-until-start';
}
if (currentSectionDurationElement) {
currentSectionDurationElement.textContent = '';
}
if (timeRemainingElement) {
const timeUntilStart = startTimeMs - currentTimeMs;
timeRemainingElement.textContent = formatDuration(timeUntilStart);
// Don't modify classes if we're in narrow screen mode
if (!isNarrowScreen() || isLandscapeSmallScreen()) {
timeRemainingElement.className = 'time-remaining blue';
} else {
// Just add the color class without changing other classes
timeRemainingElement.classList.add('blue');
}
}
} else if (currentSection) {
// During presentation - show current section
if (currentSectionNameElement) {
currentSectionNameElement.textContent = currentSection.name;
currentSectionNameElement.className = ''; // Remove any previous classes
}
if (currentSectionDurationElement) {
// Find the current section in our data to get its duration
const sectionData = presentationData.sections.find(section => section.name === currentSection.name);
if (sectionData) {
currentSectionDurationElement.textContent = `${sectionData.duration} min`;
} else {
currentSectionDurationElement.textContent = '';
}
}
if (timeRemainingElement) {
const timeRemaining = currentSection.end - currentTime.getTime();
timeRemainingElement.textContent = formatDuration(timeRemaining);
// Add color class based on time remaining
if (!isNarrowScreen() || isLandscapeSmallScreen()) {
// Only replace class in non-narrow screen mode
timeRemainingElement.className = 'time-remaining';
} else {
// In narrow screen mode, just make sure we have the necessary classes
if (!timeRemainingElement.classList.contains('portrait-mode')) {
timeRemainingElement.classList.add('portrait-mode');
}
if (!timeRemainingElement.classList.contains('narrow-screen')) {
timeRemainingElement.classList.add('narrow-screen');
}
}
// Remove any existing color classes
timeRemainingElement.classList.remove('red', 'yellow', 'green', 'blue');
// Add the appropriate color class
if (timeRemaining <= 0) {
timeRemainingElement.classList.add('red');
} else if (timeRemaining <= 1 * 60 * 1000) { // 1 minute or less
timeRemainingElement.classList.add('red');
} else if (timeRemaining <= 5 * 60 * 1000) { // 5 minutes or less
timeRemainingElement.classList.add('yellow');
} else {
timeRemainingElement.classList.add('green');
}
}
} else {
// Presentation is complete - show elapsed time since end
if (currentSectionNameElement) {
currentSectionNameElement.textContent = 'Presentation Complete';
currentSectionNameElement.className = 'presentation-complete'; // Add red styling
}
if (currentSectionDurationElement) {
currentSectionDurationElement.textContent = '';
}
if (timeRemainingElement) {
// Find the end time of the last section
const lastSection = presentationData.sections[presentationData.sections.length - 1];
const presentationStartTime = parseTime(presentationData.start_time);
const lastStartTime = parseTime(lastSection.start, presentationStartTime);
const lastEndTime = parseTime(lastSection.end, lastStartTime);
const elapsedTime = currentTime.getTime() - lastEndTime.getTime();
if (elapsedTime > 0) {
// Show elapsed time as positive count-up
timeRemainingElement.textContent = '+' + formatDuration(elapsedTime);
if (!isNarrowScreen() || isLandscapeSmallScreen()) {
// Only replace class in non-narrow screen mode
timeRemainingElement.className = 'time-remaining red';
} else {
// In narrow screen mode, preserve existing classes and just add/remove color classes
if (!timeRemainingElement.classList.contains('portrait-mode')) {
timeRemainingElement.classList.add('portrait-mode');
}
if (!timeRemainingElement.classList.contains('narrow-screen')) {
timeRemainingElement.classList.add('narrow-screen');
}
// Remove existing color classes and add red
timeRemainingElement.classList.remove('green', 'yellow', 'blue');
timeRemainingElement.classList.add('red');
}
} else {
// If somehow we're before the last section ends, show empty
timeRemainingElement.textContent = '';
if (!isNarrowScreen() || isLandscapeSmallScreen()) {
// Only replace class in non-narrow screen mode
timeRemainingElement.className = 'time-remaining';
} else {
// In narrow screen mode, preserve existing classes
if (!timeRemainingElement.classList.contains('portrait-mode')) {
timeRemainingElement.classList.add('portrait-mode');
}
if (!timeRemainingElement.classList.contains('narrow-screen')) {
timeRemainingElement.classList.add('narrow-screen');
}
// Remove any color classes
timeRemainingElement.classList.remove('red', 'green', 'yellow', 'blue');
}
}
}
}
updateTimelineDisplay();
updateNextSectionDisplay();
} catch (error) {
console.error('Error updating display:', error);
throw error;
}
}
/**
* Update just the next section display
*/
function updateNextSectionDisplay() {
try {
if (!presentationData) return;
const currentTime = new Date();
const nextSectionElement = document.getElementById('next-section');
if (!nextSectionElement) return;
const currentSection = getCurrentSection(currentTime);
const currentSectionName = currentSection ? currentSection.name : null;
const currentSectionIndex = currentSection ?
presentationData.sections.findIndex(s => s.name === currentSectionName) : -1;
let nextSection = null;
if (currentSectionIndex !== -1 && currentSectionIndex < presentationData.sections.length - 1) {
// Get the next section after current one
nextSection = presentationData.sections[currentSectionIndex + 1];
} else if (currentSectionIndex === -1 && presentationData.sections.length > 0) {
// If no current section or before presentation starts, show first section
nextSection = presentationData.sections[0];
}
if (nextSection) {
nextSectionElement.textContent = `${nextSection.name} (${nextSection.duration}m)`;
} else {
nextSectionElement.textContent = "End of presentation";
}
} catch (error) {
console.error('Error updating next section display:', error);
}
}
/**
* Gets the current section based on the given time
* @param {Date} time - Current time
* @returns {Object|null} - Current section object with index or null if not found
*/
function getCurrentSection(time) {
try {
if (!presentationData || !presentationData.sections) {
console.error('No presentation data or sections available');
return null;
}
const currentTime = time.getTime();
let currentSection = null;
presentationData.sections.some((section, index) => {
try {
// Use the presentation start time as reference for day rollover detection
const presentationStartTime = parseTime(presentationData.start_time);
const startTime = parseTime(section.start, presentationStartTime);
const endTime = parseTime(section.end, startTime);
const sectionStart = startTime.getTime();
const sectionEnd = endTime.getTime();
if (currentTime >= sectionStart && currentTime < sectionEnd) {
currentSection = {
name: section.name,
start: sectionStart,
end: sectionEnd,
index: index // Include the section index
};
return true; // Stop searching when we find the current section
}
} catch (error) {
console.error('Error processing section:', error);
}
return false;
});
return currentSection;
} catch (error) {
console.error('Error getting current section:', error);
throw error;
}
}
/**
* Adjusts either start time (before presentation) or current section's duration (during presentation)
* @param {number} minutes - Number of minutes to adjust (+/-)
*/
function adjustTimes(minutes) {
try {
if (!presentationData || !presentationData.sections) {
console.error('No presentation data available');
return;
}
const currentTime = new Date();
const presentationStartTime = parseTime(presentationData.start_time);
const currentTimeMs = currentTime.getTime();
const startTimeMs = presentationStartTime.getTime();
// Check if presentation hasn't started yet
if (currentTimeMs < startTimeMs) {
// Before presentation starts - adjust the start time
console.log(`Adjusting start time by ${minutes} minutes`);
const newStartTime = new Date(presentationStartTime.getTime() + (minutes * 60 * 1000));
const newStartTimeString = formatTime(newStartTime);
// Update the start time input and recalculate all section times
const startTimeInput = document.getElementById('start-time-input');
if (startTimeInput) {
startTimeInput.value = newStartTimeString;
}
recalculateTimesFromStart(newStartTimeString);
updateDisplay();
console.log(`Start time adjusted to: ${newStartTimeString}`);
return;
}
// After this point, handle current section adjustment (existing logic)
const currentSection = getCurrentSection(currentTime);
// If no current section (after presentation ends), don't adjust
if (!currentSection) {
console.log('No current section to adjust (presentation may be complete)');
return;
}
// Find the current section in our data array
const sectionIndex = presentationData.sections.findIndex(section =>
section.name === currentSection.name
);
if (sectionIndex === -1) {
console.error('Could not find current section in data');
return;
}
const section = presentationData.sections[sectionIndex];
const newDuration = section.duration + minutes;
// Don't allow duration to go below 1 minute
if (newDuration < 1) {
console.log('Cannot reduce section duration below 1 minute');
return;
}
console.log(`Adjusting ${section.name} duration from ${section.duration} to ${newDuration} minutes`);
// Update the section duration using our existing function
updateSectionDuration(sectionIndex, newDuration);
} catch (error) {
console.error('Error adjusting times:', error);
}
}
/**
* Scrolls to the current section in the timeline
* @param {number} currentSectionIndex - Index of the current section, or -1 if no section is active
*/
function scrollToCurrentSection(currentSectionIndex) {
try {
if (currentSectionIndex === -1) {
return;
}
// Get the scrollable timeline container
const timelineContainer = document.querySelector('.timeline-container');
if (!timelineContainer) {
console.error('Timeline container not found');
return;
}
// Find the current section element
const currentSectionElement = document.getElementById(`section-${currentSectionIndex}`);
if (!currentSectionElement) {
console.error('Current section element not found for index:', currentSectionIndex);
return;
}
// Use scrollIntoView to center the element in the visible area
currentSectionElement.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'nearest'
});
} catch (error) {
console.error('Error scrolling to current section:', error);
}
}
/**
* Validates and processes imported YAML data
* @param {Object} data - Parsed YAML data
* @returns {Object} - Validated and processed data
*/
function validateAndProcessYAML(data) {
try {
console.log('Validating imported YAML data:', data);
// Handle null/undefined data
if (!data || typeof data !== 'object') {
data = {};
}
// Initialize result with defaults
const result = {
title: data.title || "Presentation Timer",
start_time: data.start_time || formatTime(new Date()),
sections: []
};
// Validate sections array exists and has at least one section
if (!data.sections || !Array.isArray(data.sections) || data.sections.length === 0) {
throw new Error('YAML file must contain at least one section in the "sections" array');
}
// Validate each section
data.sections.forEach((section, index) => {
if (!section || typeof section !== 'object') {
throw new Error(`Section ${index + 1} must be a valid object`);
}
if (!section.name || typeof section.name !== 'string' || section.name.trim() === '') {
throw new Error(`Section ${index + 1} must have a non-empty "name" field`);
}
// Make sure duration is a number
let duration = section.duration;
if (typeof duration === 'string') {
duration = parseFloat(duration);
}
if (isNaN(duration) || duration <= 0) {
throw new Error(`Section "${section.name}" must have a positive "duration" field (in minutes)`);
}
result.sections.push({
name: section.name.trim(),
duration: duration
});
});
console.log('YAML validation successful:', result);
return result;
} catch (error) {
console.error('YAML validation failed:', error);
throw error;
}
}
/**
* Saves the YAML text to localStorage
* @param {string} yamlText - The YAML text to save
*/
function saveYAMLToStorage(yamlText) {
try {
localStorage.setItem(STORAGE_KEY, yamlText);
console.log('Successfully saved YAML to localStorage');
return true;
} catch (error) {
console.warn('Failed to save YAML to localStorage:', error);
return false;
}
}
/**