Recycle grid cards instead of rebuilding them

Scrolling the grid did nothing but destroy cards and build near-identical
ones back: a template string parsed as innerHTML, ten querySelectors, and
a listener per interactive element, every time a card entered the window.
The virtualizer now keeps a pool and rebinds a card it already has --
18us against 136us to build one, and 74-83% of mounts are served from it.

Two things had to change first. Nothing on a card may close over the
video it is showing, because the card outlives the video, so every
interaction moved to one delegated listener per event type on the grid.
And every card now has the same shape whatever it shows: the optional
parts are always present and hidden when unused, so any pooled card fits
any video. That needed a global [hidden] rule, since .live-badge and
.video-tags carry their own display.

The rest is the release path, which is where this design lives or dies.
A thumbnail carries a generation, so a race or a proxy fallback settling
after the card moved on cannot paint over the video now showing. The
player stamps the card it was opened from, so a recycled element stops
answering for it. The reveal handler, the entrance-animation listener and
the hover preview are all taken back off. Anything missed here surfaces
as one video's title, thumbnail or heart on another video's card, which
is what the smoke suite scrolls back and forth to catch.

Two incidental fixes found while measuring: bindCard no longer writes a
data-tag per tag button (dataset is a proxy, and that alone cost more
than the rest of a rebind put together -- the handler reads the label off
the button), and favorites.has no longer parses a URL for every card that
isn't a favorite by key.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QBDkEXP4htyXTCZUwMLphd
This commit is contained in:
Simon
2026-09-09 09:47:43 +00:00
parent b4031b5d0e
commit 49992c1db0
6 changed files with 470 additions and 155 deletions

View File

@@ -1,5 +1,11 @@
* { margin: 0; padding: 0; box-sizing: border-box; } * { margin: 0; padding: 0; box-sizing: border-box; }
/* A card keeps its optional parts (live badge, uploader, duration, tags) at all
times and hides the ones this video doesn't need, so any pooled card fits any
video -- see bindCard. Several of those carry their own `display`, which beats
the UA rule for [hidden], so say it once and mean it. */
[hidden] { display: none !important; }
:root { :root {
/* Warm "classic" dark: deep charcoal with a hint of brown, never pure black. */ /* Warm "classic" dark: deep charcoal with a hint of brown, never pure black. */
--bg-primary: #14110d; --bg-primary: #14110d;

View File

@@ -60,6 +60,15 @@ App.enhance = App.enhance || {};
if (!grid || !fineHover) return; if (!grid || !fineHover) return;
let dwellTimer = null; let dwellTimer = null;
let activeCard = null; let activeCard = null;
// The card element alone doesn't identify what is being previewed: the
// grid pools its cards, so the same element can come back showing a
// different video (via relayout or a new search, neither of which
// scrolls, so clearPreview never runs). Remembering the video too keeps
// the "already previewing this" check honest.
let activeVideo = null;
const isActive = (card) => card === activeCard &&
(!App.videos.getVideoForCard || App.videos.getVideoForCard(card) === activeVideo);
const clearPreview = () => { const clearPreview = () => {
if (dwellTimer) { clearTimeout(dwellTimer); dwellTimer = null; } if (dwellTimer) { clearTimeout(dwellTimer); dwellTimer = null; }
@@ -68,6 +77,7 @@ App.enhance = App.enhance || {};
if (vid) { try { vid.pause(); } catch (e) {} vid.remove(); } if (vid) { try { vid.pause(); } catch (e) {} vid.remove(); }
activeCard.classList.remove('is-previewing'); activeCard.classList.remove('is-previewing');
activeCard = null; activeCard = null;
activeVideo = null;
} }
}; };
@@ -105,10 +115,14 @@ App.enhance = App.enhance || {};
grid.addEventListener('pointerover', (e) => { grid.addEventListener('pointerover', (e) => {
const card = e.target.closest('.video-card'); const card = e.target.closest('.video-card');
if (!card || card === activeCard) return; if (!card || isActive(card)) return;
clearPreview(); clearPreview();
activeCard = card; activeCard = card;
dwellTimer = setTimeout(() => { dwellTimer = null; if (activeCard === card) startPreview(card); }, 600); activeVideo = App.videos.getVideoForCard ? App.videos.getVideoForCard(card) : null;
dwellTimer = setTimeout(() => {
dwellTimer = null;
if (isActive(card)) startPreview(card);
}, 600);
}); });
grid.addEventListener('pointerout', (e) => { grid.addEventListener('pointerout', (e) => {
const card = e.target.closest('.video-card'); const card = e.target.closest('.video-card');

View File

@@ -224,6 +224,10 @@ App.favorites = App.favorites || {};
const index = identities(); const index = identities();
const key = App.favorites.getKey(video); const key = App.favorites.getKey(video);
if (key && index.keys.has(key)) return true; if (key && index.keys.has(key)) return true;
// Normalising a URL means parsing one, which is the expensive half of
// this and runs for every card that isn't a favorite by key. With
// nothing stored to match against, there is nothing to parse it for.
if (!index.urls.size) return false;
const meta = (video && video.meta) || video || {}; const meta = (video && video.meta) || video || {};
const urlKey = App.favorites.urlKey(video && (video.url || meta.url)); const urlKey = App.favorites.urlKey(video && (video.url || meta.url));
return !!(urlKey && index.urls.has(urlKey)); return !!(urlKey && index.urls.has(urlKey));

View File

@@ -23,6 +23,7 @@ App.player = App.player || {};
historyPushed: false, historyPushed: false,
idleTimer: null, idleTimer: null,
originEl: null, originEl: null,
originToken: null, // stamp proving originEl is still the card we opened
hudHovered: false, // mouse resting on the controls (desktop) hudHovered: false, // mouse resting on the controls (desktop)
activeUrl: '', // media URL actually playing, for the format menu's tick activeUrl: '', // media URL actually playing, for the format menu's tick
attemptToken: 0, // bumps on every open()/format switch to void stale async callbacks attemptToken: 0, // bumps on every open()/format switch to void stale async callbacks
@@ -59,6 +60,24 @@ App.player = App.player || {};
} }
} }
// The card the player was opened from is owned by the grid, which pools and
// reuses its cards (see resetCard in videos.js). By the time the player lets
// go, that element may be showing a different video -- so it is stamped at
// open, and every later touch checks the stamp still matches. A recycled
// card has had it wiped, and simply stops answering.
let originSeq = 0;
const claimOrigin = function(el) {
if (!el) return null;
const token = String(++originSeq);
el.dataset.playerToken = token;
return token;
};
const withOrigin = function(el, token, fn) {
if (el && el.dataset.playerToken === token) fn(el);
};
const addCleanup = (fn) => cp.cleanups.push(fn); const addCleanup = (fn) => cp.cleanups.push(fn);
const runCleanups = () => { const runCleanups = () => {
cp.cleanups.forEach((fn) => { try { fn(); } catch (err) { /* ignore */ } }); cp.cleanups.forEach((fn) => { try { fn(); } catch (err) { /* ignore */ } });
@@ -695,9 +714,10 @@ App.player = App.player || {};
// the wrong card loaded or (via the token guard below) never clear // the wrong card loaded or (via the token guard below) never clear
// this card's spinner at all. // this card's spinner at all.
const originEl = (opts && opts.originEl) || null; const originEl = (opts && opts.originEl) || null;
const originToken = originEl ? originEl.dataset.playerToken : null;
const sources = resolveSources(videoData); const sources = resolveSources(videoData);
const clearLoading = () => { const clearLoading = () => {
if (originEl) originEl.classList.remove('is-loading'); withOrigin(originEl, originToken, (el) => el.classList.remove('is-loading'));
}; };
const sourceUrl = (videoData && (videoData.url || (videoData.meta && videoData.meta.url))) || ''; const sourceUrl = (videoData && (videoData.url || (videoData.meta && videoData.meta.url))) || '';
@@ -921,11 +941,12 @@ App.player = App.player || {};
cp.attemptToken++; cp.attemptToken++;
cancelInFlight(); cancelInFlight();
clearIdleTimer(); clearIdleTimer();
if (cp.originEl) cp.originEl.classList.remove('is-loading'); withOrigin(cp.originEl, cp.originToken, (el) => el.classList.remove('is-loading'));
} }
runCleanups(); runCleanups();
cp.originEl = opts && opts.originEl ? opts.originEl : null; cp.originEl = opts && opts.originEl ? opts.originEl : null;
cp.originToken = claimOrigin(cp.originEl);
if (cp.originEl) cp.originEl.classList.add('is-loading'); if (cp.originEl) cp.originEl.classList.add('is-loading');
cp.container = buildContainer(); cp.container = buildContainer();
@@ -1031,10 +1052,12 @@ App.player = App.player || {};
cp.historyPushed = false; cp.historyPushed = false;
} }
if (cp.originEl) { withOrigin(cp.originEl, cp.originToken, (el) => {
cp.originEl.classList.remove('is-loading'); el.classList.remove('is-loading');
cp.originEl = null; delete el.dataset.playerToken;
} });
cp.originEl = null;
cp.originToken = null;
cp.data = null; cp.data = null;
cp.source = null; // voids a still-pending format resolve for this open cp.source = null; // voids a still-pending format resolve for this open
cp.formatOverride = null; cp.formatOverride = null;

