Add a library page: seasons, race weekends and sessions as Plex shows them

The operator wants to browse the posters the way a Plex or Emby Formula 1
library shows them. The page reads the whole library from the one Kometa
file (rounds, race names in the race posters' addresses, sessions in the
episodes'), waits through a fresh server's minutes-long first answer
instead of failing, and loads each picture only when it is on screen, two
at a time, dropping the queue when the reader leaves a level: every
poster is a render of about 10 s that pulls map tiles. Each level has its
own address and back/forward work; a picture the server has none for is
a plain card with its name.

The session order per weekend format moves into site.js, so the posters
page and the library read the same list.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
This commit is contained in:
2026-11-27 10:33:19 +01:00
parent 8237aabd87
commit db9f386c7a
10 changed files with 518 additions and 16 deletions
+420
View File
@@ -0,0 +1,420 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Library · F1 Circuits API examples</title>
<meta name="description" content="Browse a Formula 1 library the way Plex or Emby shows it: seasons, race weekends and sessions, with the posters and thumbnails the F1 Circuits API renders.">
<link rel="icon" href="data:,">
<link rel="stylesheet" href="site.css">
</head>
<body>
<header class="site">
<a class="brand" href="index.html">F1 <span>Circuits</span> API</a>
<nav aria-label="Examples">
<a href="index.html">Overview</a>
<a href="circuits.html">Circuit browser</a>
<a href="tracks.html">Track images</a>
<a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a>
<a href="kometa.html">Kometa</a>
<a href="library.html" aria-current="page">Library</a>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>Library</h1>
<p class="lead">
A Formula 1 library as Plex or Emby shows it with the <a href="kometa.html">Kometa file</a>: a season is a show
with its season poster, a race weekend a season of that show with its race poster, a session an episode with its
thumbnail. The whole library comes from one call; each picture is its own call, made when it comes on screen.
</p>
<section class="card" id="data">
<h3>The library: one call</h3>
<p class="hint">
The file lists every season, its rounds and each poster’s and thumbnail’s address; the race names are read from
the race posters’ addresses, the sessions from the episodes’. The page does not call Jolpica itself.
</p>
<div class="request"></div>
<div class="status"></div>
<div class="result"></div>
</section>
<nav class="crumbs" id="crumbs" aria-label="Breadcrumb"></nav>
<div id="level"></div>
</main>
<footer class="pager">
<a rel="prev" href="kometa.html">← Kometa</a>
<a class="home" href="index.html">All examples</a>
<span></span>
</footer>
<script src="site.js"></script>
<script>
(function () {
const { h, api, setRequest, setStatus, notice, fmtSize, sniff, SESSIONS } = F1;
const $ = (id) => document.getElementById(id);
const MAX_AT_ONCE = 2;
// ---------------------------------------------------------------- the file
/** The file's address with the page's API base: the file names the public address. */
function local(url) {
const u = new URL(url);
return api(u.pathname + u.search);
}
/** Seasons, each with its rounds and each round's sessions, read from the Kometa file. */
function parse(text) {
const seasons = [];
let season = null;
let round = null;
for (const line of text.split('\n')) {
let m;
if ((m = /^ {2}"Season (\d+)":\s*$/.exec(line))) {
season = { season: m[1], poster: null, rounds: [] };
seasons.push(season);
round = null;
} else if (!season) {
continue;
} else if ((m = /^ {4}url_poster: (\S+)\s*$/.exec(line))) {
season.poster = local(m[1]);
} else if ((m = /^ {6}(\d+):\s*$/.exec(line))) {
round = { round: m[1], poster: null, name: '', sessions: [] };
season.rounds.push(round);
} else if (round && (m = /^ {8}url_poster: (\S+)\s*$/.exec(line))) {
round.poster = local(m[1]);
// /posters/race/{race name}/{season}.png
const parts = new URL(m[1]).pathname.split('/');
round.name = decodeURIComponent(parts[3] || '');
} else if (round && (m = /^ {10}(\d+):\s*$/.exec(line))) {
round.sessions.push({ episode: m[1], thumb: null, slug: '' });
} else if (round && round.sessions.length && (m = /^ {12}url_poster: (\S+)\s*$/.exec(line))) {
const s = round.sessions[round.sessions.length - 1];
s.thumb = local(m[1]);
// /posters/session/{race name}/{season}/{session}.png
s.slug = decodeURIComponent(new URL(m[1]).pathname.split('/').pop().replace(/\.png$/, ''));
}
}
for (const s of seasons) for (const r of s.rounds) r.sprint = r.sessions.some((x) => x.slug.includes('sprint'));
seasons.sort((a, b) => b.season - a.season);
return seasons;
}
const clock = (d) => d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
const elapsed = (ms) => {
if (ms < 1000) return `${Math.round(ms)} ms`;
const s = Math.round(ms / 1000);
return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`;
};
/**
* Asks for the file until it comes. On a fresh server the first answer takes minutes (it fills every
* season's schedule from Jolpica, paced): the page waits and says so. An answer that never came
* (no connection, a proxy's 502/503/504) is asked again; any other refusal is an error.
*/
async function loadLibrary() {
const card = $('data');
const url = api('/kometa/formula-1-metadata.yml');
const status = card.querySelector('.status');
setRequest(card.querySelector('.request'), url);
const since = new Date();
let attempt = 1;
let note = '';
const say = () => {
const text = `Waiting for the answer since ${clock(since)} (${elapsed(Date.now() - since)})${note}. On a fresh server the first answer takes a few minutes: it asks Jolpica for the schedule of every season, paced under Jolpica’s limit. Then it comes at once.`;
setStatus(status, 'pending', text);
const w = $('level').querySelector('.waiting .text');
if (w) w.textContent = `Waiting since ${clock(since)}: ${elapsed(Date.now() - since)}${note}.`;
};
const timer = setInterval(say, 1000);
say();
try {
for (;;) {
const t0 = performance.now();
let res;
try {
res = await fetch(url);
} catch (e) {
note = `; no answer to try ${attempt} (${e.message}), asked again`;
attempt++;
await new Promise((r) => setTimeout(r, 10000));
continue;
}
if ([502, 503, 504].includes(res.status)) {
note = `; try ${attempt} answered HTTP ${res.status}, asked again`;
attempt++;
await new Promise((r) => setTimeout(r, 10000));
continue;
}
const text = await res.text();
const ms = Math.round(performance.now() - t0);
if (!res.ok) {
setStatus(status, 'error', `HTTP ${res.status} · ${text.slice(0, 160)}`);
return null;
}
const seasons = parse(text);
const rounds = seasons.reduce((n, s) => n + s.rounds.length, 0);
const empty = seasons.filter((s) => !s.rounds.length).map((s) => s.season);
setStatus(status, 'ok', `HTTP ${res.status} · ${res.headers.get('content-type')} · ${fmtSize(text.length)} · ${elapsed(Date.now() - since)}`);
card.querySelector('.result').replaceChildren(
h('p', {}, `${seasons.length} seasons, ${rounds} race weekends.`),
empty.length ? notice(empty.length > 2 ? 'error' : 'info', `${empty.length} season(s) list no rounds in the file: ${empty.join(', ')}. The server had no schedule for them from Jolpica (a season not yet published, or Jolpica not answering).`) : null);
return seasons;
}
} finally {
clearInterval(timer);
}
}
// ---------------------------------------------------------------- one queue for every picture
/** At most MAX_AT_ONCE pictures asked at once; a level's queue is emptied when the reader leaves it. */
const queue = {
waiting: [],
running: new Set(),
add(job) {
if (job.state !== 'idle') return;
job.state = 'queued';
this.waiting.push(job);
job.queued();
this.pump();
},
drop(job) {
const i = this.waiting.indexOf(job);
if (i < 0) return;
this.waiting.splice(i, 1);
job.state = 'idle';
job.idle();
},
clear() {
for (const job of this.waiting) job.state = 'dropped';
this.waiting = [];
for (const job of this.running) job.abort.abort();
},
pump() {
while (this.running.size < MAX_AT_ONCE && this.waiting.length) {
const job = this.waiting.shift();
job.state = 'running';
job.abort = new AbortController();
this.running.add(job);
job.run(job.abort.signal).finally(() => { this.running.delete(job); this.pump(); });
}
},
};
let observer = null;
let objectURLs = [];
function leaveLevel() {
queue.clear();
if (observer) observer.disconnect();
for (const u of objectURLs) URL.revokeObjectURL(u);
objectURLs = [];
observer = new IntersectionObserver((entries) => {
for (const e of entries) {
const job = e.target._job;
if (!job) continue;
if (e.isIntersecting) queue.add(job);
else queue.drop(job);
}
});
}
/**
* A picture tile: the frame (loaded through the queue when on screen), its title, its request URL and the
* answer's status. A 404 shows a plain card with the name.
*/
function tile({ url, shape, title, sub, href, alt }) {
const frame = h('div', { class: `tile-frame ${shape}` }, h('span', { class: 'tile-note' }, 'Loads when on screen'));
const status = h('div', { class: 'status idle' }, 'Not asked yet.');
const req = h('div', { class: 'request compact' });
setRequest(req, url);
const plain = (why) => {
frame.classList.add('plain');
frame.replaceChildren(h('div', {}, h('strong', {}, title), h('span', {}, why)));
};
const job = {
state: 'idle',
queued() { setStatus(status, 'idle', 'In the queue.'); frame.firstChild.textContent = 'In the queue'; },
idle() { setStatus(status, 'idle', 'Not asked yet.'); frame.firstChild.textContent = 'Loads when on screen'; },
async run(signal) {
setStatus(status, 'pending', 'Rendering on the server…');
frame.replaceChildren(h('span', { class: 'tile-note' }, 'Rendering on the server…'));
const t0 = performance.now();
let res;
let blob;
try {
res = await fetch(url, { signal });
blob = await res.blob();
} catch (e) {
if (e.name === 'AbortError') return;
job.state = 'done';
setStatus(status, 'error', `No answer: ${e.message}`);
plain('No answer from the server.');
return;
}
job.state = 'done';
const ms = Math.round(performance.now() - t0);
const summary = `HTTP ${res.status} · ${fmtSize(blob.size)} · ${elapsed(ms)}`;
if (res.status === 404) {
let detail = '';
try { detail = JSON.parse(await blob.text()).detail || ''; } catch { /* not JSON */ }
setStatus(status, 'warn', `${summary}${detail ? ` — ${detail}` : ''}`);
plain('The server has no picture for it.');
return;
}
if (!res.ok) {
setStatus(status, 'error', summary);
plain(`The server answered HTTP ${res.status}.`);
return;
}
if (await sniff(blob) !== 'png') {
setStatus(status, 'error', `${summary} — not a PNG`);
plain('The answer is not a PNG.');
return;
}
const src = URL.createObjectURL(blob);
objectURLs.push(src);
frame.replaceChildren(h('img', { src, alt: alt || title }));
setStatus(status, 'ok', summary);
},
};
frame._job = job;
observer.observe(frame);
const body = [frame, h('div', { class: 'tile-title' }, title), sub ? h('div', { class: 'tile-sub' }, sub) : null];
return h('article', { class: 'tile' },
href ? h('a', { class: 'tile-link', href: F1.linkWithKept(href) }, ...body) : h('div', { class: 'tile-link' }, ...body),
req, status);
}
// ---------------------------------------------------------------- levels
const pageURL = (q) => `library.html${q ? `?${new URLSearchParams(q)}` : ''}`;
function crumbs(parts) {
const out = [];
parts.forEach((p, i) => {
if (i) out.push(h('span', { class: 'sep', 'aria-hidden': 'true' }, '›'));
out.push(i === parts.length - 1
? h('span', { 'aria-current': 'page' }, p.label)
: h('a', { href: F1.linkWithKept(p.href) }, p.label));
});
$('crumbs').replaceChildren(...out);
}
const weekend = (r) => (r.sprint ? 'sprint weekend' : 'standard weekend');
function levelSeasons(lib) {
crumbs([{ label: 'Library' }]);
document.title = 'Library · F1 Circuits API examples';
$('level').replaceChildren(
h('h2', {}, 'Seasons'),
h('p', {}, `${lib.length} seasons, newest first. Each is a show; its poster is `, h('code', {}, '/posters/season/{season}.png'), '.'),
h('div', { class: 'tiles posters' }, ...lib.map((s) => tile({
url: s.poster, shape: 'poster', title: s.season,
sub: s.rounds.length ? `${s.rounds.length} race weekends` : 'no rounds in the file',
href: pageURL({ season: s.season }), alt: `${s.season} season poster`,
}))));
}
function levelSeason(s) {
crumbs([{ label: 'Library', href: pageURL() }, { label: s.season }]);
document.title = `${s.season} · Library · F1 Circuits API examples`;
const sprints = s.rounds.filter((r) => r.sprint).length;
$('level').replaceChildren(
h('div', { class: 'level-head' },
tile({ url: s.poster, shape: 'poster', title: `Season ${s.season}`, alt: `${s.season} season poster` }),
h('div', {},
h('h2', {}, `${s.season}`),
h('p', {}, s.rounds.length
? `${s.rounds.length} race weekends in round order${sprints ? `, ${sprints} of them sprint weekends` : ''}. Each is a season of the show; its poster is `
: 'The file lists no rounds for this season. ', s.rounds.length ? h('code', {}, '/posters/race/{race name}/{season}.png') : null, s.rounds.length ? ', with the round, the name and the date drawn on it.' : null),
h('p', {}, 'From the file: ', h('code', {}, s.rounds.length ? `"Season ${s.season}" → seasons` : `"Season ${s.season}"`), '.'))),
s.rounds.length
? h('div', { class: 'tiles posters' }, ...s.rounds.map((r) => tile({
url: r.poster, shape: 'poster', title: `R${r.round} · ${r.name}`, sub: weekend(r),
href: pageURL({ season: s.season, round: r.round }), alt: `${r.name} ${s.season} poster`,
})))
: notice('info', 'Nothing to show: the server had no schedule for this season from Jolpica.'));
}
function levelRound(s, r) {
crumbs([{ label: 'Library', href: pageURL() }, { label: s.season, href: pageURL({ season: s.season }) }, { label: r.name }]);
document.title = `${r.name} ${s.season} · Library · F1 Circuits API examples`;
$('level').replaceChildren(
h('div', { class: 'level-head' },
tile({ url: r.poster, shape: 'poster', title: `R${r.round} · ${r.name}`, alt: `${r.name} ${s.season} poster` }),
h('div', {},
h('h2', {}, `${r.name} ${s.season}`),
h('p', {}, `Round ${r.round}, a ${weekend(r)}: ${r.sessions.length} sessions in Kometa’s episode order. Each is an episode; its thumbnail is `,
h('code', {}, '/posters/session/{race name}/{season}/{session}.png'), '.'),
h('p', {}, 'From the file: ', h('code', {}, `"Season ${s.season}" → seasons → ${r.round} → episodes`), '.'))),
h('div', { class: 'tiles thumbs' }, ...r.sessions.map((x) => tile({
url: x.thumb, shape: 'thumb', title: `Episode ${x.episode} · ${SESSIONS.label[x.slug] || x.slug}`,
sub: x.slug, alt: `${r.name} ${s.season}, ${SESSIONS.label[x.slug] || x.slug}`,
}))));
}
function waiting() {
$('level').replaceChildren(h('div', { class: 'card waiting' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }),
h('div', {},
h('p', {}, h('strong', {}, 'The server is putting the library together.')),
h('p', { class: 'text' }, 'Waiting…'),
h('p', {}, 'The first answer on a fresh server takes a few minutes; the page shows the library as soon as it comes.'))));
}
// ---------------------------------------------------------------- navigation
let library = null;
function render() {
leaveLevel();
const q = new URLSearchParams(location.search);
const season = q.get('season');
const round = q.get('round');
if (!library) { crumbs([{ label: 'Library' }]); waiting(); return; }
if (!season) return levelSeasons(library);
const s = library.find((x) => x.season === season);
if (!s) {
crumbs([{ label: 'Library', href: pageURL() }, { label: season }]);
$('level').replaceChildren(notice('error', `Season ${season} is not in the library. `, h('a', { href: F1.linkWithKept(pageURL()) }, 'Back to the seasons')));
return;
}
if (!round) return levelSeason(s);
const r = s.rounds.find((x) => x.round === round);
if (!r) {
crumbs([{ label: 'Library', href: pageURL() }, { label: s.season, href: pageURL({ season }) }, { label: `Round ${round}` }]);
$('level').replaceChildren(notice('error', `Round ${round} is not in ${season}. `, h('a', { href: F1.linkWithKept(pageURL({ season })) }, `Back to ${season}`)));
return;
}
return levelRound(s, r);
}
// Links to another level of this page change the address and the level, without loading the page again.
document.addEventListener('click', (e) => {
const a = e.target.closest('a[href]');
if (!a || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || a.target) return;
const url = new URL(a.href);
if (url.origin !== location.origin || url.pathname !== location.pathname) return;
e.preventDefault();
history.pushState(null, '', url.href);
render();
window.scrollTo(0, $('crumbs').offsetTop - 10);
});
window.addEventListener('popstate', render);
render();
loadLibrary().then((lib) => {
library = lib;
if (lib) render();
else $('level').replaceChildren(notice('error', 'The library could not be read: see the call above.'));
});
})();
</script>
</body>
</html>