Add an example site that calls every route, served at /examples/

A reader learns the API fastest from working calls: one page per area
(circuit browser, track images, GPS traces on a map, grand prix lookup,
posters, Kometa) shows the exact request URL next to its answer. Pages
call their own origin when the app serves them, and the public service
when opened from disk or given ?api=. Posters render only on a button
press, since each one fetches map tiles on the server. A body that does
not match the asked format is said in red, never shown as success.

The image copies examples/ so the deployed app serves the same pages.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
This commit is contained in:
2026-11-27 09:48:04 +01:00
parent 3271e2d563
commit b6e6e9d565
12 changed files with 2027 additions and 1 deletions
+1
View File
@@ -3,3 +3,4 @@ qgis
__pycache__/
cache/
.idea/
.venv-site/
+13 -1
View File
@@ -1,6 +1,7 @@
from fastapi import FastAPI, HTTPException, Response
from fastapi.responses import FileResponse, Response as FastAPIResponse, PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pathlib import Path
import logging
@@ -79,10 +80,21 @@ async def root():
"/grand-prix/{grand_prix_name}/year/{year}",
"/posters/race/{grand_prix_name}/{season}.png",
"/posters/season/{season}.png",
]
"/posters/session/{grand_prix_name}/{season}/{session_slug}.png",
"/kometa/formula-1-metadata.yml",
],
"examples": "/examples/",
}
# The example site: one page per area of the API, each calling the routes above (examples/index.html).
app.mount(
"/examples",
StaticFiles(directory=Path(__file__).resolve().parent / "examples", html=True),
name="examples",
)
@app.get("/posters/race/{grand_prix_name}/{season}.png")
async def get_race_poster(grand_prix_name: str, season: int, bg: BackgroundStyle = BackgroundStyle.AERIAL):
"""Plex-ready 1000x1500 race poster (PNG). Cached on disk per (race, bg).
+219
View File
@@ -0,0 +1,219 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Circuit browser · F1 Circuits API examples</title>
<meta name="description" content="Browse the F1 Circuits catalogue: countries, cities, circuits and layouts, with each layout's track image.">
<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" aria-current="page">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>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>Circuit browser</h1>
<p class="lead">
The catalogue is a tree: a country holds cities, a city holds circuits, a circuit holds layouts. Each level has a
route; pick an entry to make the next call. Every layout shows its track image.
</p>
<section class="card" id="countries">
<h2>1. Countries</h2>
<p><code>/circuits</code> lists every country, and nests its whole tree inside each one.</p>
<div class="request"></div>
<div class="status"></div>
<div class="choices" id="country-list"></div>
<details><summary>The JSON answer</summary><div class="result"></div></details>
</section>
<section class="card" id="cities">
<h2>2. Cities of a country</h2>
<p><code>/circuits/{country}</code> answers <code>{"cities": [...]}</code>, each city with its circuits.</p>
<div class="request"></div>
<div class="status idle">Pick a country above.</div>
<div class="choices" id="city-list"></div>
<details><summary>The JSON answer</summary><div class="result"></div></details>
</section>
<section class="card" id="circuits">
<h2>3. Circuits in a city</h2>
<p><code>/circuits/{country}/{city}</code> answers <code>{"circuits": [...]}</code>.</p>
<div class="request"></div>
<div class="status idle">Pick a city above.</div>
<div class="choices" id="circuit-list"></div>
<details><summary>The JSON answer</summary><div class="result"></div></details>
</section>
<section class="card" id="circuit">
<h2>4. One circuit and its layouts</h2>
<p>
<code>/circuits/{country}/{city}/{circuit}</code> answers the circuit’s name, its Wikipedia and Fandom pages and
its layouts. Each layout’s image below is its own call,
<code>/circuits/{country}/{city}/{circuit}/layout/{layout}/svg</code> (see <a href="tracks.html">Track images</a>).
</p>
<div class="request"></div>
<div class="status idle">Pick a circuit above.</div>
<div id="circuit-head"></div>
<div class="layouts" id="layout-list"></div>
<details><summary>The JSON answer</summary><div class="result"></div></details>
</section>
<section class="card" id="layout">
<h2>5. One layout</h2>
<p>
<code>/circuits/{country}/{city}/{circuit}/layout/{layout}</code> answers one layout: its slug, its description
and <code>imageUrl</code>, the source drawing on the F1 Fandom wiki.
</p>
<div class="request"></div>
<div class="status idle" data-idle="Press “Details” on a layout above.">Press “Details” on a layout above.</div>
<div class="result"></div>
</section>
</main>
<footer class="pager">
<a rel="prev" href="index.html">← Overview</a>
<a class="home" href="index.html">All examples</a>
<a rel="next" href="tracks.html">Track images →</a>
</footer>
<script src="site.js"></script>
<script>
(function () {
const { h, api, path, callJSON, setRequest, layoutYears, layoutStart } = F1;
const $ = (id) => document.getElementById(id);
const want = {
country: F1.params.get('country') || 'belgium',
city: F1.params.get('city') || 'spa',
circuit: F1.params.get('circuit') || 'circuit-de-spa-francorchamps',
};
const state = {};
function remember() {
const url = new URL(location.href);
for (const k of ['country', 'city', 'circuit']) {
if (state[k]) url.searchParams.set(k, state[k]); else url.searchParams.delete(k);
}
history.replaceState(null, '', url.href);
}
function choices(el, items, pressed, onPick) {
el.replaceChildren(...items.map((it) => {
const b = h('button', { type: 'button', 'aria-pressed': String(it.slug === pressed), title: `slug: ${it.slug}` },
it.name, ' ', h('small', {}, it.note));
b.addEventListener('click', () => {
for (const o of el.querySelectorAll('button')) o.setAttribute('aria-pressed', String(o === b));
onPick(it.slug);
});
return b;
}));
}
function clear(...ids) {
for (const id of ids) {
const card = $(id);
card.querySelector('.request').replaceChildren();
const s = card.querySelector('.status');
s.className = 'status idle';
s.textContent = s.dataset.idle || 'Pick an entry above.';
card.querySelector('.result').replaceChildren();
}
if (ids.includes('cities')) $('city-list').replaceChildren();
if (ids.includes('circuits')) $('circuit-list').replaceChildren();
if (ids.includes('circuit')) { $('circuit-head').replaceChildren(); $('layout-list').replaceChildren(); }
}
const byName = (a, b) => a.name.localeCompare(b.name);
const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
async function loadCountries() {
const v = await callJSON($('countries'), api('/circuits'));
if (!v) return;
const list = [...v.countries].sort(byName);
choices($('country-list'), list.map((c) => ({ slug: c.slug, name: c.name, note: count(Object.keys(c.localities).length, 'city', 'cities') })),
want.country, pickCountry);
if (list.some((c) => c.slug === want.country)) pickCountry(want.country);
}
async function pickCountry(slug) {
state.country = slug; state.city = state.circuit = null; remember();
clear('cities', 'circuits', 'circuit', 'layout');
const v = await callJSON($('cities'), api(path`/circuits/${slug}`));
if (!v) return;
const list = [...v.cities].sort(byName);
choices($('city-list'), list.map((c) => ({ slug: c.slug, name: c.name, note: count(Object.keys(c.circuits).length, 'circuit', 'circuits') })),
want.city, pickCity);
const next = list.find((c) => c.slug === want.city) || (list.length === 1 ? list[0] : null);
if (next) { $('city-list').querySelector(`[title="slug: ${CSS.escape(next.slug)}"]`).setAttribute('aria-pressed', 'true'); pickCity(next.slug); }
}
async function pickCity(slug) {
state.city = slug; state.circuit = null; remember();
clear('circuits', 'circuit', 'layout');
const v = await callJSON($('circuits'), api(path`/circuits/${state.country}/${slug}`));
if (!v) return;
const list = [...v.circuits].sort(byName);
choices($('circuit-list'), list.map((c) => ({ slug: c.slug, name: c.name, note: count(Object.keys(c.layouts).length, 'layout', 'layouts') })),
want.circuit, pickCircuit);
const next = list.find((c) => c.slug === want.circuit) || (list.length === 1 ? list[0] : null);
if (next) { $('circuit-list').querySelector(`[title="slug: ${CSS.escape(next.slug)}"]`).setAttribute('aria-pressed', 'true'); pickCircuit(next.slug); }
}
async function pickCircuit(slug) {
state.circuit = slug; remember();
clear('circuit', 'layout');
const { country, city } = state;
const v = await callJSON($('circuit'), api(path`/circuits/${country}/${city}/${slug}`));
if (!v) return;
$('circuit-head').replaceChildren(
h('h3', {}, v.name),
h('p', {}, 'Read more: ',
v.urls.wikipedia ? h('a', { href: v.urls.wikipedia, target: '_blank', rel: 'noopener' }, 'Wikipedia') : null,
v.urls.wikipedia && v.urls.fandom ? ' · ' : null,
v.urls.fandom ? h('a', { href: v.urls.fandom, target: '_blank', rel: 'noopener' }, 'F1 Fandom wiki') : null));
const slugs = Object.keys(v.layouts).sort((a, b) => layoutStart(a) - layoutStart(b));
$('layout-list').replaceChildren(...slugs.map((l) => layoutCard(country, city, slug, v.layouts[l])));
}
function layoutCard(country, city, circuit, layout) {
const imgUrl = api(path`/circuits/${country}/${city}/${circuit}/layout/${layout.slug}/svg`);
const req = h('div', { class: 'request compact' });
setRequest(req, imgUrl);
const img = h('img', { src: imgUrl, alt: `Track layout ${layoutYears(layout.slug)}`, loading: 'lazy' });
const tile = h('div', { class: 'track-tile' }, img);
img.addEventListener('error', () => tile.replaceChildren(F1.notice('error', 'The image did not load; open its URL to see why.')));
const q = new URLSearchParams({ country, city, circuit, layout: layout.slug }).toString();
const details = h('button', { type: 'button' }, 'Details');
details.addEventListener('click', () => {
callJSON($('layout'), api(path`/circuits/${country}/${city}/${circuit}/layout/${layout.slug}`));
$('layout').scrollIntoView({ behavior: 'smooth', block: 'start' });
});
return h('div', { class: 'layout-card' },
h('h3', {}, layoutYears(layout.slug), ' ', h('small', {}, h('code', {}, layout.slug))),
tile,
req,
h('p', {}, layout.description || 'No description.'),
h('div', { class: 'links' },
details,
h('a', { href: F1.linkWithKept(`tracks.html?${q}`) }, 'All formats'),
h('a', { href: F1.linkWithKept(`map.html?${q}`) }, 'On the map'),
layout.imageUrl ? h('a', { href: layout.imageUrl, target: '_blank', rel: 'noopener' }, 'Source drawing') : null));
}
loadCountries();
})();
</script>
</body>
</html>
+104
View File
@@ -0,0 +1,104 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grand prix lookup · F1 Circuits API examples</title>
<meta name="description" content="Look up the track of any F1 race by its name and season: the API finds the circuit and the layout raced that year.">
<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" aria-current="page">Grand prix lookup</a>
<a href="posters.html">Posters</a>
<a href="kometa.html">Kometa</a>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>Grand prix lookup</h1>
<p class="lead">
Name a race and a season, and the API answers the track it was raced on: it reads that season’s schedule from
Jolpica, matches the race by its exact name, finds the circuit in its catalogue and picks the layout of that year.
</p>
<section class="card" id="races">
<h2>1. The season’s races</h2>
<p>
This page lists the races by calling Jolpica itself, from the browser (Jolpica allows any origin). If it cannot
be reached, type the name: the API needs it exactly as Jolpica’s <code>raceName</code>, such as
<code>British Grand Prix</code>.
</p>
<div class="controls" id="race-picker"></div>
<div class="request"></div>
<div class="status"></div>
</section>
<section class="card" id="lookup">
<h2>2. The race’s track</h2>
<p><code>/grand-prix/{race name}/{season}/{format}</code>, the race name percent-encoded (a space is <code>%20</code>).</p>
<div class="controls"><fieldset id="format"><legend>Format</legend></fieldset></div>
<div id="jolpica-says"></div>
<div class="request"></div>
<div class="status idle">Choose a race.</div>
<div class="result"></div>
</section>
<h2>When the lookup finds nothing</h2>
<p>
The API answers <code>404 {"detail": "Circuit not found"}</code> when the name is not in that season’s schedule,
when Jolpica cannot be reached from the server, or when the circuit or that year’s layout is not in the catalogue
yet (browse it in the <a href="circuits.html">circuit browser</a>).
</p>
</main>
<footer class="pager">
<a rel="prev" href="map.html">← GPS traces</a>
<a class="home" href="index.html">All examples</a>
<a rel="next" href="posters.html">Posters →</a>
</footer>
<script src="site.js"></script>
<script>
(function () {
const { h, api, path, call, showImage, showGeoJSON, racePicker } = F1;
const $ = (id) => document.getElementById(id);
const card = $('lookup');
const FORMATS = ['svg', 'png', 'geojson'];
const initial = FORMATS.includes(F1.params.get('format')) ? F1.params.get('format') : 'svg';
for (const f of FORMATS) {
const input = h('input', { type: 'radio', name: 'format', value: f, checked: f === initial });
input.addEventListener('change', lookup);
$('format').append(h('label', { class: 'inline' }, input, f));
}
let chosen = null;
async function lookup() {
if (!chosen || !chosen.name || !(chosen.season >= 1950)) return;
const f = $('format').querySelector('input:checked').value;
const r = chosen.race;
$('jolpica-says').replaceChildren(r
? h('p', {}, `Jolpica: round ${r.round} on ${r.date}, at ${r.Circuit.circuitName} in ${r.Circuit.Location.locality}, ${r.Circuit.Location.country}.`)
: h('p', {}, 'Jolpica’s entry for this name is not known on this page; the API looks it up itself.'));
const answer = await call(card, api(path`/grand-prix/${chosen.name}/${chosen.season}/${f}`), { waiting: 'Looking up the race…' });
const out = card.querySelector('.result');
if (!answer) { out.replaceChildren(); return; }
const status = card.querySelector('.status');
if (f === 'geojson') await showGeoJSON(out, answer, { status });
else await showImage(out, answer, f, { alt: `${chosen.name} ${chosen.season}`, status });
}
racePicker($('race-picker'), { card: $('races'), onChange: (c) => { chosen = c; lookup(); } });
})();
</script>
</body>
</html>
+134
View File
@@ -0,0 +1,134 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>F1 Circuits API · examples</title>
<meta name="description" content="Worked examples of every route of the F1 Circuits API: circuits, track images, GPS traces, grand prix lookup, posters and Kometa metadata.">
<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" aria-current="page">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>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>The F1 Circuits API, by example</h1>
<p class="lead">
F1 Circuits serves the layout of every Formula 1 circuit, one per period the track was raced in, traced by GPS:
as an SVG drawing, a PNG image and the GeoJSON trace itself. On top of the layouts it renders race and season
posters, session thumbnails and a Kometa metadata file for a Formula 1 library in Plex.
</p>
<p>
The public address is <a href="https://f1-circuits.zurag.be/">https://f1-circuits.zurag.be</a>. Every route is a
plain <code>GET</code>, needs no key, and allows any origin (CORS), so a page anywhere can call it from the browser.
Each page below makes real calls and shows the exact URL it sends next to the answer: copy it into a terminal
(<code>curl -O &lt;url&gt;</code>) or a page of your own.
</p>
<h2>The examples</h2>
<div class="pages">
<a class="page" href="circuits.html">
<h3>Circuit browser</h3>
<p>Walk the catalogue: countries, their cities, the circuits there and each circuit’s layouts, with every layout’s track image.</p>
<ul>
<li><code>/circuits</code></li>
<li><code>/circuits/{country}</code></li>
<li><code>/circuits/{country}/{city}</code></li>
<li><code>/circuits/{country}/{city}/{circuit}</code></li>
<li><code>/circuits/{country}/{city}/{circuit}/layout/{layout}</code></li>
</ul>
</a>
<a class="page" href="tracks.html">
<h3>Track images</h3>
<p>One layout’s file in SVG, PNG or GeoJSON, chosen by its layout or by a year the circuit was raced.</p>
<ul>
<li><code>/circuits/{country}/{city}/{circuit}/layout/{layout}/{format}</code></li>
<li><code>/tracks/{country}/{city}/{circuit}/year/{year}/{format}</code></li>
</ul>
</a>
<a class="page" href="map.html">
<h3>GPS traces on a map</h3>
<p>Draw a layout’s GeoJSON trace on an OpenStreetMap or satellite map, with its length and start point.</p>
<ul>
<li><code>/circuits/{country}/{city}/{circuit}/layout/{layout}/geojson</code></li>
</ul>
</a>
<a class="page" href="grand-prix.html">
<h3>Grand prix lookup</h3>
<p>Name a race and a season; the API finds the circuit and the layout raced that year.</p>
<ul>
<li><code>/grand-prix/{race name}/{season}/{format}</code></li>
</ul>
</a>
<a class="page" href="posters.html">
<h3>Posters</h3>
<p>Race posters on five backgrounds, season posters and a thumbnail per session of a race weekend, rendered on request.</p>
<ul>
<li><code>/posters/race/{race name}/{season}.png?bg={aerial|osm|dark|light|none}</code></li>
<li><code>/posters/season/{season}.png</code></li>
<li><code>/posters/session/{race name}/{season}/{session}.png</code></li>
</ul>
</a>
<a class="page" href="kometa.html">
<h3>Kometa metadata</h3>
<p>The metadata file that gives a Plex Formula 1 library every poster and thumbnail above, and how Kometa uses it.</p>
<ul>
<li><code>/kometa/formula-1-metadata.yml</code></li>
</ul>
</a>
</div>
<h2>Choosing which API a page calls</h2>
<div class="card">
<p>
One helper (<a href="site.js"><code>site.js</code></a>) picks the address for every page, in this order:
</p>
<ol>
<li><code>?api=&lt;base&gt;</code> in the page’s address wins, such as <code>?api=http://127.0.0.1:8000</code>. Links between the pages keep it.</li>
<li>A page opened from disk (<code>file://</code>) calls the public service, <code>https://f1-circuits.zurag.be</code>.</li>
<li>A page served over http(s), as the API serves these pages at <code>/examples/</code>, calls its own origin with relative URLs.</li>
</ol>
<p>The address in use is in the header, top right; open it to change it.</p>
</div>
<h2>The API’s own index</h2>
<p>The root route lists the routes and where these examples live.</p>
<div class="card" id="root-call">
<div class="request"></div>
<div class="status"></div>
<div class="result"></div>
</div>
<h2>Words used here</h2>
<table class="kv">
<tr><th>Country, city, circuit</th><td>Slugs in lower case with hyphens, as the <code>/circuits</code> routes list them (<code>belgium</code>, <code>spa</code>, <code>circuit-de-spa-francorchamps</code>). A slug may hold accented letters; encode it in a URL.</td></tr>
<tr><th>Layout</th><td>One shape of a circuit, named by the years it was raced: <code>1950-1970</code>, <code>1983-</code> (1983 until today), or a single year.</td></tr>
<tr><th>Format</th><td><code>svg</code>, <code>png</code> or <code>geojson</code>.</td></tr>
<tr><th>Race name</th><td>The race’s name exactly as <a href="https://api.jolpi.ca/ergast/f1/2024.json">Jolpica</a> (the Ergast successor) writes it, such as <code>Belgian Grand Prix</code>; the API reads the season’s schedule there.</td></tr>
</table>
</main>
<footer class="pager">
<span></span>
<a class="home" href="index.html">All examples</a>
<a rel="next" href="circuits.html">Circuit browser →</a>
</footer>
<script src="site.js"></script>
<script>
F1.callJSON(document.getElementById('root-call'), F1.api('/'));
</script>
</body>
</html>
+149
View File
@@ -0,0 +1,149 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kometa metadata · F1 Circuits API examples</title>
<meta name="description" content="The Kometa metadata file the F1 Circuits API generates for a Formula 1 library in Plex, and what it is for.">
<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" aria-current="page">Kometa</a>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>Kometa metadata</h1>
<p class="lead">
<a href="https://kometa.wiki/">Kometa</a> (formerly Plex Meta Manager) sets titles and artwork in a Plex library
from YAML files. This route generates the file for a Formula 1 library: it gives every season, every round and every
session of a weekend its artwork, all of it rendered by this API.
</p>
<h2>What it is for</h2>
<div class="card">
<p>In a Formula 1 library as Kometa’s Formula 1 builder shapes it:</p>
<ul>
<li>each F1 season is one <strong>show</strong>, titled like the file’s keys (<code>Season 2024</code>);</li>
<li>each round of that season is a Plex <strong>season</strong> of the show;</li>
<li>each session of the race weekend is an <strong>episode</strong>.</li>
</ul>
<p>
<code>f1_season</code> lets Kometa name the rounds and episodes from that year’s schedule. The file adds the
artwork: the show gets the <a href="posters.html">season poster</a>, each round its race poster, and each episode
its session thumbnail. It covers every season from 1950 to next year; Kometa skips a show or a round the library
does not hold.
</p>
<table class="kv">
<tr><th><code>f1_season</code></th><td>The year the show holds; Kometa’s Formula 1 builder reads its schedule.</td></tr>
<tr><th><code>round_prefix: true</code></th><td>Puts the round number in front of each round’s name.</td></tr>
<tr><th><code>shorten_gp: true</code></th><td>Shortens “Grand Prix” to “GP” in the names.</td></tr>
<tr><th><code>url_poster</code> (show)</th><td><code>/posters/season/{season}.png</code></td></tr>
<tr><th><code>seasons.{round}.url_poster</code></th><td><code>/posters/race/{race name}/{season}.png</code></td></tr>
<tr><th><code>episodes.{n}.url_poster</code></th><td><code>/posters/session/{race name}/{season}/{session}.png</code>, numbered as on the <a href="posters.html">posters page</a>: 10 episodes for a standard weekend, 15 for a sprint weekend.</td></tr>
</table>
<h3>Using it in Kometa</h3>
<p>Point the library at the file’s URL in Kometa’s <code>config.yml</code>; Kometa fetches it on every run:</p>
<pre class="code" id="config"></pre>
<p>
The poster addresses inside the file use the public name the service is served under, so Plex can fetch them.
The answer is <code>text/yaml</code> and may be cached for an hour (<code>Cache-Control: public, max-age=3600</code>).
</p>
</div>
<h2>The file</h2>
<section class="card" id="yaml">
<p>
<code>/kometa/formula-1-metadata.yml</code>. The server builds it from the Jolpica schedule of every season; the
first call after a restart takes several seconds.
</p>
<div class="request"></div>
<div class="status"></div>
<div id="summary"></div>
<div class="controls">
<label>Show <select id="season-filter"><option value="">All seasons</option></select></label>
</div>
<div class="result"></div>
</section>
</main>
<footer class="pager">
<a rel="prev" href="posters.html">← Posters</a>
<a class="home" href="index.html">All examples</a>
<span></span>
</footer>
<script src="site.js"></script>
<script>
(function () {
const { h, api, call, showText, notice } = F1;
const $ = (id) => document.getElementById(id);
const fileURL = F1.absolute(api('/kometa/formula-1-metadata.yml'));
$('config').textContent = [
'libraries:',
' Formula 1: # the library’s name in Plex',
' metadata_files:',
` - url: ${fileURL}`,
].join('\n');
/** Splits the file into one block per show, counting its rounds and episodes. */
function parse(text) {
const lines = text.split('\n');
const head = [];
const seasons = [];
let cur = null;
for (const line of lines) {
const m = /^ {2}"Season (\d+)":/.exec(line);
if (m) { cur = { season: m[1], lines: [line], rounds: 0, episodes: 0 }; seasons.push(cur); continue; }
if (!cur) { head.push(line); continue; }
cur.lines.push(line);
if (/^ {6}\d+:\s*$/.test(line)) cur.rounds++;
else if (/^ {10}\d+:\s*$/.test(line)) cur.episodes++;
}
return { head, seasons };
}
async function load() {
const card = $('yaml');
const answer = await call(card, api('/kometa/formula-1-metadata.yml'), { waiting: 'The server is building the file from every season’s schedule…' });
if (!answer) return;
const text = await answer.blob.text();
const { head, seasons } = parse(text);
const rounds = seasons.reduce((n, s) => n + s.rounds, 0);
const episodes = seasons.reduce((n, s) => n + s.episodes, 0);
const empty = seasons.filter((s) => s.rounds === 0).map((s) => s.season);
const parts = [h('p', {}, `${seasons.length} shows (seasons ${seasons[0] ? seasons[0].season : '?'} to ${seasons.length ? seasons[seasons.length - 1].season : '?'}), ${rounds} rounds with a race poster, ${episodes} episodes with a session thumbnail.`)];
if (empty.length) {
parts.push(notice(empty.length > 2 ? 'error' : 'info',
`${empty.length} of ${seasons.length} shows list no rounds: `, h('code', {}, empty.join(', ')),
'. A show lists no rounds when the server had no schedule for that season from Jolpica (a season still to be published, or Jolpica not answering the server). Kometa then sets only that show’s poster.'));
}
$('summary').replaceChildren(...parts);
const filter = $('season-filter');
filter.append(...seasons.map((s) => h('option', { value: s.season }, `Season ${s.season} (${s.rounds} rounds)`)));
const show = () => {
const s = seasons.find((x) => x.season === filter.value);
showText(card.querySelector('.result'), s ? [...head, ...s.lines].join('\n') : text, { tall: true });
};
filter.addEventListener('change', show);
show();
}
load();
})();
</script>
</body>
</html>
+185
View File
@@ -0,0 +1,185 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GPS traces on a map · F1 Circuits API examples</title>
<meta name="description" content="Draw an F1 track layout's GeoJSON GPS trace on a Leaflet map with OpenStreetMap or satellite tiles.">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="">
<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" aria-current="page">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a>
<a href="kometa.html">Kometa</a>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>GPS traces on a map</h1>
<p class="lead">
Each layout was traced by GPS along the track. Its <code>geojson</code> format is that trace: a GeoJSON
<code>FeatureCollection</code> holding one <code>LineString</code> of <code>[longitude, latitude]</code> points. Any
map library draws it as it comes; this page uses <a href="https://leafletjs.com/">Leaflet</a>. Switch to the
satellite layer to see the trace follow the tarmac.
</p>
<div class="card" id="tree">
<h3>The picker is filled from one call</h3>
<div class="request"></div>
<div class="status"></div>
<div class="result"></div>
</div>
<section class="card" id="trace">
<h2>A layout’s trace</h2>
<p><code>/circuits/{country}/{city}/{circuit}/layout/{layout}/geojson</code></p>
<div id="raw-note"></div>
<div class="controls" id="picker"></div>
<div class="request"></div>
<div class="status idle">Choose a layout.</div>
<div id="problem"></div>
<div id="map" role="region" aria-label="Map of the circuit"></div>
<div id="facts"></div>
<details><summary>The GeoJSON answer</summary><div class="result"></div></details>
</section>
<h2>Draw it yourself</h2>
<p>The whole of it, with Leaflet loaded:</p>
<pre class="code" id="snippet"></pre>
</main>
<footer class="pager">
<a rel="prev" href="tracks.html">← Track images</a>
<a class="home" href="index.html">All examples</a>
<a rel="next" href="grand-prix.html">Grand prix lookup →</a>
</footer>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script src="site.js"></script>
<script>
(function () {
const { h, api, path, call, layoutPicker, layoutYears, showJSON, notice, lineOf, lineLength } = F1;
const $ = (id) => document.getElementById(id);
const card = $('trace');
// ?raw=<base> reads the repository's own files (circuits/<country>/<city>/<circuit>/<layout>.geo.json)
// from <base> instead of the API: a way to try the page against the traces themselves.
const raw = (F1.params.get('raw') || '').replace(/\/+$/, '');
if (raw) {
$('raw-note').append(notice('info', 'Reading the repository’s raw trace files from ', h('code', {}, F1.absolute(raw)),
' (set by ?raw=), not from the API. Remove ?raw= from the address to call the API.'));
}
const map = L.map('map', { scrollWheelZoom: false }).setView([50.44, 5.97], 14);
const osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);
const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
maxZoom: 19,
maxNativeZoom: 18,
attribution: 'Imagery &copy; Esri, Maxar, Earthstar Geographics',
});
L.control.layers({ 'OpenStreetMap': osm, 'Satellite (Esri)': satellite }).addTo(map);
L.control.scale({ imperial: false }).addTo(map);
map.on('focus', () => map.scrollWheelZoom.enable());
map.on('blur', () => map.scrollWheelZoom.disable());
let drawn = null;
function traceURL(p) {
if (raw) {
const e = encodeURIComponent;
return `${raw}/${e(p.country)}/${e(p.city)}/${e(p.circuit)}/${e(p.layout)}.geo.json`;
}
return api(path`/circuits/${p.country}/${p.city}/${p.circuit}/layout/${p.layout}/geojson`);
}
function facts(p, data) {
const line = lineOf(data);
const props = line.properties || {};
const coords = line.geometry.coordinates;
const traced = Math.round(lineLength(coords));
const rows = [
['Circuit', `${p.circuitName}, ${p.cityName} (${p.countryName})`],
['Layout', `${layoutYears(p.layout)} (${p.layout})`],
['GPS points', String(coords.length)],
['Length of the trace', `${(traced / 1000).toFixed(3)} km, measured along the points on this page`],
];
if (props.length) rows.push(['Length (property)', `${(props.length / 1000).toFixed(3)} km`]);
if (props.altitude !== undefined) rows.push(['Altitude (property)', `${props.altitude} m`]);
for (const [k, v] of Object.entries(props)) {
if (['length', 'altitude'].includes(k) || typeof v === 'object') continue;
rows.push([`${k} (property)`, String(v)]);
}
$('facts').replaceChildren(h('table', { class: 'kv' },
...rows.map(([k, v]) => h('tr', {}, h('th', {}, k), h('td', {}, v)))));
}
async function draw(p) {
if (!p.layout) return;
const url = traceURL(p);
const answer = await call(card, url, { label: raw ? 'raw file' : null, waiting: 'Fetching the trace…' });
const out = card.querySelector('.result');
if (drawn) { drawn.remove(); drawn = null; }
$('facts').replaceChildren();
$('problem').replaceChildren();
out.replaceChildren();
if (!answer) return;
const fail = (why, ...content) => {
const status = card.querySelector('.status');
F1.setStatus(status, 'error', `${status.textContent} — ${why}`);
$('problem').replaceChildren(notice('error', ...content));
};
const text = await answer.blob.text();
let data;
try {
data = JSON.parse(text);
} catch {
const kind = await F1.sniff(answer.blob);
fail('not GeoJSON',
`Nothing drawn: the answer is ${kind === 'svg' ? 'an SVG document' : 'not JSON'}, not GeoJSON (its Content-Type header says ${answer.type}). It starts with: `,
h('code', {}, text.slice(0, 120)));
return;
}
if (!lineOf(data)) {
fail('no LineString', 'Nothing drawn: the answer is JSON but holds no LineString feature.');
showJSON(out, data);
return;
}
drawn = L.featureGroup().addTo(map);
L.geoJSON(data, { style: { color: '#e10600', weight: 4, opacity: 0.9 } }).addTo(drawn);
const [lon, lat] = lineOf(data).geometry.coordinates[0];
L.circleMarker([lat, lon], { radius: 7, color: '#ffffff', weight: 2, fillColor: '#15151e', fillOpacity: 1 })
.bindTooltip('First point of the trace').addTo(drawn);
map.fitBounds(drawn.getBounds(), { padding: [30, 30] });
facts(p, data);
showJSON(out, data);
}
$('snippet').textContent = [
`const map = L.map('map');`,
`L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {`,
` attribution: '© OpenStreetMap contributors' }).addTo(map);`,
`const res = await fetch('${F1.absolute(api('/circuits/belgium/spa/circuit-de-spa-francorchamps/layout/1983-/geojson'))}');`,
`const track = L.geoJSON(await res.json(), { style: { color: '#e10600', weight: 4 } }).addTo(map);`,
`map.fitBounds(track.getBounds());`,
].join('\n');
layoutPicker($('picker'), { treeCard: $('tree'), sync: true, onChange: draw });
})();
</script>
</body>
</html>
+221
View File
@@ -0,0 +1,221 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Posters · F1 Circuits API examples</title>
<meta name="description" content="Render F1 race posters, season posters and session thumbnails for Plex from the F1 Circuits API.">
<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" aria-current="page">Posters</a>
<a href="kometa.html">Kometa</a>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>Posters</h1>
<p class="lead">
The API renders artwork for a Formula 1 library in Plex: a 1000×1500 poster per race and per season, and a
1920×1080 thumbnail per session of a race weekend. The server draws each one on request, fetching map tiles for its
background, and keeps it on disk afterwards; so this page renders only the one you ask for, when you press its
button.
</p>
<section class="card" id="races">
<h2>1. Choose a race</h2>
<p>The race poster and the session thumbnails name the race as Jolpica’s <code>raceName</code>; this list comes from Jolpica.</p>
<div class="controls" id="race-picker"></div>
<div class="request"></div>
<div class="status"></div>
</section>
<div class="grid-2">
<section class="card" id="race-poster">
<h2>Race poster</h2>
<p><code>/posters/race/{race name}/{season}.png?bg={background}</code>, 1000×1500: the round, the race’s name, the track and its date over a map of the circuit.</p>
<div class="controls">
<label><span>Background (<code>bg</code>)</span>
<select id="bg">
<option value="aerial">aerial: Esri satellite imagery (the default)</option>
<option value="osm">osm: OpenStreetMap street map</option>
<option value="dark">dark: Carto Dark Matter</option>
<option value="light">light: Carto Positron</option>
<option value="none">none: plain black, no tiles (fastest)</option>
</select>
</label>
<button type="button" class="primary" id="render-race">Render the race poster</button>
</div>
<div class="request compact"></div>
<div class="status idle">Not rendered yet.</div>
<div class="result preview"></div>
</section>
<section class="card" id="season-poster">
<h2>Season poster</h2>
<p><code>/posters/season/{season}.png</code>, 1000×1500: the year over a photo of that season’s cars, or over black when the server has no photo for it.</p>
<div class="controls">
<label>Season <input type="number" id="season" min="1950" max="2100"></label>
<button type="button" class="primary" id="render-season">Render the season poster</button>
</div>
<div class="request compact"></div>
<div class="status idle">Not rendered yet.</div>
<div class="result preview"></div>
</section>
</div>
<section class="card" id="session-thumb">
<h2>Session thumbnail</h2>
<p>
<code>/posters/session/{race name}/{season}/{session}.png</code>, 1920×1080: an aerial view of the circuit with
the race’s name and the session’s label. Kometa numbers a weekend’s episodes differently for a standard weekend
(10 episodes) and a sprint weekend (15); the list shows the chosen race’s format first, in episode order.
</p>
<div class="controls">
<label><span>Session (<code>session</code>)</span> <select id="session"></select></label>
<button type="button" class="primary" id="render-session">Render the thumbnail</button>
</div>
<div class="request"></div>
<div class="status idle">Not rendered yet.</div>
<div class="result preview"></div>
</section>
<h2>Every session slug</h2>
<table>
<thead><tr><th>Slug</th><th>Label on the thumbnail</th><th>Episode, standard weekend</th><th>Episode, sprint weekend</th></tr></thead>
<tbody id="slugs"></tbody>
</table>
</main>
<footer class="pager">
<a rel="prev" href="grand-prix.html">← Grand prix lookup</a>
<a class="home" href="index.html">All examples</a>
<a rel="next" href="kometa.html">Kometa →</a>
</footer>
<script src="site.js"></script>
<script>
(function () {
const { h, api, path, call, setRequest, setStatus, showImage, racePicker } = F1;
const $ = (id) => document.getElementById(id);
// Kometa's episode numbering per weekend format: the same maps the service renders from.
const STANDARD = [
['fp1', 'Free Practice 1'], ['fp2', 'Free Practice 2'], ['fp3', 'Free Practice 3'],
['pre-qualifying', 'Pre-Qualifying Buildup'], ['qualifying', 'Qualifying'], ['post-qualifying', 'Post-Qualifying'],
['pre-race', 'Pre-Race Buildup'], ['race', 'Race'], ['post-race', 'Post-Race'], ['highlights', 'Highlights'],
];
const SPRINT = [
['fp1', 'Free Practice 1'], ['pre-sprint-qualifying', 'Pre-Sprint-Qualifying Buildup'],
['sprint-qualifying', 'Sprint Qualifying'], ['post-sprint-qualifying', 'Post-Sprint-Qualifying'],
['pre-sprint', 'Pre-Sprint Buildup'], ['sprint', 'Sprint'], ['post-sprint', 'Post-Sprint'],
['pre-qualifying', 'Pre-Qualifying Buildup'], ['qualifying', 'Qualifying'], ['post-qualifying', 'Post-Qualifying'],
['pre-race', 'Pre-Race Buildup'], ['race', 'Race'], ['post-race', 'Post-Race'], ['highlights', 'Highlights'],
['bonus', 'Bonus Content'],
];
const LABEL = Object.fromEntries([...STANDARD, ...SPRINT]);
const ALL = Object.keys(LABEL);
$('slugs').replaceChildren(...ALL.map((slug) => {
const std = STANDARD.findIndex(([s]) => s === slug);
const spr = SPRINT.findIndex(([s]) => s === slug);
return h('tr', {}, h('td', {}, h('code', {}, slug)), h('td', {}, LABEL[slug]),
h('td', {}, std >= 0 ? String(std + 1) : '–'), h('td', {}, spr >= 0 ? String(spr + 1) : '–'));
}));
let chosen = null;
let seasonTouched = false;
/** Shows the URL a button will call, without calling it; a result of another URL is cleared. */
function preview(card, url) {
card._wanted = url;
if (card._shown === url) return;
setRequest(card.querySelector('.request'), url);
card.querySelector('.result').replaceChildren();
card._shown = null;
if (!card.querySelector('.status').classList.contains('pending')) {
setStatus(card.querySelector('.status'), 'idle', 'Not rendered yet: press the button.');
}
}
async function render(card, button, url, alt, portrait) {
button.disabled = true;
try {
const answer = await call(card, url, { waiting: 'Rendering on the server: it fetches map tiles first, a few seconds the first time…' });
const out = card.querySelector('.result');
if (card._wanted !== url) {
setRequest(card.querySelector('.request'), card._wanted);
setStatus(card.querySelector('.status'), 'idle', 'The choice changed while it rendered: press the button again.');
return;
}
if (!answer) { out.replaceChildren(); return; }
await showImage(out, answer, 'png', { alt, tile: false, className: portrait ? 'poster portrait' : 'poster', status: card.querySelector('.status') });
card._shown = url;
} finally {
button.disabled = false;
}
}
const raceURL = () => api(path`/posters/race/${chosen.name}/${chosen.season}.png`) + `?bg=${encodeURIComponent($('bg').value)}`;
const seasonURL = () => api(path`/posters/season/${$('season').value}.png`);
const sessionURL = () => api(path`/posters/session/${chosen.name}/${chosen.season}/${$('session').value}.png`);
function fillSessions() {
const keep = $('session').value || 'race';
const own = chosen && chosen.sprint ? SPRINT : STANDARD;
const ownSlugs = new Set(own.map(([s]) => s));
const rest = ALL.filter((s) => !ownSlugs.has(s));
const format = chosen && chosen.race ? (chosen.sprint ? 'a sprint weekend' : 'a standard weekend') : 'format unknown, standard order';
$('session').replaceChildren(
h('optgroup', { label: `This race (${format})` },
...own.map(([s, label], i) => h('option', { value: s }, `Episode ${i + 1} · ${label} (${s})`))),
h('optgroup', { label: 'The other format’s slugs' },
...rest.map((s) => h('option', { value: s }, `${LABEL[s]} (${s})`))));
$('session').value = ALL.includes(keep) ? keep : 'race';
}
function previews() {
if (chosen && chosen.name) {
preview($('race-poster'), raceURL());
preview($('session-thumb'), sessionURL());
}
if ($('season').value) preview($('season-poster'), seasonURL());
}
$('bg').addEventListener('change', previews);
$('session').addEventListener('change', previews);
$('season').addEventListener('input', () => { seasonTouched = true; previews(); });
$('render-race').addEventListener('click', () => {
if (chosen && chosen.name) render($('race-poster'), $('render-race'), raceURL(), `${chosen.name} ${chosen.season} poster`, true);
});
$('render-season').addEventListener('click', () => {
if ($('season').value) render($('season-poster'), $('render-season'), seasonURL(), `${$('season').value} season poster`, true);
});
$('render-session').addEventListener('click', () => {
if (chosen && chosen.name) render($('session-thumb'), $('render-session'), sessionURL(), `${chosen.name} ${chosen.season} ${$('session').value} thumbnail`, false);
});
racePicker($('race-picker'), {
card: $('races'),
onChange: (c) => {
chosen = c;
if (!seasonTouched) $('season').value = c.season;
fillSessions();
previews();
},
});
})();
</script>
</body>
</html>
+299
View File
@@ -0,0 +1,299 @@
/* Shared styles for the F1 Circuits API examples: one file, light and dark. */
:root {
color-scheme: light dark;
--bg: #f4f4f7;
--card: #ffffff;
--text: #15151e;
--muted: #5d5d6c;
--line: #dcdce4;
--accent: #e10600;
--accent-text: #ffffff;
--code-bg: #f0f0f4;
--ok: #1a7f37;
--warn: #9a6700;
--error: #c62828;
--tile: #ffffff;
--json-key: #0b5cad;
--json-string: #1a7f37;
--json-number: #a3480b;
--json-literal: #8250df;
--radius: 10px;
--mono: ui-monospace, SFMono-Regular, "JetBrains Mono", Menlo, Consolas, monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111116;
--card: #1b1b23;
--text: #e9e9ef;
--muted: #a3a3b3;
--line: #2e2e3a;
--accent: #ff3b30;
--code-bg: #24242e;
--ok: #4ac26b;
--warn: #d29922;
--error: #ff6b6b;
--tile: #1b1b23;
--json-key: #79b8ff;
--json-string: #85e89d;
--json-number: #ffab70;
--json-literal: #d2a8ff;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 16px/1.55 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
a { color: var(--accent); }
code, pre, kbd { font-family: var(--mono); font-size: 0.9em; }
:not(pre) > code { background: var(--code-bg); padding: 0.1em 0.35em; border-radius: 4px; }
/* ---- header and navigation ---- */
header.site {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1.25rem;
padding: 0.75rem 1.5rem;
background: var(--card);
border-bottom: 3px solid var(--accent);
}
header.site .brand {
font-weight: 800;
color: var(--text);
text-decoration: none;
letter-spacing: 0.02em;
}
header.site .brand span { color: var(--accent); }
header.site nav { display: flex; flex-wrap: wrap; gap: 0.25rem; flex: 1; }
header.site nav a {
color: var(--muted);
text-decoration: none;
padding: 0.3rem 0.6rem;
border-radius: 6px;
}
header.site nav a:hover { color: var(--text); background: var(--code-bg); }
header.site nav a[aria-current="page"] { color: var(--accent-text); background: var(--accent); }
.api-switch { font-size: 0.85rem; color: var(--muted); }
.api-switch summary { cursor: pointer; }
.api-switch summary code { color: var(--text); }
.api-switch form { display: flex; gap: 0.4rem; margin-top: 0.4rem; }
.api-switch input { width: 18rem; }
main { max-width: 1200px; margin: 0 auto; padding: 1.5rem; }
h1 { margin: 0.25rem 0 0.5rem; font-size: 1.9rem; }
h2 { margin: 2rem 0 0.5rem; font-size: 1.35rem; }
h3 { margin: 1.25rem 0 0.4rem; font-size: 1.1rem; }
.lead { color: var(--muted); font-size: 1.08rem; max-width: 60rem; }
footer.pager {
max-width: 1200px;
margin: 2rem auto 0;
padding: 1rem 1.5rem 2.5rem;
display: grid;
grid-template-columns: 1fr auto 1fr;
gap: 1rem;
border-top: 1px solid var(--line);
}
footer.pager a { text-decoration: none; font-weight: 600; }
footer.pager [rel="next"] { justify-self: end; }
footer.pager .home { justify-self: center; }
/* ---- cards, calls and results ---- */
.card {
background: var(--card);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 1rem 1.1rem;
margin: 1rem 0;
}
.card > h2:first-child, .card > h3:first-child { margin-top: 0; }
.grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(340px, 1fr)); gap: 1rem; }
.grid-2 > .card { margin: 0; }
/* The request bar: the exact URL a call sends, with Copy and Open. */
.request {
display: flex;
align-items: center;
gap: 0.5rem;
background: var(--code-bg);
border: 1px solid var(--line);
border-radius: 8px;
padding: 0.4rem 0.5rem;
min-height: 2.4rem;
}
.request .verb {
font: 700 0.75rem var(--mono);
color: var(--accent-text);
background: var(--ok);
border-radius: 4px;
padding: 0.15rem 0.4rem;
}
.request .url {
flex: 1;
overflow-x: auto;
white-space: nowrap;
font-size: 0.85rem;
scrollbar-width: thin;
}
.request .label { font-size: 0.75rem; color: var(--muted); white-space: nowrap; }
.request:empty { display: none; }
/* In a narrow card: the buttons on the first row, the whole URL wrapped below them. */
.request.compact { flex-wrap: wrap; }
.request.compact .url { order: 9; flex-basis: 100%; white-space: normal; overflow-wrap: anywhere; font-size: 0.75rem; }
.request button, .request a.open { font-size: 0.8rem; padding: 0.2rem 0.55rem; }
.request a.open {
border: 1px solid var(--line);
border-radius: 6px;
text-decoration: none;
color: var(--text);
background: var(--card);
}
.status { font-size: 0.85rem; margin: 0.4rem 0 0.6rem; color: var(--muted); min-height: 1.3em; }
.status.ok::before { content: "● "; color: var(--ok); }
.status.pending::before { content: "◌ "; color: var(--warn); }
.status.error { color: var(--error); }
.status.error::before { content: "✕ "; }
.status.idle::before { content: "○ "; }
.result:empty { display: none; }
.hint { font-size: 0.85rem; color: var(--muted); margin: 0 0 0.6rem; }
.hint.error { color: var(--error); }
pre.code {
margin: 0;
background: var(--code-bg);
border: 1px solid var(--line);
border-radius: 8px;
padding: 0.75rem;
overflow: auto;
max-height: 32rem;
font-size: 0.82rem;
line-height: 1.45;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
pre.code.tall { max-height: 70vh; }
.j-key { color: var(--json-key); }
.j-str { color: var(--json-string); }
.j-num { color: var(--json-number); }
.j-lit { color: var(--json-literal); }
.notice {
border-left: 4px solid var(--warn);
background: var(--code-bg);
padding: 0.6rem 0.8rem;
border-radius: 0 8px 8px 0;
margin: 0.6rem 0;
}
.notice.error { border-left-color: var(--error); }
.notice.info { border-left-color: var(--json-key); }
/* ---- forms ---- */
.controls { display: flex; flex-wrap: wrap; gap: 0.75rem 1rem; align-items: end; margin: 0.5rem 0 0.75rem; }
.controls label { display: flex; flex-direction: column; gap: 0.2rem; font-size: 0.8rem; color: var(--muted); }
.controls label.inline { flex-direction: row; align-items: center; gap: 0.35rem; color: var(--text); font-size: 0.9rem; }
.controls fieldset { border: none; padding: 0; margin: 0; display: flex; gap: 0.75rem; align-items: center; }
.controls legend { font-size: 0.8rem; color: var(--muted); padding: 0; margin-bottom: 0.2rem; }
select, input, button {
font: inherit;
font-size: 0.92rem;
color: var(--text);
background: var(--card);
border: 1px solid var(--line);
border-radius: 6px;
padding: 0.35rem 0.5rem;
}
input[type="number"] { width: 6.5rem; }
input.wide { min-width: 16rem; }
select { max-width: 30rem; }
button { cursor: pointer; }
button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); font-weight: 600; }
button:disabled { opacity: 0.55; cursor: progress; }
/* ---- lists of choices (circuit browser) ---- */
.choices { display: flex; flex-wrap: wrap; gap: 0.4rem; margin: 0.5rem 0; }
.choices button { font-size: 0.88rem; }
.choices button[aria-pressed="true"] { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
.choices button small { color: inherit; opacity: 0.7; }
/* ---- images ---- */
.track-tile {
background: var(--tile);
border: 1px solid var(--line);
border-radius: 8px;
display: grid;
place-items: center;
padding: 0.75rem;
min-height: 9rem;
}
.track-tile img { width: 100%; max-width: 480px; max-height: 320px; object-fit: contain; }
@media (prefers-color-scheme: dark) {
/* The service's track images are a black line on a transparent ground. */
.track-tile img { filter: invert(1); }
}
.layouts { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 1rem; }
.layout-card { border: 1px solid var(--line); border-radius: var(--radius); padding: 0.75rem; display: flex; flex-direction: column; gap: 0.5rem; }
.layout-card h3 { margin: 0; }
.layout-card p { margin: 0; font-size: 0.88rem; color: var(--muted); }
.layout-card .links { font-size: 0.85rem; display: flex; gap: 0.75rem; flex-wrap: wrap; }
.layout-card .track-tile { min-height: 7rem; }
.layout-card .track-tile img { max-height: 160px; }
.layout-card code.small { font-size: 0.72rem; word-break: break-all; }
.poster { display: block; max-width: 100%; border-radius: 8px; border: 1px solid var(--line); }
.poster.portrait { max-height: 640px; }
.preview { margin-top: 0.75rem; }
/* ---- tables ---- */
table { border-collapse: collapse; width: 100%; font-size: 0.9rem; }
th, td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line); vertical-align: top; }
th { color: var(--muted); font-weight: 600; }
td code { white-space: nowrap; }
table.kv th { width: 12rem; }
/* ---- map ---- */
#map { height: 560px; border-radius: var(--radius); border: 1px solid var(--line); }
.leaflet-container { font: inherit; }
/* ---- index ---- */
.pages { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1rem; }
.pages a.page {
display: block;
background: var(--card);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 1rem;
color: var(--text);
text-decoration: none;
}
.pages a.page:hover { border-color: var(--accent); }
.pages a.page h3 { margin: 0 0 0.3rem; color: var(--accent); }
.pages a.page p { margin: 0 0 0.5rem; color: var(--muted); font-size: 0.92rem; }
.pages a.page ul { margin: 0; padding-left: 1.1rem; font-size: 0.78rem; }
.pages a.page li code { background: none; padding: 0; overflow-wrap: anywhere; }
+549
View File
@@ -0,0 +1,549 @@
/*
* Shared helper for the F1 Circuits API examples.
*
* - Picks the API base for every page: `?api=<base>` wins; a page opened from disk (file://) calls the
* public service; a page served over http(s), by the app itself, calls its own origin (relative URLs).
* - Shows the exact request URL of every call (copyable), fetches it, and renders the answer.
* - Fills the pickers: layouts from `/circuits`, races from Jolpica.
*/
(function () {
'use strict';
const DEFAULT_API = 'https://f1-circuits.zurag.be';
const JOLPICA = 'https://api.jolpi.ca/ergast/f1';
const params = new URLSearchParams(location.search);
const apiParam = (params.get('api') || '').trim().replace(/\/+$/, '');
const base = apiParam || (location.protocol === 'file:' ? DEFAULT_API : '');
// Query parameters every internal link carries along, so a chosen base stays chosen.
const KEPT = ['api', 'raw'];
/** The URL to fetch for an API path such as `/circuits` (relative when same origin). */
function api(path) { return base + path; }
/** The absolute form of a URL, as the browser sends it. */
function absolute(url) { return new URL(url, location.href).href; }
/** Builds a path, percent-encoding every interpolated value: path`/circuits/${slug}`. */
function path(strings, ...values) {
return strings.reduce((out, s, i) => out + s + (i < values.length ? encodeURIComponent(values[i]) : ''), '');
}
/** document.createElement with attributes and children. */
function h(tag, attrs = {}, ...children) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v === null || v === undefined || v === false) continue;
if (k === 'class') el.className = v;
else if (k === 'text') el.textContent = v;
else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
else el.setAttribute(k, v === true ? '' : v);
}
for (const c of children.flat()) {
if (c === null || c === undefined || c === false) continue;
el.append(c instanceof Node ? c : document.createTextNode(String(c)));
}
return el;
}
function fmtSize(n) {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} kB`;
return `${(n / 1024 / 1024).toFixed(2)} MB`;
}
// ---------------------------------------------------------------- the page frame
function describeBase() {
if (apiParam) return { text: apiParam, why: 'chosen with ?api=' };
if (location.protocol === 'file:') return { text: DEFAULT_API, why: 'the page is opened from disk' };
return { text: location.origin, why: 'the page is served by the API itself (same origin)' };
}
function linkWithKept(href) {
const url = new URL(href, location.href);
for (const k of KEPT) {
if (params.has(k) && !url.searchParams.has(k)) url.searchParams.set(k, params.get(k));
}
return url.href;
}
function frame() {
// Carry ?api= and ?raw= on every link to another example page.
for (const a of document.querySelectorAll('a[href]')) {
const href = a.getAttribute('href');
if (/^[\w-]+\.html([?#].*)?$/.test(href)) a.href = linkWithKept(href);
}
const slot = document.getElementById('api-base');
if (!slot) return;
const d = describeBase();
const input = h('input', { name: 'api', type: 'url', placeholder: DEFAULT_API, value: apiParam });
slot.replaceChildren(h('details', { class: 'api-switch' },
h('summary', { title: d.why }, 'API: ', h('code', {}, d.text)),
h('div', {}, `Why: ${d.why}.`),
h('form', {
onsubmit: (e) => {
e.preventDefault();
const url = new URL(location.href);
const v = input.value.trim();
if (v) url.searchParams.set('api', v); else url.searchParams.delete('api');
location.href = url.href;
},
}, input, h('button', { type: 'submit' }, 'Use'))));
}
// ---------------------------------------------------------------- request bar and status
async function copyText(text, button) {
let done = false;
try {
await navigator.clipboard.writeText(text);
done = true;
} catch {
const ta = h('textarea', { style: 'position:fixed;opacity:0' });
ta.value = text;
document.body.append(ta);
ta.select();
try { done = document.execCommand('copy'); } catch { done = false; }
ta.remove();
}
const was = button.textContent;
button.textContent = done ? 'Copied' : 'Select and copy';
setTimeout(() => { button.textContent = was; }, 1500);
}
/** Shows the exact URL a call sends in a `.request` element. */
function setRequest(el, url, label) {
const abs = absolute(url);
const copy = h('button', { type: 'button', title: 'Copy the URL' }, 'Copy');
copy.addEventListener('click', () => copyText(abs, copy));
el.replaceChildren(...[
h('span', { class: 'verb' }, 'GET'),
h('code', { class: 'url', title: decodeURI(abs) }, abs),
label ? h('span', { class: 'label' }, label) : null,
copy,
h('a', { class: 'open', href: abs, target: '_blank', rel: 'noopener' }, 'Open'),
].filter(Boolean));
}
function setStatus(el, kind, text) {
if (!el) return;
el.className = `status ${kind}`;
el.textContent = text;
}
/** A line of explanation under a control; never a call's status. */
function setHint(el, kind, text) {
el.className = `hint${kind ? ` ${kind}` : ''}`;
el.textContent = text;
}
async function errorDetail(blob) {
try {
const text = await blob.text();
try {
const j = JSON.parse(text);
if (j && j.detail) return typeof j.detail === 'string' ? j.detail : JSON.stringify(j.detail);
} catch { /* not JSON */ }
return text.slice(0, 160);
} catch { return ''; }
}
/**
* Calls a URL for a card holding `.request`, `.status` and `.result`: shows the URL, fetches it, says
* the answer's status, type, size and time. Returns the answer, or null when it failed (the status says
* why) or was replaced by a newer call on the same card.
*/
async function call(card, url, opts = {}) {
setRequest(card.querySelector('.request'), url, opts.label);
const statusEl = card.querySelector('.status');
if (card._abort) card._abort.abort();
const ctl = new AbortController();
card._abort = ctl;
setStatus(statusEl, 'pending', opts.waiting || 'Waiting for the answer…');
const t0 = performance.now();
let res;
let blob;
try {
res = await fetch(url, { signal: ctl.signal });
blob = await res.blob();
} catch (e) {
if (e.name === 'AbortError') return null;
setStatus(statusEl, 'error', `No answer: ${e.message}. The address is unreachable, offline, or the browser blocked it (CORS).`);
return null;
}
if (ctl.signal.aborted) return null;
const ms = Math.round(performance.now() - t0);
const type = res.headers.get('content-type') || 'no content type';
const summary = `HTTP ${res.status} · ${type} · ${fmtSize(blob.size)} · ${ms} ms`;
if (!res.ok) {
const detail = await errorDetail(blob);
setStatus(statusEl, 'error', detail ? `${summary} — ${detail}` : summary);
return null;
}
setStatus(statusEl, 'ok', summary);
return { status: res.status, type, blob, ms, size: blob.size, url };
}
/** Fetches JSON for a card and shows it in its `.result`; returns the parsed value or null. */
async function callJSON(card, url, opts = {}) {
const answer = await call(card, url, opts);
const out = card.querySelector('.result');
if (!answer) { if (out && !opts.keep) out.replaceChildren(); return null; }
let value;
try {
value = JSON.parse(await answer.blob.text());
} catch (e) {
setStatus(card.querySelector('.status'), 'error', `The answer is not JSON: ${e.message}`);
return null;
}
if (out && opts.show !== false) showJSON(out, value);
return value;
}
// ---------------------------------------------------------------- renderers
function escapeHTML(s) {
return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
}
/** JSON text with arrays of plain numbers kept on one line (coordinates, bounding boxes). */
function prettyJSON(value) {
return JSON.stringify(value, null, 2)
.replace(/\[\s+(-?\d[\d.eE+-]*(?:,\s+-?\d[\d.eE+-]*)*)\s+\]/g, (_, inner) => `[${inner.replace(/\s+/g, ' ')}]`);
}
/** JSON text as HTML with keys, strings, numbers and literals marked; tokenised first, then escaped. */
function highlightJSON(text) {
const re = /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g;
let out = '';
let last = 0;
let m;
while ((m = re.exec(text))) {
out += escapeHTML(text.slice(last, m.index));
const [, str, colon, lit, num] = m;
if (str) out += colon ? `<span class="j-key">${escapeHTML(str)}</span>${colon}` : `<span class="j-str">${escapeHTML(str)}</span>`;
else if (lit) out += `<span class="j-lit">${lit}</span>`;
else out += `<span class="j-num">${num}</span>`;
last = re.lastIndex;
}
return out + escapeHTML(text.slice(last));
}
function showJSON(el, value, opts = {}) {
const pre = h('pre', { class: `code${opts.tall ? ' tall' : ''}` });
pre.innerHTML = highlightJSON(typeof value === 'string' ? value : prettyJSON(value));
el.replaceChildren(pre);
return pre;
}
function showText(el, text, opts = {}) {
const pre = h('pre', { class: `code${opts.tall ? ' tall' : ''}` }, text);
el.replaceChildren(pre);
return pre;
}
/** What the first bytes of a body are: 'png', 'svg', 'json' or 'unknown'. */
async function sniff(blob) {
const head = new Uint8Array(await blob.slice(0, 256).arrayBuffer());
if (head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4e && head[3] === 0x47) return 'png';
const text = new TextDecoder().decode(head).trimStart();
if (text.startsWith('<?xml') || text.startsWith('<svg')) return 'svg';
if (text.startsWith('{') || text.startsWith('[')) return 'json';
return 'unknown';
}
function notice(kind, ...content) { return h('div', { class: `notice ${kind}` }, ...content); }
function objectURL(el, blob) {
if (el._objectURL) URL.revokeObjectURL(el._objectURL);
el._objectURL = URL.createObjectURL(blob);
return el._objectURL;
}
/**
* Shows an image answer. `expected` is 'png' or 'svg'; when the body is something else, says so first
* (loudly) and shows what came back.
*/
async function showImage(el, answer, expected, opts = {}) {
const got = await sniff(answer.blob);
const parts = [];
let blob = answer.blob;
if (got !== expected) {
if (opts.status) setStatus(opts.status, 'error', `${opts.status.textContent} — not ${expected.toUpperCase()}`);
parts.push(notice('error', `Asked for ${expected.toUpperCase()}, but the body is ${got === 'unknown' ? 'not an image this page knows' : `${got === 'svg' ? 'an' : 'a'} ${got.toUpperCase()} document`} (the Content-Type header says ${answer.type}).`));
if (got === 'svg') blob = new Blob([blob], { type: 'image/svg+xml' });
else if (got !== 'png') { el.replaceChildren(...parts); return false; }
if (got === 'svg') parts.push(h('p', {}, 'What came back, shown as an SVG:'));
} else if (expected === 'svg') {
blob = new Blob([blob], { type: 'image/svg+xml' });
}
const img = h('img', { src: objectURL(el, blob), alt: opts.alt || 'Answer', class: opts.className || '' });
parts.push(opts.tile === false ? img : h('div', { class: 'track-tile' }, img));
el.replaceChildren(...parts);
return got === expected;
}
/**
* Validates a GeoJSON answer and shows a summary and its text. Returns the parsed object or null; with
* `opts.status`, a body that is not GeoJSON also turns that status line red.
*/
async function showGeoJSON(el, answer, opts = {}) {
const fail = () => { if (opts.status) setStatus(opts.status, 'error', `${opts.status.textContent} — not GeoJSON`); };
const text = await answer.blob.text();
let data;
try {
data = JSON.parse(text);
} catch {
fail();
const kind = await sniff(answer.blob);
el.replaceChildren(
notice('error', `Asked for GeoJSON, but the body is ${kind === 'svg' ? 'an SVG document' : 'not JSON'} (the Content-Type header says ${answer.type}). It starts with:`),
h('pre', { class: 'code' }, text.slice(0, 400)));
return null;
}
const summary = geoSummary(data);
if (!summary.ok) fail();
el.replaceChildren(summary.ok
? notice('info', summary.text)
: notice('error', summary.text));
showJSON(el.appendChild(h('div')), data);
return summary.ok ? data : null;
}
function lineOf(data) {
const feature = data && data.type === 'FeatureCollection' && Array.isArray(data.features)
? data.features.find((f) => f && f.geometry && f.geometry.type === 'LineString')
: null;
return feature || null;
}
function geoSummary(data) {
if (!data || data.type !== 'FeatureCollection') return { ok: false, text: `Not a GeoJSON FeatureCollection (its type is ${data && data.type}).` };
const line = lineOf(data);
if (!line) return { ok: false, text: `A FeatureCollection of ${data.features.length} feature(s), none of them a LineString.` };
const n = line.geometry.coordinates.length;
return { ok: true, text: `A FeatureCollection of ${data.features.length} feature(s); its LineString has ${n} GPS points [longitude, latitude].` };
}
/** Length of a [lon, lat] line in metres (haversine). */
function lineLength(coords) {
const R = 6371008.8;
const rad = (d) => (d * Math.PI) / 180;
let m = 0;
for (let i = 1; i < coords.length; i++) {
const [lon1, lat1] = coords[i - 1];
const [lon2, lat2] = coords[i];
const a = Math.sin(rad(lat2 - lat1) / 2) ** 2 + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(rad(lon2 - lon1) / 2) ** 2;
m += 2 * R * Math.asin(Math.sqrt(a));
}
return m;
}
// ---------------------------------------------------------------- the layout picker (from /circuits)
let treePromise = null;
/** The whole circuit tree from one `/circuits` call, shown in `card` the first time. */
function circuitTree(card) {
if (!treePromise) {
treePromise = callJSON(card, api('/circuits'), { show: false }).then((v) => {
if (!v) return null;
const out = card.querySelector('.result');
if (out) {
const n = { countries: 0, cities: 0, circuits: 0, layouts: 0 };
for (const c of v.countries) {
n.countries++;
for (const l of Object.values(c.localities)) {
n.cities++;
for (const ci of Object.values(l.circuits)) { n.circuits++; n.layouts += Object.keys(ci.layouts).length; }
}
}
out.replaceChildren(h('p', {}, `${n.countries} countries, ${n.cities} cities, ${n.circuits} circuits and ${n.layouts} layouts. The answer nests the whole tree: country → localities → circuits → layouts.`));
}
return v;
});
}
return treePromise;
}
const byName = (a, b) => a.name.localeCompare(b.name);
/** A layout's slug in years: "1983-" → "1983 – today". */
function layoutYears(slug) {
const [from, to] = slug.split('-');
if (slug.endsWith('-')) return `${from} – today`;
return to ? `${from} – ${to}` : from;
}
/** The first year a layout slug covers. */
function layoutStart(slug) { return parseInt(slug, 10); }
const DEFAULT_PICK = { country: 'belgium', city: 'spa', circuit: 'circuit-de-spa-francorchamps', layout: '1983-' };
/**
* Four selects (country, city, circuit and, with `layout: true`, layout) filled from the tree.
* `sync: true` keeps the choice in the page's query string. Calls onChange(pick) on every change.
*/
async function layoutPicker(root, { treeCard, layout = true, sync = false, onChange }) {
const sel = {
country: h('select', { 'aria-label': 'Country' }),
city: h('select', { 'aria-label': 'City' }),
circuit: h('select', { 'aria-label': 'Circuit' }),
layout: layout ? h('select', { 'aria-label': 'Layout' }) : null,
};
root.replaceChildren(...[
h('label', {}, 'Country', sel.country),
h('label', {}, 'City', sel.city),
h('label', {}, 'Circuit', sel.circuit),
layout ? h('label', {}, 'Layout (years)', sel.layout) : null,
].filter(Boolean));
const tree = await circuitTree(treeCard);
if (!tree) { root.append(notice('error', 'The picker could not be filled: the /circuits call failed (see above).')); return null; }
const countries = [...tree.countries].sort(byName);
const want = {};
for (const k of Object.keys(DEFAULT_PICK)) want[k] = params.get(k) || DEFAULT_PICK[k];
const fill = (select, items, wanted) => {
select.replaceChildren(...items.map((it) => h('option', { value: it.value }, it.label)));
select.value = items.some((it) => it.value === wanted) ? wanted : (items[0] ? items[0].value : '');
};
const pick = () => {
const country = countries.find((c) => c.slug === sel.country.value);
const city = country && country.localities[sel.city.value];
const circuit = city && city.circuits[sel.circuit.value];
return {
country: sel.country.value, city: sel.city.value, circuit: sel.circuit.value,
layout: layout ? sel.layout.value : null,
countryName: country && country.name, cityName: city && city.name, circuitName: circuit && circuit.name,
layouts: circuit ? Object.keys(circuit.layouts).sort((a, b) => layoutStart(a) - layoutStart(b)) : [],
circuitData: circuit || null,
};
};
const refill = (level) => {
if (level <= 0) fill(sel.country, countries.map((c) => ({ value: c.slug, label: c.name })), want.country);
const country = countries.find((c) => c.slug === sel.country.value);
if (level <= 1) fill(sel.city, Object.values(country.localities).sort(byName).map((l) => ({ value: l.slug, label: l.name })), want.city);
const city = country.localities[sel.city.value];
if (level <= 2) fill(sel.circuit, Object.values(city.circuits).sort(byName).map((c) => ({ value: c.slug, label: c.name })), want.circuit);
if (layout && level <= 3) {
const circuit = city.circuits[sel.circuit.value];
const slugs = Object.keys(circuit.layouts).sort((a, b) => layoutStart(a) - layoutStart(b));
fill(sel.layout, slugs.map((s) => ({ value: s, label: layoutYears(s) })), want.layout);
}
};
const changed = () => {
const p = pick();
if (sync) {
const url = new URL(location.href);
for (const k of ['country', 'city', 'circuit', 'layout']) if (p[k]) url.searchParams.set(k, p[k]);
history.replaceState(null, '', url.href);
}
onChange(p);
};
sel.country.addEventListener('change', () => { refill(1); changed(); });
sel.city.addEventListener('change', () => { refill(2); changed(); });
sel.circuit.addEventListener('change', () => { refill(3); changed(); });
if (layout) sel.layout.addEventListener('change', changed);
refill(0);
changed();
return { pick };
}
// ---------------------------------------------------------------- the race picker (from Jolpica)
const seasonCache = new Map();
function jolpicaURL(season) { return `${JOLPICA}/${season}.json?limit=100`; }
/** True when a Jolpica race entry is a sprint weekend (it has a Sprint section). */
function isSprint(race) { return !!race && Object.keys(race).some((k) => k.toLowerCase().startsWith('sprint')); }
/**
* A season input, a race select filled from Jolpica (called from the browser; it allows any origin)
* and the race name as it goes into the URL, editable: when Jolpica cannot be reached the reader types it.
*/
function racePicker(root, { card, defaultSeason = 2024, onChange }) {
const thisYear = new Date().getFullYear();
const season = h('input', { type: 'number', min: 1950, max: thisYear + 1, value: params.get('season') || defaultSeason, 'aria-label': 'Season' });
const race = h('select', { 'aria-label': 'Race' });
const name = h('input', { type: 'text', class: 'wide', value: params.get('race') || '', placeholder: 'Belgian Grand Prix', 'aria-label': 'Race name' });
const hint = h('p', { class: 'hint' });
root.replaceChildren(
h('label', {}, 'Season', season),
h('label', {}, 'Race (from Jolpica)', race),
h('label', {}, 'Race name, as it goes into the URL', name));
root.after(hint);
let races = [];
let wanted = params.get('race') || '';
const current = () => {
const r = races.find((x) => x.raceName === name.value) || null;
return { season: parseInt(season.value, 10), name: name.value.trim(), race: r, sprint: isSprint(r) };
};
const sync = () => {
const url = new URL(location.href);
url.searchParams.set('season', season.value);
url.searchParams.set('race', name.value.trim());
history.replaceState(null, '', url.href);
};
const changed = () => { sync(); onChange(current()); };
async function load() {
const s = parseInt(season.value, 10);
if (!(s >= 1950)) return;
let list = seasonCache.get(s);
if (!list) {
const value = await callJSON(card, jolpicaURL(s), { show: false, label: 'Jolpica, not this API', waiting: 'Asking Jolpica for the season’s races…' });
list = value && value.MRData && value.MRData.RaceTable ? value.MRData.RaceTable.Races : null;
if (list) seasonCache.set(s, list);
} else {
setRequest(card.querySelector('.request'), jolpicaURL(s), 'Jolpica, not this API');
}
if (!list) {
races = [];
race.replaceChildren(h('option', { value: '' }, 'Jolpica did not answer'));
race.disabled = true;
setHint(hint, 'error', 'The race list could not be loaded from Jolpica. Type the race name exactly as Jolpica writes it, such as “Belgian Grand Prix”.');
if (!name.value) name.value = wanted || 'Belgian Grand Prix';
changed();
return;
}
races = list;
race.disabled = false;
race.replaceChildren(...list.map((r) => h('option', { value: r.raceName },
`R${r.round} · ${r.raceName} · ${r.date}${isSprint(r) ? ' · sprint' : ''}`)));
const keep = list.find((r) => r.raceName === (wanted || name.value));
race.value = keep ? keep.raceName : (list[0] ? list[0].raceName : '');
name.value = race.value;
wanted = '';
setHint(hint, '', `${list.length} races in ${s}. The API matches the name exactly as Jolpica’s raceName, then finds the circuit and the layout of that year.`);
changed();
}
season.addEventListener('change', () => { wanted = name.value; load(); });
race.addEventListener('change', () => { name.value = race.value; changed(); });
name.addEventListener('change', changed);
load();
return { current };
}
window.F1 = {
DEFAULT_API, JOLPICA, params, base,
api, absolute, path, h, fmtSize, notice,
setRequest, setStatus, setHint, call, callJSON,
prettyJSON, showJSON, showText, showImage, showGeoJSON, sniff, lineOf, lineLength,
circuitTree, layoutPicker, layoutYears, layoutStart,
racePicker, isSprint, jolpicaURL, linkWithKept,
};
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', frame);
else frame();
})();
+151
View File
@@ -0,0 +1,151 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Track images · F1 Circuits API examples</title>
<meta name="description" content="Fetch one F1 track layout as SVG, PNG or GeoJSON, by layout or by the year it was raced.">
<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" aria-current="page">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>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>Track images</h1>
<p class="lead">
Every layout comes in three formats: <code>svg</code> (a vector drawing), <code>png</code> (an image) and
<code>geojson</code> (the GPS trace it was drawn from). Ask for one by its layout, or by a year: the API then picks
the layout that was raced that year.
</p>
<div class="card" id="tree">
<h3>The pickers below are filled from one call</h3>
<div class="request"></div>
<div class="status"></div>
<div class="result"></div>
</div>
<section class="card" id="by-layout">
<h2>By layout</h2>
<p><code>/circuits/{country}/{city}/{circuit}/layout/{layout}/{format}</code></p>
<div class="controls" id="layout-picker"></div>
<div class="controls"><fieldset id="layout-format"><legend>Format</legend></fieldset></div>
<div class="request"></div>
<div class="status idle">Choose a layout.</div>
<div class="result"></div>
</section>
<section class="card" id="by-year">
<h2>By year</h2>
<p>
<code>/tracks/{country}/{city}/{circuit}/year/{year}/{format}</code>. A year no layout of the circuit covers has
no track; the list under the picker shows the years each layout covers.
</p>
<div class="controls" id="year-picker"></div>
<div class="controls">
<label>Year <input type="number" id="year" min="1950" max="2100"></label>
<fieldset id="year-format"><legend>Format</legend></fieldset>
</div>
<p class="hint" id="year-layouts"></p>
<div class="request"></div>
<div class="status idle">Choose a circuit and a year.</div>
<div class="result"></div>
</section>
<h2>About the answers</h2>
<table class="kv">
<tr><th><code>svg</code></th><td><code>image/svg+xml</code>, sent as an attachment: an <code>&lt;img&gt;</code> shows it, a browser tab opening the URL saves it. A black line on a transparent ground.</td></tr>
<tr><th><code>png</code></th><td><code>image/png</code>, shown inline.</td></tr>
<tr><th><code>geojson</code></th><td><code>application/geo+json</code>: a <code>FeatureCollection</code> whose <code>LineString</code> is the trace as <code>[longitude, latitude]</code> points; see <a href="map.html">GPS traces</a> to draw one.</td></tr>
<tr><th>Caching</th><td>Every file answers <code>Cache-Control: public, max-age=31536000</code> and an <code>ETag</code>.</td></tr>
</table>
</main>
<footer class="pager">
<a rel="prev" href="circuits.html">← Circuit browser</a>
<a class="home" href="index.html">All examples</a>
<a rel="next" href="map.html">GPS traces →</a>
</footer>
<script src="site.js"></script>
<script>
(function () {
const { h, api, path, call, showImage, showGeoJSON, layoutPicker, layoutYears, layoutStart } = F1;
const $ = (id) => document.getElementById(id);
const FORMATS = ['svg', 'png', 'geojson'];
function formatRadios(fieldset, name, initial, onChange) {
for (const f of FORMATS) {
const input = h('input', { type: 'radio', name, value: f, checked: f === initial });
input.addEventListener('change', () => onChange(f));
fieldset.append(h('label', { class: 'inline' }, input, f));
}
return () => fieldset.querySelector('input:checked').value;
}
async function show(card, url, format, alt) {
const answer = await call(card, url, { waiting: 'Fetching the file…' });
const out = card.querySelector('.result');
if (!answer) { out.replaceChildren(); return; }
const status = card.querySelector('.status');
if (format === 'geojson') await showGeoJSON(out, answer, { status });
else await showImage(out, answer, format, { alt, status });
}
// ---- by layout
const initialFormat = FORMATS.includes(F1.params.get('format')) ? F1.params.get('format') : 'svg';
let layoutPick = null;
const layoutFormat = formatRadios($('layout-format'), 'layout-format', initialFormat, () => byLayout());
function byLayout() {
if (!layoutPick || !layoutPick.layout) return;
const p = layoutPick;
const f = layoutFormat();
show($('by-layout'), api(path`/circuits/${p.country}/${p.city}/${p.circuit}/layout/${p.layout}/${f}`), f,
`${p.circuitName}, ${layoutYears(p.layout)}`);
}
layoutPicker($('layout-picker'), { treeCard: $('tree'), sync: true, onChange: (p) => { layoutPick = p; byLayout(); } });
// ---- by year
let yearPick = null;
const yearInput = $('year');
const yearFormat = formatRadios($('year-format'), 'year-format', 'png', () => byYear());
function byYear() {
if (!yearPick) return;
const p = yearPick;
const f = yearFormat();
const y = parseInt(yearInput.value, 10);
if (!(y > 0)) return;
show($('by-year'), api(path`/tracks/${p.country}/${p.city}/${p.circuit}/year/${y}/${f}`), f, `${p.circuitName}, ${y}`);
}
yearInput.addEventListener('change', byYear);
layoutPicker($('year-picker'), {
treeCard: $('tree'),
layout: false,
onChange: (p) => {
const first = yearPick === null;
yearPick = p;
const ranges = p.layouts.map(layoutYears).join(' · ');
F1.setHint($('year-layouts'), '', `Layouts of ${p.circuitName}: ${ranges}`);
const newest = p.layouts[p.layouts.length - 1];
const wanted = first ? parseInt(F1.params.get('year'), 10) : NaN;
yearInput.value = wanted > 0 ? wanted : (newest ? Math.max(layoutStart(newest), 1950) : 2024);
byYear();
},
});
})();
</script>
</body>
</html>
+2
View File
@@ -25,6 +25,8 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py ./
COPY models/ ./models/
COPY circuits/ ./circuits/
# The example site the app serves at /examples/.
COPY examples/ ./examples/
EXPOSE 8000