-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1691 lines (1516 loc) · 59.3 KB
/
script.js
File metadata and controls
1691 lines (1516 loc) · 59.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
// Smooth scroll for navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
// Theme toggle
const THEME_STORAGE_KEY = 'sim1-theme';
const themeToggleBtn = document.getElementById('themeToggleBtn');
function applyTheme(theme) {
const isLight = theme === 'light';
document.body.classList.toggle('theme-light', isLight);
if (themeToggleBtn) {
themeToggleBtn.setAttribute('aria-pressed', String(isLight));
themeToggleBtn.querySelector('.theme-toggle-text').textContent = isLight ? 'Light' : 'Night';
themeToggleBtn.setAttribute('aria-label', isLight ? 'Switch to night mode' : 'Switch to light mode');
}
window.dispatchEvent(new CustomEvent('sim1-themechange', { detail: { theme } }));
}
const savedTheme = localStorage.getItem(THEME_STORAGE_KEY) || 'dark';
applyTheme(savedTheme);
if (themeToggleBtn) {
themeToggleBtn.addEventListener('click', () => {
const nextTheme = document.body.classList.contains('theme-light') ? 'dark' : 'light';
localStorage.setItem(THEME_STORAGE_KEY, nextTheme);
applyTheme(nextTheme);
updateNavbarBackground();
});
}
// Back to top button
const backToTopBtn = document.getElementById('backToTopBtn');
function updateBackToTopVisibility() {
if (!backToTopBtn) return;
backToTopBtn.classList.toggle('is-visible', window.pageYOffset > 500);
}
if (backToTopBtn) {
backToTopBtn.addEventListener('click', () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
}
// Scroll progress bar
const scrollProgress = document.querySelector('.scroll-progress');
window.addEventListener('scroll', () => {
const windowHeight = document.documentElement.scrollHeight - window.innerHeight;
const scrolled = (window.scrollY / windowHeight) * 100;
scrollProgress.style.width = scrolled + '%';
updateBackToTopVisibility();
});
updateBackToTopVisibility();
// Navbar background on scroll
const navbar = document.querySelector('.navbar');
function updateNavbarBackground() {
if (!navbar) return;
const styles = getComputedStyle(document.body);
const bg = window.pageYOffset > 100
? styles.getPropertyValue('--navbar-bg-scrolled').trim()
: styles.getPropertyValue('--navbar-bg').trim();
navbar.style.backgroundColor = bg;
}
window.addEventListener('scroll', () => {
const currentScroll = window.pageYOffset;
void currentScroll;
updateNavbarBackground();
});
updateNavbarBackground();
// Newsletter form handling
const newsletterForm = document.querySelector('.newsletter-form');
if (newsletterForm) {
newsletterForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = newsletterForm.querySelector('.email-input').value;
if (email) {
// Show success message
const btn = newsletterForm.querySelector('.submit-btn');
const originalText = btn.textContent;
btn.textContent = 'Subscribed!';
btn.style.background = 'var(--success)';
setTimeout(() => {
btn.textContent = originalText;
btn.style.background = '';
newsletterForm.reset();
}, 3000);
}
});
}
// Intersection Observer for fade-in animations
const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.opacity = '1';
entry.target.style.transform = 'translateY(0)';
}
});
}, observerOptions);
// Observe all sections
document.querySelectorAll('.section').forEach(section => {
section.style.opacity = '0';
section.style.transform = 'translateY(20px)';
section.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
observer.observe(section);
});
// ── Adaptive video loading (viewport priority + super low → low → HQ) ──
// Mirror: videos/… → videos_super_low/… → videos_low/… (ffmpeg; missing tier falls back).
window.SIM1 = window.SIM1 || {};
SIM1.heroTryAutoplay = () => {};
(function initAdaptiveVideoLoading() {
const adaptiveVideos = new Set();
const adaptiveState = new WeakMap();
const hqRingMeta = new WeakMap();
const MAX_CONCURRENT_HQ = 2;
const MAX_CONCURRENT_LOW = 2;
let hqUpgradeCount = 0;
let lowUpgradeCount = 0;
/** Gate YouTube until every adaptive video with superUrl has tried super (canplay or error → fallback). */
const youtubeSuperPending = new Set();
const youtubeSuperReadyCallbacks = [];
function markYoutubeSuperReady(v) {
if (!youtubeSuperPending.has(v)) return;
youtubeSuperPending.delete(v);
if (youtubeSuperPending.size === 0) {
youtubeSuperReadyCallbacks.splice(0).forEach((fn) => {
try {
fn();
} catch (e) {}
});
}
}
SIM1.onAllSuperLowReadyForYoutube = function (cb) {
if (typeof cb !== 'function') return;
if (youtubeSuperPending.size === 0) cb();
else youtubeSuperReadyCallbacks.push(cb);
};
const IO_OPTS = { rootMargin: '75% 0px 75% 0px', threshold: [0, 0.05, 0.15, 0.35, 0.6, 1] };
function toSuperLowUrl(hqUrl) {
if (!hqUrl || !hqUrl.startsWith('videos/')) return null;
return 'videos_super_low/' + hqUrl.slice('videos/'.length);
}
function toLowUrl(hqUrl) {
if (!hqUrl || !hqUrl.startsWith('videos/')) return null;
return 'videos_low/' + hqUrl.slice('videos/'.length);
}
function viewportCenterScore(el) {
const r = el.getBoundingClientRect();
if (r.width < 2 && r.height < 2) return -1e9;
const cy = (r.top + r.bottom) / 2;
const mid = window.innerHeight * 0.5;
return 1000 - Math.abs(cy - mid);
}
function bufferedFraction(v) {
if (!v.duration || !Number.isFinite(v.duration) || v.duration <= 0) return 0;
let end = 0;
for (let i = 0; i < v.buffered.length; i++) {
end = Math.max(end, v.buffered.end(i));
}
return Math.min(1, end / v.duration);
}
/** Off-DOM preload so current tier keeps playing until next tier is buffered. `onReady(preloadEl)`. */
function preloadVideoUrl(url, onReady, onError, ringOpts) {
let settled = false;
const p = document.createElement('video');
p.muted = true;
p.setAttribute('playsinline', '');
p.preload = 'auto';
p.style.cssText =
'position:absolute;left:-9999px;top:0;width:2px;height:2px;opacity:0;pointer-events:none;visibility:hidden';
p.src = url;
document.body.appendChild(p);
p.load();
if (ringOpts && ringOpts.mainVideo && ringOpts.st) {
startTierRingLoad(ringOpts.mainVideo, ringOpts.st, p);
}
const finishOk = () => {
if (settled) return;
settled = true;
onReady(p);
if (p.parentNode) p.parentNode.removeChild(p);
};
const finishErr = () => {
if (settled) return;
settled = true;
if (p.parentNode) p.parentNode.removeChild(p);
onError();
};
p.addEventListener('canplaythrough', finishOk, { once: true });
p.addEventListener('error', finishErr, { once: true });
p.addEventListener(
'canplay',
() => {
if (p.readyState >= 3) finishOk();
},
{ once: true }
);
}
function freezeCurrentFrameAsPoster(v) {
try {
const w = v.videoWidth;
const h = v.videoHeight;
if (!w || !h) return;
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
canvas.getContext('2d').drawImage(v, 0, 0);
v.poster = canvas.toDataURL('image/jpeg', 0.82);
} catch (e) {}
}
function clearTierPoster(v) {
v.removeAttribute('poster');
}
/** After preload, swap main element src; poster hides decode gap. */
function swapMainToUrl(v, st, url, nextPhase, savedTime, wasPlaying, onDone, onFail) {
const vw = v.closest('.video-wrapper');
if (vw) vw.classList.add('demo-poster-ready');
freezeCurrentFrameAsPoster(v);
v.src = url;
v.load();
if (st._ringProgressEl && st._ringProgressEl !== v) {
retargetTierRingProgress(v, st, v);
}
let applied = false;
const apply = () => {
if (applied) return;
applied = true;
stopHqRingLoad(v, st);
v.removeEventListener('canplaythrough', onCap);
v.removeEventListener('canplay', onCp);
v.removeEventListener('error', onErr);
clearTierPoster(v);
st.phase = nextPhase;
if (v.duration && Number.isFinite(v.duration)) {
v.currentTime = Math.min(Math.max(0, savedTime), Math.max(0, v.duration - 0.05));
}
if (wasPlaying) tryPlayAdaptive(v);
if (onDone) onDone();
};
const onCap = () => apply();
const onCp = () => {
if (v.readyState >= 3) apply();
};
const onErr = () => {
if (applied) return;
applied = true;
stopHqRingLoad(v, st);
v.removeEventListener('canplaythrough', onCap);
v.removeEventListener('canplay', onCp);
v.removeEventListener('error', onErr);
clearTierPoster(v);
if (onFail) onFail();
};
v.addEventListener('canplaythrough', onCap, { once: true });
v.addEventListener('canplay', onCp, { once: true });
v.addEventListener('error', onErr, { once: true });
}
function attachHqRing(v) {
if (hqRingMeta.has(v)) return;
const host = v.closest('.solver-vid-wrap, .method-video-wrapper, .video-wrapper') || v.parentElement;
if (!host) return;
const wrap = document.createElement('div');
wrap.className = 'video-hq-ring';
wrap.setAttribute('aria-hidden', 'true');
wrap.innerHTML =
'<svg viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true">' +
'<circle class="video-hq-ring-track" cx="12" cy="12" r="9" fill="none" stroke="rgba(255,255,255,0.16)" stroke-width="2"/>' +
'<circle class="video-hq-ring-prog" cx="12" cy="12" r="9" fill="none" stroke="rgba(255,255,255,0.72)" stroke-width="2" ' +
'stroke-linecap="round" transform="rotate(-90 12 12)"/>' +
'</svg>';
host.appendChild(wrap);
const prog = wrap.querySelector('.video-hq-ring-prog');
const R = 9;
const circumference = 2 * Math.PI * R;
prog.style.strokeDasharray = String(circumference);
prog.style.strokeDashoffset = String(circumference);
hqRingMeta.set(v, { wrap, prog, circumference });
}
function updateTierRingProgress(mediaEl) {
const owner = mediaEl._tierRingOwner != null ? mediaEl._tierRingOwner : mediaEl;
const m = hqRingMeta.get(owner);
if (!m) return;
if (!m.wrap.classList.contains('is-visible')) return;
const dur = mediaEl.duration;
let frac = 0;
if (dur && Number.isFinite(dur) && dur > 0) {
frac = bufferedFraction(mediaEl);
}
m.prog.style.strokeDashoffset = String(m.circumference * (1 - frac));
m.wrap.classList.toggle('video-hq-ring--pulse', frac < 0.02 && !(dur && dur > 0));
}
function stopHqRingLoad(v, st) {
if (!st) return;
const srcEl = st._ringProgressEl || v;
if (st._ringOnProg) {
srcEl.removeEventListener('progress', st._ringOnProg);
st._ringOnProg = null;
}
if (st._ringOnCap) {
srcEl.removeEventListener('canplaythrough', st._ringOnCap);
st._ringOnCap = null;
}
if (st._ringInterval) {
clearInterval(st._ringInterval);
st._ringInterval = null;
}
st._ringProgressEl = null;
st.ringSession = (st.ringSession || 0) + 1;
const m = hqRingMeta.get(v);
if (m) {
m.wrap.classList.remove('is-visible', 'video-hq-ring--pulse');
}
}
/** Ring tracks `progressSource` (preload element or main <video>). `v` = main video for DOM placement. */
function startTierRingLoad(v, st, progressSource) {
const ps = progressSource || v;
stopHqRingLoad(v, st);
attachHqRing(v);
const m = hqRingMeta.get(v);
if (!m) return;
ps._tierRingOwner = v;
st._ringProgressEl = ps;
const sid = st.ringSession;
m.wrap.classList.add('is-visible');
updateTierRingProgress(ps);
const cleanup = () => {
if (st.ringSession !== sid) return;
const el = st._ringProgressEl || v;
if (st._ringOnProg) {
el.removeEventListener('progress', st._ringOnProg);
st._ringOnProg = null;
}
if (st._ringOnCap) {
el.removeEventListener('canplaythrough', st._ringOnCap);
st._ringOnCap = null;
}
if (st._ringInterval) {
clearInterval(st._ringInterval);
st._ringInterval = null;
}
st._ringProgressEl = null;
if (el && el._tierRingOwner === v) delete el._tierRingOwner;
m.wrap.classList.remove('is-visible', 'video-hq-ring--pulse');
};
const onProg = () => {
if (st.ringSession !== sid) return;
const el = st._ringProgressEl || v;
updateTierRingProgress(el);
};
st._ringOnProg = onProg;
st._ringOnCap = null;
ps.addEventListener('progress', onProg);
st._ringInterval = window.setInterval(() => {
onProg();
}, 280);
window.setTimeout(() => {
if (st.ringSession === sid) cleanup();
}, 120000);
}
function retargetTierRingProgress(v, st, newSource) {
const old = st._ringProgressEl || v;
if (old && old._tierRingOwner === v) delete old._tierRingOwner;
newSource._tierRingOwner = v;
if (st._ringOnProg) {
old.removeEventListener('progress', st._ringOnProg);
newSource.addEventListener('progress', st._ringOnProg);
}
st._ringProgressEl = newSource;
updateTierRingProgress(newSource);
}
function tryPlayAdaptive(v) {
if (v.id === 'demoVideo') {
SIM1.heroTryAutoplay();
return;
}
v.play().catch(() => {});
}
function loadHqFallback(v, st) {
st.phase = 'loading-hq';
preloadVideoUrl(
st.hqUrl,
() => {
freezeCurrentFrameAsPoster(v);
v.src = st.hqUrl;
v.load();
retargetTierRingProgress(v, st, v);
let applied = false;
const apply = () => {
if (applied) return;
applied = true;
stopHqRingLoad(v, st);
clearTierPoster(v);
st.phase = 'hq';
tryPlayAdaptive(v);
};
v.addEventListener('canplaythrough', apply, { once: true });
v.addEventListener('canplay', () => {
if (v.readyState >= 3) apply();
}, { once: true });
v.addEventListener('error', () => {
st.phase = 'idle';
stopHqRingLoad(v, st);
clearTierPoster(v);
}, { once: true });
},
() => {
st.phase = 'idle';
stopHqRingLoad(v, st);
},
{ mainVideo: v, st: st }
);
}
function loadLowOrHqFromIdle(v, st) {
if (st.lowUrl) {
st.phase = 'loading-low';
preloadVideoUrl(
st.lowUrl,
() => {
swapMainToUrl(
v,
st,
st.lowUrl,
'low',
0,
false,
() => scheduleHqUpgrades(),
() => loadHqFallback(v, st)
);
},
() => {
stopHqRingLoad(v, st);
loadHqFallback(v, st);
},
{ mainVideo: v, st: st }
);
} else {
loadHqFallback(v, st);
}
}
function beginSuperLoad(v, st) {
if (st.phase !== 'idle' || !st.superUrl) return;
st.phase = 'loading-super';
const onSuperErr = () => {
v.removeEventListener('error', onSuperErr);
v.removeEventListener('canplay', onSuperOk);
markYoutubeSuperReady(v);
loadLowOrHqFromIdle(v, st);
};
const onSuperOk = () => {
v.removeEventListener('error', onSuperErr);
st.phase = 'super';
markYoutubeSuperReady(v);
tryPlayAdaptive(v);
scheduleLowUpgrades();
scheduleHqUpgrades();
};
v.addEventListener('error', onSuperErr);
v.addEventListener('canplay', onSuperOk, { once: true });
v.src = st.superUrl;
v.load();
}
function ensureAdaptiveLoad(v, st) {
if (!st.inView) return;
if (st.upgrading || st.upgradingLow) return;
if (st.phase === 'hq') {
tryPlayAdaptive(v);
return;
}
if (st.phase === 'low' && v.readyState >= 2 && !v.error) {
tryPlayAdaptive(v);
return;
}
if (st.phase === 'super' && v.readyState >= 2 && !v.error) {
tryPlayAdaptive(v);
return;
}
if (st.phase === 'loading-super' || st.phase === 'loading-low' || st.phase === 'loading-hq') return;
if (st.phase === 'idle') {
if (st.superUrl) {
beginSuperLoad(v, st);
} else {
loadLowOrHqFromIdle(v, st);
}
}
}
function startLowUpgrade(v, st) {
if (st.phase !== 'super' || st.upgradingLow || !st.lowUrl || !st.inView) return;
st.upgradingLow = true;
lowUpgradeCount++;
const savedTime = v.currentTime;
const wasPlaying = !v.paused;
const handleLowTierFail = () => {
stopHqRingLoad(v, st);
st.upgradingLow = false;
lowUpgradeCount--;
if (st.hqUrl) {
startHqUpgradeFromSuperAfterLowFail(v, st, savedTime, wasPlaying);
}
scheduleLowUpgrades();
};
preloadVideoUrl(
st.lowUrl,
() => {
swapMainToUrl(
v,
st,
st.lowUrl,
'low',
savedTime,
wasPlaying,
() => {
st.upgradingLow = false;
lowUpgradeCount--;
scheduleHqUpgrades();
scheduleLowUpgrades();
},
handleLowTierFail
);
},
handleLowTierFail,
{ mainVideo: v, st: st }
);
}
/** Low tier preload failed while still on super — try HQ with same smooth swap. */
function startHqUpgradeFromSuperAfterLowFail(v, st, savedTime, wasPlaying) {
if (!st.hqUrl || st.upgrading) return;
st.upgrading = true;
hqUpgradeCount++;
preloadVideoUrl(
st.hqUrl,
() => {
freezeCurrentFrameAsPoster(v);
v.src = st.hqUrl;
v.load();
retargetTierRingProgress(v, st, v);
let applied = false;
const apply = () => {
if (applied) return;
applied = true;
stopHqRingLoad(v, st);
clearTierPoster(v);
st.phase = 'hq';
st.upgrading = false;
hqUpgradeCount--;
if (v.duration && Number.isFinite(v.duration)) {
v.currentTime = Math.min(Math.max(0, savedTime), Math.max(0, v.duration - 0.05));
}
if (wasPlaying) tryPlayAdaptive(v);
scheduleHqUpgrades();
};
v.addEventListener('canplaythrough', apply, { once: true });
v.addEventListener('canplay', () => {
if (v.readyState >= 3) apply();
}, { once: true });
v.addEventListener(
'error',
() => {
st.upgrading = false;
hqUpgradeCount--;
stopHqRingLoad(v, st);
clearTierPoster(v);
scheduleHqUpgrades();
},
{ once: true }
);
},
() => {
st.upgrading = false;
hqUpgradeCount--;
stopHqRingLoad(v, st);
scheduleHqUpgrades();
},
{ mainVideo: v, st: st }
);
}
function scheduleLowUpgrades() {
if (lowUpgradeCount >= MAX_CONCURRENT_LOW) return;
const candidates = [];
for (const v of adaptiveVideos) {
const st = adaptiveState.get(v);
if (!st || st.phase !== 'super' || st.upgradingLow || !st.inView || !st.lowUrl) continue;
candidates.push({ v, st, score: viewportCenterScore(v) });
}
candidates.sort((a, b) => b.score - a.score);
for (const { v, st } of candidates) {
if (lowUpgradeCount >= MAX_CONCURRENT_LOW) break;
if (st.phase !== 'super' || st.upgradingLow) continue;
startLowUpgrade(v, st);
}
}
function startHqUpgrade(v, st) {
const fromLow = st.phase === 'low' && st.lowUrl;
const fromSuperNoLow = st.phase === 'super' && !st.lowUrl && st.hqUrl;
if ((!fromLow && !fromSuperNoLow) || st.upgrading) return;
st.upgrading = true;
hqUpgradeCount++;
const savedTime = v.currentTime;
const wasPlaying = !v.paused;
const onFail = () => {
st.upgrading = false;
hqUpgradeCount--;
stopHqRingLoad(v, st);
scheduleHqUpgrades();
};
preloadVideoUrl(
st.hqUrl,
() => {
freezeCurrentFrameAsPoster(v);
v.src = st.hqUrl;
v.load();
retargetTierRingProgress(v, st, v);
let applied = false;
const apply = () => {
if (applied) return;
applied = true;
stopHqRingLoad(v, st);
clearTierPoster(v);
st.phase = 'hq';
st.upgrading = false;
hqUpgradeCount--;
if (v.duration && Number.isFinite(v.duration)) {
v.currentTime = Math.min(Math.max(0, savedTime), Math.max(0, v.duration - 0.05));
}
if (wasPlaying) tryPlayAdaptive(v);
scheduleHqUpgrades();
};
v.addEventListener('canplaythrough', apply, { once: true });
v.addEventListener('canplay', () => {
if (v.readyState >= 3) apply();
}, { once: true });
v.addEventListener('error', onFail, { once: true });
},
onFail,
{ mainVideo: v, st: st }
);
}
function scheduleHqUpgrades() {
if (hqUpgradeCount >= MAX_CONCURRENT_HQ) return;
const candidates = [];
for (const v of adaptiveVideos) {
const st = adaptiveState.get(v);
if (!st || st.upgrading || !st.inView || !st.hqUrl) continue;
if (st.phase === 'low' && st.lowUrl) {
candidates.push({ v, st, score: viewportCenterScore(v) });
} else if (st.phase === 'super' && !st.lowUrl) {
candidates.push({ v, st, score: viewportCenterScore(v) });
}
}
candidates.sort((a, b) => b.score - a.score);
for (const { v, st } of candidates) {
if (hqUpgradeCount >= MAX_CONCURRENT_HQ) break;
if (st.upgrading) continue;
if (!(st.phase === 'low' || (st.phase === 'super' && !st.lowUrl))) continue;
startHqUpgrade(v, st);
}
}
const io = new IntersectionObserver((entries) => {
for (const entry of entries) {
const v = entry.target;
const st = adaptiveState.get(v);
if (!st) continue;
st.inView = entry.isIntersecting;
st.intersectionRatio = entry.intersectionRatio;
if (entry.isIntersecting) {
ensureAdaptiveLoad(v, st);
scheduleLowUpgrades();
scheduleHqUpgrades();
} else {
v.pause();
}
}
}, IO_OPTS);
function registerAdaptiveVideo(el) {
if (!el || el.tagName !== 'VIDEO' || adaptiveState.has(el)) return;
let hq =
el.dataset.adaptiveHq ||
el.getAttribute('data-adaptive-hq') ||
(el.querySelector('source') && el.querySelector('source').getAttribute('src'));
if (!hq) return;
el.innerHTML = '';
el.dataset.adaptiveHq = hq;
el.preload = 'none';
el.autoplay = false;
const st = {
hqUrl: hq,
lowUrl: toLowUrl(hq),
superUrl: toSuperLowUrl(hq),
phase: 'idle',
upgrading: false,
upgradingLow: false,
inView: false,
intersectionRatio: 0,
ringSession: 0,
_ringInterval: null
};
adaptiveState.set(el, st);
adaptiveVideos.add(el);
if (st.superUrl) {
youtubeSuperPending.add(el);
const ric =
window.requestIdleCallback ||
function (cb) {
return window.setTimeout(() => cb({ didTimeout: false }), 1);
};
ric(
() => {
const s2 = adaptiveState.get(el);
if (s2 && s2.phase === 'idle') beginSuperLoad(el, s2);
},
{ timeout: 4000 }
);
}
io.observe(el);
}
document.querySelectorAll('video.video-adaptive').forEach(registerAdaptiveVideo);
SIM1.registerAdaptiveVideo = registerAdaptiveVideo;
})();
// ── Hero Video Player ──
const demoVideo = document.getElementById('demoVideo');
const demoWrapper = document.querySelector('.video-wrapper');
if (demoVideo && demoWrapper) {
function formatTime(s) {
if (isNaN(s)) return '0:00';
return `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
}
// First frame as poster (JPEG data URL), then play only when poster is ready AND canplay
let heroPosterReady = false;
let heroCanPlay = false;
function tryHeroAutoplay() {
if (!heroPosterReady || !heroCanPlay) return;
demoVideo.play().catch(() => {});
}
function captureHeroPoster() {
if (heroPosterReady) return true;
try {
const w = demoVideo.videoWidth;
const h = demoVideo.videoHeight;
if (!w || !h) return false;
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
canvas.getContext('2d').drawImage(demoVideo, 0, 0);
demoVideo.poster = canvas.toDataURL('image/jpeg', 0.82);
heroPosterReady = true;
demoWrapper.classList.add('demo-poster-ready');
tryHeroAutoplay();
return true;
} catch (e) {
heroPosterReady = true;
demoWrapper.classList.add('demo-poster-ready');
tryHeroAutoplay();
return true;
}
}
demoVideo.addEventListener('loadeddata', function onHeroLoadedData() {
if (captureHeroPoster()) return;
const onSeeked = () => {
demoVideo.removeEventListener('seeked', onSeeked);
captureHeroPoster();
};
demoVideo.addEventListener('seeked', onSeeked);
demoVideo.currentTime = 0;
}, { once: true });
demoVideo.addEventListener('canplay', () => {
heroCanPlay = true;
tryHeroAutoplay();
});
demoVideo.addEventListener('error', () => {
heroPosterReady = true;
demoWrapper.classList.add('demo-poster-ready');
heroCanPlay = true;
tryHeroAutoplay();
});
SIM1.heroTryAutoplay = tryHeroAutoplay;
const progressBar = demoWrapper.querySelector('.progress-bar');
const progressFilled = demoWrapper.querySelector('.progress-filled');
const currentTimeEl = demoWrapper.querySelector('.current-time');
const durationEl = demoWrapper.querySelector('.duration');
const fullscreenBtn = demoWrapper.querySelector('.fullscreen-btn');
// Play state via CSS class
demoVideo.addEventListener('play', () => demoWrapper.classList.add('is-playing'));
demoVideo.addEventListener('pause', () => demoWrapper.classList.remove('is-playing'));
// Toggle play on any play-pause-btn or the video itself
function togglePlay() {
demoVideo.paused ? demoVideo.play() : demoVideo.pause();
}
demoWrapper.querySelectorAll('.play-pause-btn').forEach(btn => btn.addEventListener('click', togglePlay));
demoVideo.addEventListener('click', togglePlay);
// Progress
demoVideo.addEventListener('timeupdate', () => {
if (!demoVideo.duration) return;
progressFilled.style.width = `${(demoVideo.currentTime / demoVideo.duration) * 100}%`;
if (currentTimeEl) currentTimeEl.textContent = formatTime(demoVideo.currentTime);
if (durationEl) durationEl.textContent = formatTime(demoVideo.duration);
});
demoVideo.addEventListener('loadedmetadata', () => {
if (durationEl) durationEl.textContent = formatTime(demoVideo.duration);
});
progressBar && progressBar.addEventListener('click', (e) => {
const pos = (e.clientX - progressBar.getBoundingClientRect().left) / progressBar.offsetWidth;
demoVideo.currentTime = pos * demoVideo.duration;
});
// Fullscreen
fullscreenBtn && fullscreenBtn.addEventListener('click', () => {
document.fullscreenElement ? document.exitFullscreen() : demoWrapper.requestFullscreen();
});
// Keyboard shortcuts (space / arrows)
document.addEventListener('keydown', (e) => {
if (e.target.tagName === 'INPUT') return;
if (e.key === ' ') { e.preventDefault(); togglePlay(); }
if (e.key === 'ArrowLeft') demoVideo.currentTime = Math.max(0, demoVideo.currentTime - 5);
if (e.key === 'ArrowRight') demoVideo.currentTime = Math.min(demoVideo.duration, demoVideo.currentTime + 5);
});
}
// Chart bar animations on scroll
const chartBars = document.querySelectorAll('.bar, .comp-bar');
const chartObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const bar = entry.target;
const originalHeight = bar.style.height;
bar.style.height = '0%';
bar.style.transition = 'height 1s ease-out';
setTimeout(() => {
bar.style.height = originalHeight;
}, 100);
chartObserver.unobserve(bar);
}
});
}, { threshold: 0.5 });
chartBars.forEach(bar => {
chartObserver.observe(bar);
});
// Method card hover effect enhancement
document.querySelectorAll('.method-card').forEach(card => {
card.addEventListener('mouseenter', () => {
card.style.borderColor = 'var(--accent-primary)';
});
card.addEventListener('mouseleave', () => {
card.style.borderColor = 'var(--border-color)';
});
});
// Architecture item animations
document.querySelectorAll('.arch-item').forEach((item, index) => {
item.style.opacity = '0';
item.style.transform = 'translateY(20px)';
item.style.transition = `opacity 0.6s ease ${index * 0.2}s, transform 0.6s ease ${index * 0.2}s`;
setTimeout(() => {
item.style.opacity = '1';
item.style.transform = 'translateY(0)';
}, 500 + index * 200);
});
// Metric card counter animation
const metricCards = document.querySelectorAll('.metric-card');
const metricObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const card = entry.target;
card.style.transform = 'scale(1.05)';
setTimeout(() => {
card.style.transform = 'scale(1)';
}, 300);
metricObserver.unobserve(card);
}
});
}, { threshold: 0.5 });
metricCards.forEach(card => {
card.style.transition = 'transform 0.3s ease';
metricObserver.observe(card);
});
// Copy citation functionality
function fallbackCopyText(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
textarea.style.pointerEvents = 'none';
document.body.appendChild(textarea);
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
const ok = document.execCommand('copy');
document.body.removeChild(textarea);
return ok;
}
async function copyText(text) {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return true;
}
return fallbackCopyText(text);
}
document.querySelectorAll('.citation-copy-btn').forEach((btn) => {
btn.addEventListener('click', async () => {
const codeEl = btn.closest('.citation-box')?.querySelector('code');
if (!codeEl) return;
const ok = await copyText(codeEl.textContent);
if (!ok) return;
const copyIcon = btn.querySelector('.copy-icon');
const checkIcon = btn.querySelector('.check-icon');
copyIcon.style.display = 'none';
checkIcon.style.display = 'block';
btn.classList.add('copied');
setTimeout(() => {
copyIcon.style.display = '';
checkIcon.style.display = 'none';