| 1 | // scene-fonts.mjs — the deck's faces a scene is sent (scenes and clips |
| 2 | // spec §3, docs/scenes.md "Fonts"), for scene-layer.mjs: the families |
| 3 | // its data names in data.fonts, found in the page's font manifest, each |
| 4 | // face read once a page as a data: URL, the only way a face reaches a |
| 5 | // sealed frame. |
| 6 | |
| 7 | /** The deck faces a scene's data names (data.fonts), from a page's font manifest. */ |
| 8 | export function sceneFonts (data, manifest) { |
| 9 | const names = data && Array.isArray(data.fonts) ? data.fonts.filter(n => typeof n === 'string') : [] |
| 10 | if (!names.length || !manifest) return [] |
| 11 | const families = [...Object.values(manifest.uploaded || {}), ...Object.values(manifest.families || {})] |
| 12 | const out = [] |
| 13 | for (const name of names) { |
| 14 | const fam = families.find(f => f && f.css === name) |
| 15 | for (const face of (fam && Array.isArray(fam.faces) ? fam.faces : [])) { |
| 16 | if (face && face.url) out.push({ family: name, url: face.url, weight: String(face.weight || 400), style: face.style || 'normal' }) |
| 17 | } |
| 18 | } |
| 19 | return out |
| 20 | } |
| 21 | |
| 22 | // asData is a font file as a data: URL. Each file is read once a page. |
| 23 | const read = new Map() |
| 24 | function asData (win, url) { |
| 25 | if (!read.has(url)) { |
| 26 | read.set(url, win.fetch(url, { credentials: 'same-origin' }) |
| 27 | .then(r => (r.ok ? r.blob() : null)) |
| 28 | .then(b => b && new Promise(resolve => { |
| 29 | const f = new win.FileReader() |
| 30 | f.onload = () => resolve(f.result) |
| 31 | f.onerror = () => resolve(null) |
| 32 | f.readAsDataURL(b) |
| 33 | })) |
| 34 | .catch(() => null)) |
| 35 | } |
| 36 | return read.get(url) |
| 37 | } |
| 38 | |
| 39 | function manifestOf (doc) { |
| 40 | try { |
| 41 | const m = doc.querySelector('meta[name="slides-fonts"]') |
| 42 | return m ? JSON.parse(m.getAttribute('content') || 'null') : null |
| 43 | } catch { |
| 44 | return null |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | /** The faces data names, each as {family, src, weight, style} with src a data: URL; a face that cannot be read is left out. */ |
| 49 | export function frameFonts (data, doc, win) { |
| 50 | return Promise.all(sceneFonts(data, manifestOf(doc)).map(f => |
| 51 | asData(win, f.url).then(src => src && { family: f.family, src, weight: f.weight, style: f.style }))).then(l => l.filter(Boolean)) |
| 52 | } |
| 53 | |