-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1101 lines (932 loc) · 34.3 KB
/
Copy pathcontent.js
File metadata and controls
1101 lines (932 loc) · 34.3 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 () {
const { isHostnameAllowed, isYouTubeHostname } = globalThis.VideoControllerDomains;
const I18n = globalThis.VideoControllerI18n;
chrome.storage.local.get(['allowedDomains', 'locale'], (res) => {
const allowed = res.allowedDomains || [];
if (!isHostnameAllowed(window.location.hostname, allowed)) {
return;
}
let t = I18n.createTranslator(I18n.resolveLocale(res.locale || 'auto'));
let currentSpeed = 1.0;
let autoApplySpeed = true;
let videoObserver = null;
let speedSyncInterval = null;
// SponsorBlock state
let sbEnabled = false;
let sbCategories = ['sponsor'];
let sbSegments = [];
let sbCurrentVideoId = null;
let sbSegmentsVideoId = null;
let sbFetching = false;
let sbRetryAfter = 0;
let sbSkipListener = null;
let sbBoundVideo = null;
let sbNavigationListener = null;
let sbVideoCheckInterval = null;
let sbLastSkipFrom = null;
let sbLastSkipSegment = null;
let sbSkippedSegmentIds = new Set();
// Breathing room before retrying a failed segments request.
const SB_RETRY_COOLDOWN = 10000;
// YouTube speed panel state
// How often the widgets verify they are still in the live actions row.
const WIDGET_SELF_CHECK_INTERVAL = 3000;
let ytSpeedPanelEnabled = false;
let ytSummaryBtnEnabled = false;
const DEFAULT_HOTKEYS = {
decrease: { alt: true, key: 'ArrowLeft' },
increase: { alt: true, key: 'ArrowRight' },
reset: { alt: true, key: 'r' }
};
let currentHotkeys = { ...DEFAULT_HOTKEYS };
function loadHotkeys() {
chrome.storage.local.get(['hotkeys'], (result) => {
currentHotkeys = { ...(result.hotkeys || DEFAULT_HOTKEYS) };
});
}
function notifyState(patch) {
chrome.runtime.sendMessage({ type: 'UPDATE_TAB_STATE', ...patch }, () => {
if (chrome.runtime.lastError) {
// The background worker may be temporarily unavailable.
}
});
}
function applyRateToVideos(rate) {
const videos = document.querySelectorAll('video');
videos.forEach((video) => {
if (!(video instanceof HTMLVideoElement) || !('playbackRate' in video)) {
return;
}
try {
if (Math.abs(video.playbackRate - rate) > 0.01) {
video.playbackRate = rate;
}
} catch (error) {
console.warn('Failed to set playbackRate:', error);
}
});
}
function setSpeed(rate, options = {}) {
const bounded = Math.max(0.0, Math.min(4.0, Math.round(Number(rate) * 10) / 10));
currentSpeed = Number.isNaN(bounded) ? 1.0 : bounded;
applyRateToVideos(currentSpeed);
updateSpeedPanel();
if (options.notifyBackground !== false) {
notifyState({ speed: currentSpeed });
}
}
function setSpeedForAllVideos(rate) {
applyRateToVideos(rate);
}
function observeNewVideos() {
if (videoObserver) {
videoObserver.disconnect();
}
videoObserver = new MutationObserver((mutations) => {
const speedToApply = autoApplySpeed ? currentSpeed : 1.0;
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
const videos = node.tagName === 'VIDEO' ? [node] : node.querySelectorAll?.('video') || [];
videos.forEach((video) => {
if (!(video instanceof HTMLVideoElement) || !('playbackRate' in video)) {
return;
}
try {
if (Math.abs(video.playbackRate - speedToApply) > 0.01) {
video.playbackRate = speedToApply;
}
} catch (error) {
console.warn('Failed to set playbackRate for a new video:', error);
}
if (sbEnabled && sbSegments.length > 0 && video !== sbBoundVideo) {
attachSkipListener(video);
}
});
});
});
});
if (document.body) {
videoObserver.observe(document.body, { childList: true, subtree: true });
}
}
function startSpeedSync() {
if (speedSyncInterval) {
clearInterval(speedSyncInterval);
}
speedSyncInterval = setInterval(() => {
applyRateToVideos(currentSpeed);
}, 2000);
}
// Reused across repeats so holding an arrow updates one notification instead
// of tearing it down and fading a new one in every step.
let speedNotificationTimers = [];
function scheduleNotificationHide(notification) {
speedNotificationTimers.push(setTimeout(() => {
notification.style.opacity = '0';
speedNotificationTimers.push(setTimeout(() => notification.remove(), 200));
}, 1000));
}
function showSpeedNotification(rate) {
speedNotificationTimers.forEach(clearTimeout);
speedNotificationTimers = [];
const existing = document.getElementById('video-speed-notification');
if (existing) {
existing.textContent = `${rate.toFixed(1)}×`;
existing.style.opacity = '1';
scheduleNotificationHide(existing);
return;
}
const player = getPlayerContainer();
const container = player || document.body;
if (player) {
const pos = getComputedStyle(player).position;
if (pos === 'static') player.style.position = 'relative';
}
const positionStyles = player
? 'position: absolute; top: 16px; right: 16px'
: 'position: fixed; top: 20px; right: 20px';
const notification = document.createElement('div');
notification.id = 'video-speed-notification';
notification.style.cssText = [
positionStyles,
'padding: 8px 16px',
'background: rgba(0, 0, 0, 0.8)',
'color: #fff',
"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
'font-size: 14px',
'font-weight: 600',
'border-radius: 8px',
'z-index: 999999',
'pointer-events: none',
'opacity: 0',
'transition: opacity 0.2s ease'
].join(';');
notification.textContent = `${rate.toFixed(1)}×`;
container.appendChild(notification);
speedNotificationTimers.push(setTimeout(() => {
notification.style.opacity = '1';
}, 10));
scheduleNotificationHide(notification);
}
function changeSpeed(delta) {
const newSpeed = Math.max(0.0, Math.min(4.0, Math.round((currentSpeed + delta) * 10) / 10));
setSpeed(newSpeed);
showSpeedNotification(newSpeed);
}
function setAutoApply(value, syncBackground = true) {
autoApplySpeed = Boolean(value);
if (autoApplySpeed) {
setSpeed(currentSpeed);
} else {
setSpeedForAllVideos(1.0);
}
if (syncBackground) {
notifyState({ autoApply: autoApplySpeed });
}
}
// --- SponsorBlock ---
function isYouTube() {
return isYouTubeHostname(window.location.hostname);
}
function isYouTubeWatchPage() {
return isYouTube() && window.location.pathname === '/watch';
}
function getYouTubeVideoId() {
try {
const url = new URL(window.location.href);
return url.searchParams.get('v') || null;
} catch (e) {
return null;
}
}
// Reports whether the answer can be trusted: the API replies 404 when a video
// genuinely has no segments, while a network error or 5xx means "ask again".
// Without that split a single failed request looked like an empty video and
// was never retried.
async function fetchSponsorSegments(videoId, categories) {
const params = new URLSearchParams();
params.set('videoID', videoId);
categories.forEach((cat) => params.append('category', cat));
try {
const response = await fetch(`https://sponsor.ajay.app/api/skipSegments?${params}`);
if (response.status === 404) return { ok: true, segments: [] };
if (!response.ok) return { ok: false, segments: [] };
return { ok: true, segments: await response.json() };
} catch (e) {
return { ok: false, segments: [] };
}
}
function segmentId(seg) {
return seg.segment.join(',');
}
function getPlayerContainer() {
return document.querySelector('#movie_player')
|| document.querySelector('.html5-video-player');
}
function createUnskipButton(skipFromTime, notificationEl) {
const HOVER_BG = 'rgba(74, 176, 255, 0.3)';
const DEFAULT_BG = 'rgba(74, 176, 255, 0.15)';
const btn = document.createElement('button');
btn.textContent = t('sbUndo');
btn.style.cssText = [
'border: 1px solid rgba(74, 176, 255, 0.5)',
`background: ${DEFAULT_BG}`,
'color: #4ab0ff',
'font-size: 12px',
'font-weight: 700',
'padding: 3px 10px',
'border-radius: 5px',
'cursor: pointer',
'transition: background 0.15s ease',
'white-space: nowrap'
].join(';');
btn.addEventListener('mouseenter', () => { btn.style.background = HOVER_BG; });
btn.addEventListener('mouseleave', () => { btn.style.background = DEFAULT_BG; });
btn.addEventListener('click', (e) => {
e.stopPropagation();
if (sbBoundVideo && sbLastSkipSegment) {
sbSkippedSegmentIds.add(segmentId(sbLastSkipSegment));
sbBoundVideo.currentTime = skipFromTime;
}
notificationEl.style.opacity = '0';
setTimeout(() => notificationEl.remove(), 300);
});
return btn;
}
function dismissNotification(el) {
if (!el.parentNode) return;
el.style.opacity = '0';
setTimeout(() => el.remove(), 300);
}
function categoryLabel(category) {
const key = `cat${category.charAt(0).toUpperCase()}${category.slice(1)}Lower`;
const label = t(key);
return label === key ? category : label;
}
function showSkipNotification(category, skipFromTime) {
const existing = document.getElementById('sb-skip-notification');
if (existing) existing.remove();
const player = getPlayerContainer();
const container = player || document.body;
if (player) {
const pos = getComputedStyle(player).position;
if (pos === 'static') player.style.position = 'relative';
}
const el = document.createElement('div');
el.id = 'sb-skip-notification';
const positionStyles = player
? 'position: absolute; top: 16px; left: 50%; transform: translateX(-50%)'
: 'position: fixed; top: 60px; left: 50%; transform: translateX(-50%)';
el.style.cssText = [
positionStyles,
'display: flex',
'align-items: center',
'gap: 10px',
'padding: 8px 14px',
'background: rgba(0, 0, 0, 0.85)',
'color: #4ab0ff',
"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
'font-size: 13px',
'font-weight: 600',
'border-radius: 8px',
'z-index: 999999',
'opacity: 0',
'transition: opacity 0.25s ease'
].join(';');
const textSpan = document.createElement('span');
textSpan.textContent = t('sbSkipped', { category: categoryLabel(category) });
el.appendChild(textSpan);
if (typeof skipFromTime === 'number' && sbBoundVideo) {
el.appendChild(createUnskipButton(skipFromTime, el));
}
container.appendChild(el);
requestAnimationFrame(() => { el.style.opacity = '1'; });
setTimeout(() => dismissNotification(el), 4000);
}
function sbDetachListener() {
if (sbSkipListener && sbBoundVideo) {
sbBoundVideo.removeEventListener('timeupdate', sbSkipListener);
}
sbSkipListener = null;
sbBoundVideo = null;
}
function attachSkipListener(video) {
if (sbBoundVideo === video && sbSkipListener) return;
sbDetachListener();
sbBoundVideo = video;
sbSkipListener = () => {
if (!sbEnabled || sbSegments.length === 0) return;
const t = video.currentTime;
for (const seg of sbSegments) {
const [start, end] = seg.segment;
if (sbSkippedSegmentIds.has(segmentId(seg))) continue;
if (t >= start && t < end - 0.5) {
sbLastSkipFrom = t;
sbLastSkipSegment = seg;
video.currentTime = end;
showSkipNotification(seg.category, t);
const savedSeconds = end - t;
chrome.storage.local.get(['sbTotalSkipped', 'sbTotalTimeSaved'], (data) => {
chrome.storage.local.set({
sbTotalSkipped: (data.sbTotalSkipped || 0) + 1,
sbTotalTimeSaved: (data.sbTotalTimeSaved || 0) + savedSeconds
});
});
break;
}
}
};
video.addEventListener('timeupdate', sbSkipListener);
}
function sbTryAttachToVideo() {
if (!sbEnabled || sbSegments.length === 0) return;
const video = document.querySelector('video');
if (video && video !== sbBoundVideo) {
attachSkipListener(video);
}
}
function sbResetState() {
sbDetachListener();
removeSegmentMarkers();
sbSkippedSegmentIds.clear();
// Segments belong to the video we are leaving; keeping them would skip the
// next video at the previous one's timestamps.
sbSegments = [];
sbSegmentsVideoId = null;
sbRetryAfter = 0;
sbLastSkipFrom = null;
sbLastSkipSegment = null;
}
async function sbCheckVideo() {
if (!isYouTubeWatchPage() || !sbEnabled) return;
const videoId = getYouTubeVideoId();
if (!videoId) return;
// The cooldown only holds back retries for the same video; a new one is
// never made to wait out the previous video's failure.
const isSameVideo = videoId === sbCurrentVideoId;
const needsSegments = videoId !== sbSegmentsVideoId
&& !sbFetching
&& (!isSameVideo || Date.now() >= sbRetryAfter);
if (needsSegments) {
if (!isSameVideo) {
sbResetState();
sbCurrentVideoId = videoId;
}
sbFetching = true;
const result = await fetchSponsorSegments(videoId, sbCategories);
sbFetching = false;
// A navigation during the request makes this answer worthless.
if (getYouTubeVideoId() !== videoId) return;
sbSegments = result.segments;
// Only a trusted answer marks the video as done; after a failure the id
// stays unset so the periodic check retries after a short cooldown.
sbSegmentsVideoId = result.ok ? videoId : null;
sbRetryAfter = result.ok ? 0 : Date.now() + SB_RETRY_COOLDOWN;
}
sbTryAttachToVideo();
renderSegmentMarkers();
}
function sbStartVideoCheck() {
if (sbVideoCheckInterval) clearInterval(sbVideoCheckInterval);
sbVideoCheckInterval = setInterval(() => {
if (!sbEnabled || !isYouTubeWatchPage()) return;
// Also covers a video whose fetch failed: its id is still unconfirmed.
const videoId = getYouTubeVideoId();
if (videoId && videoId !== sbSegmentsVideoId) {
sbCheckVideo();
return;
}
sbTryAttachToVideo();
}, 1500);
}
function sbSetupNavigationListener() {
if (sbNavigationListener) return;
sbNavigationListener = () => {
sbCurrentVideoId = null;
sbResetState();
sbCheckVideo();
};
document.addEventListener('yt-navigate-finish', sbNavigationListener);
window.addEventListener('popstate', sbNavigationListener);
}
function sbLoadSettings(callback) {
chrome.storage.local.get(['sbEnabled', 'sbCategories'], (res) => {
sbEnabled = res.sbEnabled === true;
sbCategories = res.sbCategories || ['sponsor'];
if (callback) callback();
});
}
function sbInit() {
if (!isYouTube()) return;
sbLoadSettings(() => {
sbCheckVideo();
sbSetupNavigationListener();
sbStartVideoCheck();
});
}
function removeSegmentMarkers() {
const container = document.getElementById('sb-segment-markers');
if (container) container.remove();
}
function createMarkerElement(start, end, duration) {
const leftPct = (start / duration) * 100;
const rightPct = 100 - (end / duration) * 100;
const bar = document.createElement('li');
bar.style.cssText = [
'position: absolute',
'height: 100%',
`left: ${leftPct}%`,
`right: ${rightPct}%`,
'background: #00d400',
'opacity: 0.7',
'pointer-events: none'
].join(';');
bar.innerHTML = ' ';
return bar;
}
function renderSegmentMarkers() {
removeSegmentMarkers();
if (!sbEnabled || sbSegments.length === 0 || !sbBoundVideo) return;
const duration = sbBoundVideo.duration;
if (!duration || !isFinite(duration)) {
sbBoundVideo.addEventListener('loadedmetadata', () => renderSegmentMarkers(), { once: true });
return;
}
const progressBar = document.querySelector('.ytp-progress-bar-container');
if (!progressBar) return;
const container = document.createElement('ul');
container.id = 'sb-segment-markers';
container.style.cssText = [
'position: absolute',
'top: 0',
'left: 0',
'width: 100%',
'height: 100%',
'margin: 0',
'padding: 0',
'list-style: none',
'pointer-events: none',
'z-index: 41'
].join(';');
for (const seg of sbSegments) {
const [start, end] = seg.segment;
container.appendChild(createMarkerElement(start, end, duration));
}
progressBar.prepend(container);
}
// --- End SponsorBlock ---
// --- YouTube Speed Panel ---
// The chips used to copy their colours off a neighbouring button on every
// observer tick. Every click spawns the speed notification, which is itself
// a mutation, so the sampling re-ran constantly and any odd neighbour — an
// icon button with a transparent background, a row mid-render — leaked into
// our own look. YouTube's theme variables are inherited by our nodes anyway,
// so the stylesheet reads them directly and nothing touches inline styles.
function injectSpeedPanelStyles() {
if (document.getElementById('vsc-yt-styles')) return;
const style = document.createElement('style');
style.id = 'vsc-yt-styles';
// Everything is static: geometry keeps both chips the same size, and the
// colours come from YouTube's own theme variables, which our nodes inherit.
// The html[dark] pair is only a fallback for when those variables are gone.
style.textContent = `
#vsc-speed-panel,
#vsc-summary-btn {
box-sizing: border-box;
height: 36px;
border: none;
/* Large enough to stay a capsule at any height. */
border-radius: 999px;
background: var(--yt-spec-badge-chip-background, rgba(0, 0, 0, 0.05));
color: var(--yt-spec-text-primary, #0f0f0f);
font-family: "Roboto", "Arial", sans-serif;
font-size: 14px;
font-weight: 500;
user-select: none;
transition: box-shadow 0.15s;
}
html[dark] #vsc-speed-panel,
html[dark] #vsc-summary-btn {
background: var(--yt-spec-badge-chip-background, rgba(255, 255, 255, 0.1));
color: var(--yt-spec-text-primary, #fff);
}
/* Tints follow the text colour, so they work in either theme. */
#vsc-summary-btn:hover {
box-shadow: inset 0 0 0 999px color-mix(in srgb, currentColor 10%, transparent);
}
#vsc-speed-panel {
display: inline-flex;
align-items: center;
gap: 2px;
margin-right: 8px;
padding: 0 2px;
}
#vsc-speed-panel button {
border: none;
background: transparent;
color: inherit;
font-size: 12px;
width: 26px;
height: 26px;
border-radius: 50%;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
transition: background 0.15s;
}
#vsc-speed-panel button:hover {
background: color-mix(in srgb, currentColor 18%, transparent);
}
#vsc-speed-panel .vsc-speed-label {
display: inline-flex;
/* Bottom edges line up, so the smaller × hangs at the baseline. */
align-items: flex-end;
justify-content: center;
gap: 2px;
color: inherit;
font-size: 14px;
font-weight: 600;
line-height: 1;
cursor: pointer;
padding: 0 2px;
min-width: 38px;
font-variant-numeric: tabular-nums;
}
#vsc-speed-panel .vsc-speed-x {
font-size: 11px;
font-weight: 500;
line-height: 1;
opacity: 0.75;
}
#vsc-speed-panel .vsc-speed-label:hover {
text-decoration: underline;
}
#vsc-summary-btn {
display: inline-flex;
align-items: center;
justify-content: center;
margin-right: 8px;
padding: 0 16px;
cursor: pointer;
}
`;
document.head.appendChild(style);
}
function getCleanVideoUrl() {
const id = new URLSearchParams(window.location.search).get('v');
return id ? `https://www.youtube.com/watch?v=${id}` : window.location.href;
}
function handleSummaryClick(btn) {
const text = t('summaryPrompt').replace('{URL}', getCleanVideoUrl());
navigator.clipboard.writeText(text).catch(() => {});
window.open('https://gemini.google.com/app', '_blank');
const label = btn.querySelector('.vsc-summary-text');
if (label && !btn.dataset.busy) {
btn.dataset.busy = '1';
label.textContent = t('summaryCopied');
setTimeout(() => {
label.textContent = t('summaryBtn');
delete btn.dataset.busy;
}, 1500);
}
}
// Click steps once; holding the button keeps stepping by the same amount.
const HOLD_START_DELAY = 400;
const HOLD_STEP_INTERVAL = 120;
function bindHoldRepeat(button, delta) {
let startTimer = null;
let repeatTimer = null;
let repeating = false;
function stopRepeat() {
clearTimeout(startTimer);
clearInterval(repeatTimer);
startTimer = null;
repeatTimer = null;
}
button.addEventListener('pointerdown', (event) => {
if (event.button !== 0) return;
repeating = false;
startTimer = setTimeout(() => {
repeating = true;
repeatTimer = setInterval(() => changeSpeed(delta), HOLD_STEP_INTERVAL);
}, HOLD_START_DELAY);
});
['pointerup', 'pointerleave', 'pointercancel'].forEach((type) => {
button.addEventListener(type, stopRepeat);
});
button.addEventListener('click', (event) => {
event.stopPropagation();
// The hold already stepped, so its trailing click must not add one more.
if (repeating) {
repeating = false;
return;
}
changeSpeed(delta);
});
}
function isVisible(element) {
return Boolean(element && element.offsetParent);
}
// A watch page carries dozens of #top-level-buttons-computed nodes — every
// recommendation renderer has one — and all but the real action row are
// hidden. Picking blindly used to park the widgets in an invisible one,
// where the "already injected" check then kept them for the rest of the
// page's life, so visibility is what decides here.
function getActionsContainer() {
const scoped = document.querySelectorAll('ytd-watch-metadata #top-level-buttons-computed');
const visibleScoped = Array.from(scoped).find(isVisible);
if (visibleScoped) return visibleScoped;
return Array.from(document.querySelectorAll('#top-level-buttons-computed')).find(isVisible)
|| null;
}
// Re-homes a widget that YouTube left behind in a container it has since
// hidden or replaced. Returns true when the caller has nothing left to do.
function relocateChip(id, container) {
const existing = document.getElementById(id);
if (!existing) return false;
if (existing.parentElement !== container) {
container.prepend(existing);
}
return true;
}
function injectSpeedPanel() {
if (!ytSpeedPanelEnabled || !isYouTubeWatchPage()) return;
const container = getActionsContainer();
if (!container) return;
if (relocateChip('vsc-speed-panel', container)) return;
injectSpeedPanelStyles();
const panel = document.createElement('div');
panel.id = 'vsc-speed-panel';
const btnDec = document.createElement('button');
btnDec.textContent = '\u25C0';
btnDec.title = t('ytDecreaseTitle');
bindHoldRepeat(btnDec, -0.1);
// The value and the × are separate nodes so the × can sit on the baseline
// instead of being centred against the digits.
const value = document.createElement('span');
value.className = 'vsc-speed-value';
value.textContent = currentSpeed.toFixed(1);
const times = document.createElement('span');
times.className = 'vsc-speed-x';
times.textContent = '×';
const label = document.createElement('span');
label.className = 'vsc-speed-label';
label.append(value, times);
label.title = t('ytResetTitle');
label.addEventListener('click', (e) => {
e.stopPropagation();
setSpeed(1.0);
showSpeedNotification(1.0);
});
const btnInc = document.createElement('button');
btnInc.textContent = '\u25B6';
btnInc.title = t('ytIncreaseTitle');
bindHoldRepeat(btnInc, 0.1);
panel.appendChild(btnDec);
panel.appendChild(label);
panel.appendChild(btnInc);
container.prepend(panel);
}
function injectSummaryButton() {
if (!ytSummaryBtnEnabled || !isYouTubeWatchPage()) return;
const container = getActionsContainer();
if (!container) return;
if (relocateChip('vsc-summary-btn', container)) return;
injectSpeedPanelStyles();
const summaryBtn = document.createElement('button');
summaryBtn.id = 'vsc-summary-btn';
summaryBtn.title = t('summaryTitle');
const label = document.createElement('span');
label.className = 'vsc-summary-text';
label.textContent = t('summaryBtn');
summaryBtn.appendChild(label);
summaryBtn.addEventListener('click', (e) => {
e.stopPropagation();
handleSummaryClick(summaryBtn);
});
container.prepend(summaryBtn);
}
function updateSpeedPanel() {
const value = document.querySelector('#vsc-speed-panel .vsc-speed-value');
if (value) value.textContent = currentSpeed.toFixed(1);
}
function removeSpeedPanel() {
const panel = document.getElementById('vsc-speed-panel');
if (panel) panel.remove();
}
function removeSummaryButton() {
const summaryBtn = document.getElementById('vsc-summary-btn');
if (summaryBtn) summaryBtn.remove();
}
function syncYouTubeWidgets() {
if (!isYouTubeWatchPage()) {
removeSpeedPanel();
removeSummaryButton();
return;
}
injectSpeedPanel();
injectSummaryButton();
}
function setupYouTubeWidgetObserver() {
if (!isYouTube()) return;
let debounceTimer = null;
const scheduleSync = () => {
if (!ytSpeedPanelEnabled && !ytSummaryBtnEnabled) return;
if (debounceTimer) return;
debounceTimer = setTimeout(() => {
debounceTimer = null;
syncYouTubeWidgets();
}, 300);
};
new MutationObserver(scheduleSync).observe(document.body, { childList: true, subtree: true });
// In-page navigation reuses existing nodes, so a childList mutation is not
// guaranteed to follow. SponsorBlock already tracks the same two events.
document.addEventListener('yt-navigate-finish', scheduleSync);
window.addEventListener('popstate', scheduleSync);
// Last resort: anything the observer misses is picked up on the next tick.
setInterval(scheduleSync, WIDGET_SELF_CHECK_INTERVAL);
}
function loadYouTubeWidgetSettings(callback) {
chrome.storage.local.get(['ytSpeedPanel', 'ytSummaryBtn'], (settings) => {
ytSpeedPanelEnabled = settings.ytSpeedPanel === true;
// The Summary button used to be bundled with the speed panel setting.
ytSummaryBtnEnabled = settings.ytSummaryBtn === undefined
? settings.ytSpeedPanel === true
: settings.ytSummaryBtn === true;
if (callback) callback();
});
}
function initYouTubeWidgets() {
if (!isYouTube()) return;
loadYouTubeWidgetSettings(() => {
setupYouTubeWidgetObserver();
syncYouTubeWidgets();
});
}
// --- End YouTube Speed Panel ---
function applyInitialState(state) {
currentSpeed = typeof state?.speed === 'number' ? state.speed : 1.0;
autoApplySpeed = state?.autoApply !== false;
if (autoApplySpeed) {
setSpeed(currentSpeed, { notifyBackground: false });
} else {
setSpeedForAllVideos(1.0);
}
updateSpeedPanel();
}
function initialize() {
observeNewVideos();
startSpeedSync();
sbInit();
initYouTubeWidgets();
// The background handshake comes last and guarded. It used to wrap the
// whole setup, so a sleeping or just-reloaded service worker left the tab
// with no widgets at all until the page was reloaded.
try {
chrome.runtime.sendMessage({ type: 'GET_TAB_STATE' }, (response) => {
if (chrome.runtime.lastError) return;
applyInitialState(response?.state);
});
} catch (error) {
console.warn('Video Speed Control: background unavailable, keeping defaults', error);
}
}
document.addEventListener('keydown', (event) => {
const activeElement = document.activeElement;
const isInputField = activeElement && (
activeElement.tagName === 'INPUT'
|| activeElement.tagName === 'TEXTAREA'
|| activeElement.contentEditable === 'true'
);
if (isInputField) {
return;
}
function matchHotkey(hotkey, e) {
if (!hotkey) {
return false;
}
return !!e.ctrlKey === !!hotkey.ctrl
&& !!e.shiftKey === !!hotkey.shift
&& !!e.altKey === !!hotkey.alt
&& !!e.metaKey === !!hotkey.meta
&& e.key.toLowerCase() === hotkey.key.toLowerCase();
}
if (matchHotkey(currentHotkeys.decrease, event)) {
event.preventDefault();
changeSpeed(-0.1);
return;
}
if (matchHotkey(currentHotkeys.increase, event)) {
event.preventDefault();
changeSpeed(0.1);
return;
}
if (matchHotkey(currentHotkeys.reset, event)) {
event.preventDefault();
setSpeed(1.0);
showSpeedNotification(1.0);
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
switch (request.type) {
case 'SET_SPEED': {
setSpeed(request.value);
sendResponse({ success: true, videosFound: document.querySelectorAll('video').length, currentSpeed });
break;