oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/editor-fonts.mjs — the font gate every change this person
2// makes in the editor passes (internal/slides/fontgate.go; AGENTS.md,
3// "Fonts: never a flash"). Docs' fontGatePlugin and wait, adopted, and
4// kept out of editor-entry.js so that file stays wiring.
5//
6// Paul, 2026-10-26: "No flashing, ever!" A change this person makes —
7// an op batch (a theme, a font override, a code block, a new slide,
8// a duplicate, a paste of blocks), a code mark typed, pasted or
9// dropped in a slide's text, an undo, a redo — that would put slide
10// text in a family whose four faces are not all in is cancelled
11// before anything changes. Then, like a short modal: the stage, the
12// strip, the inspector and the Slide menu go inert, and the status
13// strip under the bar says a font is loading, at once. Input
14// meanwhile goes nowhere, which a person can see; nothing is queued
15// or replayed, because a replayed keystroke is not the keystroke
16// (Docs' review 7). Once the family is in, the change is made, once,
17// as it was asked for. If the family fails or misses the deadline the
18// change is dropped, editing comes back and the strip says why.
19//
20// One wait at a time: anything else that would change the deck during
21// it is refused, and the strip says so, so the deck cannot move under
22// the change. A collaborator's update waits for the wait to end before
23// it reaches Yjs (onUpdates, free()), in order.
24//
25// A wait never begins in an IME composition: a composition that picks
26// up a family that is not in draws it in its fallback for the visit
27// instead (it is not on screen, so nothing moves).
28//
29// createEditorFontGate takes the tab's font session (fonts-gate.mjs's
30// globalThis.slidesFonts, or the system session), the editor's root,
31// getDoc() for the live Y.Doc and onRefused() for a change that did not
32// happen (the inspector refills from the deck). It returns gate(keys,
33// run), free() (resolves when no wait is on; every waiter is released,
34// in order, however a wait ends), familiesAfter(mutate), afterHistory()
35// (an undo or a redo just made), cold(), plugin() and a waiting getter.
36import * as Y from 'yjs'
37import { ySyncPluginKey } from 'y-prosemirror'
38import { Plugin } from 'prosemirror-state'
39import { view } from './view.mjs'
40import { ACTION_TIMEOUT_MS } from './font-session.mjs'
41import { FAMILY_KEYS } from './font-families.mjs'
42import { fontStatus } from './font-status.mjs'
43import { createInert } from './editor-inert.mjs'
44
45export function createEditorFontGate ({ fonts, root, getDoc, onRefused = () => {} }) {
46 let waiting = false
47 let released = []
48 const free = () => (waiting ? new Promise(resolve => released.push(resolve)) : Promise.resolve())
49 const fontNote = fontStatus(root.querySelector('[slides-fonts-status]'))
50 // How long a font that could not be loaded is said, unless dismissed.
51 const UNAVAILABLE_NOTE_MS = 8000
52 const MONO = 'mono'
53
54 // A deck's uploaded families are fetched under the deck's own base
55 // (fontgate.go). A change can bring in one this tab has never heard
56 // of — a pick here, a collaborator's — so on a session that can learn
57 // them (font-session.mjs's learn) every change is checked.
58 const base = root.dataset && root.dataset.deck ? `/d/${root.dataset.deck}` : ''
59 const learns = () => !!base && typeof fonts.learn === 'function'
60
61 // Whether some family could still need a wait: once every family is
62 // on (or committed), nothing can, and the checks below cost nothing.
63 const coldFamilies = () => fonts.web && (learns() || (fonts.keys || FAMILY_KEYS).some(k => !fonts.inUse.includes(k)))
64
65 // familiesAfter is the families of the deck as mutate(scratch) would
66 // leave it, worked out on a copy so the deck itself is untouched. An
67 // uploaded family the changed deck names is learned from it, so the
68 // change waits for it like any family it brings in.
69 function familiesAfter (mutate) {
70 const scratch = new Y.Doc()
71 Y.applyUpdate(scratch, Y.encodeStateAsUpdate(getDoc()))
72 if (learns()) {
73 const before = view(scratch)
74 settleUnknown(before)
75 // The deck's own sets first: a change worked out before and never
76 // made (refused, or a wait still on) left its sets learned.
77 fonts.learn(before.meta && before.meta.fontFiles, base)
78 }
79 mutate(scratch)
80 const after = view(scratch)
81 if (learns()) fonts.learn(after.meta && after.meta.fontFiles, base)
82 return fonts.familiesOfView(after)
83 }
84
85 // learnLive learns the deck's sets as the deck has them now: after a
86 // change that was worked out and not made.
87 function learnLive () {
88 if (!learns()) return
89 const m = view(getDoc()).meta
90 fonts.learn(m && m.fontFiles, base)
91 }
92
93 // afterHistory follows an undo or a redo, in the same task: the deck
94 // may now have another set of an uploaded family's faces (one this tab
95 // had on the page before, so loaded), which goes on in place of the
96 // set there now. A set that is not ready leaves the page's own set
97 // where it is (font-session.mjs's commit). Undo and redo pass the gate
98 // on the families in use (editor-entry.js); this is the rest.
99 function afterHistory () {
100 if (!learns()) return
101 learnLive()
102 const keys = fonts.familiesOfView(view(getDoc())).filter(k => k.startsWith('u:'))
103 if (keys.length) fonts.commitFallback(keys)
104 }
105
106 // A family the deck shows already that this tab never learned (a
107 // change taken in without a check: a resync) is on screen in its
108 // stack's next family. Learned now, it is committed there, so it
109 // never swaps in.
110 function settleUnknown (before) {
111 const known = fonts.keys || []
112 const unknown = fonts.familiesOfView(before).filter(k => k.startsWith('u:') && !known.includes(k))
113 if (!unknown.length) return
114 fonts.learn(before.meta && before.meta.fontFiles, base)
115 fonts.commitFallback(unknown)
116 }
117
118 // refused tells the person a change did not happen and lets the
119 // inspector show the deck again. It never throws: whatever it calls is
120 // told off in the console, and the caller's own cleanup still runs.
121 function refused (kind, ms = 0) {
122 try {
123 fontNote.say(kind, ms)
124 } catch (err) {
125 console.error('fonts:', err)
126 }
127 try {
128 onRefused()
129 } catch (err) {
130 console.error('fonts:', err)
131 }
132 }
133
134 // release lets everything that waited for this wait go, in the order
135 // it queued (a collaborator's batch, a stage install, a resync).
136 function release () {
137 const waiters = released
138 released = []
139 for (const r of waiters) r()
140 }
141
142 // gateLocal runs a person's own change now if its families are in,
143 // after a wait if they are coming, and never if a wait is on. It
144 // resolves to whether the change was made, and never rejects.
145 function gateLocal (keys, run) {
146 if (waiting) {
147 learnLive()
148 refused('refused')
149 return Promise.resolve(false)
150 }
151 const cold = keys.filter(k => !fonts.ready(k))
152 if (!cold.length) {
153 fonts.use(keys)
154 return Promise.resolve(run() !== false)
155 }
156 return wait(keys, run)
157 }
158
159 // wait holds the change while its families load, then runs it once,
160 // or refuses it. Whichever way it ends — loaded, failed, timed out, or
161 // anything in here throwing — the editor comes back and every waiter
162 // queued behind it is released, in order, in the finally: a refusal
163 // that threw before the release once left a collaborator's batch, and
164 // every batch after it, stuck for the rest of the visit (Astra, #27).
165 async function wait (keys, run) {
166 waiting = true
167 let loaded = false
168 let ran = false
169 try {
170 setInert(true)
171 try {
172 loaded = await fonts.waitFor(keys, ACTION_TIMEOUT_MS)
173 } catch {
174 loaded = false
175 }
176 if (loaded) fonts.use(keys)
177 waiting = false
178 // Editing back, and focus with it, before the change: so the
179 // change and its selection are painted in one frame.
180 setInert(false)
181 ran = loaded && run() !== false
182 } catch (err) {
183 console.error('fonts:', err)
184 ran = false
185 } finally {
186 waiting = false
187 try {
188 setInert(false)
189 } catch (err) {
190 console.error('fonts:', err)
191 }
192 try {
193 if (ran) fontNote.clear()
194 } catch (err) {
195 console.error('fonts:', err)
196 }
197 // Loaded but no longer possible (its view went away): not a font
198 // that failed, and not said as one.
199 if (!ran) {
200 try {
201 learnLive()
202 } catch (err) {
203 console.error('fonts:', err)
204 }
205 refused(loaded ? 'interrupted' : 'unavailable', UNAVAILABLE_NOTE_MS)
206 }
207 release()
208 }
209 return ran
210 }
211
212 // The editor goes inert while a change waits (editor-inert.mjs).
213 const setInert = createInert(root, () => fontNote.say('loading'))
214
215 // The ProseMirror half: one plugin per view bound to a slide's text
216 // (stage.mjs's plugins; the notes are drawn in the chrome's face and
217 // get none). The one mark that brings in a family is code.
218 const hasCode = (doc, marks) => {
219 const c = doc.type.schema.marks.c
220 if (marks && c.isInSet(marks)) return true
221 let found = false
222 doc.descendants(n => {
223 if (found) return false
224 if (n.isText && c.isInSet(n.marks)) found = true
225 return !found
226 })
227 return found
228 }
229 function fontGatePlugin () {
230 let pmView = null
231 return new Plugin({
232 view (v) {
233 pmView = v
234 return { destroy () { if (pmView === v) pmView = null } }
235 },
236 filterTransaction (tr, state) {
237 // Yjs's own changes (a collaborator, undo, redo, a resync) reach
238 // the view as they are; they were checked before they reached Yjs.
239 if (tr.getMeta(ySyncPluginKey)) return true
240 if (!tr.docChanged && !tr.storedMarksSet) return true
241 if (waiting) {
242 fontNote.say('refused')
243 return false
244 }
245 if (!coldFamilies() || fonts.inUse.includes(MONO)) return true
246 const marks = tr.storedMarksSet ? tr.storedMarks : state.storedMarks
247 if (!hasCode(tr.doc, marks)) return true
248 if (fonts.ready(MONO)) {
249 fonts.use([MONO])
250 return true
251 }
252 if (pmView && pmView.composing) {
253 fonts.commitFallback([MONO])
254 return true
255 }
256 const v = pmView
257 wait([MONO], () => {
258 if (!v || pmView !== v || v.state.doc !== tr.before) return false
259 // Through the view's own dispatch, which keeps a change made
260 // while a resync is pending as its transactions too
261 // (editor-entry.js's aroundDispatch).
262 v.dispatch(tr)
263 return true
264 })
265 return false
266 }
267 })
268 }
269
270 return {
271 gate: gateLocal,
272 free,
273 familiesAfter,
274 afterHistory,
275 cold: coldFamilies,
276 plugin: fontGatePlugin,
277 get waiting () { return waiting }
278 }
279}
280