Extract eager shell and shared view renderers before app boot

This commit is contained in:
Jonathan Sykes
2026-10-08 04:38:37 +08:00
parent cdd26b6ae5
commit 3c9a24ae45
9 changed files with 2198 additions and 2012 deletions

View File

@@ -0,0 +1,40 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const {readFileSync}=require('node:fs');
const {createHash}=require('node:crypto');
const {join}=require('node:path');
const app=readFileSync(join(__dirname,'app.js'),'utf8');
test('Phase 4 preserves the exact player, continuity, tracking and queue bodies',()=>{
{const start=app.indexOf("const Player = {");assert.ok(start>=0,"Player");const body=app.slice(start,start+30343);assert.equal(createHash('sha256').update(body).digest('hex'),"373df46f4f994717472d26a6bac07449f6ca0a930cb666bfe3895d1dc65aa351","Player body unchanged");}
{const start=app.indexOf("const Transition = (() => {");assert.ok(start>=0,"Transition");const body=app.slice(start,start+8588);assert.equal(createHash('sha256').update(body).digest('hex'),"71997a537078308a41f0cbf8e29fd1658fb3a199c4f5a25d8af0931f1c2a6d50","Transition body unchanged");}
{const start=app.indexOf("const Wave = (() => {");assert.ok(start>=0,"Wave");const body=app.slice(start,start+5241);assert.equal(createHash('sha256').update(body).digest('hex'),"7252f4e856c59aef8aabfcd394ce4bcba656110cbd01a1a8af662eeb48166a3c","Wave body unchanged");}
{const start=app.indexOf("const StatsTrack = (() => {");assert.ok(start>=0,"StatsTrack");const body=app.slice(start,start+1462);assert.equal(createHash('sha256').update(body).digest('hex'),"9aae2631ba3bfad918319579b7120814af06c84949394d04e52c65345332d514","StatsTrack body unchanged");}
{const start=app.indexOf("function wirePlayerEvents() {");assert.ok(start>=0,"wirePlayerEvents");const body=app.slice(start,start+4913);assert.equal(createHash('sha256').update(body).digest('hex'),"1c5a2b5ce310f6aef6764325eda85a95f47e4f507f2049036ce1da206379908c","wirePlayerEvents body unchanged");}
{const start=app.indexOf("function updatePlayBtn() {");assert.ok(start>=0,"updatePlayBtn");const body=app.slice(start,start+522);assert.equal(createHash('sha256').update(body).digest('hex'),"1326233af07ae92a5ecc81cc211bd98d21ed5f291dc4eb59d040b8df9baba8c8","updatePlayBtn body unchanged");}
{const start=app.indexOf("function persist() {");assert.ok(start>=0,"persist");const body=app.slice(start,start+147);assert.equal(createHash('sha256').update(body).digest('hex'),"01e5c5dbc80616266db09b3829dc45b66476a3256b1c169d8e44f4983b24ac45","persist body unchanged");}
{const start=app.indexOf("function playFromList(list, index, source = '', { playFull = false } = {}) {");assert.ok(start>=0,"playFromList");const body=app.slice(start,start+401);assert.equal(createHash('sha256').update(body).digest('hex'),"f8009c9674b3478959997dca881fb7b9e1ab3708c98e5abdf1958d752e47ee41","playFromList body unchanged");}
{const start=app.indexOf("function advanceQueue() {");assert.ok(start>=0,"advanceQueue");const body=app.slice(start,start+596);assert.equal(createHash('sha256').update(body).digest('hex'),"be405b9c163e3d41a949ef11f6022ef13115b04083e3b6ad21d97beba1f45ae6","advanceQueue body unchanged");}
{const start=app.indexOf("function playNext() {");assert.ok(start>=0,"playNext");const body=app.slice(start,start+143);assert.equal(createHash('sha256').update(body).digest('hex'),"859d2ffd2e8c89a8d9c0dd0cf429fd403675452cedba2e34aa3dc72683d4f8c6","playNext body unchanged");}
{const start=app.indexOf("function playPrev() {");assert.ok(start>=0,"playPrev");const body=app.slice(start,start+268);assert.equal(createHash('sha256').update(body).digest('hex'),"ece8d33bd03c8146a6a702534c8fed50ff606170685b08d730b19d9d3c68cf48","playPrev body unchanged");}
{const start=app.indexOf("function onTrackEnded() {");assert.ok(start>=0,"onTrackEnded");const body=app.slice(start,start+702);assert.equal(createHash('sha256').update(body).digest('hex'),"d6e147238ad9656fa1c2335973b37597749bcfd02df1a66390b306fe1194ae0d","onTrackEnded body unchanged");}
{const start=app.indexOf("function sleepFadeSec() {");assert.ok(start>=0,"sleepFadeSec");const body=app.slice(start,start+138);assert.equal(createHash('sha256').update(body).digest('hex'),"3f986c8cc474d8313476e9c209b9264e3724011ffaee887f47178bb5155a4d77","sleepFadeSec body unchanged");}
{const start=app.indexOf("function applySleepFade(remaining) {");assert.ok(start>=0,"applySleepFade");const body=app.slice(start,start+346);assert.equal(createHash('sha256').update(body).digest('hex'),"9bd0fa697b271c6b80c128ff1d0a7b00afcb3ccf08f98b5c7e7dc86fd4329681","applySleepFade body unchanged");}
{const start=app.indexOf("function startSleepTimer(minutes, { endOfSong = false } = {}) {");assert.ok(start>=0,"startSleepTimer");const body=app.slice(start,start+487);assert.equal(createHash('sha256').update(body).digest('hex'),"f0a93401ab90196096074cb607b28d52c5903e11dbdfb8ddb95114e143af2409","startSleepTimer body unchanged");}
{const start=app.indexOf("function cancelSleepTimer() {");assert.ok(start>=0,"cancelSleepTimer");const body=app.slice(start,start+253);assert.equal(createHash('sha256').update(body).digest('hex'),"cf396ab758a70eede6af7444539a82ca15af801a9a57024dd5542067e9fa771a","cancelSleepTimer body unchanged");}
{const start=app.indexOf("function finishSleep() {");assert.ok(start>=0,"finishSleep");const body=app.slice(start,start+662);assert.equal(createHash('sha256').update(body).digest('hex'),"7ee93bf760bad5f39f4644339963918c5b369b2acc554b8e561c1a1f070ac6fb","finishSleep body unchanged");}
{const start=app.indexOf("const EQ = (() => {");assert.ok(start>=0,"EQ");const body=app.slice(start,start+7917);assert.equal(createHash('sha256').update(body).digest('hex'),"f0cba011c94f33e6fd0ab778021f4c97238262dfa0a8dd40bf3f17149c227528","EQ body unchanged");}
{const start=app.indexOf("const EqRender = (() => {");assert.ok(start>=0,"EqRender");const body=app.slice(start,start+5912);assert.equal(createHash('sha256').update(body).digest('hex'),"f014dd41dafebc33f09e87be866074afd7a2443c5bb452103a435585353a828f","EqRender body unchanged");}
{const start=app.indexOf("const Level = (() => {");assert.ok(start>=0,"Level");const body=app.slice(start,start+3892);assert.equal(createHash('sha256').update(body).digest('hex'),"e48ad7797384ac31bb8b864662fc2a546b04470b981042f016874ba750957226","Level body unchanged");}
});
test('eager shell and Settings definitions load before app state and defer reading it',()=>{
const html=readFileSync(join(__dirname,'index.html'),'utf8');
for(const file of ['shell-core.js','views-core.js','section-rail.js']) {
assert.ok(html.indexOf('src="'+file+'"')<html.indexOf('src="app.js"'));
const vm=require('node:vm');const context=vm.createContext({window:{},document:{}});
// Evaluation before any data/$/els/Player declaration must be safe.
vm.runInContext(readFileSync(join(__dirname,file),'utf8'),context);
}
const views=readFileSync(join(__dirname,'views-core.js'),'utf8');
assert.ok(views.includes('async function renderSettings()'));
});

