/* * Shared helper for the F1 Circuits API examples. * * - Picks the API base for every page: `?api=` 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) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[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 ? `${escapeHTML(str)}${colon}` : `${escapeHTML(str)}`; else if (lit) out += `${lit}`; else out += `${num}`; 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(' { 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(); })();