ontoref-outreach/scripts/decks/lib/fetch-fonts.mjs
Jesús Pérez da93544de3 decks: the slides stop being pixels — Slidev's own render, captured and re-homed
The published deck was a hand-written carousel of exported PNGs: the words of every
slide were an IMAGE of words. Nothing indexed them, no glossary tooltip could reach
them, no screen reader read them, and the page drifted from the source the moment a
slide changed.

The deck is NOT re-parsed. Slidev's markdown is not standard markdown, and its meaning
does not live in the markdown anyway — it lives in a compiled bundle of UnoCSS
utilities, theme rules and <style scoped> blocks. Re-implementing that is
re-implementing a renderer, in any language. So Slidev renders (its own /print route,
the one `slidev export` drives) and we capture what it produced: the DOM, and the CSS
the browser actually applied.

Measured on the served page: 0 → 2152 indexable words, 16/16 slides reachable, 0
third-party origins added, 0 broken references.

Twelve traps, none of which raised an error:
  · The CSS must be asked of the BROWSER (17 stylesheets; index.html links 2).
  · Collapsing :root/html/body imports the SPA's viewport cage — it clipped the deck
    at 900px and swallowed 14 of 16 slides, silently.
  · UnoCSS's preflight, scoped, kills the glossary underline it was supposed to enable.
  · :not() inherits its argument's specificity — the boundary guard grew with every
    exemption until it reverted the slide scaling. :not(:where(…)) contributes zero.
  · scale(calc(100cqw / 980)) is invalid CSS and is dropped in silence; on a phone the
    box was 328px while the content stayed 980px and two thirds of every slide was cut.
  · The site's markdown renderer destroys an inline <script>: curly quotes, injected
    <p>, &amp;&amp;. CSS and JS go to external files — correctness, not optimisation.
  · The 980x552 frame CUT 12 of 16 slides (Slidev cuts them too; nobody had seen it,
    because the slides were PNGs of themselves).
  · transform: translateY(0) — an IDENTITY transform — makes <main> the containing
    block for position:fixed, and the zoom modal landed at top = -221px.

Two views over one DOM (slider default, stacked reads with Ctrl+F), an index derived
from each slide's own H1, a sticky rail, zoom, and Slidev's own copy buttons revived —
they shipped in the captured DOM at 0x0, unclickable by any human.

Twelve gates (A–L), and IN THE CHAIN: `just decks` in sync-full, `decks-check` in
`check` (on disk), `decks-served` in `check-live` (the page). A generator outside the
chain is a generator that does not run.
2026-07-14 19:41:51 +01:00

73 lines
3.4 KiB
JavaScript

// Self-host the deck's webfonts.
//
// The Slidev build links a cross-origin Google Fonts stylesheet, so document.styleSheets
// cannot read it and the capture drops its @font-face rules with no error. On macOS
// nothing looks wrong — Avenir Next is a system font — and everywhere else the deck
// silently falls back to whatever the OS happens to have.
//
// Two facts, both measured:
// · Google serves only Nunito Sans and Victor Mono for that URL. It IGNORES
// `Avenir+Next` — a proprietary Linotype face, absent from Google Fonts and not
// licensable for self-hosting. It stays in the stack as a local preference; the
// stack's next entry is what we now guarantee for everyone else. (Decided 2026-07-14:
// Mac readers see Avenir Next, everyone else Nunito Sans — a conscious split.)
// · The User-Agent decides the format. A generic UA gets .ttf; a modern Chrome UA gets
// .woff2, roughly a third of the bytes.
import { writeFile, mkdir } from 'node:fs/promises'
import { readFile } from 'node:fs/promises'
import { basename, join } from 'node:path'
import { DIST, postcss, publicBase, publicDir } from './paths.mjs'
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 '
+ '(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
// latin + latin-ext. Greek, cyrillic and vietnamese are subsets an es/en deck never
// types. Select on the range's own start codepoint — the file hashes carry no meaning,
// and guessing from them is how a whole family gets deleted by accident.
const LATIN = /^U\+0000-00FF/i
const LATIN_EXT = /^U\+0100-02BA/i
const wantedRange = (r) => LATIN.test(r.trim()) || LATIN_EXT.test(r.trim())
export async function fetchFonts(id, { apply = true } = {}) {
const index = await readFile(join(DIST, 'index.html'), 'utf8')
const href = index.match(/<link[^>]+href="(https:\/\/fonts\.googleapis\.com[^"]+)"/)?.[1]
if (!href) return { skipped: 'el build no enlaza Google Fonts', css: '', files: [] }
const res = await fetch(href.replaceAll('&amp;', '&'), { headers: { 'User-Agent': UA } })
if (!res.ok) throw new Error(`Google Fonts: HTTP ${res.status}`)
let css = await res.text()
const requested = [...href.matchAll(/family=([^:&]+)/g)].map(m => decodeURIComponent(m[1]).replace(/\+/g, ' '))
const served = [...new Set([...css.matchAll(/font-family:\s*'([^']+)'/g)].map(m => m[1]))]
const notServed = requested.filter(f => !served.includes(f))
const base = `${publicBase(id)}/fonts`
const dir = join(publicDir(id), 'fonts')
if (apply) await mkdir(dir, { recursive: true })
const root = postcss.parse(css)
const keep = []
root.walkAtRules('font-face', at => {
const src = at.toString()
const range = src.match(/unicode-range:\s*([^;]+)/i)?.[1]
if (range && !wantedRange(range)) { at.remove(); return }
const url = src.match(/url\((https:\/\/fonts\.gstatic\.com[^)]+)\)/)?.[1]
if (url) keep.push(url)
})
const files = []
for (const url of [...new Set(keep)]) {
const name = basename(new URL(url).pathname)
if (apply) {
const r = await fetch(url, { headers: { 'User-Agent': UA } })
if (!r.ok) throw new Error(`fuente ${url}: HTTP ${r.status}`)
await writeFile(join(dir, name), Buffer.from(await r.arrayBuffer()))
}
files.push(name)
}
let out = root.toString()
for (const url of [...new Set(keep)]) out = out.replaceAll(url, `${base}/${basename(new URL(url).pathname)}`)
return { css: out, files, served, notServed }
}