File diff suppressed because it is too large Load Diff

View File

@@ -57,7 +57,10 @@
"/feature-bootstrap.js",
"/eq-parameters.js",
"/assets.json",
"/device-db.js"
"/device-db.js",
"/shell-core.js",
"/views-core.js",
"/section-rail.js"
],
"background": false
},
@@ -249,7 +252,8 @@
"embeddedIn": [
"/app.js",
"/settings-sections.js",
"/settings-sections.css"
"/settings-sections.css",
"/views-core.js"
],
"background": false
},

View File

@@ -19,7 +19,7 @@
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="preload" href="fonts/BricolageGrotesque-latin.woff2" as="font" type="font/woff2" crossorigin />
<link rel="preload" href="fonts/HankenGrotesk-latin.woff2" as="font" type="font/woff2" crossorigin />
<script type="application/json" id="ytp-assets">{"buildTag":"static","groups":{"core":{"contract":1,"eager":true,"files":["/index.html","/styles.css","/service-ui.css","/refresh.css","/layout-base.css","/recommendations.css","/flag-ui.js","/async-guard.js","/visible-timer.js","/asset-sync-core.js","/sw-update.js","/fingerprint.js","/opfs.js","/opfs-worker.js","/lyrics-core.js","/lyrics-display.js","/sha256.js","/resume-core.js","/loudness-wasm.js","/loudness.js","/sha256-wasm.js","/settings-sections.js","/related-videos.js","/related-videos.css","/audio-continuity.js","/fullscreen-orientation.js","/fullscreen-orientation.css","/download-actions.js","/download-actions.css","/download-errors.js","/downloads.js","/downloads-page.js","/offline-pages.css","/saved-page.js","/server-backfill.js","/saved-page.css","/prewarm-next.js","/settings-sections.css","/app.js","/manifest.webmanifest","/icons/icon-192.png","/icons/icon-512.png","/fonts/fonts.css","/fonts/BricolageGrotesque-latin-ext.woff2","/fonts/BricolageGrotesque-latin.woff2","/fonts/HankenGrotesk-latin-ext.woff2","/fonts/HankenGrotesk-latin.woff2","/fonts/JetBrainsMono-latin-ext.woff2","/fonts/JetBrainsMono-latin.woff2","/lazy.js","/feature-bootstrap.js","/eq-parameters.js","/assets.json","/device-db.js"],"background":false},"layout:glass-stage":{"contract":1,"eager":false,"files":["/theme-glass.css","/theme-glass-panel.css","/glass-panel-layout.js"],"background":true,"dependencies":["feature:layout-controls"]},"layout:classic":{"contract":1,"eager":false,"files":["/theme-classic.css"],"background":true},"layout:bento-hub":{"contract":1,"eager":false,"files":["/theme-bento-hub.css","/bento-hub.js","/fonts/PlusJakartaSans-latin.woff2","/fonts/PlusJakartaSans-latin-ext.woff2"],"background":true,"dependencies":["feature:layout-controls"]},"layout:f7-swipe":{"contract":1,"eager":false,"files":["/theme-f7.css","/vendor/framework7-swipe.min.js","/f7-layout.js"],"background":true},"feature:piano":{"contract":1,"eager":false,"files":["/piano-core.js","/piano.js","/piano-engine.mjs"],"background":true},"feature:midi":{"contract":1,"eager":false,"files":["/midi.js"],"background":true},"feature:party-dj":{"contract":1,"eager":false,"files":["/party-dj.js"],"background":true},"feature:lyrics-window":{"contract":1,"eager":false,"files":["/lyrics-window.js"],"background":true},"feature:lower-third":{"contract":1,"eager":false,"files":["/lower-third.js","/lower-third.css"],"background":true},"feature:vocal-reducer":{"contract":1,"eager":false,"files":["/vocal-reducer.js"],"background":true},"feature:eq-core":{"contract":1,"eager":false,"files":["/eq-core.js"],"background":true},"feature:setlist-import":{"contract":1,"eager":false,"files":["/setlist-import.js"],"background":true},"feature:car-mode":{"contract":1,"eager":false,"files":["/car-mode.js","/car-mode.css"],"background":true},"feature:p2p":{"contract":1,"eager":false,"files":["/p2p-core.js","/p2p-client.js","/p2p-transfer.js","/p2p-recv-worker.js","/hash-worker.js"],"background":true},"feature:direct":{"contract":1,"eager":false,"files":["/direct-protocol.js","/direct-stream.js","/direct-media.js","/direct-media.css","/direct-recv-worker.js"],"background":true,"dependencies":["feature:p2p"]},"feature:video-edit":{"contract":1,"eager":false,"files":["/video-edit.js"],"background":true},"feature:stats":{"contract":1,"eager":false,"files":["/stats-core.js"],"background":true},"feature:export":{"contract":1,"eager":false,"files":["/export.js"],"background":true},"feature:playlist":{"contract":1,"eager":true,"files":[],"embeddedIn":["/app.js"],"background":false},"feature:settings":{"contract":1,"eager":true,"files":[],"embeddedIn":["/app.js","/settings-sections.js","/settings-sections.css"],"background":false},"feature:service-mode":{"contract":1,"eager":true,"files":[],"embeddedIn":["/app.js","/service-ui.css"],"background":false},"feature:lyrics-editor":{"contract":1,"eager":true,"files":[],"embeddedIn":["/app.js","/lyrics-core.js","/lyrics-display.js"],"background":false},"feature:layout-controls":{"contract":1,"eager":false,"background":true,"files":["/theme-glass-controls.css","/glass-controls.js"]},"layout:sanctuary-stage":{"contract":1,"eager":false,"background":true,"files":[]},"layout:liturgical":{"contract":1,"eager":false,"background":true,"files":[]},"layout:living-hymnal":{"contract":1,"eager":false,"background":true,"files":[]},"layout:broadcaster":{"contract":1,"eager":false,"background":true,"files":[]},"layout:contemplative":{"contract":1,"eager":false,"background":true,"files":[]}},"files":{}}</script>
<script type="application/json" id="ytp-assets">{"buildTag":"static","groups":{"core":{"contract":1,"eager":true,"files":["/index.html","/styles.css","/service-ui.css","/refresh.css","/layout-base.css","/recommendations.css","/flag-ui.js","/async-guard.js","/visible-timer.js","/asset-sync-core.js","/sw-update.js","/fingerprint.js","/opfs.js","/opfs-worker.js","/lyrics-core.js","/lyrics-display.js","/sha256.js","/resume-core.js","/loudness-wasm.js","/loudness.js","/sha256-wasm.js","/settings-sections.js","/related-videos.js","/related-videos.css","/audio-continuity.js","/fullscreen-orientation.js","/fullscreen-orientation.css","/download-actions.js","/download-actions.css","/download-errors.js","/downloads.js","/downloads-page.js","/offline-pages.css","/saved-page.js","/server-backfill.js","/saved-page.css","/prewarm-next.js","/settings-sections.css","/app.js","/manifest.webmanifest","/icons/icon-192.png","/icons/icon-512.png","/fonts/fonts.css","/fonts/BricolageGrotesque-latin-ext.woff2","/fonts/BricolageGrotesque-latin.woff2","/fonts/HankenGrotesk-latin-ext.woff2","/fonts/HankenGrotesk-latin.woff2","/fonts/JetBrainsMono-latin-ext.woff2","/fonts/JetBrainsMono-latin.woff2","/lazy.js","/feature-bootstrap.js","/eq-parameters.js","/assets.json","/device-db.js","/shell-core.js","/views-core.js","/section-rail.js"],"background":false},"layout:glass-stage":{"contract":1,"eager":false,"files":["/theme-glass.css","/theme-glass-panel.css","/glass-panel-layout.js"],"background":true,"dependencies":["feature:layout-controls"]},"layout:classic":{"contract":1,"eager":false,"files":["/theme-classic.css"],"background":true},"layout:bento-hub":{"contract":1,"eager":false,"files":["/theme-bento-hub.css","/bento-hub.js","/fonts/PlusJakartaSans-latin.woff2","/fonts/PlusJakartaSans-latin-ext.woff2"],"background":true,"dependencies":["feature:layout-controls"]},"layout:f7-swipe":{"contract":1,"eager":false,"files":["/theme-f7.css","/vendor/framework7-swipe.min.js","/f7-layout.js"],"background":true},"feature:piano":{"contract":1,"eager":false,"files":["/piano-core.js","/piano.js","/piano-engine.mjs"],"background":true},"feature:midi":{"contract":1,"eager":false,"files":["/midi.js"],"background":true},"feature:party-dj":{"contract":1,"eager":false,"files":["/party-dj.js"],"background":true},"feature:lyrics-window":{"contract":1,"eager":false,"files":["/lyrics-window.js"],"background":true},"feature:lower-third":{"contract":1,"eager":false,"files":["/lower-third.js","/lower-third.css"],"background":true},"feature:vocal-reducer":{"contract":1,"eager":false,"files":["/vocal-reducer.js"],"background":true},"feature:eq-core":{"contract":1,"eager":false,"files":["/eq-core.js"],"background":true},"feature:setlist-import":{"contract":1,"eager":false,"files":["/setlist-import.js"],"background":true},"feature:car-mode":{"contract":1,"eager":false,"files":["/car-mode.js","/car-mode.css"],"background":true},"feature:p2p":{"contract":1,"eager":false,"files":["/p2p-core.js","/p2p-client.js","/p2p-transfer.js","/p2p-recv-worker.js","/hash-worker.js"],"background":true},"feature:direct":{"contract":1,"eager":false,"files":["/direct-protocol.js","/direct-stream.js","/direct-media.js","/direct-media.css","/direct-recv-worker.js"],"background":true,"dependencies":["feature:p2p"]},"feature:video-edit":{"contract":1,"eager":false,"files":["/video-edit.js"],"background":true},"feature:stats":{"contract":1,"eager":false,"files":["/stats-core.js"],"background":true},"feature:export":{"contract":1,"eager":false,"files":["/export.js"],"background":true},"feature:playlist":{"contract":1,"eager":true,"files":[],"embeddedIn":["/app.js"],"background":false},"feature:settings":{"contract":1,"eager":true,"files":[],"embeddedIn":["/app.js","/settings-sections.js","/settings-sections.css","/views-core.js"],"background":false},"feature:service-mode":{"contract":1,"eager":true,"files":[],"embeddedIn":["/app.js","/service-ui.css"],"background":false},"feature:lyrics-editor":{"contract":1,"eager":true,"files":[],"embeddedIn":["/app.js","/lyrics-core.js","/lyrics-display.js"],"background":false},"feature:layout-controls":{"contract":1,"eager":false,"background":true,"files":["/theme-glass-controls.css","/glass-controls.js"]},"layout:sanctuary-stage":{"contract":1,"eager":false,"background":true,"files":[]},"layout:liturgical":{"contract":1,"eager":false,"background":true,"files":[]},"layout:living-hymnal":{"contract":1,"eager":false,"background":true,"files":[]},"layout:broadcaster":{"contract":1,"eager":false,"background":true,"files":[]},"layout:contemplative":{"contract":1,"eager":false,"background":true,"files":[]}},"files":{}}</script>
<script src="lazy.js"></script>
<link rel="stylesheet" href="fonts/fonts.css" />
<link rel="preconnect" href="https://i.ytimg.com" crossorigin />
@@ -669,6 +669,9 @@
<script src="prewarm-next.js"></script>
<script src="eq-parameters.js"></script>
<script src="feature-bootstrap.js"></script>
<script src="shell-core.js"></script>
<script src="views-core.js"></script>
<script src="section-rail.js"></script>
<script src="app.js"></script>
</body>
</html>