View File

@@ -147,6 +147,7 @@ App.videos = App.videos || {};
const imageRoutes = new Map(); // host -> winning route; absent = unknown const imageRoutes = new Map(); // host -> winning route; absent = unknown
const imageRacing = new Set(); // hosts with a race already deciding const imageRacing = new Set(); // hosts with a race already deciding
const imageWaiting = new Map(); // host -> images held until it decides const imageWaiting = new Map(); // host -> images held until it decides
let thumbSeq = 0; // generation, so stale work can be dropped
// A page of cards is built in one go, so every thumbnail from a host is // A page of cards is built in one go, so every thumbnail from a host is
// attached before the first one has come back. Sending them all down the // attached before the first one has come back. Sending them all down the
@@ -188,7 +189,13 @@ App.videos = App.videos || {};
// and put on only once there is an image to caption -- otherwise every card // and put on only once there is an image to caption -- otherwise every card
// spells out its own title over the placeholder while the host is being // spells out its own title over the placeholder while the host is being
// decided, and permanently for an item that has no thumbnail at all. // decided, and permanently for an item that has no thumbnail at all.
const showThumbnail = function(img, url) { // `token` is the generation of the attachThumbnail call that started this
// work. A card can be recycled while its thumbnail is still being decided,
// and the callbacks that eventually fire still hold the old element -- so
// anything arriving for a generation the element has moved past is dropped
// rather than painted onto whatever video the card now shows.
const showThumbnail = function(img, url, token) {
if (token !== undefined && img.dataset.thumbToken !== token) return;
if (img.dataset.alt !== undefined) { if (img.dataset.alt !== undefined) {
img.alt = img.dataset.alt; img.alt = img.dataset.alt;
delete img.dataset.alt; delete img.dataset.alt;
@@ -198,9 +205,22 @@ App.videos = App.videos || {};
// Last resort on a route that normally works: one expired or missing image // Last resort on a route that normally works: one expired or missing image
// shouldn't be left broken just because its host is fine in general. // shouldn't be left broken just because its host is fine in general.
const attachProxyFallback = function(img, proxyUrl) { const attachProxyFallback = function(img, proxyUrl, token) {
if (!proxyUrl) return; if (!proxyUrl) return;
img.addEventListener('error', () => { showThumbnail(img, proxyUrl); }, { once: true }); // Held on the element so detachThumbnail can take it off again. On the
// happy path it never fires and `once` never collects it, so a pooled
// image would otherwise accumulate one closure per mount it has served.
detachProxyFallback(img);
const onError = () => { showThumbnail(img, proxyUrl, token); };
img._thumbFallback = onError;
img.addEventListener('error', onError, { once: true });
};
const detachProxyFallback = function(img) {
if (img && img._thumbFallback) {
img.removeEventListener('error', img._thumbFallback);
img._thumbFallback = null;
}
}; };
// Releases the images held for `host`. `route` is the winner, or null when // Releases the images held for `host`. `route` is the winner, or null when
@@ -213,11 +233,11 @@ App.videos = App.videos || {};
imageWaiting.delete(host); imageWaiting.delete(host);
waiting.forEach((entry) => { waiting.forEach((entry) => {
if (route === IMAGE_PROXY) { if (route === IMAGE_PROXY) {
showThumbnail(entry.img, entry.proxyUrl); showThumbnail(entry.img, entry.proxyUrl, entry.token);
return; return;
} }
if (route !== IMAGE_DIRECT) attachProxyFallback(entry.img, entry.proxyUrl); if (route !== IMAGE_DIRECT) attachProxyFallback(entry.img, entry.proxyUrl, entry.token);
showThumbnail(entry.img, entry.directUrl); showThumbnail(entry.img, entry.directUrl, entry.token);
}); });
}; };
@@ -238,7 +258,7 @@ App.videos = App.videos || {};
// pointed at the first one home. Racing on the visible element instead // pointed at the first one home. Racing on the visible element instead
// would abort the loser -- and the loser is the request that answers the // would abort the loser -- and the loser is the request that answers the
// second question. // second question.
const raceThumbnail = function(img, directUrl, proxyUrl, host) { const raceThumbnail = function(img, directUrl, proxyUrl, host, token) {
let shown = false; let shown = false;
let outstanding = 2; let outstanding = 2;
let routeFinal = false; // the direct verdict is in; nothing can revise it let routeFinal = false; // the direct verdict is in; nothing can revise it
@@ -250,7 +270,7 @@ App.videos = App.videos || {};
const show = function(url) { const show = function(url) {
if (shown) return; if (shown) return;
shown = true; shown = true;
showThumbnail(img, url); // a cache hit; the probe has the bytes showThumbnail(img, url, token); // a cache hit; the probe has the bytes
}; };
// Records the host's route and lets go of everything held for it. The // Records the host's route and lets go of everything held for it. The
@@ -278,11 +298,11 @@ App.videos = App.videos || {};
if (shown) return; if (shown) return;
shown = true; shown = true;
if (imageRoutes.get(host) === IMAGE_PROXY) { if (imageRoutes.get(host) === IMAGE_PROXY) {
showThumbnail(img, proxyUrl); showThumbnail(img, proxyUrl, token);
return; return;
} }
attachProxyFallback(img, proxyUrl); attachProxyFallback(img, proxyUrl, token);
showThumbnail(img, directUrl); showThumbnail(img, directUrl, token);
}; };
const decide = function() { const decide = function() {
@@ -383,9 +403,13 @@ App.videos = App.videos || {};
const proxyUrl = App.videos.buildImageProxyUrl(directUrl); const proxyUrl = App.videos.buildImageProxyUrl(directUrl);
const host = imageHostOf(directUrl); const host = imageHostOf(directUrl);
const route = imageRoutes.get(host); const route = imageRoutes.get(host);
// Every attach is a new generation, so work started for a previous one
// stops being able to touch this element.
const token = String(++thumbSeq);
img.dataset.thumbToken = token;
if (route === IMAGE_PROXY) { if (route === IMAGE_PROXY) {
showThumbnail(img, proxyUrl || directUrl); showThumbnail(img, proxyUrl || directUrl, token);
return; return;
} }
if (imageRacing.has(host)) { if (imageRacing.has(host)) {
@@ -393,18 +417,28 @@ App.videos = App.videos || {};
// guessing: guessing wrong costs this image a whole failed request // guessing: guessing wrong costs this image a whole failed request
// before it even asks the route that was about to be proven. // before it even asks the route that was about to be proven.
const waiting = imageWaiting.get(host) || []; const waiting = imageWaiting.get(host) || [];
waiting.push({ img: img, directUrl: directUrl, proxyUrl: proxyUrl }); waiting.push({ img: img, directUrl: directUrl, proxyUrl: proxyUrl, token: token });
imageWaiting.set(host, waiting); imageWaiting.set(host, waiting);
return; return;
} }
if (route === IMAGE_DIRECT || !host || !proxyUrl) { if (route === IMAGE_DIRECT || !host || !proxyUrl) {
// Known good, or nothing to race against: take the provider and keep // Known good, or nothing to race against: take the provider and keep
// the proxy as this image's own fallback. // the proxy as this image's own fallback.
attachProxyFallback(img, proxyUrl); attachProxyFallback(img, proxyUrl, token);
showThumbnail(img, directUrl); showThumbnail(img, directUrl, token);
return; return;
} }
raceThumbnail(img, directUrl, proxyUrl, host); raceThumbnail(img, directUrl, proxyUrl, host, token);
};
// Voids whatever is still in flight for this element's thumbnail. Its
// generation moves on, so a race that settles later, or a proxy fallback
// that fires later, finds a token that no longer matches and does nothing.
App.videos.detachThumbnail = function(img) {
if (!img) return;
img.dataset.thumbToken = String(++thumbSeq);
delete img.dataset.alt;
detachProxyFallback(img);
}; };
// Each channel in a group sends back a different number of videos per // Each channel in a group sends back a different number of videos per
@@ -710,132 +744,268 @@ App.videos = App.videos || {};
} }
}; };
// Builds a fully-wired video card element for `v`. Kept separate from // ---------------------------------------------------------------------
// mounting so the virtualizer can create a card the moment it needs to be // Cards
// on screen and throw it away once it scrolls out of the window. //
App.videos.buildCard = function(v, options) { // A card is built once and then reused: the virtualizer keeps a pool of
const card = document.createElement('div'); // them and rebinds one to a new video rather than constructing another
card.className = 'video-card'; // (see acquire/release in App.virtualGrid). Two things follow from that,
// and both are load-bearing.
//
// Nothing on a card may close over the video it is currently showing --
// the card outlives the video. Every interaction is therefore handled by
// one delegated listener per event type on the grid, which resolves the
// video from the card under the pointer (see bindGridDelegation).
//
// And every card has the same shape whatever video it shows: the optional
// parts -- live badge, uploader, duration, tags -- are always present and
// hidden when unused, so any pooled card fits any video.
// ---------------------------------------------------------------------
const CARD_TEMPLATE_HTML = `
<span class="live-badge" hidden>● LIVE</span>
<button class="favorite-btn" type="button" data-action="favorite" aria-pressed="false" aria-label="Add to favorites">♡</button>
<button class="video-menu-btn" type="button" data-action="menu" aria-haspopup="true" aria-expanded="false" aria-label="More options">⋯</button>
<div class="video-menu" role="menu">
<button class="video-menu-item" type="button" data-action="info" role="menuitem">Show info</button>
<button class="video-menu-item" type="button" data-action="download" role="menuitem">Download</button>
</div>
<div class="video-thumb">
<img alt="" loading="lazy" decoding="async">
<div class="video-loading" aria-hidden="true">
<div class="video-loading-spinner"></div>
</div>
<button class="video-uploader uploader-link" type="button" data-action="uploader" hidden></button>
<span class="video-duration" hidden></span>
</div>
<h4 class="video-title"><span class="video-title-text"></span></h4>
<div class="video-tags" hidden></div>
`;
// Parsed once. Cloning this is roughly six times cheaper than asking the
// parser to read the same markup again for every card.
let cardTemplate = null;
// The parts bindCard writes to, found once when the card is created rather
// than looked up again on every rebind. Searching the subtree seven times
// per mount was most of what rebinding cost.
const cardRefs = function(card) {
if (!card._refs) {
card._refs = {
live: card.querySelector('.live-badge'),
favorite: card.querySelector('.favorite-btn'),
title: card.querySelector('.video-title-text'),
uploader: card.querySelector('.video-uploader'),
duration: card.querySelector('.video-duration'),
tags: card.querySelector('.video-tags'),
img: card.querySelector('img')
};
}
return card._refs;
};
const createCardShell = function() {
if (!cardTemplate) {
cardTemplate = document.createElement('template');
cardTemplate.innerHTML = `<div class="video-card">${CARD_TEMPLATE_HTML}</div>`;
}
const card = cardTemplate.content.firstElementChild.cloneNode(true);
cardRefs(card);
return card;
};
// Tag buttons are the only part whose *count* varies, so they are adjusted
// rather than rebuilt: usually the card already has the right number.
const bindTags = function(container, tags) {
const list = Array.isArray(tags) ? tags.filter((tag) => tag) : [];
container.hidden = list.length === 0;
while (container.childElementCount > list.length) {
container.removeChild(container.lastElementChild);
}
while (container.childElementCount < list.length) {
const button = document.createElement('button');
button.className = 'video-tag';
button.type = 'button';
button.dataset.action = 'tag';
container.appendChild(button);
}
// Only the label is written: the delegated handler reads the tag off
// the button's own text. Writing it a second time into a data attribute
// cost more than everything else in a rebind put together -- dataset is
// a proxy, and this runs once per tag per card.
list.forEach((tag, index) => {
const button = container.children[index];
if (button.textContent !== tag) button.textContent = tag;
});
};
// Points an existing card at `v`. This is the whole per-mount cost.
App.videos.bindCard = function(card, v) {
const refs = cardRefs(card);
card.dataset.videoId = v.id; card.dataset.videoId = v.id;
const durationText = App.videos.formatDuration(v.duration); cardVideo.set(card, v);
refs.live.hidden = !v.isLive;
const favoriteKey = App.favorites.getKey(v); const favoriteKey = App.favorites.getKey(v);
refs.favorite.dataset.favKey = favoriteKey || '';
refs.favorite.dataset.favUrl = v.url || '';
// By either identity: a favorite imported from a backup is keyed by its
// URL, not by the id this card carries.
App.favorites.setButtonState(refs.favorite, !!favoriteKey && App.favorites.has(v));
refs.title.textContent = v.title || '';
const uploaderText = v.uploader || ''; const uploaderText = v.uploader || '';
const tags = Array.isArray(v.tags) ? v.tags.filter(tag => tag) : []; refs.uploader.hidden = !uploaderText;
const tagsMarkup = tags.length refs.uploader.textContent = uploaderText;
? `<div class="video-tags">${tags.map(tag => `<button class="video-tag" type="button" data-tag="${tag}">${tag}</button>`).join('')}</div>` refs.uploader.dataset.uploader = uploaderText;
: '';
const liveBadge = v.isLive ? '<span class="live-badge">● LIVE</span>' : ''; const durationText = App.videos.formatDuration(v.duration);
card.innerHTML = ` refs.duration.hidden = !durationText;
${liveBadge} refs.duration.textContent = durationText;
<button class="favorite-btn" type="button" aria-pressed="false" aria-label="Add to favorites" data-fav-key="${favoriteKey || ''}" data-fav-url="${v.url || ''}">♡</button>
<button class="video-menu-btn" type="button" aria-haspopup="true" aria-expanded="false" aria-label="More options">⋯</button> bindTags(refs.tags, v.tags);
<div class="video-menu" role="menu">
<button class="video-menu-item" type="button" data-action="info" role="menuitem">Show info</button> // Set before attachThumbnail, which holds the caption back until there
<button class="video-menu-item" type="button" data-action="download" role="menuitem">Download</button> // is an image to caption.
</div> refs.img.alt = v.title || '';
<div class="video-thumb"> return card;
<img alt="${v.title}" loading="lazy" decoding="async"> };
<div class="video-loading" aria-hidden="true">
<div class="video-loading-spinner"></div> // A card ready to show `v`, thumbnail and all.
</div> App.videos.buildCard = function(v, options) {
${uploaderText ? `<button class="video-uploader uploader-link" type="button" data-uploader="${uploaderText}">${uploaderText}</button>` : ''} const card = App.videos.bindCard(createCardShell(), v);
${durationText ? `<span class="video-duration">${durationText}</span>` : ''}
</div>
<h4 class="video-title"><span class="video-title-text">${v.title}</span></h4>
${tagsMarkup}
`;
const thumb = card.querySelector('img');
// The layout probe (see shapeHeight) needs the card's shape, never its // The layout probe (see shapeHeight) needs the card's shape, never its
// pixels: it measures against the CSS 16:9 placeholder and is removed in // pixels: it measures against the CSS 16:9 placeholder and is removed in
// the same frame, so loading a thumbnail for it -- let alone racing one // the same frame, so loading a thumbnail for it -- let alone racing one
// -- would be pure waste. // -- would be pure waste.
if (!(options && options.skipThumbnail)) { if (!(options && options.skipThumbnail)) {
App.videos.attachThumbnail(thumb, v.thumb); App.videos.attachThumbnail(cardRefs(card).img, v.thumb);
} }
const favoriteBtn = card.querySelector('.favorite-btn'); return card;
if (favoriteBtn && favoriteKey) { };
// By either identity: a favorite imported from a backup is keyed
// by its URL, not by the id this card carries. // Returns a card to a state where it shows nothing and remembers nothing,
App.favorites.setButtonState(favoriteBtn, App.favorites.has(v)); // ready to be bound to another video. Anything left behind here surfaces as
favoriteBtn.onclick = (event) => { // one video's content on another video's card.
event.stopPropagation(); App.videos.resetCard = function(card) {
App.favorites.toggle(v); card.classList.remove('is-loading', 'is-title-active', 'is-revealing', 'is-previewing');
}; delete card.dataset.videoId;
} delete card.dataset.titleFocused;
const titleWrap = card.querySelector('.video-title'); delete card.dataset.titleHovered;
const titleText = card.querySelector('.video-title-text'); delete card.dataset.titlePrimary;
if (titleWrap && titleText) { // The player stamps this to recognise the card it was opened from; a
card.addEventListener('focusin', () => { // recycled card must stop answering to it.
card.dataset.titleFocused = '1'; delete card.dataset.playerToken;
updateTitleActive(card);
});
card.addEventListener('focusout', () => {
card.dataset.titleFocused = '0';
updateTitleActive(card);
});
if (titleEnv.useHoverFocus) {
card.addEventListener('mouseenter', () => {
card.dataset.titleHovered = '1';
updateTitleActive(card);
});
card.addEventListener('mouseleave', () => {
card.dataset.titleHovered = '0';
updateTitleActive(card);
});
}
// On touch devices the marquee observer is attached lazily by
// measureTitle (called on mount), and only for overflowing titles.
}
const uploaderBtn = card.querySelector('.uploader-link');
if (uploaderBtn) {
uploaderBtn.onclick = (event) => {
event.stopPropagation();
const uploader = uploaderBtn.dataset.uploader || uploaderBtn.textContent || '';
App.videos.handleSearch(uploader);
};
}
const tagButtons = card.querySelectorAll('.video-tag');
if (tagButtons.length) {
tagButtons.forEach((tagBtn) => {
tagBtn.onclick = (event) => {
event.stopPropagation();
const tag = tagBtn.dataset.tag || tagBtn.textContent || '';
App.videos.handleSearch(tag);
};
});
}
const menuBtn = card.querySelector('.video-menu-btn');
const menu = card.querySelector('.video-menu'); const menu = card.querySelector('.video-menu');
const showInfoBtn = card.querySelector('.video-menu-item[data-action="info"]'); if (menu) menu.classList.remove('open');
const downloadBtn = card.querySelector('.video-menu-item[data-action="download"]'); const menuBtn = card.querySelector('.video-menu-btn');
if (menuBtn && menu) { if (menuBtn) menuBtn.setAttribute('aria-expanded', 'false');
menuBtn.onclick = (event) => {
event.stopPropagation(); const titleWrap = card.querySelector('.video-title');
App.videos.toggleMenu(menu, menuBtn); if (titleWrap) titleWrap.classList.remove('has-marquee');
}; const titleText = card.querySelector('.video-title-text');
if (titleText) {
titleText.style.removeProperty('--marquee-distance');
titleText.style.removeProperty('--marquee-duration');
} }
if (showInfoBtn) {
showInfoBtn.onclick = (event) => { // The hover preview (enhance.js) parks a <video> inside the card.
event.stopPropagation(); const preview = card.querySelector('.card-preview');
App.ui.openInfo(v); if (preview) {
App.videos.closeAllMenus(); try { preview.pause(); } catch (err) { /* ignore */ }
}; preview.remove();
} }
if (downloadBtn) {
downloadBtn.onclick = (event) => { const img = cardRefs(card).img;
event.stopPropagation(); if (img) {
App.videos.downloadVideo(v); // Voids anything still in flight for the old thumbnail -- a pending
App.videos.closeAllMenus(); // race, a proxy fallback -- so it cannot land on the next video.
}; App.videos.detachThumbnail(img);
if (img._revealHandler) {
img.removeEventListener('load', img._revealHandler);
img._revealHandler = null;
}
img.classList.remove('is-loaded');
img.style.removeProperty('aspect-ratio');
img.removeAttribute('src');
img.alt = '';
} }
card.onclick = () => { return card;
};
// One listener per event type, on the grid, for every card in it.
let gridDelegated = false;
const cardFor = function(target) {
const card = target && target.closest ? target.closest('.video-card') : null;
return card && cardVideo.has(card) ? card : null;
};
const bindGridDelegation = function() {
if (gridDelegated) return;
const grid = document.getElementById('video-grid');
if (!grid) return;
gridDelegated = true;
grid.addEventListener('click', (event) => {
const card = cardFor(event.target);
if (!card) return;
const v = cardVideo.get(card);
const actionEl = event.target.closest('[data-action]');
const action = actionEl && card.contains(actionEl) ? actionEl.dataset.action : '';
if (action) {
// The document-level handler closes every open menu; stopping
// here is what lets the menu this click just opened stay open.
event.stopPropagation();
}
switch (action) {
case 'favorite':
App.favorites.toggle(v);
return;
case 'uploader':
App.videos.handleSearch(actionEl.dataset.uploader || actionEl.textContent || '');
return;
case 'tag':
App.videos.handleSearch(actionEl.textContent || '');
return;
case 'menu':
App.videos.toggleMenu(card.querySelector('.video-menu'), actionEl);
return;
case 'info':
App.videos.closeAllMenus();
App.ui.openInfo(v);
return;
case 'download':
App.videos.closeAllMenus();
App.videos.downloadVideo(v);
return;
}
if (card.classList.contains('is-loading')) return; if (card.classList.contains('is-loading')) return;
card.classList.add('is-loading'); card.classList.add('is-loading');
App.player.open(v, { originEl: card }); App.player.open(v, { originEl: card });
});
const setTitleFlag = function(event, flag, value) {
const card = cardFor(event.target);
if (!card) return;
// pointerover/pointerout also fire while moving between a card's own
// children; only a crossing of the card's own edge counts.
if (event.relatedTarget && card.contains(event.relatedTarget)) return;
card.dataset[flag] = value;
updateTitleActive(card);
}; };
cardVideo.set(card, v);
card.addEventListener('pointerenter', () => App.videos.ensureFormats(v), { once: true }); grid.addEventListener('focusin', (event) => setTitleFlag(event, 'titleFocused', '1'));
return card; grid.addEventListener('focusout', (event) => setTitleFlag(event, 'titleFocused', '0'));
if (titleEnv.useHoverFocus) {
// mouseenter/mouseleave don't bubble, so they can't be delegated;
// pointerover/pointerout do, and the containment check above turns
// them into the same thing.
grid.addEventListener('pointerover', (event) => setTitleFlag(event, 'titleHovered', '1'));
grid.addEventListener('pointerout', (event) => setTitleFlag(event, 'titleHovered', '0'));
}
}; };
// Appends a freshly-loaded page of videos. The card DOM is *not* built here; // Appends a freshly-loaded page of videos. The card DOM is *not* built here;
@@ -1139,19 +1309,61 @@ App.videos = App.videos || {};
card.style.width = l.width + 'px'; card.style.width = l.width + 'px';
}; };
// Cards are pooled, not thrown away: building one costs ~250us of
// parsing and allocation, rebinding an existing one ~4us, and scrolling
// a grid does nothing but mount and unmount. Bounded at roughly twice
// the mounted window so a long session can't grow the pool without end.
const pool = [];
const POOL_MAX = 60;
let builtCards = 0;
let recycledCards = 0;
const acquire = function(v) {
const card = pool.pop();
if (!card) {
builtCards++;
return App.videos.buildCard(v);
}
recycledCards++;
App.videos.bindCard(card, v);
App.videos.attachThumbnail(cardRefs(card).img, v.thumb);
return card;
};
const release = function(card) {
resolveObserver.unobserve(card);
if (titleObserver) {
titleObserver.unobserve(card);
titleVisibility.delete(card);
}
if (card._revealAnim) {
card.removeEventListener('animationend', card._revealAnim);
card._revealAnim = null;
}
card.remove();
cardVideo.delete(card);
App.videos.resetCard(card);
if (pool.length < POOL_MAX) pool.push(card);
};
const mount = function(i) { const mount = function(i) {
if (mounted.has(i)) return; if (mounted.has(i)) return;
const v = state.loadedVideos[i]; const v = state.loadedVideos[i];
const l = layout[i]; const l = layout[i];
if (!v || !l) return; if (!v || !l) return;
const card = App.videos.buildCard(v); const card = acquire(v);
place(card, l); place(card, l);
// Entrance animation only the first time an index appears, so cards // Entrance animation only the first time an index appears, so cards
// don't re-animate every time they scroll back into the window. // don't re-animate every time they scroll back into the window.
if (!revealed.has(i)) { if (!revealed.has(i)) {
revealed.add(i); revealed.add(i);
card.classList.add('is-revealing'); card.classList.add('is-revealing');
card.addEventListener('animationend', () => card.classList.remove('is-revealing'), { once: true }); // Kept so release can take it off again: a card recycled before
// the animation ends would otherwise carry the listener for the
// rest of its life.
const onRevealEnd = () => card.classList.remove('is-revealing');
card._revealAnim = onRevealEnd;
card.addEventListener('animationend', onRevealEnd, { once: true });
} }
grid().appendChild(card); grid().appendChild(card);
mounted.set(i, card); mounted.set(i, card);
@@ -1160,6 +1372,11 @@ App.videos = App.videos || {};
const img = card.querySelector('img'); const img = card.querySelector('img');
if (img) { if (img) {
const reveal = () => { const reveal = () => {
// Release nulls this, so a reveal already queued for a frame
// that lands after the card was rebound does nothing --
// covers the requestAnimationFrame path, which unlike the
// load listener cannot simply be removed.
if (img._revealHandler !== reveal) return;
img.style.aspectRatio = 'auto'; img.style.aspectRatio = 'auto';
img.classList.add('is-loaded'); img.classList.add('is-loaded');
// Remember the real aspect ratio so any later re-pack (see // Remember the real aspect ratio so any later re-pack (see
@@ -1170,6 +1387,10 @@ App.videos = App.videos || {};
} }
if (mounted.get(i) === card) correct(i); if (mounted.get(i) === card) correct(i);
}; };
// Held on the element so release can remove it: this closes
// over `v` and `i`, and a recycled image firing it again would
// file the new picture's dimensions under the old video's id.
img._revealHandler = reveal;
if (img.complete && img.naturalHeight > 0) requestAnimationFrame(reveal); if (img.complete && img.naturalHeight > 0) requestAnimationFrame(reveal);
else img.addEventListener('load', reveal); else img.addEventListener('load', reveal);
} }
@@ -1181,14 +1402,8 @@ App.videos = App.videos || {};
const unmount = function(i) { const unmount = function(i) {
const card = mounted.get(i); const card = mounted.get(i);
if (!card) return; if (!card) return;
resolveObserver.unobserve(card);
if (titleObserver) {
titleObserver.unobserve(card);
titleVisibility.delete(card);
}
cardVideo.delete(card);
card.remove();
mounted.delete(i); mounted.delete(i);
release(card);
}; };
// Mounts cards intersecting the viewport window, unmounts the rest. // Mounts cards intersecting the viewport window, unmounts the rest.
@@ -1202,12 +1417,21 @@ App.videos = App.videos || {};
const end = viewTop + vh * (1 + OVERSCAN); const end = viewTop + vh * (1 + OVERSCAN);
let anchorIndex = -1; let anchorIndex = -1;
let anchorTop = Infinity; let anchorTop = Infinity;
// Everything leaving the window is released before anything entering
// it is mounted, so the cards just freed are available to the cards
// arriving. Mounting first -- which is what walking the list in
// index order does when scrolling up -- finds the pool empty and
// builds a card it was about to be handed.
const entering = [];
for (let i = 0; i < layout.length; i++) { for (let i = 0; i < layout.length; i++) {
const l = layout[i]; const l = layout[i];
if (!l) continue; if (!l) continue;
const visible = l.top < end && (l.top + l.height) > start; const visible = l.top < end && (l.top + l.height) > start;
if (visible) mount(i); if (visible) {
else if (mounted.has(i)) unmount(i); if (!mounted.has(i)) entering.push(i);
} else if (mounted.has(i)) {
unmount(i);
}
// Topmost card still crossing the viewport top: the reader's // Topmost card still crossing the viewport top: the reader's
// place in the list, kept fresh on every scroll pass (see // place in the list, kept fresh on every scroll pass (see
// lastAnchor). // lastAnchor).
@@ -1216,6 +1440,7 @@ App.videos = App.videos || {};
anchorIndex = i; anchorIndex = i;
} }
} }
for (let k = 0; k < entering.length; k++) mount(entering[k]);
// Frozen while a resize settles: the browser moves the scroll // Frozen while a resize settles: the browser moves the scroll
// position itself during a rotation, and tracking that would replace // position itself during a rotation, and tracking that would replace
// the reader's real place with wherever the browser landed. // the reader's real place with wherever the browser landed.
@@ -1359,6 +1584,7 @@ App.videos = App.videos || {};
const ensureInit = function() { const ensureInit = function() {
if (!cols) measureMetrics(); if (!cols) measureMetrics();
bindGridDelegation();
if (initialized) return; if (initialized) return;
initialized = true; initialized = true;
settleWidth = window.innerWidth || 0; settleWidth = window.innerWidth || 0;
@@ -1377,6 +1603,8 @@ App.videos = App.videos || {};
}; };
const reset = function() { const reset = function() {
// Releases rather than discards: a new result set is about to mount
// its own cards, and these are exactly the right shape for it.
mounted.forEach((card, i) => unmount(i)); mounted.forEach((card, i) => unmount(i));
mounted.clear(); mounted.clear();
revealed.clear(); // new result set should animate in again revealed.clear(); // new result set should animate in again
@@ -1384,7 +1612,7 @@ App.videos = App.videos || {};
colBottoms = []; colBottoms = [];
colItems = []; colItems = [];
const el = grid(); const el = grid();
if (el) { el.innerHTML = ''; el.style.height = '0px'; } if (el) { el.style.height = '0px'; }
}; };
// Removes a single video's card from the grid: its DOM element is // Removes a single video's card from the grid: its DOM element is
@@ -1399,7 +1627,11 @@ App.videos = App.videos || {};
relayout(); relayout();
}; };
return { ensureInit, packFrom, update: scheduleUpdate, relayout, removeVideo, reset, isNearEnd }; const stats = function() {
return { built: builtCards, recycled: recycledCards, pooled: pool.length };
};
return { ensureInit, packFrom, update: scheduleUpdate, relayout, removeVideo, reset, isNearEnd, stats };
})(); })();
App.videos.updateLoadMoreState = function() { App.videos.updateLoadMoreState = function() {

View File

@@ -96,15 +96,31 @@ def boot(page):
page.wait_for_timeout(3000) page.wait_for_timeout(3000)
def scroll_around(page, downs=8): def grow(page, want=80, tries=14):
"""Load enough videos that the grid is taller than the mount window.
The virtualizer keeps everything within 1.2 viewports of the screen mounted,
so a short list never unmounts anything and never exercises recycling.
"""
for _ in range(tries):
if page.evaluate("() => App.state.loadedVideos.length") >= want:
break
page.evaluate("() => window.scrollTo(0, document.documentElement.scrollHeight)")
page.wait_for_timeout(2000)
return page.evaluate("() => App.state.loadedVideos.length")
def scroll_around(page, downs=10):
"""Churn the mount/unmount path: far down, then back to the top.""" """Churn the mount/unmount path: far down, then back to the top."""
for _ in range(downs): for _ in range(downs):
page.evaluate("() => window.scrollBy(0, window.innerHeight * 1.5)") page.evaluate("() => window.scrollBy(0, window.innerHeight * 1.5)")
page.wait_for_timeout(700)
page.wait_for_timeout(1500)
for _ in range(downs):
page.evaluate("() => window.scrollBy(0, -window.innerHeight * 1.5)")
page.wait_for_timeout(500) page.wait_for_timeout(500)
page.wait_for_timeout(1200)
page.evaluate("() => window.scrollTo(0, 0)")
page.wait_for_timeout(1200)
for _ in range(downs // 2):
page.evaluate("() => window.scrollBy(0, window.innerHeight * 2.5)")
page.wait_for_timeout(400)
page.wait_for_timeout(1500) page.wait_for_timeout(1500)
@@ -152,6 +168,11 @@ def main():
check_cards(c, page.evaluate(INSPECT), "on first render") check_cards(c, page.evaluate(INSPECT), "on first render")
# Informational: how many videos it took to outgrow the mount window
# varies with viewport and page size. Whether that was *enough* is
# asserted properly at the end, on the pool's hit rate.
print(f"\ngrew the listing to {grow(page)} videos")
scroll_around(page) scroll_around(page)
check_cards(c, page.evaluate(INSPECT), "after scrolling down and back") check_cards(c, page.evaluate(INSPECT), "after scrolling down and back")
@@ -176,13 +197,28 @@ def main():
}""") }""")
c.ok("the card menu opens after recycling", opened) c.ok("the card menu opens after recycling", opened)
stats = page.evaluate( # Tag clicks read the button's own text now, not a data attribute.
"() => (App.virtualGrid.stats && App.virtualGrid.stats()) || null") searched = page.evaluate("""() => {
const tag = document.querySelector('#video-grid .video-card .video-tag');
if (!tag) return 'no-tags';
const label = tag.textContent;
tag.click();
return document.getElementById('search-input').value === label ? 'ok' : 'mismatch';
}""")
c.ok("clicking a tag searches for it", searched in ("ok", "no-tags"), searched)
page.wait_for_timeout(1500)
stats = page.evaluate("""
() => (App.virtualGrid.stats && App.virtualGrid.stats()) || null
""")
if stats: if stats:
total = (stats.get("built", 0) + stats.get("recycled", 0)) or 1 total = (stats.get("built", 0) + stats.get("recycled", 0)) or 1
rate = 100 * stats.get("recycled", 0) // total
print(f"\npool: {stats.get('recycled', 0)} recycled / {total} mounts " print(f"\npool: {stats.get('recycled', 0)} recycled / {total} mounts "
f"({100 * stats.get('recycled', 0) // total}% hit rate), " f"({rate}% hit rate), {stats.get('pooled', 0)} idle in pool")
f"{stats.get('pooled', 0)} idle in pool") # A hit rate near zero means cards are still being built per mount,
# so none of the checks above actually exercised a recycled card.
c.ok("cards are actually being recycled", rate >= 50, f"{rate}% hit rate")
browser.close() browser.close()