The picker showed shorter PDOK and USGS credits than the design's lines; it now shows them word for word, as it does IGN's and EOX's. A season photo dated by its category says so on its card, and a candidate with no date gives no entry, since the service refuses one. Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
770 lines
38 KiB
HTML
770 lines
38 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<title>Photo picker · F1 Circuits API examples</title>
|
||
<meta name="description" content="Pick a freely licensed Wikimedia Commons photo per circuit layout and per season for the F1 Circuits posters, and copy its entry for the picks file.">
|
||
<link rel="icon" href="data:,">
|
||
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
|
||
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="">
|
||
<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="builder.html">Poster builder</a>
|
||
<a href="kometa.html">Kometa</a>
|
||
<a href="library.html">Library</a>
|
||
<a href="picker.html" aria-current="page">Photo picker</a>
|
||
<a href="licences.html">Licences</a>
|
||
</nav>
|
||
<div id="api-base"></div>
|
||
</header>
|
||
|
||
<!-- bw as the service draws it: Pillow's convert("L"), L = 0.299 R + 0.587 G + 0.114 B on the sRGB values. -->
|
||
<svg width="0" height="0" style="position:absolute" aria-hidden="true" focusable="false">
|
||
<filter id="bw" color-interpolation-filters="sRGB">
|
||
<feColorMatrix type="matrix" values="0.299 0.587 0.114 0 0 0.299 0.587 0.114 0 0 0.299 0.587 0.114 0 0 0 0 0 1 0"/>
|
||
</filter>
|
||
</svg>
|
||
|
||
<main>
|
||
<h1>Photo picker</h1>
|
||
<p class="lead">
|
||
Per layout, the main choice is what <code>bg=satellite</code> draws: the country’s own aerial photo or
|
||
EOxCloudless 2025, or the dark map instead. A layout may also have a Wikimedia Commons photo picked for
|
||
<code>bg=photo</code>, which falls back to what <code>bg=satellite</code> draws while none is picked; a season poster
|
||
shows that season’s cars only from a picked photo. The photos are the candidates
|
||
<code>tools/commons_candidates.py</code> found, cropped to the poster’s frame as the service crops them, in natural
|
||
colour or black and white. Each choice gives the entry to copy into the picks file. The page writes nothing to the
|
||
server: a pick is a change to the repository.
|
||
</p>
|
||
<p>
|
||
Only CC0, public domain, CC BY and CC BY-SA files are listed, with Commons’ quality marks first, then size, then
|
||
landscape. A search also finds ground photos, maps and the odd helicopter, so look at each one before you pick it.
|
||
</p>
|
||
|
||
<section class="card" id="files">
|
||
<h2>1. The lists</h2>
|
||
<p class="hint">The candidates come with the site; the picks are read from the repository, beside the page’s folder.
|
||
Run <code>python3 -m http.server</code> in the working copy and open <code>/examples/picker.html</code> there to
|
||
have both, or load a picks file from disk below.</p>
|
||
<div id="cand-file">
|
||
<div class="request"></div>
|
||
<div class="status"></div>
|
||
<div class="result"></div>
|
||
</div>
|
||
<div id="picks-circuits">
|
||
<div class="request"></div>
|
||
<div class="status"></div>
|
||
<div class="result"></div>
|
||
</div>
|
||
<div id="picks-seasons">
|
||
<div class="request"></div>
|
||
<div class="status"></div>
|
||
<div class="result"></div>
|
||
</div>
|
||
</section>
|
||
|
||
<section class="card" id="choose">
|
||
<h2>2. What to pick for</h2>
|
||
<div class="controls">
|
||
<label><span>Pick for</span>
|
||
<span class="seg" id="mode">
|
||
<button type="button" data-v="layout">A layout</button><button type="button" data-v="season">A season</button>
|
||
</span>
|
||
</label>
|
||
<label><span>Photo (<code>photo</code>)</span>
|
||
<span class="seg" id="treat">
|
||
<button type="button" data-v="natural">natural</button><button type="button" data-v="bw">bw</button>
|
||
</span>
|
||
</label>
|
||
<label id="frame-label"><span>Frame</span>
|
||
<span class="seg" id="frame">
|
||
<button type="button" data-v="poster">poster 1000×1500</button><button type="button" data-v="thumb">thumbnail 1920×1080</button>
|
||
</span>
|
||
</label>
|
||
</div>
|
||
<div class="controls" id="layout-picker"></div>
|
||
<div class="controls" id="season-picker" hidden>
|
||
<label>Season <select id="season" aria-label="Season"></select></label>
|
||
</div>
|
||
<div class="request"></div>
|
||
<div class="status"></div>
|
||
<div class="result"></div>
|
||
</section>
|
||
|
||
<section class="card" id="entry" hidden>
|
||
<h2>3. The entry to copy</h2>
|
||
<div id="entry-body"></div>
|
||
</section>
|
||
|
||
<div id="photos-root">
|
||
<h2 id="sat-title" hidden>bg=satellite: the satellite, or the map</h2>
|
||
<div id="sat"></div>
|
||
<h2 id="others-title">Picks of the circuit’s other layouts</h2>
|
||
<div id="others"></div>
|
||
<h2 id="cands-title">Candidates</h2>
|
||
<div id="cands"></div>
|
||
</div>
|
||
</main>
|
||
|
||
<footer class="pager">
|
||
<a rel="prev" href="library.html">← Library</a>
|
||
<a class="home" href="index.html">All examples</a>
|
||
<a rel="next" href="licences.html">Licences →</a>
|
||
</footer>
|
||
<footer class="disclaimer">
|
||
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
|
||
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
|
||
Licensing B.V.</p>
|
||
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
|
||
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
|
||
</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, notice, setRequest, setStatus, showJSON, layoutPicker, layoutYears, params, api, path, call, showImage } = F1;
|
||
const $ = (id) => document.getElementById(id);
|
||
|
||
const FRAMES = { poster: [1000, 1500], thumb: [1920, 1080] };
|
||
const PICK_FIELDS = ['file', 'licence', 'author', 'credit', 'date'];
|
||
const FILES = {
|
||
candidates: { card: $('cand-file'), url: 'data/candidates.json', what: 'the candidates (examples/data/candidates.json)' },
|
||
circuits: { card: $('picks-circuits'), url: '../circuits/photos.json', what: 'the layouts’ picks (circuits/photos.json)' },
|
||
seasons: { card: $('picks-seasons'), url: '../seasons/photos.json', what: 'the seasons’ picks (seasons/photos.json)' },
|
||
};
|
||
|
||
const state = {
|
||
mode: params.get('mode') === 'season' ? 'season' : 'layout',
|
||
treat: params.get('photo') === 'bw' ? 'bw' : 'natural',
|
||
frame: params.get('frame') === 'thumb' ? 'thumb' : 'poster',
|
||
candidates: null,
|
||
picks: { circuits: null, seasons: null },
|
||
pick: null, // the layout picker's choice
|
||
chosen: null, // { key, cand }
|
||
};
|
||
|
||
function syncURL() {
|
||
const url = new URL(location.href);
|
||
url.searchParams.set('mode', state.mode);
|
||
url.searchParams.set('photo', state.treat);
|
||
url.searchParams.set('frame', state.frame);
|
||
if (state.mode === 'season' && $('season').value) url.searchParams.set('season', $('season').value);
|
||
history.replaceState(null, '', url.href);
|
||
}
|
||
|
||
// ------------------------------------------------------------ the three files
|
||
|
||
/** A picks file read: an object of entries; keys starting with "$" (the format note) are kept but are no pick. */
|
||
function validPicks(value) {
|
||
if (!value || typeof value !== 'object' || Array.isArray(value)) return 'it is not a JSON object';
|
||
for (const [k, v] of Object.entries(value)) {
|
||
if (k.startsWith('$')) continue;
|
||
if (!v || typeof v !== 'object' || (typeof v.file !== 'string' && v.use !== 'map')) return `its entry “${k}” has no file and does not say {"use": "map"}`;
|
||
}
|
||
return '';
|
||
}
|
||
|
||
function validCandidates(value) {
|
||
if (!value || typeof value !== 'object' || !value.layouts || !value.seasons) return 'it has no layouts and seasons';
|
||
return '';
|
||
}
|
||
|
||
/** Reads one file over http, or offers to load it from disk when that fails; calls done(value) once read. */
|
||
async function readFile(name, done) {
|
||
const f = FILES[name];
|
||
const card = f.card;
|
||
const out = card.querySelector('.result');
|
||
const url = new URL(f.url, location.href).href;
|
||
setRequest(card.querySelector('.request'), url, name === 'candidates' ? 'a file of the site, not the API' : 'a file of the repository, not the API');
|
||
setStatus(card.querySelector('.status'), 'pending', `Reading ${f.what}…`);
|
||
const check = name === 'candidates' ? validCandidates : validPicks;
|
||
let why = '';
|
||
try {
|
||
const res = await fetch(url, { cache: 'no-cache' });
|
||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||
const value = JSON.parse(await res.text());
|
||
why = check(value);
|
||
if (!why) {
|
||
accept(name, value, `Read ${f.what} from ${url}.`);
|
||
done(value);
|
||
return;
|
||
}
|
||
} catch (e) {
|
||
why = e instanceof SyntaxError ? 'it is not JSON' : e.message;
|
||
}
|
||
setStatus(card.querySelector('.status'), 'error', `Could not read ${f.what}: ${why}.`);
|
||
const input = h('input', { type: 'file', accept: '.json,application/json' });
|
||
input.addEventListener('change', async () => {
|
||
const file = input.files && input.files[0];
|
||
if (!file) return;
|
||
try {
|
||
const value = JSON.parse(await file.text());
|
||
const bad = check(value);
|
||
if (bad) { setStatus(card.querySelector('.status'), 'error', `${file.name}: ${bad}.`); return; }
|
||
accept(name, value, `Loaded ${f.what} from disk (${file.name}).`);
|
||
done(value);
|
||
} catch (e) {
|
||
setStatus(card.querySelector('.status'), 'error', `${file.name} is not JSON: ${e.message}`);
|
||
}
|
||
});
|
||
out.replaceChildren(notice('error',
|
||
name === 'candidates'
|
||
? 'Without the candidates there is nothing to show. '
|
||
: 'Without the picks file the page cannot show what is picked, nor the whole file with a new pick. ',
|
||
'The page reads it relative to itself; served by the API only /examples/ is there. Load it from disk: ', input));
|
||
}
|
||
|
||
function accept(name, value, text) {
|
||
const f = FILES[name];
|
||
const card = f.card;
|
||
setStatus(card.querySelector('.status'), 'ok', text);
|
||
const out = card.querySelector('.result');
|
||
if (name === 'candidates') {
|
||
const ls = Object.values(value.layouts);
|
||
const ss = Object.values(value.seasons);
|
||
const about = value.about || {};
|
||
out.replaceChildren(h('p', { class: 'hint' },
|
||
`${ls.filter((l) => l.length).length} of ${ls.length} layouts and ${ss.filter((s) => s.length).length} of ${ss.length} seasons have at least one candidate. `,
|
||
about.made ? `Listed ${about.made.replace('T', ' ').replace('+00:00', ' UTC')}` : '',
|
||
about.requests ? ` with ${about.requests} requests to Commons.` : '.'));
|
||
} else {
|
||
const n = Object.keys(value).filter((k) => !k.startsWith('$')).length;
|
||
out.replaceChildren(h('p', { class: 'hint' }, `${n} pick${n === 1 ? '' : 's'} so far.`,
|
||
value.$comment ? h('span', {}, ' Its note: ', h('em', {}, String(value.$comment))) : ''));
|
||
}
|
||
if (name === 'candidates') state.candidates = value; else state.picks[name] = value;
|
||
}
|
||
|
||
// ------------------------------------------------------------ cards
|
||
|
||
/** Commons' thumbnail of a file: from the candidates when listed, else its standard 500-px thumbnail address. */
|
||
function thumbOf(file) {
|
||
const c = state.candidates;
|
||
if (c) {
|
||
for (const list of [...Object.values(c.layouts), ...Object.values(c.seasons)]) {
|
||
const hit = list.find((x) => x.file === file);
|
||
if (hit) return hit.thumb;
|
||
}
|
||
}
|
||
return `https://commons.wikimedia.org/wiki/Special:FilePath/${encodeURIComponent(file)}?width=500`;
|
||
}
|
||
|
||
function pageOf(file) { return `https://commons.wikimedia.org/wiki/File:${encodeURIComponent(file.replace(/ /g, '_'))}`; }
|
||
|
||
/** How much the service scales a photo up to cover the frame, when it does. */
|
||
function scaleUp(c) {
|
||
const [fw, fh] = FRAMES[frameNow()];
|
||
if (!c.width || !c.height) return 0;
|
||
const s = Math.max(fw / c.width, fh / c.height);
|
||
return s > 1 ? s : 0;
|
||
}
|
||
|
||
function frameNow() { return state.mode === 'season' ? 'poster' : state.frame; }
|
||
|
||
function photoCard(c, opts = {}) {
|
||
const up = scaleUp(c);
|
||
const tags = [
|
||
...(c.marks || []).map((m) => h('span', { class: 'tag mark', title: 'A Commons quality mark' }, m)),
|
||
...(c.restrictions || []).map((r) => h('span', { class: 'tag warn', title: 'A right beside copyright the file names' }, `${r} rights`)),
|
||
up ? h('span', { class: 'tag warn', title: 'Smaller than the frame: the service scales it up' }, `scaled up ×${up.toFixed(2)}`) : null,
|
||
].filter(Boolean);
|
||
const chosen = opts.choose && state.chosen && state.chosen.cand && state.chosen.cand.file === c.file;
|
||
const card = h('article', { class: `photo-card${opts.picked ? ' picked' : ''}${chosen ? ' chosen' : ''}` },
|
||
h('div', { class: 'photo-frame' },
|
||
h('img', { src: c.thumb || thumbOf(c.file), alt: c.file, loading: 'lazy', decoding: 'async', referrerpolicy: 'no-referrer' })),
|
||
opts.label ? h('div', { class: 'meta' }, h('b', {}, opts.label)) : null,
|
||
h('div', { class: 'name' }, c.file),
|
||
h('div', { class: 'meta' },
|
||
h('b', { title: c.date_from === 'category' ? 'The file gives no date: the season it is filed under' : null },
|
||
c.date ? `${c.date}${c.date_from === 'category' ? ' (its season)' : ''}` : 'undated'),
|
||
c.width ? ` · ${c.width}×${c.height}` : '',
|
||
' · ', c.licence_url ? h('a', { href: c.licence_url, target: '_blank', rel: 'noopener' }, c.licence) : c.licence,
|
||
h('br'), c.author),
|
||
tags.length ? h('div', { class: 'tags' }, ...tags) : null,
|
||
c.found ? h('div', { class: 'meta', title: 'How the tool found it' },
|
||
`Found by ${c.found.map((f) => (f === 'marked' ? 'a search for its category’s quality-marked files' : f)).join('; ')}`) : null,
|
||
h('div', { class: 'actions' },
|
||
opts.choose ? h('button', { type: 'button', class: 'primary', onclick: () => opts.choose(card) }, 'Choose') : null,
|
||
h('a', { href: c.page || pageOf(c.file), target: '_blank', rel: 'noopener' }, 'On Commons')));
|
||
return card;
|
||
}
|
||
|
||
/** A pick as the picks file holds it: a photo, or {"use": "map"}. */
|
||
function pickCard(entry, label, picked) {
|
||
if (typeof entry.file === 'string' && entry.use === 'map') {
|
||
const card = photoCard({ ...entry, thumb: thumbOf(entry.file) }, { label, picked });
|
||
card.querySelector('.name').after(h('div', { class: 'tags' }, h('span', { class: 'tag', title: 'Its entry also says "use": "map"' }, 'the dark map for bg=satellite')));
|
||
return card;
|
||
}
|
||
if (entry.use === 'map') {
|
||
return h('article', { class: `photo-card${picked ? ' picked' : ''}` },
|
||
h('div', { class: 'map-frame plain' }, h('span', {}, 'The dark map')),
|
||
h('div', { class: 'meta' }, h('b', {}, label)),
|
||
h('div', { class: 'name' }, '{"use": "map"}: the dark map for bg=satellite'));
|
||
}
|
||
return photoCard({ ...entry, thumb: thumbOf(entry.file) }, { label, picked });
|
||
}
|
||
|
||
function grid(cards, extra = '') {
|
||
const cls = `photos${frameNow() === 'thumb' ? ' thumb' : ''}${extra ? ` ${extra}` : ''}`;
|
||
return h('div', { class: cls }, ...cards);
|
||
}
|
||
|
||
// ------------------------------------------------------------ the entry to copy
|
||
|
||
function entryOf(c) {
|
||
const e = {};
|
||
for (const k of PICK_FIELDS) e[k] = c[k] === undefined ? null : c[k];
|
||
return e;
|
||
}
|
||
|
||
/**
|
||
* The picks file's text with one entry set: its "$" keys first as they stand, then every pick by key. Written from
|
||
* a list of pairs, not an object: an object lists keys such as "2024" before "$comment", whatever their order.
|
||
*/
|
||
function withPick(file, key, entry) {
|
||
const notes = Object.entries(file).filter(([k]) => k.startsWith('$'));
|
||
const picks = new Map(Object.entries(file).filter(([k]) => !k.startsWith('$')));
|
||
if (entry === null) picks.delete(key); else picks.set(key, entry);
|
||
const sorted = [...picks.keys()].sort((a, b) => a.localeCompare(b, 'en', { numeric: true })).map((k) => [k, picks.get(k)]);
|
||
const pairs = [...notes, ...sorted];
|
||
const indent = (text) => text.replace(/\n/g, '\n ');
|
||
return pairs.length
|
||
? `{\n${pairs.map(([k, v]) => ` ${JSON.stringify(k)}: ${indent(JSON.stringify(v, null, 2))}`).join(',\n')}\n}`
|
||
: '{}';
|
||
}
|
||
|
||
function copyBlock(title, text) {
|
||
const button = h('button', { type: 'button' }, 'Copy');
|
||
button.addEventListener('click', async () => {
|
||
try { await navigator.clipboard.writeText(text); button.textContent = 'Copied'; } catch { button.textContent = 'Select and copy'; }
|
||
setTimeout(() => { button.textContent = 'Copy'; }, 1500);
|
||
});
|
||
const body = h('div');
|
||
showJSON(body, text);
|
||
return h('div', { class: 'copy-block' }, h('div', { class: 'head' }, h('span', {}, title), button), body);
|
||
}
|
||
|
||
/**
|
||
* The entry a choice leaves for a key, from the one there now: one entry may carry the photo fields (bg=photo),
|
||
* "use": "map" (bg=satellite), or both. Choosing a photo keeps "use": "map"; the map keeps the photo; keeping the
|
||
* satellite drops only "use". null: no entry is left.
|
||
*/
|
||
function entryFor(existing, kind, cand) {
|
||
const photo = existing && typeof existing.file === 'string'
|
||
? Object.fromEntries(PICK_FIELDS.filter((k) => k in existing).map((k) => [k, existing[k]])) : null;
|
||
const map = !!existing && existing.use === 'map';
|
||
if (kind === 'photo') return { ...entryOf(cand), ...(map ? { use: 'map' } : {}) };
|
||
if (kind === 'map') return { ...(photo || {}), use: 'map' };
|
||
return photo;
|
||
}
|
||
|
||
/** What of the entry there now a choice keeps, said in one sentence. */
|
||
function keeps(existing, kind) {
|
||
if (!existing) return '';
|
||
if (kind === 'photo' && existing.use === 'map') return ' It keeps "use": "map" for bg=satellite.';
|
||
if (kind === 'map' && typeof existing.file === 'string') return ' It keeps the photo picked for bg=photo.';
|
||
if (kind === 'satellite') return ' It keeps the photo picked for bg=photo, without "use".';
|
||
return '';
|
||
}
|
||
|
||
function showEntry() {
|
||
const section = $('entry');
|
||
const body = $('entry-body');
|
||
if (!state.chosen) { section.hidden = true; return; }
|
||
const { key, cand, fileName, fileKey, kind } = state.chosen;
|
||
const file = state.picks[fileKey];
|
||
const existing = file && Object.prototype.hasOwnProperty.call(file, key) ? file[key] : null;
|
||
if (kind === 'photo' && !cand.date) {
|
||
body.replaceChildren(notice('error', `${cand.file} has no date, and the service refuses an entry without one: run tools/commons_candidates.py again, or choose another.`));
|
||
section.hidden = false;
|
||
return;
|
||
}
|
||
const entry = entryFor(existing, kind, cand);
|
||
const rule = [' ', h('a', { href: F1.linkWithKept('licences.html') }, 'The licences page'), ' states the rule.'];
|
||
const what = kind === 'satellite' ? 'the satellite, not the map' : kind === 'map' ? 'the dark map instead of the satellite' : cand.file;
|
||
const parts = [h('p', {}, 'For ', h('code', {}, key), ': ', h('b', {}, what), '.')];
|
||
if (entry) {
|
||
parts.push(
|
||
h('p', {}, 'Copy the entry into ', h('code', {}, fileName), ', or the whole file below with the entry in place.', keeps(existing, kind)),
|
||
copyBlock(`The entry, for ${fileName}`, `${JSON.stringify(key)}: ${JSON.stringify(entry, null, 2)}`));
|
||
} else if (!file) {
|
||
parts.push(h('p', {}, 'No entry is needed for it.'));
|
||
} else if (existing) {
|
||
parts.push(h('p', {}, `No entry is left for it: remove the one ${fileName} has now.`));
|
||
} else {
|
||
parts.push(h('p', { class: 'hint' }, `No entry is needed for it, and ${fileName} has none: nothing to change.`));
|
||
}
|
||
if (kind === 'satellite') {
|
||
const src = satelliteSource(key);
|
||
parts.push(notice('info', `bg=satellite draws ${src.name} for this layout; a poster from it is ${src.poster}. A picture’s licence follows its sources.`, ...rule));
|
||
} else if (kind === 'map') {
|
||
parts.push(notice('info', 'The service draws the dark OpenStreetMap map for this layout in place of the satellite: for bg=satellite, and for bg=photo while no photo is picked. A poster on it is CC BY 4.0.', ...rule));
|
||
} else {
|
||
const sa = /\bBY-SA\b/i.test(cand.licence);
|
||
parts.push(notice('info', fileKey === 'circuits' ? 'This photo serves bg=photo only; bg=satellite does not change. ' : '', sa
|
||
? `${cand.licence} is share-alike: a poster made from it is adapted material, shared under CC BY-SA terms. Such a poster is CC BY-SA 4.0.`
|
||
: `A poster made from it is CC BY 4.0: a picture’s licence follows its sources, and ${cand.licence} asks no share-alike.`, ...rule));
|
||
if ((cand.restrictions || []).length) {
|
||
parts.push(notice('', `Commons names ${cand.restrictions.join(' and ')} rights for this file: rights beside its copyright licence, such as a person’s likeness or a trade mark shown in it.`));
|
||
}
|
||
}
|
||
if (!file) parts.push(notice('error', `${fileName} was not read, so the whole file cannot be shown${kind === 'photo' ? '' : ', nor whether it has an entry for this layout now'}: load it from disk above.`));
|
||
else if (entry || existing) parts.push(copyBlock(`The whole of ${fileName} ${entry ? 'with this entry' : 'without an entry for it'}`, withPick(file, key, entry)));
|
||
body.replaceChildren(...parts);
|
||
section.hidden = false;
|
||
}
|
||
|
||
function choose(key, cand, card, fileName, fileKey) {
|
||
for (const el of document.querySelectorAll('.photo-card.chosen')) el.classList.remove('chosen');
|
||
card.classList.add('chosen');
|
||
state.chosen = { key, cand, fileName, fileKey, mode: state.mode, kind: 'photo' };
|
||
markChoices();
|
||
showEntry();
|
||
$('entry').scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||
}
|
||
|
||
/** "Keep the satellite" (no entry) or "use the map instead" ({"use": "map"}) for a layout. */
|
||
function chooseSurface(key, kind) {
|
||
for (const el of document.querySelectorAll('.photo-card.chosen')) el.classList.remove('chosen');
|
||
state.chosen = { key, kind, fileName: 'circuits/photos.json', fileKey: 'circuits', mode: 'layout' };
|
||
markChoices();
|
||
showEntry();
|
||
$('entry').scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||
}
|
||
|
||
function markChoices() {
|
||
for (const b of document.querySelectorAll('#sat .choices button')) {
|
||
b.setAttribute('aria-pressed', String(!!state.chosen && state.chosen.kind === b.dataset.kind));
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------ without a photo: the satellite, or the map
|
||
|
||
// What bg=satellite draws (the operator, 2026-11-27): the country's own aerial photo, else EOxCloudless 2025; a
|
||
// Commons photo only ever for bg=photo. The layers the service uses; past maxNativeZoom (the deepest level every
|
||
// circuit of that country has, checked 2026-11-27) Leaflet scales the deepest tiles up.
|
||
const NATIONAL = {
|
||
netherlands: { name: 'PDOK’s aerial photo', url: 'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg',
|
||
maxNativeZoom: 19, credit: 'Luchtfoto: PDOK / Samenwerkingsverband Beeldmateriaal, CC BY 4.0', licence: 'CC BY 4.0', poster: 'CC BY 4.0' },
|
||
france: { name: 'IGN’s BD ORTHO 2021–2023', url: 'https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS2021-2023&STYLE=normal&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/jpeg',
|
||
maxNativeZoom: 18, credit: '© IGN – BD ORTHO, 2021–2023', licence: 'Licence Ouverte (Etalab) 2.0', poster: 'CC BY 4.0' },
|
||
'united-states': { name: 'USGS imagery', url: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}',
|
||
maxNativeZoom: 16, credit: 'USDA, USGS The National Map: Orthoimagery', licence: 'public domain', poster: 'CC BY 4.0' },
|
||
};
|
||
const EOX = {
|
||
name: 'EOxCloudless 2025',
|
||
url: 'https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2025_3857/default/g/{z}/{y}/{x}.jpg',
|
||
maxNativeZoom: 15,
|
||
credit: 'EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2025)',
|
||
licence: 'CC BY-NC-SA 4.0',
|
||
poster: 'CC BY-NC-SA 4.0',
|
||
};
|
||
|
||
/** What bg=satellite draws for a layout that does not ask for the map. */
|
||
function satelliteSource(key) {
|
||
return NATIONAL[key.split('/')[0]] || EOX;
|
||
}
|
||
|
||
const traces = new Map();
|
||
const races = new Map();
|
||
let satMaps = [];
|
||
let satShown = '';
|
||
|
||
/** A layout's GPS trace as [lat, lon] points, or null when it has none. */
|
||
async function traceOf(p) {
|
||
const key = `${p.country}/${p.city}/${p.circuit}/${p.layout}`;
|
||
if (!traces.has(key)) {
|
||
traces.set(key, (async () => {
|
||
const res = await fetch(api(path`/circuits/${p.country}/${p.city}/${p.circuit}/layout/${p.layout}/geojson`));
|
||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||
const line = F1.lineOf(await res.json());
|
||
const pts = line ? line.geometry.coordinates.map(([lon, lat]) => [lat, lon]) : [];
|
||
return pts.length > 1 ? pts : null;
|
||
})());
|
||
}
|
||
return traces.get(key);
|
||
}
|
||
|
||
/** The latest race at a circuit within a layout's years, from Jolpica; null when none. */
|
||
async function raceOn(p) {
|
||
const id = p.circuitData && p.circuitData.ergastId;
|
||
if (!id) return null;
|
||
if (!races.has(id)) {
|
||
races.set(id, (async () => {
|
||
const all = [];
|
||
for (let offset = 0; ; offset += 100) {
|
||
const res = await fetch(`${F1.JOLPICA}/circuits/${encodeURIComponent(id)}/races.json?limit=100&offset=${offset}`);
|
||
if (!res.ok) throw new Error(`Jolpica answered HTTP ${res.status}`);
|
||
const d = (await res.json()).MRData;
|
||
all.push(...d.RaceTable.Races);
|
||
if (offset + 100 >= Number(d.total)) return all;
|
||
}
|
||
})());
|
||
}
|
||
const list = await races.get(id);
|
||
const first = parseInt(p.layout, 10);
|
||
const last = p.layout.endsWith('-') ? Infinity : parseInt(p.layout.split('-')[1] || p.layout, 10);
|
||
const fit = list.filter((r) => Number(r.season) >= first && Number(r.season) <= last);
|
||
return fit.length ? fit[fit.length - 1] : null;
|
||
}
|
||
|
||
function mapCard(src, note) {
|
||
const box = h('div', { class: 'map-box' });
|
||
const card = h('article', { class: 'photo-card' },
|
||
h('div', { class: 'map-frame' }, box),
|
||
note ? h('div', { class: 'meta' }, h('b', {}, note)) : null,
|
||
h('div', { class: 'name' }, src.name),
|
||
h('div', { class: 'meta' }, src.credit, h('br'), `${src.licence}; a poster from it: `, h('b', {}, src.poster)));
|
||
card._box = box;
|
||
card._src = src;
|
||
return card;
|
||
}
|
||
|
||
function serviceCard(p) {
|
||
const route = frameNow() === 'thumb' ? 'session thumbnail' : 'race poster';
|
||
const button = h('button', { type: 'button' }, `Render the service’s ${route}`);
|
||
const card = h('article', { class: 'photo-card' },
|
||
h('div', { class: 'map-frame plain result' }, h('span', {}, 'What the service draws now, on demand: it renders and may fetch tiles first.')),
|
||
h('div', { class: 'name' }, `The service’s ${route}, bg=satellite`),
|
||
h('div', { class: 'request compact' }),
|
||
h('div', { class: 'status idle' }, 'Not rendered yet.'),
|
||
h('div', { class: 'actions' }, button));
|
||
button.addEventListener('click', async () => {
|
||
button.disabled = true;
|
||
const st = card.querySelector('.status');
|
||
try {
|
||
setStatus(st, 'pending', 'Finding a race on this layout at Jolpica…');
|
||
const race = await raceOn(p);
|
||
if (!race) { setStatus(st, 'error', `Jolpica lists no race at this circuit in ${layoutYears(p.layout)}.`); return; }
|
||
const url = frameNow() === 'thumb'
|
||
? api(path`/posters/session/${race.raceName}/${race.season}/race.png`) + '?bg=satellite'
|
||
: api(path`/posters/race/${race.raceName}/${race.season}.png`) + '?bg=satellite';
|
||
const answer = await call(card, url, { label: `${race.raceName} ${race.season}`, waiting: 'Rendering on the server…' });
|
||
const frame = card.querySelector('.map-frame');
|
||
if (!answer) { frame.replaceChildren(h('span', {}, 'No picture: see the status below.')); return; }
|
||
frame.classList.remove('plain');
|
||
await showImage(frame, answer, 'png', { alt: `${race.raceName} ${race.season}, bg=satellite`, tile: false, status: st });
|
||
} catch (e) {
|
||
setStatus(st, 'error', e.message);
|
||
} finally {
|
||
button.disabled = false;
|
||
}
|
||
});
|
||
return card;
|
||
}
|
||
|
||
function renderSat(p, key, current) {
|
||
const sig = `${key}|${frameNow()}`;
|
||
const src = satelliteSource(key);
|
||
const status = !state.picks.circuits ? 'circuits/photos.json was not read, so what this layout uses now is not known.'
|
||
: current && current.use === 'map' ? 'Its entry says "use": "map": bg=satellite draws the dark map for it now.'
|
||
: `Its entry does not ask for the map: bg=satellite draws ${src.name} for it now.`;
|
||
const head = h('p', { class: 'hint' }, `bg=satellite draws ${src.name} for this layout, and bg=photo does too while it has no picked photo. Judge it below, its trace drawn in white: keep the satellite, or have the service draw the dark map instead. `, h('b', {}, status));
|
||
const choices = h('div', { class: 'choices' },
|
||
h('button', { type: 'button', 'data-kind': 'satellite', onclick: () => chooseSurface(key, 'satellite') }, 'Keep the satellite (no entry)'),
|
||
h('button', { type: 'button', 'data-kind': 'map', onclick: () => chooseSurface(key, 'map') }, 'Use the map instead'));
|
||
if (sig === satShown && satMaps.length) {
|
||
$('sat').firstChild.replaceWith(head);
|
||
$('sat').querySelector('.choices').replaceWith(choices);
|
||
markChoices();
|
||
return;
|
||
}
|
||
for (const m of satMaps) m.remove();
|
||
satMaps = [];
|
||
satShown = sig;
|
||
const country = p.country;
|
||
const cards = [];
|
||
if (NATIONAL[country]) cards.push(mapCard(NATIONAL[country], 'What bg=satellite draws for this country'));
|
||
cards.push(mapCard(EOX, NATIONAL[country] ? 'What bg=satellite draws where the national photo has no tiles' : 'What bg=satellite draws here'));
|
||
cards.push(serviceCard(p));
|
||
$('sat').replaceChildren(head, grid(cards), choices);
|
||
markChoices();
|
||
traceOf(p).then((pts) => {
|
||
if (satShown !== sig) return;
|
||
for (const card of cards.filter((c) => c._box)) {
|
||
// Whole zoom levels: at a fractional one the browser draws seams between tiles that read as flaws in the imagery.
|
||
const m = L.map(card._box, { attributionControl: false, scrollWheelZoom: false });
|
||
L.tileLayer(card._src.url, { maxZoom: 19, maxNativeZoom: card._src.maxNativeZoom }).addTo(m);
|
||
if (pts) {
|
||
const line = L.polyline(pts, { color: '#ffffff', weight: 2, opacity: 0.9 }).addTo(m);
|
||
m.fitBounds(line.getBounds(), { padding: [14, 14] });
|
||
} else {
|
||
m.setView([0, 0], 2);
|
||
card._box.after(h('div', { class: 'meta' }, 'This layout has no trace to frame.'));
|
||
}
|
||
satMaps.push(m);
|
||
}
|
||
}).catch((err) => {
|
||
for (const card of cards.filter((c) => c._box)) card._box.replaceWith(notice('error', `The layout’s trace could not be read: ${err.message}`));
|
||
});
|
||
}
|
||
|
||
// ------------------------------------------------------------ rendering a layout or a season
|
||
|
||
function picksOf(name) {
|
||
const file = state.picks[name];
|
||
return file ? Object.fromEntries(Object.entries(file).filter(([k]) => !k.startsWith('$'))) : null;
|
||
}
|
||
|
||
function render() {
|
||
syncURL();
|
||
$('photos-root').className = state.treat === 'bw' ? 'treat-bw' : '';
|
||
$('frame-label').hidden = state.mode === 'season';
|
||
$('layout-picker').hidden = state.mode !== 'layout';
|
||
$('season-picker').hidden = state.mode !== 'season';
|
||
// The /circuits call fills the layout picker only.
|
||
for (const sel of ['.request', '.status', '.result']) $('choose').querySelector(`:scope > ${sel}`).hidden = state.mode !== 'layout';
|
||
for (const [id, v] of [['mode', state.mode], ['treat', state.treat], ['frame', state.frame]]) {
|
||
for (const b of $(id).querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.v === v));
|
||
}
|
||
if (state.chosen && state.chosen.mode !== state.mode) { state.chosen = null; showEntry(); }
|
||
if (!state.candidates) {
|
||
$('others-title').hidden = true;
|
||
$('others').replaceChildren();
|
||
$('cands-title').textContent = 'Candidates';
|
||
$('cands').replaceChildren(notice('error', 'The candidates were not read (see 1).'));
|
||
return;
|
||
}
|
||
if (state.mode === 'layout') renderLayout(); else renderSeason();
|
||
}
|
||
|
||
function renderLayout() {
|
||
const p = state.pick;
|
||
if (!p || !p.layout) return;
|
||
const circuitKey = `${p.country}/${p.city}/${p.circuit}`;
|
||
const key = `${circuitKey}/${p.layout}`;
|
||
const picks = picksOf('circuits');
|
||
const list = state.candidates.layouts[key];
|
||
const current = picks && picks[key];
|
||
if (state.chosen && state.chosen.key !== key) { state.chosen = null; showEntry(); }
|
||
$('sat-title').hidden = false;
|
||
renderSat(p, key, current);
|
||
|
||
// The circuit's other layouts, and this one's pick when it has one.
|
||
$('others-title').hidden = false;
|
||
$('others-title').textContent = `For bg=photo (optional): the picks of ${p.circuitName || 'this circuit'}’s layouts`;
|
||
if (!picks) {
|
||
$('others').replaceChildren(notice('error', 'circuits/photos.json was not read (see 1), so the picks are not shown.'));
|
||
} else {
|
||
const cards = p.layouts.filter((l) => picks[`${circuitKey}/${l}`]).map((l) => {
|
||
const k = `${circuitKey}/${l}`;
|
||
const label = `${layoutYears(l)}${l === p.layout ? ' (this layout, picked now)' : ''}`;
|
||
return pickCard(picks[k], label, l === p.layout);
|
||
});
|
||
$('others').replaceChildren(cards.length ? grid(cards, 'small')
|
||
: h('p', { class: 'hint' }, `None of its ${p.layouts.length} layout${p.layouts.length === 1 ? '' : 's'} has a pick yet.`));
|
||
}
|
||
|
||
const undated = ((state.candidates.about || {}).undated_per_circuit || {})[circuitKey];
|
||
$('cands-title').textContent = `Candidates for bg=photo (optional), ${layoutYears(p.layout)}${list ? ` (${list.length})` : ''}`;
|
||
if (!list) {
|
||
$('cands').replaceChildren(notice('error', `The candidates file has no entry for ${key}: run tools/commons_candidates.py again.`));
|
||
return;
|
||
}
|
||
const why = undated ? ` The tool found ${undated} more photo${undated === 1 ? '' : 's'} of this circuit with no date it can read; a layout lists only photos dated within its years.` : '';
|
||
if (!list.length) {
|
||
$('cands').replaceChildren(notice('', `Commons has no freely licensed aerial photo of this circuit dated ${layoutYears(p.layout)} that the tool found: bg=photo draws what bg=satellite draws for it (above).${why}`));
|
||
return;
|
||
}
|
||
$('cands').replaceChildren(
|
||
why ? h('p', { class: 'hint' }, why.trim()) : '',
|
||
grid(list.map((c) => photoCard(c, {
|
||
picked: current && current.file === c.file,
|
||
label: current && current.file === c.file ? 'Picked now' : null,
|
||
choose: (card) => choose(key, c, card, 'circuits/photos.json', 'circuits'),
|
||
}))));
|
||
}
|
||
|
||
function renderSeason() {
|
||
const year = $('season').value;
|
||
if (!year) return;
|
||
$('sat-title').hidden = true;
|
||
$('sat').replaceChildren();
|
||
for (const m of satMaps) m.remove();
|
||
satMaps = [];
|
||
satShown = '';
|
||
const picks = picksOf('seasons');
|
||
const list = state.candidates.seasons[year] || null;
|
||
const current = picks && picks[year];
|
||
|
||
$('others-title').hidden = false;
|
||
$('others-title').textContent = 'Picks of the seasons nearest to it';
|
||
if (!picks) {
|
||
$('others').replaceChildren(notice('error', 'seasons/photos.json was not read (see 1), so the picks are not shown.'));
|
||
} else {
|
||
const near = Object.keys(picks).sort((a, b) => Math.abs(a - year) - Math.abs(b - year) || a - b).slice(0, 10);
|
||
$('others').replaceChildren(near.length
|
||
? grid(near.map((y) => pickCard(picks[y], `${y}${y === year ? ' (this season, picked now)' : ''}`, y === year)), 'small')
|
||
: h('p', { class: 'hint' }, 'No season has a pick yet.'));
|
||
}
|
||
|
||
$('cands-title').textContent = `Candidates for ${year}${list ? ` (${list.length})` : ''}`;
|
||
if (!list) {
|
||
$('cands').replaceChildren(notice('error', `The candidates file has no entry for ${year}: run tools/commons_candidates.py again.`));
|
||
return;
|
||
}
|
||
if (!list.length) {
|
||
$('cands').replaceChildren(notice('', `No freely licensed photo in “${year} Formula One season cars” was found; until one is picked, the season poster is drawn without a photo.`));
|
||
return;
|
||
}
|
||
state.chosen = state.chosen && state.chosen.key === year ? state.chosen : null;
|
||
$('cands').replaceChildren(h('p', { class: 'hint' }, `From Commons’ “${year} Formula One season cars”, the best ${list.length} by quality marks, size and landscape.`),
|
||
grid(list.map((c) => photoCard(c, {
|
||
picked: current && current.file === c.file,
|
||
label: current && current.file === c.file ? 'Picked now' : null,
|
||
choose: (card) => choose(year, c, card, 'seasons/photos.json', 'seasons'),
|
||
}))));
|
||
if (!state.chosen) showEntry();
|
||
}
|
||
|
||
// ------------------------------------------------------------ controls
|
||
|
||
function seg(id, key) {
|
||
$(id).addEventListener('click', (e) => {
|
||
const b = e.target.closest('button');
|
||
if (!b) return;
|
||
state[key] = b.dataset.v;
|
||
render();
|
||
if (state.chosen) showEntry();
|
||
});
|
||
}
|
||
seg('mode', 'mode');
|
||
seg('treat', 'treat');
|
||
seg('frame', 'frame');
|
||
$('season').addEventListener('change', () => { state.chosen = null; render(); });
|
||
|
||
function fillSeasons() {
|
||
const years = Object.keys(state.candidates.seasons).sort();
|
||
const want = params.get('season') || '2024';
|
||
$('season').replaceChildren(...years.map((y) => h('option', { value: y }, `${y} · ${state.candidates.seasons[y].length} candidate${state.candidates.seasons[y].length === 1 ? '' : 's'}`)));
|
||
$('season').value = years.includes(want) ? want : years[years.length - 1];
|
||
}
|
||
|
||
render();
|
||
readFile('candidates', () => { fillSeasons(); render(); });
|
||
readFile('circuits', render);
|
||
readFile('seasons', render);
|
||
layoutPicker($('layout-picker'), {
|
||
treeCard: $('choose'),
|
||
sync: true,
|
||
onChange: (p) => { state.pick = p; state.chosen = null; render(); },
|
||
});
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html>
|