247
frontend/section-rail.js Normal file
View File

@@ -0,0 +1,247 @@
/* Eager UI definitions. Read app lexical state only when called after initialization. */
const SectionRail = (() => {
const CLASSIC_ICONS = {
player: '<rect x="3" y="4" width="18" height="13" rx="2"/><path d="M8 21h8m-4-4v4"/>',
meta: '<path d="M9 18V5l11-2v13M9 8l11-2"/><ellipse cx="6" cy="18" rx="3" ry="2"/><ellipse cx="17" cy="16" rx="3" ry="2"/>',
notes: '<path d="M14 3H4v18h16V11M9 15l2-5 7-7 3 3-7 7z"/>',
related: '<path d="m10 14 4-4m-5 6-1 1a4 4 0 0 1-6-6l4-4a4 4 0 0 1 6 0m0 10a4 4 0 0 0 6 0l4-4a4 4 0 0 0-6-6l-1 1"/>',
list: '<path d="M9 6h12M9 12h12M9 18h12M3 6h1M3 12h1M3 18h1"/>',
};
const SECTIONS = [
{ id: 'player', sel: '.player-stage', icon: '📺', label: 'Player' },
{ id: 'meta', sel: '#nowPlayingMeta', icon: '🎵', label: 'Now playing', fold: true },
{ id: 'notes', sel: '#notesPanel', icon: '📝', label: 'Lyrics', fold: true },
{ id: 'related', sel: '#relatedPanel', icon: '🔗', label: 'Related', fold: true },
{ id: 'list', sel: '#listPane', icon: '📋', label: 'List' },
];
const st = { active: '', btns: new Map(), labelTimer: null, raf: 0, bottom: -1 };
const rail = () => document.getElementById('sectionRail');
const folds = () => (data.settings.foldedCards ||= {});
const isFolded = (id) => !!folds()[id];
const elOf = (s) => document.querySelector(s.sel);
// Only cards that are actually on screen belong in the rail.
const visible = () => SECTIONS.filter((s) => {
const el = elOf(s);
return el && !el.classList.contains('hidden') && el.offsetParent !== null;
});
function applyFold(sec) {
const el = elOf(sec);
if (!el || !sec.fold) return;
el.classList.toggle('folded', isFolded(sec.id));
if (sec.id === 'notes') {
const b = document.getElementById('notesFoldBtn');
if (b) b.setAttribute('aria-expanded', String(!isFolded(sec.id)));
}
// The Related card already had its own +/− button; keep the two in step.
if (sec.id === 'related') {
relatedCollapsed = isFolded(sec.id);
const rl = document.getElementById('relatedList');
const rb = document.getElementById('relatedToggleBtn');
if (rl) rl.classList.toggle('hidden', relatedCollapsed);
if (rb) rb.textContent = relatedCollapsed ? '+' : '−';
}
}
function setFolded(id, on) {
const sec = SECTIONS.find((x) => x.id === id);
if (!sec || !sec.fold) return;
folds()[id] = !!on;
persist();
applyFold(sec);
paint(); // NOT render() — folding a card must not rebuild the list
}
function flashLabel(btn) {
clearTimeout(st.labelTimer);
[...st.btns.values()].forEach((b) => b.classList.remove('show-label'));
btn.classList.add('show-label');
st.labelTimer = setTimeout(() => btn.classList.remove('show-label'), 1400);
}
function onTap(sec, btn) {
const el = elOf(sec);
if (!el) return;
flashLabel(btn);
if (sec.id === 'player' || sec.id === 'meta') restoreNowPlayingList();
if (st.active === sec.id && sec.fold) {
// Already here: this is the second tap — fold or unfold the card.
setFolded(sec.id, !isFolded(sec.id));
if (isFolded(sec.id)) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
return;
}
st.active = sec.id; // claim it now so the next tap folds
paint();
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function build() {
const r = rail();
if (!r) return;
const items = visible();
// A rail with one entry is noise; so is one on the empty home screen.
if (items.length < 2) { r.classList.add('hidden'); r.innerHTML = ''; st.btns.clear(); return; }
const key = items.map((s) => s.id).join(',');
if (r.dataset.key !== key) {
r.dataset.key = key;
r.innerHTML = '';
st.btns.clear();
for (const sec of items) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'sec-rail-btn';
btn.dataset.sec = sec.id;
btn.setAttribute('aria-label', sec.label);
btn.innerHTML = `<span class="legacy-nav-icon" aria-hidden="true">${sec.icon}</span><svg class="classic-nav-icon" hidden viewBox="0 0 24 24" aria-hidden="true">${CLASSIC_ICONS[sec.id]}</svg><span class="sec-rail-label">${escapeHtml(sec.label)}</span>`;
btn.addEventListener('click', () => onTap(sec, btn));
r.appendChild(btn);
st.btns.set(sec.id, btn);
}
}
r.classList.remove('hidden');
placeRail();
paint();
}
// The page does NOT scroll the document: `.player-pane` is the scroller in
// the browser, but the installed PWA in portrait scrolls `.body` instead
// (`.player-pane` goes overflow:visible there). So find the real scroller
// rather than assuming one.
function scrollerOf(el) {
for (let e = el && el.parentElement; e; e = e.parentElement) {
const cs = getComputedStyle(e);
if (/(auto|scroll)/.test(cs.overflowY) && e.scrollHeight > e.clientHeight + 4) return e;
}
return document.scrollingElement || document.documentElement;
}
// The visible box to measure against — the scroller's own rect, or the
// window when the document itself scrolls.
function viewBox() {
const first = elOf(visible()[0] || SECTIONS[0]);
const sc = scrollerOf(first);
if (!sc || sc === document.scrollingElement || sc === document.documentElement) {
return { top: 0, height: window.innerHeight };
}
const r = sc.getBoundingClientRect();
return { top: r.top, height: r.height };
}
// Which card is the reader looking at? The one whose top is closest to a
// line a third of the way down the visible box — steadier than "first
// visible", which flickers between two cards at a boundary.
function currentId() {
const items = visible();
if (!items.length) return '';
const box = viewBox();
const line = box.top + box.height / 3;
let best = '', bestD = Infinity;
let near = items[0].id, nearD = Infinity; // fallback: closest card overall
for (const sec of items) {
const el = elOf(sec);
if (!el) continue;
const r = el.getBoundingClientRect();
const d = Math.abs(r.top - line);
// Distance to the visible band, for the fallback below.
const outside = Math.max(box.top - r.bottom, r.top - (box.top + box.height), 0);
if (outside < nearD || (outside === nearD && d < bestD)) { nearD = outside; near = sec.id; }
if (r.bottom < box.top || r.top > box.top + box.height) continue;
if (d < bestD) { bestD = d; best = sec.id; }
}
// Scrolled past the last card (or a card is taller than the viewport and
// its top has gone by): never leave the rail with nothing highlighted.
return best || near;
}
// The mini player and the bottom nav are both position:fixed bottom:0, and
// either can be absent (nothing playing / landscape). Measure whatever is
// actually pinned down there and park the rail above it, rather than
// guessing an offset that is wrong on the next phone.
function placeRail() {
const r = rail();
let occupied = 0;
for (const id of ['bottomNav', 'miniBar']) {
const el = document.getElementById(id);
if (!el || el.classList.contains('hidden')) continue;
const box = el.getBoundingClientRect();
if (!box.height) continue;
if (getComputedStyle(el).position !== 'fixed') continue;
// Count any fixed bar sitting in the lower half. It must NOT be required
// to touch the viewport bottom: on an iPhone XR the bottom nav ends
// above the home-indicator gap, so a "bottom >= innerHeight" test missed
// it entirely and the rail was parked underneath it.
if (box.top > window.innerHeight * 0.5) occupied = Math.max(occupied, window.innerHeight - box.top);
}
// 14px was too tight: the mini player is a floating CARD with a shadow and
// rounded corners, so its visual edge reads higher than its box.
const want = Math.round(occupied + 24);
if (st.bottom !== want) {
st.bottom = want;
if (r) r.style.setProperty('--rail-bottom', want + 'px');
// Published for anything else that must sit above the bottom bars —
// the watch-party panel's leave button was hidden behind them.
document.documentElement.style.setProperty('--bottom-chrome', Math.round(occupied) + 'px');
}
}
function paint() {
for (const [id, btn] of st.btns) {
btn.classList.toggle('active', id === st.active);
btn.classList.toggle('folded', isFolded(id));
}
}
function onScroll() {
if (st.raf) return;
st.raf = requestAnimationFrame(() => {
st.raf = 0;
// Panels appear and disappear outside render() too (the Related card
// shows once a video's related list arrives), and a card with no icon
// would leave the rail with nothing highlighted. build() is a no-op
// unless the set of visible cards actually changed.
build();
placeRail();
const id = currentId();
if (id && id !== st.active) { st.active = id; paint(); }
});
}
function boot() {
const fb = document.getElementById('notesFoldBtn');
if (fb) fb.addEventListener('click', () => setFolded('notes', !isFolded('notes')));
SECTIONS.forEach(applyFold);
// Scroll events from an element do NOT bubble, so a window listener never
// fires here. A capture-phase listener on document catches them all, and
// keeps working when the scroller changes between browser and installed
// PWA (different elements scroll in each).
document.addEventListener('scroll', onScroll, { passive: true, capture: true });
window.addEventListener('resize', () => { build(); placeRail(); onScroll(); });
// The mini player appears AFTER the scroll that reveals it, so a scroll
// handler alone measures the layout as it was a moment ago and parks the
// rail underneath it. Watch the two bottom bars for real.
const watch = ['bottomNav', 'miniBar'].map((id) => document.getElementById(id)).filter(Boolean);
if (watch.length && typeof MutationObserver !== 'undefined') {
// The mini bar slides in over 0.25s, so a measurement taken the instant
// it appears catches it mid-animation and lands the rail a few pixels
// too low. Measure now and again once it has settled.
const mo = new MutationObserver(() => { placeRail(); setTimeout(placeRail, 320); });
watch.forEach((el) => mo.observe(el, { attributes: true, attributeFilter: ['class', 'style'] }));
}
if (watch.length && typeof ResizeObserver !== 'undefined') {
const ro = new ResizeObserver(() => placeRail());
watch.forEach((el) => ro.observe(el));
}
build();
onScroll();
}
// Called from render(): cards appear and disappear as videos load.
function refresh() {
SECTIONS.forEach(applyFold);
build();
placeRail();
onScroll();
}
return { boot, refresh, setFolded, isFolded };
})();

