-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1851 lines (1542 loc) · 60.2 KB
/
content.js
File metadata and controls
1851 lines (1542 loc) · 60.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
(function () {
// State Management
let injected = false;
let updateInterval = null;
let playlistTargetIndex = null; // Store user preference
let is24HourMode = true; // Default to 24h
let lastVideoId = null; // Track current video ID
let navigationDebounceTimer = null; // Debounce navigation events
let isInjecting = false; // Injection lock
let currentInjectionId = 0; // Track injection attempts
let pageObserver = null; // DOM observer for page changes
const DEBUG = true; // Set to true for debugging
let lastTimeState = { h: null, m: null, s: null, ampm: null }; // Track flip clock state
let customTargetActive = { video: false, chapter: false, playlist: false }; // Track custom target interaction
// Ad Detection & Card Transition State
let isCurrentlyShowingAd = false;
let adCheckInterval = null;
let messageRotationInterval = null;
let currentMessageIndex = 0;
let isTransitioning = false; // Lock to prevent overlapping transitions
let adDebounceTimer = null; // Debounce rapid state changes
let consecutiveAdDetections = 0; // Counter for reliable detection
// Card Visibility Settings
let showVideoCard = true;
let showChapterCard = true;
let showPlaylistCard = true;
// Theme Settings
let useSolidBackground = false; // Default to glassmorphism theme
const adMessages = [
"Perfect time for a stretch! 🧘",
"Ads keep the lights on 💡",
"Your video will be right back 🎬",
"Patience is a virtue... ⏳",
"Grabbing some popcorn 🍿",
"Almost there... hang tight! 🚀"
];
// --- 1. UTILITIES ---
function formatTimeShort(seconds) {
if (isNaN(seconds) || seconds < 0) return "0:00";
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
if (h > 0) return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
return `${m}:${s.toString().padStart(2, '0')}`;
}
function getFinishTime(secondsFromNow) {
const date = new Date(Date.now() + secondsFromNow * 1000);
return date.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit', hour12: !is24HourMode });
}
function parseDuration(durationStr) {
if (!durationStr) return 0;
const parts = durationStr.split(':').map(Number);
if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
if (parts.length === 2) return parts[0] * 60 + parts[1];
return parts[0];
}
function getCurrentVideoId() {
try {
const urlParams = new URLSearchParams(location.search);
return urlParams.get('v');
} catch {
return null;
}
}
function debugLog(...args) {
if (DEBUG) {
console.log('[YT Time Manager]', ...args);
}
}
function isAdPlaying() {
try {
// Method 1: Check for ad overlay
const adOverlay = document.querySelector('.ytp-ad-player-overlay');
if (adOverlay && adOverlay.offsetParent !== null) return true;
// Method 2: Check video container class
const playerContainer = document.querySelector('.html5-video-player');
if (playerContainer?.classList.contains('ad-showing')) return true;
if (playerContainer?.classList.contains('ad-interrupting')) return true;
// Method 3: Check for ad module
const adModule = document.querySelector('.ytp-ad-module');
if (adModule && adModule.offsetParent !== null) return true;
// Method 4: Check for skip button or ad text
const skipButton = document.querySelector('.ytp-ad-skip-button, .ytp-ad-skip-button-modern, .ytp-skip-ad-button');
const adText = document.querySelector('.ytp-ad-text');
if (skipButton || adText) return true;
// Method 5: Check for video ad UI left controls
const videoAdUi = document.querySelector('.ytp-ad-player-overlay-instream-info');
if (videoAdUi) return true;
return false;
} catch (e) {
debugLog('Error in isAdPlaying:', e);
return false;
}
}
// --- 1.5 SETTINGS ---
async function loadSettings() {
try {
const result = await chrome.storage.local.get([
'is24HourMode',
'showVideoCard',
'showChapterCard',
'showPlaylistCard',
'useSolidBackground'
]);
if (result.is24HourMode !== undefined) {
is24HourMode = result.is24HourMode;
}
// Load card visibility settings (default to true)
showVideoCard = result.showVideoCard !== false;
showChapterCard = result.showChapterCard !== false;
showPlaylistCard = result.showPlaylistCard !== false;
// Load theme setting (default to false - glassmorphism)
useSolidBackground = result.useSolidBackground === true;
} catch (e) {
console.error("Failed to load settings:", e);
}
}
function saveSettings() {
try {
chrome.storage.local.set({
is24HourMode,
showVideoCard,
showChapterCard,
showPlaylistCard,
useSolidBackground
});
} catch (e) {
console.error("Failed to save settings:", e);
}
}
// --- 2. SCRAPERS ---
function getChapterInfo(video) {
const duration = video.duration;
const currentTime = video.currentTime;
if (isNaN(duration) || isNaN(currentTime)) return null;
let chapters = [];
// Strategy 1: Macro Markers List (Most reliable if available)
const macroMarkers = document.querySelectorAll('ytd-macro-markers-list-item-renderer');
if (macroMarkers.length > 0) {
macroMarkers.forEach(marker => {
const timeStr = marker.querySelector('#time')?.textContent?.trim();
const title = marker.querySelector('#title')?.textContent?.trim();
if (timeStr) {
const time = parseDuration(timeStr);
chapters.push({ time, title });
}
});
}
// Strategy 2: Visual Markers (Progress Bar)
if (chapters.length === 0) {
const markers = Array.from(document.querySelectorAll('.ytp-chapter-marker'));
if (markers.length > 0) {
chapters = markers.map(marker => {
let pct = parseFloat(marker.style.left);
if (isNaN(pct)) pct = parseFloat(marker.style.paddingLeft);
return {
time: (pct / 100) * duration,
title: null
};
}).sort((a, b) => a.time - b.time);
}
}
// Strategy 3: Description Timestamps (Fallback)
if (chapters.length === 0) {
const descriptionEl = document.querySelector('#description-inline-expander') || document.querySelector('#description');
if (descriptionEl) {
const text = descriptionEl.innerText;
const regex = /(?:(\d{1,2}):)?(\d{1,2}):(\d{2})\s+(.*)/g;
let match;
while ((match = regex.exec(text)) !== null) {
const h = match[1] ? parseInt(match[1]) : 0;
const m = parseInt(match[2]);
const s = parseInt(match[3]);
const title = match[4]?.trim().split('\n')[0];
const seconds = h * 3600 + m * 60 + s;
if (seconds < duration) {
chapters.push({ time: seconds, title });
}
}
}
}
chapters.sort((a, b) => a.time - b.time);
chapters = chapters.filter((c, index, self) => {
return c.time >= 0 && c.time < duration && (index === 0 || c.time > self[index-1].time + 1);
});
if (chapters.length === 0) return null;
let currentChapter = null;
let nextChapterTime = duration;
for (let i = 0; i < chapters.length; i++) {
if (currentTime >= chapters[i].time) {
currentChapter = chapters[i];
nextChapterTime = (i + 1 < chapters.length) ? chapters[i + 1].time : duration;
} else {
break;
}
}
if (!currentChapter) {
if (chapters[0].time > 0) {
currentChapter = { time: 0, title: "Intro" };
nextChapterTime = chapters[0].time;
} else {
return null;
}
}
if (!currentChapter.title) {
const hoverTitle = document.querySelector('.ytp-chapter-title-content')?.textContent;
currentChapter.title = hoverTitle || "Chapter";
}
return {
title: currentChapter.title,
remaining: nextChapterTime - currentTime,
endTime: nextChapterTime,
startTime: currentChapter.time,
duration: nextChapterTime - currentChapter.time,
progress: (currentTime - currentChapter.time) / (nextChapterTime - currentChapter.time)
};
}
function getPlaylistInfo(video, targetIndex = null) {
const playlistPanel = document.querySelector('ytd-playlist-panel-renderer');
if (!playlistPanel) return null;
const currentVideoItem = playlistPanel.querySelector('ytd-playlist-panel-video-renderer[selected]');
if (!currentVideoItem) return null;
let totalRemaining = 0;
let count = 0;
let foundCurrent = false;
let totalDuration = 0;
let currentElapsed = 0;
const items = Array.from(playlistPanel.querySelectorAll('ytd-playlist-panel-video-renderer'));
if (items.length === 0) return null;
// Attempt to determine absolute indices
let firstAbsoluteIndex = -1;
let firstDomIndexWithNumber = -1;
for (let i = 0; i < items.length; i++) {
const indexEl = items[i].querySelector('#index');
if (indexEl) {
const val = parseInt(indexEl.textContent.trim());
if (!isNaN(val)) {
firstAbsoluteIndex = val;
firstDomIndexWithNumber = i;
break;
}
}
}
// Fallback: assume 1-based from start of DOM if no index found
if (firstAbsoluteIndex === -1) {
firstAbsoluteIndex = 1;
firstDomIndexWithNumber = 0;
}
// Calculate current video's absolute index
const currentDomIndex = items.indexOf(currentVideoItem);
const currentAbsoluteIndex = firstAbsoluteIndex + (currentDomIndex - firstDomIndexWithNumber);
// Determine the last available index in DOM
const lastDomIndex = items.length - 1;
const lastAbsoluteIndex = firstAbsoluteIndex + (lastDomIndex - firstDomIndexWithNumber);
// Determine target index
// If not set, default to last available (this is the only time we "change" it for the user)
let effectiveTargetIndex = targetIndex;
if (effectiveTargetIndex === null) {
effectiveTargetIndex = lastAbsoluteIndex;
}
// Calculation Logic
// We only sum up to the target.
// If target < current, we effectively calculate nothing (or just current video remainder?)
// Let's stick to the loop logic: it breaks if index > target.
// If target < current, the loop will break before adding any *future* videos.
// But we still add the current video's remainder if we are ON the current video.
// We clamp the calculation loop to what is loaded in DOM
const calculationTargetIndex = Math.min(effectiveTargetIndex, lastAbsoluteIndex);
for (let i = 0; i < items.length; i++) {
const item = items[i];
const absoluteIndex = firstAbsoluteIndex + (i - firstDomIndexWithNumber);
// Stop if we passed the target
if (absoluteIndex > calculationTargetIndex) break;
const durationStr = item.querySelector('#text.ytd-thumbnail-overlay-time-status-renderer')?.textContent?.trim();
const itemDuration = parseDuration(durationStr);
totalDuration += itemDuration;
if (item === currentVideoItem) {
foundCurrent = true;
if (video && !isNaN(video.duration) && !isNaN(video.currentTime)) {
totalRemaining += (video.duration - video.currentTime);
currentElapsed += video.currentTime;
}
continue;
}
if (foundCurrent) {
// Only add if we are <= target (checked by loop break above)
// But wait, if target < current, we shouldn't be here?
// If target < current, absoluteIndex > calculationTargetIndex will trigger BEFORE we reach current?
// No, current is at `currentAbsoluteIndex`.
// If target (50) < current (100). calculationTargetIndex is 50.
// Loop runs 1..50. Breaks.
// We never reach current (100).
// So foundCurrent is false. totalRemaining is 0.
// This is correct: "Finish at 50" when at 100 means "Already finished".
if (durationStr) {
totalRemaining += itemDuration;
count++;
}
} else {
currentElapsed += itemDuration;
}
}
return {
videosRemaining: count,
totalSeconds: totalRemaining,
progress: totalDuration > 0 ? (currentElapsed / totalDuration) : 0,
currentIndex: currentAbsoluteIndex,
totalVideos: lastAbsoluteIndex,
targetIndex: effectiveTargetIndex // Return the user's target (or default), NOT clamped to current
};
}
// --- 3. UI CONSTRUCTION ---
async function loadUI() {
try {
const response = await fetch(chrome.runtime.getURL('overlay.html'));
const html = await response.text();
const container = document.createElement('div');
container.innerHTML = html;
const ui = container.firstElementChild;
// Apply initial settings
const toggle24h = ui.querySelector('#dt-24h-toggle');
if (toggle24h) toggle24h.checked = is24HourMode;
attachListeners(ui);
// Initialize Flip Clock
initFlipClock(ui);
return ui;
} catch (e) {
console.error("Failed to load UI:", e);
return null;
}
}
function attachListeners(container) {
const speedDown = container.querySelector('#dt-speed-down');
const speedUp = container.querySelector('#dt-speed-up');
const playlistInput = container.querySelector('#dt-playlist-target-input');
if(speedDown) speedDown.addEventListener('click', () => changeSpeed(-0.25));
if(speedUp) speedUp.addEventListener('click', () => changeSpeed(0.25));
// Playlist Input Listener
if(playlistInput) {
playlistInput.addEventListener('input', (e) => {
const val = parseInt(e.target.value);
if (!isNaN(val) && val > 0) {
playlistTargetIndex = val;
const video = document.querySelector('video');
if (video) updateUI(video);
}
});
}
// Settings Listeners
const settingsBtn = container.querySelector('#dt-settings-btn');
const settingsPanelEl = container.querySelector('#dt-settings-panel');
const toggle24h = container.querySelector('#dt-24h-toggle');
if(settingsBtn && settingsPanelEl) {
settingsBtn.addEventListener('click', (e) => {
e.stopPropagation();
settingsPanelEl.classList.toggle('hidden');
// Expand container to accommodate settings panel
if (!settingsPanelEl.classList.contains('hidden')) {
container.classList.add('dt-settings-open');
} else {
container.classList.remove('dt-settings-open');
}
});
// Close settings when clicking outside
document.addEventListener('click', (e) => {
if (!settingsPanelEl.contains(e.target) && !settingsBtn.contains(e.target)) {
settingsPanelEl.classList.add('hidden');
container.classList.remove('dt-settings-open');
}
});
}
if(toggle24h) {
toggle24h.checked = is24HourMode; // Set initial state
toggle24h.addEventListener('change', (e) => {
is24HourMode = e.target.checked;
saveSettings();
const video = document.querySelector('video');
if (video) updateUI(video);
});
}
// Card visibility toggles
const toggleVideoCard = container.querySelector('#dt-toggle-video-card');
const toggleChapterCard = container.querySelector('#dt-toggle-chapter-card');
const togglePlaylistCard = container.querySelector('#dt-toggle-playlist-card');
if (toggleVideoCard) {
toggleVideoCard.checked = showVideoCard;
toggleVideoCard.addEventListener('change', (e) => {
showVideoCard = e.target.checked;
saveSettings();
updateCardVisibility();
});
}
if (toggleChapterCard) {
toggleChapterCard.checked = showChapterCard;
toggleChapterCard.addEventListener('change', (e) => {
showChapterCard = e.target.checked;
saveSettings();
updateCardVisibility();
});
}
if (togglePlaylistCard) {
togglePlaylistCard.checked = showPlaylistCard;
togglePlaylistCard.addEventListener('change', (e) => {
showPlaylistCard = e.target.checked;
saveSettings();
updateCardVisibility();
});
}
// Theme toggle
const toggleSolidBg = container.querySelector('#dt-toggle-solid-bg');
if (toggleSolidBg) {
toggleSolidBg.checked = useSolidBackground;
toggleSolidBg.addEventListener('change', (e) => {
useSolidBackground = e.target.checked;
saveSettings();
applyTheme();
});
}
// Custom Target Listeners
attachCustomTargetListeners(container, 'video');
attachCustomTargetListeners(container, 'chapter');
attachCustomTargetListeners(container, 'playlist');
}
function attachCustomTargetListeners(container, type) {
// Duration Inputs
const durH = container.querySelector(`#dt-${type}-custom-duration-container input[data-unit="h"]`);
const durM = container.querySelector(`#dt-${type}-custom-duration-container input[data-unit="m"]`);
// Speed Input
const speedInput = container.querySelector(`#dt-${type}-custom-speed`);
// Finish Inputs
const finH = container.querySelector(`#dt-${type}-custom-finish-container input[data-unit="h"]`);
const finM = container.querySelector(`#dt-${type}-custom-finish-container input[data-unit="m"]`);
const finAmpm = container.querySelector(`#dt-${type}-custom-finish-container .dt-ampm-select`);
if (!durH || !speedInput || !finH) return;
function getRemainingContent() {
const video = document.querySelector('video');
if (!video) return 0;
if (type === 'video') {
return video.duration - video.currentTime;
} else if (type === 'chapter') {
const chapterInfo = getChapterInfo(video);
return chapterInfo ? chapterInfo.remaining : 0;
} else if (type === 'playlist') {
const playlistInfo = getPlaylistInfo(video, playlistTargetIndex);
return playlistInfo ? playlistInfo.totalSeconds : 0;
}
return 0;
}
function updateSpeed(newSpeed) {
const video = document.querySelector('video');
if (video) {
if (newSpeed < 0.25) newSpeed = 0.25;
if (newSpeed > 16) newSpeed = 16;
video.playbackRate = newSpeed;
updateUI(video);
}
}
// Helper to get total seconds from duration inputs
function getDurationSeconds() {
const h = parseInt(durH.value) || 0;
const m = parseInt(durM.value) || 0;
return h * 3600 + m * 60;
}
// Helper to get target date from finish inputs
function getFinishDate() {
const now = new Date();
let h = parseInt(finH.value);
const m = parseInt(finM.value) || 0;
if (isNaN(h)) return null;
if (!is24HourMode && finAmpm) {
const ampm = finAmpm.value;
if (ampm === 'PM' && h < 12) h += 12;
if (ampm === 'AM' && h === 12) h = 0;
}
let targetDate = new Date(now);
targetDate.setHours(h);
targetDate.setMinutes(m);
targetDate.setSeconds(0);
if (targetDate < now) {
targetDate.setDate(targetDate.getDate() + 1);
}
return targetDate;
}
// 1. Duration Inputs
[durH, durM].forEach(input => {
input.addEventListener('change', () => {
customTargetActive[type] = true;
const targetSeconds = getDurationSeconds();
const contentRemaining = getRemainingContent();
if (targetSeconds > 0 && contentRemaining > 0) {
const requiredSpeed = contentRemaining / targetSeconds;
updateSpeed(requiredSpeed);
durH.blur(); durM.blur();
}
});
});
// 2. Speed Input
speedInput.addEventListener('change', (e) => {
customTargetActive[type] = true;
const val = parseFloat(e.target.value);
if (!isNaN(val) && val > 0) {
updateSpeed(val);
speedInput.blur();
}
});
// 3. Finish Inputs
[finH, finM, finAmpm].forEach(input => {
input.addEventListener('change', () => {
customTargetActive[type] = true;
const targetDate = getFinishDate();
if (!targetDate) return;
const now = new Date();
const secondsUntilFinish = (targetDate - now) / 1000;
const contentRemaining = getRemainingContent();
if (secondsUntilFinish > 0 && contentRemaining > 0) {
const requiredSpeed = contentRemaining / secondsUntilFinish;
updateSpeed(requiredSpeed);
finH.blur(); finM.blur();
}
});
});
}
function updateCustomInputs(type, remainingSeconds, speed) {
const container = document.getElementById('yt-time-manager-container');
const durH = container.querySelector(`#dt-${type}-custom-duration-container input[data-unit="h"]`);
const durM = container.querySelector(`#dt-${type}-custom-duration-container input[data-unit="m"]`);
const speedInput = document.getElementById(`dt-${type}-custom-speed`);
const finH = container.querySelector(`#dt-${type}-custom-finish-container input[data-unit="h"]`);
const finM = container.querySelector(`#dt-${type}-custom-finish-container input[data-unit="m"]`);
const finAmpm = container.querySelector(`#dt-${type}-custom-finish-container .dt-ampm-select`);
if (!durH || !speedInput || !finH) return;
// Update AM/PM visibility (Always update this, regardless of interaction)
if (finAmpm) {
if (is24HourMode) finAmpm.classList.add('hidden');
else finAmpm.classList.remove('hidden');
}
// Only update values if user has interacted with this section
if (!customTargetActive[type]) return;
// Calculate Duration
const targetDuration = remainingSeconds / speed;
if (document.activeElement !== durH && document.activeElement !== durM) {
const h = Math.floor(targetDuration / 3600);
const m = Math.floor((targetDuration % 3600) / 60);
durH.value = h.toString().padStart(2, '0');
durM.value = m.toString().padStart(2, '0');
}
// Update Speed
if (document.activeElement !== speedInput) {
speedInput.value = speed.toFixed(2);
}
// Calculate Finish Time
if (document.activeElement !== finH && document.activeElement !== finM && document.activeElement !== finAmpm) {
const finishDate = new Date(Date.now() + targetDuration * 1000);
let h = finishDate.getHours();
const m = finishDate.getMinutes();
let ampm = '';
if (!is24HourMode) {
ampm = h >= 12 ? 'PM' : 'AM';
h = h % 12;
h = h ? h : 12;
if (finAmpm) finAmpm.value = ampm;
}
finH.value = h.toString().padStart(2, '0');
finM.value = m.toString().padStart(2, '0');
}
}
function changeSpeed(delta) {
const video = document.querySelector('video');
if (video) {
let newRate = video.playbackRate + delta;
if (newRate < 0.25) newRate = 0.25;
if (newRate > 16) newRate = 16;
video.playbackRate = newRate;
updateUI(video);
}
}
function updateDetailsList(listId, remainingSeconds, currentSpeed, activeClass) {
const list = document.getElementById(listId);
if (!list) return;
const speeds = [1, 1.25, 1.5, 1.75, 2];
if (!speeds.includes(currentSpeed)) {
speeds.push(currentSpeed);
speeds.sort((a, b) => a - b);
}
// Check if we need to rebuild the structure (speed list changed)
const currentSpeeds = Array.from(list.querySelectorAll('.dt-speed-clickable'))
.map(row => parseFloat(row.dataset.speed));
const speedsChanged = currentSpeeds.length !== speeds.length ||
!speeds.every((speed, i) => speed === currentSpeeds[i]);
if (speedsChanged || list.children.length === 0) {
// Rebuild HTML structure only when necessary
let html = '';
speeds.forEach(speed => {
const adjustedRemaining = remainingSeconds / speed;
const isActive = speed === currentSpeed;
const activeClassStr = isActive ? `active ${activeClass}` : '';
html += `
<div class="dt-detail-row ${activeClassStr} dt-speed-clickable" data-speed="${speed}">
<span class="dt-time-remaining">${formatTimeShort(adjustedRemaining)}</span>
<span class="dt-speed-value">${speed}x</span>
<span class="dt-finish-time">${getFinishTime(adjustedRemaining)}</span>
</div>
`;
});
list.innerHTML = html;
// Attach event listener only once
if (!list.dataset.listenerAttached) {
list.addEventListener('click', (e) => {
const row = e.target.closest('.dt-speed-clickable');
if (row) {
const newSpeed = parseFloat(row.dataset.speed);
const video = document.querySelector('video');
if (video && newSpeed) {
video.playbackRate = newSpeed;
updateUI(video);
}
}
});
list.dataset.listenerAttached = 'true';
}
} else {
// Just update text content of existing elements (no flickering!)
const rows = list.querySelectorAll('.dt-speed-clickable');
speeds.forEach((speed, index) => {
const row = rows[index];
if (!row) return;
const adjustedRemaining = remainingSeconds / speed;
const isActive = speed === currentSpeed;
// Update active state
if (isActive) {
if (!row.classList.contains('active')) {
row.classList.add('active', activeClass);
}
} else {
row.classList.remove('active', activeClass);
}
// Update text content only
const timeRemaining = row.querySelector('.dt-time-remaining');
const finishTime = row.querySelector('.dt-finish-time');
if (timeRemaining) {
const newTime = formatTimeShort(adjustedRemaining);
if (timeRemaining.textContent !== newTime) {
timeRemaining.textContent = newTime;
}
}
if (finishTime) {
const newFinish = getFinishTime(adjustedRemaining);
if (finishTime.textContent !== newFinish) {
finishTime.textContent = newFinish;
}
}
});
}
}
// --- 3.5 FLIP CLOCK LOGIC ---
function initFlipClock(container) {
const clockContainer = container.querySelector('#dt-flip-clock');
if (!clockContainer) return;
// Clear existing
clockContainer.innerHTML = '';
// Create units
const units = ['hours', 'minutes', 'seconds'];
units.forEach((unit, index) => {
const unitEl = document.createElement('div');
unitEl.className = 'dt-flip-unit';
unitEl.id = `dt-unit-${unit}`;
// Initial structure
unitEl.innerHTML = `
<div class="dt-flip-top"></div>
<div class="dt-flip-bottom"></div>
<div class="dt-flip-leaf-front"></div>
<div class="dt-flip-leaf-back"></div>
`;
clockContainer.appendChild(unitEl);
// Add separator if not last
if (index < units.length - 1) {
const sep = document.createElement('div');
sep.className = 'dt-flip-separator';
sep.textContent = ':';
clockContainer.appendChild(sep);
}
});
// AM/PM Unit
const ampmEl = document.createElement('div');
ampmEl.className = 'dt-flip-ampm';
ampmEl.id = 'dt-unit-ampm';
clockContainer.appendChild(ampmEl);
}
function updateFlipClock(date) {
const hRaw = date.getHours();
const mRaw = date.getMinutes();
const sRaw = date.getSeconds();
let h = hRaw;
let ampm = '';
if (!is24HourMode) {
ampm = h >= 12 ? 'PM' : 'AM';
h = h % 12;
h = h ? h : 12; // the hour '0' should be '12'
}
const hStr = h.toString().padStart(2, '0');
const mStr = mRaw.toString().padStart(2, '0');
const sStr = sRaw.toString().padStart(2, '0');
flip('hours', hStr);
flip('minutes', mStr);
flip('seconds', sStr);
// Update AM/PM text directly (no flip needed usually, or simple fade)
const ampmEl = document.getElementById('dt-unit-ampm');
if (ampmEl && lastTimeState.ampm !== ampm) {
ampmEl.textContent = ampm;
lastTimeState.ampm = ampm;
}
}
function flip(unit, newValue) {
const el = document.getElementById(`dt-unit-${unit}`);
if (!el) return;
const top = el.querySelector('.dt-flip-top');
const bottom = el.querySelector('.dt-flip-bottom');
const front = el.querySelector('.dt-flip-leaf-front');
const back = el.querySelector('.dt-flip-leaf-back');
if (!top || !bottom || !front || !back) return;
// Check if value changed
const currentValue = top.getAttribute('data-value');
if (currentValue === newValue) return;
// If first run (currentValue is null), just set it without animation
if (currentValue === null) {
top.setAttribute('data-value', newValue);
bottom.setAttribute('data-value', newValue);
front.setAttribute('data-value', newValue);
back.setAttribute('data-value', newValue);
return;
}
// Setup animation state
// Top: Current Value
// Bottom: New Value (revealed at end)
// Front: Current Value (flips down)
// Back: New Value (flips down to become bottom)
top.setAttribute('data-value', newValue); // Actually, top should be NEW value? No.
// Standard Flip Logic:
// Static Top: New Value
// Static Bottom: Old Value -> New Value (at end)
// Animating Front: Old Value
// Animating Back: New Value
// Let's refine:
// 1. Static Top shows NEW value immediately (behind the front leaf)
top.setAttribute('data-value', newValue);
// 2. Static Bottom shows OLD value (until animation ends)
bottom.setAttribute('data-value', currentValue);
// 3. Front Leaf shows OLD value
front.setAttribute('data-value', currentValue);
// 4. Back Leaf shows NEW value
back.setAttribute('data-value', newValue);
// Remove animation classes to reset
el.classList.remove('flipping');
void el.offsetWidth; // Trigger reflow
el.classList.add('flipping');
// Cleanup after animation
// We can use a timeout matching the CSS animation duration (600ms)
setTimeout(() => {
bottom.setAttribute('data-value', newValue);
front.setAttribute('data-value', newValue); // FIX: Update front to new value so it matches when animation resets
el.classList.remove('flipping');
}, 600);
}
function updateUI(video) {
const container = document.getElementById('yt-time-manager-container');
if (!container) return;
const duration = video.duration;
const currentTime = video.currentTime;
const playbackRate = video.playbackRate;
if (isNaN(duration) || duration <= 0) return;
// 1. Update Header
document.getElementById('dt-speed-val').textContent = playbackRate.toFixed(2);
// document.getElementById('dt-current-clock').textContent = new Date().toLocaleTimeString([], { hour12: !is24HourMode });
updateFlipClock(new Date());
// 2. Update Video Section
const videoRemainingRaw = duration - currentTime;
const videoRemaining = videoRemainingRaw / playbackRate;
document.getElementById('dt-video-remaining').textContent = formatTimeShort(videoRemaining);
document.getElementById('dt-video-finish').textContent = getFinishTime(videoRemaining);
const videoProgress = (currentTime / duration) * 100;
document.getElementById('dt-video-progress').style.width = `${videoProgress}%`;
// Update Video Details
updateDetailsList('dt-video-details-list', videoRemainingRaw, playbackRate, 'video-active');
updateCustomInputs('video', videoRemainingRaw, playbackRate);
// 3. Update Chapter Section
const chapterInfo = getChapterInfo(video);
const chapterSection = document.getElementById('dt-chapter-section');
if (chapterInfo && chapterInfo.remaining > 0) {
chapterSection.classList.remove('hidden');
document.getElementById('dt-chapter-name').textContent = chapterInfo.title;
const chapterRemaining = chapterInfo.remaining / playbackRate;
document.getElementById('dt-chapter-remaining').textContent = formatTimeShort(chapterRemaining);
document.getElementById('dt-chapter-finish').textContent = getFinishTime(chapterRemaining);
const chapterProgress = Math.max(0, Math.min(100, chapterInfo.progress * 100));
document.getElementById('dt-chapter-progress').style.width = `${chapterProgress}%`;
// Update Chapter Details (using raw remaining time for calculation)
updateDetailsList('dt-chapter-details-list', chapterInfo.remaining, playbackRate, 'chapter-active');
updateCustomInputs('chapter', chapterInfo.remaining, playbackRate);
} else {
chapterSection.classList.add('hidden');
}
// 4. Update Playlist Section
const playlistInfo = getPlaylistInfo(video, playlistTargetIndex);
const playlistSection = document.getElementById('dt-playlist-section');
if (playlistInfo && playlistInfo.totalVideos > 0) {
playlistSection.classList.remove('hidden');
// Update Inputs
const input = document.getElementById('dt-playlist-target-input');
const totalLabel = document.getElementById('dt-playlist-total-count');
if (input && totalLabel) {
// If user hasn't set a custom target, always default to playlist total
if (playlistTargetIndex === null) {
input.value = playlistInfo.totalVideos;
} else if (document.activeElement !== input) {
// If user has set a value, keep it displayed (unless they're typing)
if (parseInt(input.value) !== playlistTargetIndex) {
input.value = playlistTargetIndex;
}
}
totalLabel.textContent = `/ ${playlistInfo.totalVideos}`;
}
const playlistRemaining = playlistInfo.totalSeconds / playbackRate;
document.getElementById('dt-playlist-remaining').textContent = formatTimeShort(playlistRemaining);
document.getElementById('dt-playlist-finish').textContent = getFinishTime(playlistRemaining);
const playlistProgress = Math.max(0, Math.min(100, playlistInfo.progress * 100));
document.getElementById('dt-playlist-progress').style.width = `${playlistProgress}%`;
// Update Playlist Details
updateDetailsList('dt-playlist-details-list', playlistInfo.totalSeconds, playbackRate, 'playlist-active');