// fixtures/deck-fonts.mjs — the deck's two font fields when a family // from the person's own library is in play (internal/slides/deckfonts.go). // // A family is offered in each field's "Your fonts" group, its value the // family's CSS name. Choosing one asks the server to record it for the // deck (POST /d/{sqid}/fonts, which answers the family as // meta.fontFiles carries it), then commits ONE set_meta: the family in // fontFiles, and the role's stack set to the family in front of the // theme's own stack for that role. One change, so one undo takes it all // back. Choosing anything else writes meta.fonts as deckOp always has, // and in the same op drops from fontFiles every family neither role's // stack now leads with. // // The pure half (leadFamily … plainFontOp) is held by // deck-fonts.test.mjs; mountDeckFonts is the wiring inspector.mjs uses. import { deckOp } from './inspector-ops.mjs' import { safeFontStack, leadFamily } from './font-families.mjs' export { leadFamily } const ROLES = ['heading', 'body'] /** What a font field shows for a stack: the uploaded family it leads with, else the stack itself. */ export function fontChoice (stack, fontFiles) { const lead = leadFamily(stack) if (lead && (fontFiles || []).some(f => same(f.css, lead))) return lead return stack || '' } /** The theme's own stack for role ('heading' or 'body'), from the font manifest (fontgate.go). */ export function themeStack (meta, manifest, role) { const themes = (manifest && manifest.themes) || {} const theme = meta && themes[meta.theme] ? meta.theme : manifest && manifest.defaultTheme const pair = themes[theme] return (pair && pair[ROLES.indexOf(role)]) || 'sans-serif' } // A browser matches family names without regard to case, and so does // the document (font-files.mjs): Brand and BRAND are one name. const same = (a, b) => typeof a === 'string' && typeof b === 'string' && a.toLowerCase() === b.toLowerCase() // The families a pair of stacks still leads with. function keepUsed (fontFiles, fonts) { const used = ROLES.map(r => leadFamily(fonts && fonts[r])).filter(Boolean) return (fontFiles || []).filter(f => used.some(n => same(n, f.css))) } /** The set_meta for choosing family (a deck.FontFamily) for role. */ export function pickOp (role, family, meta, manifest) { const fonts = { heading: '', body: '', ...(meta && meta.fonts ? meta.fonts : {}) } const stack = `'${family.css}', ${themeStack(meta, manifest, role)}` // fontPattern's 200: a long name keeps its quote and a generic family. fonts[role] = safeFontStack(stack) || `'${family.css}', sans-serif` // The deck named the family (POST /d/{sqid}/fonts): a name it already // lists is this same family, now perhaps with more faces, and is // replaced; any other family keeps its own name and place. const files = (meta && meta.fontFiles ? meta.fontFiles : []).filter(f => !same(f.css, family.css)) files.push(family) return { op: 'set_meta', fonts: { heading: fonts.heading, body: fonts.body }, fontFiles: keepUsed(files, fonts) } } /** deckOp for a font field's other choices, dropping in the same op the families no role leads with now. */ export function plainFontOp (field, value, meta) { const op = deckOp(field, value, meta) const had = (meta && meta.fontFiles) || [] if (!had.length) return op const kept = keepUsed(had, op.fonts || {}) if (kept.length !== had.length) op.fontFiles = kept.length ? kept : null return op } /** * Mounts the font fields' behaviour. base is the deck's /d/{sqid}; * getMeta() is the deck's meta now; commit(ops) applies a batch; * refill() puts the fields back to what the deck has (a refused pick); * manifest is the font manifest, read off the page when not given. * Returns change(field, select), which commits for a font field's change * and resolves once a pick's answer has been dealt with. * * Only a field's newest choice is ever written: every change to a field * starts a new generation for it, and a pick whose answer comes back * after a later choice for the same field (Theme's, another family) * commits nothing. The other field's choices do not count. */ export function mountDeckFonts ({ base, getMeta, commit, refill, fetchFn = (...args) => globalThis.fetch(...args), manifest = pageManifest() }) { const generation = { heading: 0, body: 0 } async function pick (role, css, gen) { const current = () => generation[role] === gen try { const res = await fetchFn(`${base}/fonts`, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ family: css }) }) if (!res.ok) throw new Error(`deck fonts: ${res.status}`) const family = await res.json() if (!current()) return // The deck as it is when the answer comes, not when the field // changed: an edit in between is kept. commit([pickOp(role, family, getMeta(), manifest)]) } catch (err) { console.error(err) if (current()) refill() } } return { change (field, select) { const role = field.slice(5) const gen = ++generation[role] const opt = select.selectedOptions && select.selectedOptions[0] if (opt && opt.parentElement && opt.parentElement.tagName === 'OPTGROUP') return pick(role, select.value, gen) commit([plainFontOp(field, select.value, getMeta())]) return Promise.resolve() } } } function pageManifest () { try { const tag = globalThis.document && document.querySelector('meta[name="slides-fonts"]') return tag ? JSON.parse(tag.getAttribute('content') || 'null') : null } catch { return null } } /** * Fills a font field with a stack. When the stack leads with one of the * deck's uploaded families that this person's "Your fonts" group does * not offer (a co-editor's), the field shows it anyway, as a selected * option they cannot choose, labelled with the family's own name (data, * as a deck title is): the field never looks blank, and anything they * own is still theirs to switch to. setValue is inspector-block.mjs's. */ export function fillFontField (select, stack, fontFiles, setValue) { if (!select) return const value = fontChoice(stack, fontFiles) for (const o of [...select.querySelectorAll('option[data-deck-font]')]) if (o.value !== value) o.remove() const family = (fontFiles || []).find(f => f.css === value) if (family && ![...select.options].some(o => o.value === value)) { const o = select.ownerDocument.createElement('option') o.value = value o.textContent = family.family || family.css o.disabled = true o.setAttribute('data-deck-font', '') select.append(o) } setValue(select, value) } /** * Asks the library for this person's families again (GET /fonts as * JSON, deckfonts.go's yourFonts) and offers them in each field's group, * labelled label (the page's own words): a family uploaded in the Fonts * tab Deck settings opened is offered once the editor's window has focus * again. refill() then puts the fields back to what the deck has. */ export async function refreshYourFonts ({ selects, label, refill, fetchFn = (...args) => globalThis.fetch(...args) }) { const res = await fetchFn('/fonts', { credentials: 'same-origin', headers: { Accept: 'application/json' } }) if (!res.ok) return const families = await res.json() if (!Array.isArray(families)) return for (const select of selects) { if (!select) continue const doc = select.ownerDocument let group = select.querySelector('optgroup') if (!families.length) { if (group) group.remove() continue } if (!group) { group = doc.createElement('optgroup') group.label = label || '' select.insertBefore(group, select.querySelector('option[data-deck-font]')) } group.replaceChildren(...families.map(f => { const o = doc.createElement('option') o.value = f.value o.textContent = f.label return o })) } refill() }