304
frontend/shell-core.js Normal file
View File

@@ -0,0 +1,304 @@
/* Eager UI definitions. Read app lexical state only when called after initialization. */
const Recommendations = (() => {
let cards = [], fetchedAt = 0, loading = false, error = false, actor = '', queuedRefresh = false;
let listHost = null;
const deviceFingerprint = () => window.getFingerprint ? window.getFingerprint() : 'unknown';
const fingerprint = () => data.profile?.name ? 'profile:' + data.profile.name.toLowerCase() : 'device:' + deviceFingerprint();
function load() {
const fp = fingerprint();
if (fp === actor) return;
actor = fp; cards = []; fetchedAt = 0;
try {
const saved = JSON.parse(localStorage.getItem('ytpRecommendations:' + fp) || 'null');
if (saved && Array.isArray(saved.cards)) cards = saved.cards;
} catch { /* no saved recommendations */ }
}
function paint(host) {
if (!host) return;
host.replaceChildren();
const heading = document.createElement('div'); heading.className = 'rec-heading';
const copy = document.createElement('div');
const title = document.createElement('h2'); title.textContent = 'Recommended for you';
const sub = document.createElement('p'); sub.textContent = error && cards.length ? 'Saved picks · reconnect to refresh' : 'Familiar favorites and something new, inspired by your listening.';
copy.append(title, sub);
const refresh = document.createElement('button'); refresh.type = 'button'; refresh.className = 'rec-refresh';
refresh.textContent = loading ? 'Updating…' : 'Refresh'; refresh.disabled = loading;
refresh.onclick = () => update(true);
heading.append(copy, refresh); host.appendChild(heading);
if (!cards.length) {
const empty = document.createElement('p'); empty.className = 'rec-empty'; empty.setAttribute('role', 'status');
empty.textContent = loading ? 'Finding your next listen…' : error ? 'Recommendations are unavailable. You can still search or play your playlists.' : 'Search or play a few videos to start discovering recommendations here.';
host.appendChild(empty); return;
}
const grid = document.createElement('div'); grid.className = 'rec-grid';
cards.forEach((v, i) => {
const item = document.createElement('article'); item.className = 'rec-item';
const play = document.createElement('button'); play.type = 'button'; play.className = 'rec-play';
play.setAttribute('aria-label', 'Play ' + v.title);
const cover = document.createElement('span'); cover.className = 'rec-cover';
const img = document.createElement('img'); img.src = v.thumbnail || ''; img.alt = ''; img.loading = 'lazy'; img.decoding = 'async'; cover.appendChild(img);
const title = document.createElement('span'); title.className = 'rec-title'; title.textContent = v.title;
const channel = document.createElement('span'); channel.className = 'rec-channel'; channel.textContent = v.channel || '';
play.append(cover, title, channel); play.onclick = () => { setHomeOverPlayer(false); playFromList(cards.slice(), i, 'recommendations'); };
const reason = document.createElement('div'); reason.className = 'rec-reason'; reason.textContent = v.reason || 'Recommended for you';
const actions = document.createElement('div'); actions.className = 'rec-actions';
const queue = document.createElement('button'); queue.type = 'button'; queue.textContent = '+ Queue'; queue.setAttribute('aria-label', 'Queue ' + v.title); queue.onclick = () => addToQueue(v);
const more = document.createElement('button'); more.type = 'button'; more.textContent = '•••'; more.setAttribute('aria-label', 'More actions for ' + v.title); more.onclick = () => openCardMenu(v);
actions.append(queue, more); item.append(play, reason, actions); grid.appendChild(item);
});
host.appendChild(grid);
}
function repaint() {
if (!WEB) return;
const home = $('homeRecommendations');
if (home) { home.classList.remove('hidden'); paint(home); }
els.playerPane?.classList.add('has-recommendations');
if (listHost?.isConnected) paint(listHost);
requestAnimationFrame(updateBottomChrome);
}
async function update(force = false) {
load();
if (!WEB) return;
if (loading) { if (force) queuedRefresh = true; return; }
if (!force && Date.now() - fetchedAt < 300000) return;
const fp = actor; loading = true; error = false; repaint();
try {
const name = data.profile?.name || '';
const result = await webFetch('/api/recommendations?fp=' + encodeURIComponent(deviceFingerprint()) + (name ? '&profile=' + encodeURIComponent(name) : ''), { headers: name ? profileHeaders(name) : {} });
if (fp !== fingerprint()) return;
if (!result.ok || !Array.isArray(result.results)) throw new Error('invalid recommendations');
cards = result.results;
try { localStorage.setItem('ytpRecommendations:' + fp, JSON.stringify({ cards })); } catch { /* full */ }
} catch { error = true; }
finally {
loading = false; fetchedAt = fp === fingerprint() ? Date.now() : 0; repaint();
if (queuedRefresh || fp !== fingerprint()) { queuedRefresh = false; update(true); }
}
}
function home() { if (WEB) { load(); repaint(); update(); } }
function inList() {
if (!WEB) return;
listHost = document.createElement('section'); listHost.className = 'recommendations'; listHost.setAttribute('aria-label', 'Recommended videos');
els.cards.appendChild(listHost); load(); paint(listHost); update();
}
return { home, inList, update };
})();
function renderSidebar() {
els.playlistList.innerHTML = '';
for (const pl of data.playlists) {
const stats = playlistOfflineStats(pl);
let offlineBadge = '';
if (stats.total > 0) {
if (stats.cached === stats.total) {
offlineBadge = `<span class="pl-offline-badge all" title="Available offline">⬇</span>`;
} else if (stats.cached > 0) {
offlineBadge = `<span class="pl-offline-badge partial" title="${stats.cached} of ${stats.total} videos available offline">${stats.cached}/${stats.total}</span>`;
}
}
const item = document.createElement('div');
item.className = 'playlist-item' + (view.type === 'playlist' && view.id === pl.id ? ' active' : '');
item.innerHTML = `<span class="pl-name"></span>${offlineBadge}<span class="pl-count">${pl.videos.length}</span>`;
item.querySelector('.pl-name').textContent = pl.name;
item.addEventListener('click', () => { view = { type: 'playlist', id: pl.id }; render(); });
els.playlistList.appendChild(item);
}
document.querySelectorAll('.nav-item').forEach((b) => {
b.classList.toggle('active', b.dataset.view === view.type);
});
// Keep bottom-nav in sync with sidebar nav active state
document.querySelectorAll('.bottom-nav-btn').forEach((b) => {
b.classList.toggle('active', b.dataset.view === view.type);
});
updateQueueBadge();
updateDownloadBadge();
renderHomePlaylists();
}
function renderHomePlaylists() {
if (window.BentoHub) BentoHub.playlists = () => data.playlists || [];
const wrap = document.getElementById('homePlaylists');
const hero = document.querySelector('#playerPlaceholder .hero');
const grid = document.getElementById('homePlGrid');
if (!wrap || !hero || !grid) return;
Recommendations.home();
const lists = data.playlists || [];
wrap.classList.toggle('hidden', !lists.length);
hero.classList.toggle('hidden', !!lists.length);
// The hero is centered art; the grid wants the full box, so the placeholder
// switches from centering to stretching (and tightens its padding), and the
// stage drops its 16:9 lock so the grid gets the pane's real height.
if (els.placeholder) els.placeholder.classList.toggle('showing-playlists', !!lists.length);
if (els.playerPane) els.playerPane.classList.toggle('home-playlists', !!lists.length);
if (!lists.length) { grid.innerHTML = ''; return; }
grid.innerHTML = '';
for (const pl of lists) {
const count = pl.videos.length;
const thumb = (pl.videos.find((v) => v && v.thumbnail) || {}).thumbnail || '';
const stats = playlistOfflineStats(pl);
let offlineHtml = '';
if (stats.total > 0) {
if (stats.cached === stats.total) {
offlineHtml = `<span class="home-pl-offline all" title="Available offline">⬇</span>`;
} else if (stats.cached > 0) {
offlineHtml = `<span class="home-pl-offline partial" title="${stats.cached} of ${stats.total} videos available offline">${stats.cached}/${stats.total}</span>`;
}
}
const card = document.createElement('button');
card.className = 'home-pl-card';
card.type = 'button';
card.innerHTML = `
<span class="home-pl-thumb">
${thumb ? `<img src="${escapeHtml(thumb)}" alt="" loading="lazy" decoding="async" />`
: '<span class="home-pl-thumb-fallback">🎵</span>'}
${offlineHtml}
<span class="home-pl-play" title="Play all">▶</span>
</span>
<span class="home-pl-name"></span>
<span class="home-pl-count">${count} video${count === 1 ? '' : 's'}</span>`;
card.querySelector('.home-pl-name').textContent = pl.name;
card.title = pl.name;
card.addEventListener('click', () => { view = { type: 'playlist', id: pl.id }; render(); });
card.querySelector('.home-pl-play').addEventListener('click', (e) => {
e.stopPropagation(); // the ▶ badge plays; the rest of the card opens the list
if (count) playFromList(pl.videos, 0, 'playlist:' + pl.id);
else toast('That playlist is empty');
});
grid.appendChild(card);
}
// Measure after layout — scrollHeight is meaningless until the cards lay out.
requestAnimationFrame(updateHomeGridScrollState);
}
function updateHomeGridScrollState() {
const grid = document.getElementById('homePlGrid');
if (!grid) return;
const overflows = grid.scrollHeight > grid.clientHeight + 1;
grid.classList.toggle('is-scrollable', overflows);
grid.classList.toggle('at-end', !overflows ||
grid.scrollTop + grid.clientHeight >= grid.scrollHeight - 2);
}
function updateBottomChrome() {
let occupied = 0;
for (const id of ['bottomNav', 'miniBar']) {
const el = document.getElementById(id);
if (!el || el.classList.contains('hidden')) continue;
const box = el.getBoundingClientRect();
if (!box.height || getComputedStyle(el).position !== 'fixed') continue;
if (box.top > window.innerHeight * 0.5) occupied = Math.max(occupied, window.innerHeight - box.top);
}
document.documentElement.style.setProperty('--bottom-chrome', Math.round(occupied) + 'px');
}
function setHomeOverPlayer(on) {
const pane = els.playerPane;
if (!pane) return;
on = !!on && !!(current && current.meta);
// Service mode hides the bottom bar and mini bar (and, in its Video view,
// lives inside this pane): leave it first or the home screen is a dead end.
if (on && isServiceModeOpen()) exitServiceMode();
if (pane.classList.contains('home-over') === on) return;
pane.classList.toggle('home-over', on);
pane.classList.toggle('empty', on);
if (els.placeholder) els.placeholder.classList.toggle('hidden', !on);
if (on) {
renderHomePlaylists();
showMiniBar();
const body = document.querySelector('.body');
if (body) body.scrollTo({ top: 0 });
}
}
function showMiniBar() {
if (!current || !current.meta) return;
$('miniTitle').textContent = current.meta.title;
const miniCh = $('miniChannel');
miniCh.textContent = current.meta.channel || '';
miniCh.classList.toggle('link', !!channelKeyOf(current.meta));
$('miniBar').classList.remove('hidden');
updateMiniBar();
requestAnimationFrame(updateBottomChrome);
}
function updateMiniBar() {
if (!current || !current.meta) return;
const cur = Player.master.currentTime || 0;
const dur = Player.master.duration || 0;
$('miniTime').textContent = fmtTime(cur);
if (dur > 0) {
$('miniProgressFill').style.width = Math.min(100, (cur / dur) * 100) + '%';
}
}
function hideMiniBar() {
$('miniBar').classList.add('hidden');
requestAnimationFrame(updateBottomChrome);
}
function setTile(btn, label) {
const tl = btn.querySelector('.tl');
if (tl) tl.textContent = label; else btn.textContent = label;
}
function updateNowPlayingActions() {
if (!current || !current.meta) return;
const id = current.meta.id;
renderAvailability(id);
// Custom (edited) videos are already a saved-offline cut of a source video;
// re-saving or re-editing them makes no sense, so hide those actions.
const isCustom = !!current.meta.custom;
if (els.editBtn) els.editBtn.hidden = isCustom;
if (els.saveBtn) els.saveBtn.hidden = isCustom;
// The server cache exists only behind the web PWA backend.
if (els.brokenBtn) {
els.brokenBtn.hidden = isCustom || !WEB;
els.brokenBtn.disabled = reportingBroken.has(id);
els.brokenBtn.textContent = reportingBroken.has(id) ? '⏳ Reporting…' : '⚠ Broken';
}
{ const ch = $('npChannel'); if (ch) { const ok = isUploadId(id) || cachedIds.has(id); ch.classList.toggle('verified', ok); ch.title = ok ? 'Available on this device or the server' : ''; } }
const btn = els.saveBtn;
if (!btn) return;
if (removing.has(id)) {
setTile(btn, 'Removing…');
btn.classList.remove('done');
btn.disabled = true;
} else if (downloading.has(id)) {
setTile(btn, 'Saving…');
btn.classList.remove('done');
btn.disabled = true;
} else if (cachedIds.has(id)) {
setTile(btn, 'Saved');
btn.classList.add('done');
btn.disabled = false;
btn.title = 'Saved for offline — click to remove from cache';
} else {
setTile(btn, 'Save');
btn.classList.remove('done');
btn.disabled = false;
btn.title = 'Save this video for offline playback';
}
}
function renderSmartSidebar() {
const list = $('smartPlaylistList');
if (!list) return;
list.innerHTML = '';
SMART_PLAYLISTS.forEach((sp) => {
const item = document.createElement('div');
const isActive = view.type === 'smart' && view.smartType === sp.id;
item.className = 'playlist-item smart-item' + (isActive ? ' active' : '');
item.innerHTML = `<span class="pl-name">${sp.label}</span>`;
item.addEventListener('click', () => { view = { type: 'smart', smartType: sp.id }; render(); });
list.appendChild(item);
});
if (WEB && data.settings.p2pReceive !== false) {
const item = document.createElement('div');
item.className = 'playlist-item smart-item' + (view.type === 'p2p' ? ' active' : '');
item.innerHTML = '<span class="pl-name">📡 On other devices</span>';
item.addEventListener('click', () => { view = { type: 'p2p' }; render(); });
list.appendChild(item);
}
}

View File

@@ -137,6 +137,9 @@ const SHELL = [
'/car-mode.css',
'/lower-third.css',
'/settings-sections.css',
'/shell-core.js',
'/views-core.js',
'/section-rail.js',
'/app.js',
'/manifest.webmanifest',
'/icons/icon-192.png',

1501
frontend/views-core.js Normal file

File diff suppressed because it is too large Load Diff