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-entry.js — the editor bundle's entry: wiring only.
2// fixtures/build-bundles.mjs bundles this file and everything it
3// imports into internal/slides/static/editor.<hash>.js, the one
4// script the app serves (spec §8: the editor is the one surface that
5// needs it).
6//
7// The shape is Docs' editor-entry.js, adopted: load the log into a
8// Y.Doc, bind the editor, save what this tab produces through the
9// save queue, hear about everybody else's writes on the stream and
10// fetch them through live-updates, rebuild from server truth through
11// the resync controller when a batch is refused. What differs is what
12// the editor IS: not one ProseMirror over one fragment but a stage
13// (stage.mjs) binding a view to every text block of the server's own
14// slide HTML, a strip (strip.mjs) of the server's SVG thumbnails, an
15// inspector (inspector.mjs) whose every control is one op, a canvas
16// overlay (canvas.mjs), every box a tab stop (stage-focus.mjs) and
17// listed in View → Outline (outline.mjs), the menu on a selected box
18// (box-menu.mjs), and the desktop/phone switcher (switcher.mjs).
19// Every structural edit goes through the same ops vocabulary the API
20// uses (ops.mjs) and ends in a re-fetch of the slide once the save has
21// landed — the server renders; this tab never does.
22//
23// yjs stays at the version fixtures/package.json pins for the vectors:
24// this bundle and core/'s Rust CRDT agree on one wire format.
25import * as Y from 'yjs'
26import { ySyncPluginKey } from 'y-prosemirror'
27import { carry, createKeeper, freshClientID, derivedStep } from './carry.mjs'
28import { schema } from './schema.mjs'
29import { createSystemSession } from './font-session.mjs'
30import { createEditorFontGate } from './editor-fonts.mjs'
31import { parseFrames } from './frames.mjs'
32import { createSaveQueue, createPoster, answerTimeoutMs, reachable, KEEPALIVE_BYTES } from './save-queue.mjs'
33import { mountSaveStatus, queueStatusState } from './status.mjs'
34import { createLiveUpdates, updatesURL } from './live-updates.mjs'
35import { createResyncController } from './resync-controller.mjs'
36import { mountStage, slideIDs, slideAfter, notesFragment, BOUND_TYPES } from './stage.mjs'
37import { mountStageFocus } from './stage-focus.mjs'
38import { mountOutline } from './outline.mjs'
39import { mountBoxMenu } from './box-menu.mjs'
40import { mountBoxMenuAppears } from './box-menu-appears.mjs'
41import { mountStepMarks } from './step-marks.mjs'
42import { mountPlayThrough } from './play-through.mjs'
43import { mountSceneLayer, scenePositions } from './scene-layer.mjs'
44import { presses } from './presses.mjs'
45import { regionOp } from './inspector-ops.mjs'
46import { mountStrip } from './strip.mjs'
47import { mountReorder } from './strip-reorder.mjs'
48import { classify } from './changes.mjs'
49import { textKeys } from './text-keys.mjs'
50import { mountLinkDialog, linkPrompt } from './link-dialog.mjs'
51import { applyOps, view } from './ops.mjs'
52import { ROOT_SCENES, undoScope } from './ydoc.mjs'
53import { mountSelection, parseHash, formatHash } from './selection.mjs'
54import { mountInspector } from './inspector.mjs'
55import { mountCanvas } from './canvas.mjs'
56import { mountSwitcher, routeEdit } from './switcher.mjs'
57import { createCommands } from './commands.mjs'
58import { createPresence, newClientId } from './presence.mjs'
59import { tabClientId, claimClientId, clientIdKey } from './client-id.mjs'
60import { mountPresenceView } from './presence-view.mjs'
61import { createUploader, refusal, sha256Hex } from './uploads.mjs'
62import { mountClipCard } from './clip-card.mjs'
63import { saveSceneCode } from './scene-code.mjs'
64import { mountHead } from './head.mjs'
65import { mountFormatBar } from './format-bar.mjs'
66import { mountInspect } from './inspect.mjs'
67import { createAssist } from './assist.mjs'
68import { mountAssist } from './assist-panel.mjs'
69import { mountPhoneFrame } from './phone-frame.mjs'
70import { mountNotesCard, countWords } from './notes-card.mjs'
71
72// Coalesce a burst of typing into one request. Docs' number and Docs'
73// reasoning: under the ~300ms at which a delay stops reading as "the
74// app responded", and the floor on how fast an edit reaches anyone.
75const DEBOUNCE_MS = 250
76
77// Origins. Bytes the server sent are 'remote' and are never saved
78// back; this tab's structural ops are 'local'; y-prosemirror tags its
79// own transactions with ySyncPluginKey; an undo's origin is the undo
80// manager itself. The undo manager tracks the middle two and only
81// those, so undo is this person's edits and never somebody else's
82// (spec §3.1).
83const REMOTE = 'remote'
84const LOCAL = 'local'
85// CARRIED is a change this tab made while diverged, applied to the
86// rebuilt document by a resync (attemptResync). It is this person's own,
87// so the undo manager tracks it like LOCAL.
88const CARRIED = 'carried'
89
90// The undo manager's capture window: changes made within it of each other
91// are one undo step.
92const UNDO_CAPTURE_MS = 500
93
94// How long after a change a thumbnail is re-fetched.
95const THUMB_MS = 600
96
97// fontsFor is the tab's font session: the gate's (fonts-gate.mjs runs
98// first and leaves it on globalThis.slidesFonts), or, if its script
99// never arrived, a session in which everything is in its system faces
100// for the visit and the editor shows a held page itself once it has
101// mounted.
102function fontsFor () {
103 if (globalThis.slidesFonts) return globalThis.slidesFonts
104 const root = document.documentElement
105 return Object.assign(createSystemSession(), {
106 fontsReady: Promise.resolve(),
107 familiesOfView: () => [],
108 familiesOfSection: () => [],
109 prepareSection: async () => {},
110 settled () {
111 if (root.getAttribute('data-slides-fonts') !== 'pending') return
112 clearTimeout(globalThis.__slidesFontsHold)
113 root.setAttribute('data-slides-fonts', 'shown')
114 }
115 })
116}
117
118
119async function fetchFrames (url) {
120 const res = await fetch(url, { credentials: 'same-origin' })
121 if (!res.ok) throw new Error(`load ${url}: ${res.status}`)
122 return {
123 frames: parseFrames(new Uint8Array(await res.arrayBuffer())),
124 seq: Number(res.headers.get('Slides-Seq'))
125 }
126}
127
128export async function mountEditor (root) {
129 const fonts = fontsFor()
130 // Shown already, before this mount: the gate's layout deadline passed
131 // while this bundle or the log was on its way. Then nothing this
132 // mount does may move the slide on screen: the stored viewport is
133 // not applied for this page (the person can still switch).
134 const shownBeforeMount = document.documentElement.getAttribute('data-slides-fonts') === 'shown'
135 const sqid = root.dataset.deck
136 const base = `/d/${sqid}/updates`
137 const streamURL = `/d/${sqid}/stream`
138 const fetchSlide = async (id, vp) => {
139 const res = await fetch(`/d/${sqid}/slides/${id}.html?vp=${vp}`, { credentials: 'same-origin' })
140 if (!res.ok) throw new Error(`slide ${id}: ${res.status}`)
141 return res.text()
142 }
143
144 // A thumbnail is an <img> of the server's SVG (internal/slides/
145 // thumbs.go). The deck's seq is on the URL so the browser asks again
146 // after a change and reads its own cache in between; the route
147 // revalidates on an ETag, so the ask is a 304 for every slide that
148 // did not actually move. noteSeq is called wherever a seq arrives —
149 // this tab's own save, and a batch pulled in from somebody else's.
150 let thumbSeq = Number(root.dataset.seq) || 0
151 const noteSeq = seq => {
152 if (Number.isFinite(seq) && seq > thumbSeq) thumbSeq = seq
153 }
154 const thumbURL = id => `/d/${sqid}/slides/${id}.svg?seq=${thumbSeq}`
155
156 const status = await mountSaveStatus(root)
157 const stripEl = root.querySelector('[slides-strip]')
158 const stagePane = root.querySelector('[slides-stage-pane]')
159 const stageEl = stagePane.querySelector('[slides-stage]')
160 const phoneEl = stagePane.querySelector('[slides-stage-phone]')
161 const phoneScreenEl = phoneEl.querySelector('[slides-phone-screen]')
162 const notesPane = stagePane.querySelector('[slides-notes-pane]')
163 const inspectorEl = root.querySelector('[slides-inspector]')
164 const presentForm = root.querySelector('[slides-present-form]')
165 const dialog = mountLinkDialog(root.querySelector('[slides-link-dialog]'))
166 const text = {
167 slide: root.dataset.textSlide
168 }
169 // A slide's presses and its place in the talk (steps and presenter
170 // spec §4): the strip's and the stage control's words.
171 const talkText = {
172 one: root.dataset.textPressesOne,
173 many: root.dataset.textPressesMany,
174 exit: root.dataset.textPressesExit,
175 full: root.dataset.textTalkFull,
176 parked: root.dataset.textTalkParked
177 }
178 const presenceText = {
179 slide: root.dataset.textPresenceSlide,
180 block: root.dataset.textPresenceBlock,
181 more: root.dataset.textPresenceMore,
182 joined: root.dataset.textPresenceJoined,
183 left: root.dataset.textPresenceLeft
184 }
185 const types = {}
186 for (const k of Object.keys(root.dataset)) if (k.startsWith('type')) types[k.slice(4).toLowerCase()] = root.dataset[k]
187 const uploadText = {
188 uploading: root.dataset.textUploadUploading,
189 checking: root.dataset.textUploadChecking,
190 done: root.dataset.textUploadDone,
191 failed: root.dataset.textUploadFailed,
192 toolarge: root.dataset.textUploadToolarge,
193 type: root.dataset.textUploadType,
194 altfirst: root.dataset.textUploadAltfirst,
195 remove: root.dataset.textAssetRemove
196 }
197
198 // Images (assets.go, spec §2.7). The three requests are here — this
199 // is the only file that knows this deck's URLs — and the state
200 // machine that sequences them is uploads.mjs.
201 //
202 // The PUT goes wherever the sign step said: the bucket itself with a
203 // real store, or back to this app in development, where blobs.Dir has
204 // nothing to presign. Either way it carries no credentials of ours —
205 // a presigned URL is the credential, and sending a cookie to a bucket
206 // would be a mistake with no upside.
207 const assetJSON = async (path, body) => {
208 const res = await fetch(`/d/${sqid}${path}`, {
209 method: 'POST',
210 credentials: 'same-origin',
211 headers: { 'Content-Type': 'application/json' },
212 body: JSON.stringify(body)
213 })
214 if (!res.ok) throw await refusal(res)
215 return res.json()
216 }
217 const putBytes = async (url, file, headers) => {
218 const sameOrigin = url.startsWith('/')
219 const res = await fetch(url, {
220 method: 'PUT',
221 credentials: sameOrigin ? 'same-origin' : 'omit',
222 headers,
223 body: file
224 })
225 if (!res.ok) throw await refusal(res)
226 }
227 const uploader = createUploader({
228 sign: body => assetJSON('/uploads', body),
229 put: putBytes,
230 register: body => assetJSON('/assets', body),
231 // A clip's staged bytes, read back to draw its poster (assets.go).
232 staged: ref => `/d/${sqid}/uploads/${encodeURIComponent(ref)}`,
233 applyOp: () => {},
234 onState: (state, detail) => { if (inspector) inspector.onUploadState(state, detail) }
235 })
236
237 // A clip's video, picked in its card or as Insert → Clip adds one
238 // (clip-card.mjs): its poster and itself through the same uploader.
239 const clipCard = mountClipCard({
240 root,
241 getSlideId: () => (stage ? stage.slideId : ''),
242 getBlock: () => (stage && selection && selection.current ? blockJSON(stage.slideId, selection.current) : null),
243 commit: ops => commit(ops),
244 uploadClip: (file, opts) => uploader.uploadClip(file, opts),
245 labels: uploadText
246 })
247
248 // A dropped batch is stickier than any one save queue's status: once
249 // a batch is ever dropped, the person keeps seeing it (Docs' rule) —
250 // as `failed`, its own state, because a dropped batch is not being
251 // retried and "Offline, retrying" would say it is. A slide that
252 // would not load is said in its own line until one does. The rules
253 // are status.mjs, where they are tested.
254 const setStatus = state => status.save(state)
255
256 // Whichever of these is live right now. A resync replaces them all.
257 let ydoc = null
258 let undoManager = null
259 let stage = null
260 let phoneStage = null
261 let strip = null
262 let head = null
263 let selection = null
264 let inspector = null
265 let canvas = null
266 let stageFocus = null
267 let currentQueue = null
268 let currentLive = null
269 let thumbTimer = null
270 let currentView = 'desktop'
271
272 // --- presence: who else has this deck open, and where (spec §3.3) ---
273 //
274 // Presence outlives any one Y.Doc — it is not document state, and a
275 // resync (a new stage, a new selection, a new everything above) is
276 // not somebody leaving the deck. So this is mounted once, over the
277 // strip's own <ol> and the stage's own element, and never destroyed
278 // or recreated the way stage/strip/selection/inspector are inside
279 // attemptResync. getSlideId and getState read `stage` and
280 // `selection` by closure, live, whichever resync's mount is current.
281 const presenceView = mountPresenceView({
282 stripEl,
283 stageEl,
284 liveEl: root.querySelector('[slides-presence-live]'),
285 text: presenceText,
286 getSlideId: () => (stage ? stage.slideId : '')
287 })
288 // One id per tab, kept across a reload (client-id.mjs): a fresh one
289 // per load drew this tab's own previous self as a colleague until the
290 // server expired it. A duplicated tab copies the stored id, so the
291 // claim below makes it give the copy up for a fresh one.
292 let tabStorage = null
293 try { tabStorage = globalThis.sessionStorage } catch { /* a fresh id per load then */ }
294 const presence = createPresence({
295 clientId: tabClientId({ storage: tabStorage, deck: sqid }),
296 post: body => fetch(`/d/${sqid}/presence`, {
297 method: 'POST',
298 credentials: 'same-origin',
299 headers: { 'Content-Type': 'application/json' },
300 body: JSON.stringify(body)
301 }),
302 getState: () => ({
303 slide: stage ? stage.slideId : '',
304 block: selection ? selection.current : ''
305 })
306 })
307
308 let idChannel = null
309 try { idChannel = new BroadcastChannel(clientIdKey(sqid)) } catch { /* no rival check */ }
310 claimClientId({
311 channel: idChannel,
312 getId: () => presence.clientId,
313 onTaken: () => {
314 const id = newClientId()
315 try { if (tabStorage) tabStorage.setItem(clientIdKey(sqid), id) } catch { /* per-load then */ }
316 presence.setClientId(id)
317 }
318 }).claim()
319
320 const keys = textKeys({
321 undo: () => undo(),
322 redo: () => redo(),
323 link: view => linkPrompt(view, dialog)
324 })
325 // What the card shows (inspect.mjs): the selection's box, the notes'
326 // marks or the slide's options, as the root's data-inspect. The bar
327 // says where the caret went; the selection, what is selected. A box's
328 // text taking focus, by any means, selects that box. The marks act on
329 // what the card shows (format-bar.mjs's target), and are told again
330 // whenever that changes.
331 const inspect = mountInspect({ root, onChange: () => formatBar.sync() })
332 const formatBar = mountFormatBar({
333 root,
334 keys,
335 onCaret: (where, block) => {
336 if (where === 'stage' && block && selection) selection.select(block)
337 inspect.caret(where)
338 },
339 target: () => {
340 const kind = inspect.current()
341 if (kind === 'notes') return { where: 'notes' }
342 if (kind === 'box' && selection && selection.current) return { where: 'stage', block: selection.current }
343 return null
344 }
345 })
346
347 // --- the font gate every local change passes (editor-fonts.mjs) ---
348 const fontGate = createEditorFontGate({
349 fonts,
350 root,
351 getDoc: () => ydoc,
352 onRefused: () => { if (inspector) inspector.fill() }
353 })
354 const gateLocal = fontGate.gate
355 const free = fontGate.free
356 const coldFamilies = fontGate.cold
357 const familiesAfter = fontGate.familiesAfter
358 const fontGatePlugin = fontGate.plugin
359
360 // --- the one write path: every structural edit is a batch of ops ---
361
362 // A batch is one undo step: the undo manager would otherwise fold
363 // two commands made within its capture window (500 ms — a menu
364 // press right after a field change) into one, and undo would take
365 // both back at once.
366 //
367 // It passes the font gate first, and resolves to whether it was
368 // applied: a batch that needs a family that is not in waits for it,
369 // and one whose family cannot be had is refused. onError, when given,
370 // hears a batch the ops module refused, which then resolves false
371 // (the assistant's answer, which may name a slide a colleague has
372 // just removed); without it a refusal is logged, as it always was.
373 function commit (ops, { onError } = {}) {
374 let keys = []
375 if (coldFamilies()) {
376 try {
377 keys = familiesAfter(d => applyOps(d, ops, LOCAL))
378 } catch {
379 // The batch itself is refused below, with its own message.
380 keys = []
381 }
382 }
383 return gateLocal(keys, () => {
384 try {
385 if (undoManager) undoManager.stopCapturing()
386 applyOps(ydoc, ops, LOCAL)
387 return true
388 } catch (err) {
389 if (onError) {
390 onError(err)
391 return false
392 }
393 console.error('ops:', err)
394 if (inspector) inspector.fill()
395 return true
396 }
397 })
398 }
399 // The assistant's write: commit, and the undo step it became, closed
400 // off so a keystroke straight after it is a step of its own and the
401 // panel's Undo takes back the answer and nothing else.
402 const lastStep = () => (undoManager && undoManager.undoStack[undoManager.undoStack.length - 1]) || null
403 async function commitAnswer (ops) {
404 let error = null
405 const before = lastStep()
406 const applied = await commit(ops, { onError: err => { error = err } })
407 // A batch that changed nothing the undo manager tracks made no step
408 // of its own: the newest one is somebody's earlier edit, which the
409 // panel's Undo must not take back (Claude Fable, #42).
410 const newest = lastStep()
411 const step = applied && newest !== before ? newest : null
412 if (undoManager) undoManager.stopCapturing()
413 return { applied, error, step }
414 }
415 // Undo that step, only while it is still the newest: after anything
416 // else, Undo in the Edit menu is the honest control.
417 const undoStep = step => gateLocal(fonts.inUse, () => {
418 if (!step || lastStep() !== step) return false
419 undoManager.undo()
420 fontGate.afterHistory()
421 return true
422 })
423 // Undo and redo arrive through Yjs, so the plugin above never sees
424 // them. What they bring back was on screen in this visit, in families
425 // that stay in; they still pass the gate, so neither runs during a
426 // wait, and if a family somehow is not in they wait like anything else.
427 // An undo or a redo can move an uploaded family to another set of its
428 // faces, which goes on the page with it (afterHistory).
429 const undo = () => gateLocal(fonts.inUse, () => { if (undoManager) { undoManager.undo(); fontGate.afterHistory(); if (inspector) inspector.fill({ force: true }) } })
430 const redo = () => gateLocal(fonts.inUse, () => { if (undoManager) { undoManager.redo(); fontGate.afterHistory(); if (inspector) inspector.fill({ force: true }) } })
431 const slideJSON = id => view(ydoc).slides.find(s => s.id === id) || null
432 const blockJSON = (slideId, id) => {
433 const s = slideJSON(slideId)
434 return s ? s.blocks.find(b => b.id === id) || null : null
435 }
436
437 // --- the stage follows the URL hash: #<slide id>[/<block id>] ---
438
439 function wantedSlide () {
440 const ids = slideIDs(ydoc)
441 const { slide } = parseHash(location.hash)
442 return ids.includes(slide) ? slide : (ids[0] || '')
443 }
444 async function showSlide (id) {
445 if (!stage) return
446 try {
447 await stage.load(id)
448 if (phoneStage && currentView === 'both') await phoneStage.load(id)
449 } catch (err) {
450 console.error('stage:', err)
451 }
452 }
453 async function refreshStages () {
454 if (!stage) return
455 try {
456 await stage.refresh()
457 if (phoneStage && currentView === 'both') await phoneStage.refresh()
458 } catch (err) {
459 console.error('stage:', err)
460 }
461 }
462 function onLoaded (id) {
463 status.loadFailed(false)
464 if (strip) strip.setCurrent(id)
465 // Another slide, or this one fetched again after an edit: the
466 // finished slide, and its own count.
467 playThrough.refresh()
468 syncTalkRows()
469 syncScenes()
470 if (notesPane) notesPane.hidden = !id
471 inspect.slideShown(id)
472 notesCard.refresh()
473 if (head) head.slideShown(!!id)
474 // The stage's whole DOM was just replaced: its boxes are made tab
475 // stops again before the selection is marked on them.
476 if (stageFocus) stageFocus.refresh()
477 if (selection) selection.reapply()
478 if (inspector) inspector.fill()
479 outline.fill()
480 if (canvas) canvas.place()
481 // The stage's whole DOM was just replaced, presence's own overlay
482 // element with it: place() re-attaches it, and a slide change is
483 // somewhere this tab went.
484 presenceView.place()
485 presence.changed()
486 // Focus that was on a box itself goes back on it (stage-focus.mjs).
487 const back = heldBox
488 heldBox = ''
489 if (back && stageFocus && selection) stageFocus.restore(back, selection.current)
490 }
491 let heldBox = ''
492 function onLoadError () {
493 status.loadFailed(true)
494 }
495
496 // Thumbnails re-fetch a little after the change that dirtied them,
497 // and never before a local change has been saved: flushSoon is what
498 // remote changes call, flushNow is what a landed save calls.
499 function flushSoon () {
500 if (thumbTimer) clearTimeout(thumbTimer)
501 thumbTimer = setTimeout(() => { thumbTimer = null; strip && strip.flush() }, THUMB_MS)
502 }
503
504 // A local structural change is re-fetched once its save has landed
505 // (the server cannot render what it has not received yet). Deferred
506 // a tick, because observers run before the doc's 'update' event
507 // hands the bytes to the queue; one refresh per burst.
508 let refreshPending = false
509 function refreshAfterSave () {
510 if (refreshPending) return
511 refreshPending = true
512 setTimeout(async () => {
513 try {
514 if (currentQueue) await currentQueue.flush()
515 } finally {
516 refreshPending = false
517 }
518 await refreshStages()
519 }, 0)
520 }
521 let fillPending = false
522 function fillSoon () {
523 if (fillPending) return
524 fillPending = true
525 requestAnimationFrame(() => {
526 fillPending = false
527 inspector && inspector.fill(); outline.fill(); boxMenu.sync(); boxMenuAppears.sync(); stepMarks.place()
528 // Any edit shows the finished slide; the strip's talk and counts,
529 // and the Slide menu's talk toggles, follow the document.
530 playThrough.refresh()
531 if (strip) strip.relabel()
532 syncTalkRows()
533 syncScenes()
534 })
535 }
536
537 function watchDoc (doc, slides, meta) {
538 let order = slideIDs(doc)
539 slides.observeDeep((events, tr) => {
540 const c = classify(events, slides)
541 const current = stage ? stage.slideId : ''
542 if (c.order) {
543 strip.sync()
544 const ids = slideIDs(doc)
545 if (!ids.includes(current)) {
546 const next = slideAfter(order, ids, current)
547 const go = () => {
548 location.hash = next ? '#' + next : ''
549 if (!next) showSlide('')
550 }
551 // A slide this tab has just made is not on the server until
552 // its save lands, and the stage fetches the server's HTML for
553 // it: moving there first answered 404 and left the stage on
554 // its empty state (the first slide of an empty deck, most
555 // often when a font wait had held the change). So a local
556 // change moves the stage once it is saved; a remote one is on
557 // the server already.
558 if (tr.origin === REMOTE) go()
559 else {
560 setTimeout(async () => {
561 let saved = true
562 try {
563 if (currentQueue) saved = await currentQueue.flush()
564 } finally {
565 if (saved !== false) go()
566 }
567 }, 0)
568 }
569 }
570 order = ids
571 }
572 for (const id of c.text) strip.mark(id)
573 // Notes written or emptied, here or by a colleague: the closed
574 // card's tab counts the slide's words again.
575 if (c.text.includes(current)) notesCard.refresh()
576 for (const id of c.structure) {
577 strip.mark(id)
578 // The server has already rendered a remote change; a local one
579 // — this tab's op, or its undo — is re-fetched once saved.
580 if (id !== current) continue
581 if (tr.origin === REMOTE) showSlide(current)
582 else refreshAfterSave()
583 }
584 if (tr.origin === REMOTE) flushSoon()
585 fillSoon()
586 })
587 // The theme, accent and fonts are on every section's style; the
588 // title is the page's heading.
589 meta.observe((event, tr) => {
590 const title = meta.get('title')
591 if (typeof title === 'string') {
592 if (head) head.setTitle(title)
593 document.title = title
594 }
595 if ([...event.keysChanged].some(k => k !== 'title')) {
596 for (const id of slideIDs(doc)) strip.mark(id)
597 if (tr.origin === REMOTE) { refreshStages(); flushSoon() } else refreshAfterSave()
598 }
599 fillSoon()
600 })
601 // The assets map is the third root (spec §2.7), and it is watched
602 // for the same reason meta is: nothing else observes it, so
603 // registering or removing an image would otherwise change the
604 // document and leave the Unused images list — and every slide that
605 // draws the picture — showing what was true a moment ago.
606 doc.getMap('assets').observe((event, tr) => {
607 for (const id of slideIDs(doc)) strip.mark(id)
608 if (tr.origin === REMOTE) { refreshStages(); flushSoon() } else refreshAfterSave()
609 fillSoon()
610 })
611 // And the scenes (scenes and clips spec §2), for the same reason: a
612 // scene's words, data, code or stills change the slides that show
613 // it, its block's card (scene-card.mjs) and the frame running it,
614 // made afresh with the new init (syncScenes, from fillSoon).
615 doc.getMap(ROOT_SCENES).observeDeep((events, tr) => {
616 for (const id of slideIDs(doc)) strip.mark(id)
617 if (tr.origin === REMOTE) { refreshStages(); flushSoon() } else refreshAfterSave()
618 fillSoon()
619 })
620 }
621
622 // sendSave posts a batch (createPoster): one for the page, not one per
623 // save queue, so a server found not to gunzip is remembered across a
624 // resync, which builds a new queue.
625 const sendSave = createPoster({ url: base })
626
627 function makeSaveQueue (getLive) {
628 return createSaveQueue({
629 // Keepalive, at most KEEPALIVE_BYTES a batch, gzipped from 1KB, and
630 // given up if it is not answered (createPoster, answerTimeoutMs):
631 // WebKit sends no ordinary request while a link the page opened is
632 // still loading, and the page stays editable meanwhile —
633 // save-queue.mjs's own comment has the case (Docs #94).
634 post: async (bytes, onWire) => {
635 const res = await sendSave(bytes, onWire)
636 const live = getLive()
637 if (res.ok) {
638 const seq = Number(res.headers.get('Slides-Seq'))
639 if (live && Number.isFinite(seq)) live.noteOwnSeq(seq)
640 noteSeq(seq)
641 }
642 if (res.ok && strip) strip.flush()
643 return res
644 },
645 mergeUpdates: Y.mergeUpdates,
646 debounceMs: DEBOUNCE_MS,
647 maxBatchBytes: KEEPALIVE_BYTES,
648 answerTimeoutMs,
649 // A save refused with no answer is "retrying" only if the server
650 // cannot be reached either (reachable); otherwise it stays saving.
651 probe: () => reachable('/healthz'),
652 onStatus: state => {
653 if (state === 'failed') {
654 status.drop()
655 resyncController.reportDivergence()
656 }
657 setStatus(queueStatusState(state))
658 }
659 })
660 }
661
662 // --- the views: desktop, phone, both (switcher.mjs) ---
663
664 // --- the notes card (notes-card.mjs): open or closed, its height ---
665 // Reading localStorage at all throws where site data is blocked; the
666 // card then keeps its state for this visit.
667 let notesStorage = null
668 try { notesStorage = globalThis.localStorage } catch { /* this visit only */ }
669 const notesCard = mountNotesCard({
670 root: stagePane,
671 storage: notesStorage,
672 words: () => (ydoc && stage && stage.slideId ? countWords(notesFragment(ydoc, stage.slideId)) : 0),
673 onChange: open => { if (head) head.notesShown(open) }
674 })
675 // --- View → Outline (outline.mjs): the slide's boxes, by name ---
676 // The popover is the page's, so this outlives a resync; what it lists
677 // is read live. A row selects its box and puts focus on it.
678 const outline = mountOutline({
679 popover: root.querySelector('[slides-outline]'),
680 getBlocks: () => (ydoc && stage && stage.slideId && slideJSON(stage.slideId)?.blocks) || [],
681 getSelected: () => (selection ? selection.current : ''),
682 select: id => {
683 if (!selection) return
684 selection.select(id)
685 if (stageFocus) stageFocus.focus(id)
686 },
687 labels: { types }
688 })
689 // --- the menu on a box (box-menu.mjs): its round button, its rows ---
690 // The page's, like the Outline; what it acts on is read live.
691 const boxMenu = mountBoxMenu({
692 root,
693 stageEl,
694 getSelected: () => (selection ? selection.current : ''),
695 getSlide: () => (ydoc && stage && stage.slideId ? slideJSON(stage.slideId) : null),
696 run: name => commands.run(name),
697 setRegion: (id, region) => {
698 const block = blockJSON(stage.slideId, id)
699 if (block) commit([regionOp(stage.slideId, block, region)])
700 },
701 focusBox: id => { if (stageFocus) stageFocus.focus(id) },
702 select: id => { if (selection) selection.select(id) },
703 after: (name, id) => { if (stageFocus) stageFocus.after(name, id) }
704 })
705 // Its Appears rows (box-menu-appears.mjs), and the press numbers drawn
706 // beside the boxes while one is selected (step-marks.mjs): the page's
707 // too, reading the stage live.
708 const boxMenuAppears = mountBoxMenuAppears({
709 menu: root.querySelector('[slides-box-menu]'),
710 getSelected: () => (selection ? selection.current : ''),
711 getSlide: () => (ydoc && stage && stage.slideId ? slideJSON(stage.slideId) : null),
712 close: () => boxMenu.close({ restore: true }),
713 commit: ops => commit(ops)
714 })
715 const stepMarks = mountStepMarks({
716 stageEl,
717 getSelected: () => (selection ? selection.current : ''),
718 getSlide: () => (ydoc && stage && stage.slideId ? slideJSON(stage.slideId) : null),
719 getScenes: () => (ydoc ? view(ydoc).scenes : null)
720 })
721 // The "3 presses" control that plays the slide through on the stage
722 // (play-through.mjs), and the Slide menu's talk toggles pressed for
723 // the slide on the stage.
724 const playThrough = mountPlayThrough({
725 stageEl,
726 getSlide: () => (ydoc && stage && stage.slideId ? slideJSON(stage.slideId) : null),
727 getScenes: () => (ydoc ? view(ydoc).scenes : null),
728 onExit: () => stepMarks.place(),
729 onDraw: moved => syncScenes(moved),
730 texts: talkText
731 })
732 // A scene runs on the stage while its box is chosen, or while the
733 // slide is played through; otherwise its stills show (scene-layer.mjs).
734 const sceneLayer = mountSceneLayer({ root: stagePane, deck: () => (ydoc ? view(ydoc) : null), base: `/d/${sqid}` })
735 function syncScenes (moved = false) {
736 const all = stage && stage.slideId ? scenePositions(stageEl) : []
737 const chosen = selection ? selection.current : ''
738 sceneLayer.show(stage ? stage.slideId : '', playThrough.playing() ? all : all.filter(p => p.block === chosen), { jump: !moved })
739 }
740 function syncTalkRows () {
741 const slide = ydoc && stage && stage.slideId ? slideJSON(stage.slideId) : null
742 const talk = (slide && slide.talk) || ''
743 for (const row of root.querySelectorAll('[slides-menu="slide"] [aria-pressed][data-command^="slide-talk-"]')) {
744 const on = String(row.dataset.command === 'slide-talk-' + talk)
745 if (row.getAttribute('aria-pressed') !== on) row.setAttribute('aria-pressed', on)
746 }
747 }
748 let phoneFrame = null
749 async function applyView (v) {
750 currentView = v
751 stagePane.dataset.view = root.dataset.view = v
752 phoneEl.hidden = v !== 'both'
753 if (phoneFrame) phoneFrame.update()
754 if (!stage) return
755 await stage.setViewport(v === 'phone' ? 'phone' : 'desktop')
756 if (v === 'both') await phoneStage.load(stage.slideId)
757 if (inspector) inspector.fill()
758 if (canvas) canvas.place()
759 }
760
761 // attemptResync builds the whole editor from the server's log — the
762 // first mount and every later resync alike (Docs' shape; see its
763 // resync-controller.mjs header for why a rebuild is the only way
764 // back once a batch has been refused).
765 // What this tab writes while it is diverged — a change that waited for
766 // its font and ran after a save was refused, or anything typed before
767 // the rebuild — cannot go through the old document's save queue (the
768 // server refused a batch it depends on the order of), and must not be
769 // lost either: a resync used to rebuild from the server's frames and
770 // throw it away (Astra, #27). So it is kept here, as the Y updates it
771 // produced, and applied once to the rebuilt document and saved through
772 // its queue. These are the change's own bytes, not keys replayed.
773 // The keeper (carry.mjs) holds them as entries — { updates, replay? }:
774 // the updates one change made, and the transactions that made it (held,
775 // while a local change runs; mirrored, for an undo or a redo) — and
776 // gives the document its client ids, so one change held back cannot
777 // hold back the ones after it.
778 const unsaved = createKeeper()
779 let held = null
780 // mirrored is the replay of the undo or redo in this Yjs transaction:
781 // derived from ySync's mirror of it, which runs in Yjs's observer phase,
782 // before the update reaches keep. 'many' when more than one view
783 // mirrored it (an undo across blocks): that one goes as its updates.
784 let mirrored = null
785
786 // aroundDispatch runs every transaction a slide's text view makes
787 // (stage.mjs's bindView). While a resync is pending, a local change is
788 // kept as the transactions that made it — the one dispatched and every
789 // one the plugins appended — beside its Yjs updates, so the resync can
790 // replay it when its updates cannot be carried: written on the refused
791 // text, or on a change of this tab's that could not be (carry.mjs).
792 // Transactions ySync makes to mirror Yjs, and ones that change nothing,
793 // are left alone. Where the change was made is the view's Y text,
794 // found again on the rebuilt document by its own id.
795 //
796 // An undo or a redo is the undo manager's Yjs change, which reaches the
797 // view as ySync's mirror of it: its steps replace the whole document, so
798 // the change it made is derived from the mirror's before and after as
799 // one step (carry.mjs's derivedStep) and kept with its update. Without
800 // it an undo that put text back — a Backspace undone — was lost when
801 // that text belonged to a replayed change (Claude Fable, #29).
802 function aroundDispatch (pmView, tr, transactions, apply) {
803 if (held || !resyncController.diverged || !transactions.some(t => t.docChanged)) return apply()
804 const ysync = transactions.map(t => t.getMeta(ySyncPluginKey)).filter(Boolean)
805 if (ysync.length) {
806 if (ysync.some(m => m.isUndoRedoOperation)) {
807 const step = derivedStep(tr.before, transactions[transactions.length - 1].doc)
808 if (step) mirrored = mirrored ? 'many' : { tr: { before: tr.before, steps: [step] }, schema, locate: locator(pmView) }
809 }
810 return apply()
811 }
812 held = { tr: { before: tr.before, steps: transactions.flatMap(t => t.steps) }, schema, locate: locator(pmView) }
813 try {
814 apply()
815 } finally {
816 held = null
817 }
818 }
819
820 // locator finds a view's Y text again on the rebuilt document by its id.
821 function locator (pmView) {
822 const type = ySyncPluginKey.getState(pmView.state).type
823 const at = Y.createRelativePositionFromTypeIndex(type, 0, -1)
824 return d => {
825 const found = Y.createAbsolutePositionFromRelativePosition(at, d)
826 return found && found.type instanceof Y.XmlFragment ? found.type : null
827 }
828 }
829
830 async function attemptResync () {
831 // A change of this person's that is waiting for its font runs first,
832 // on the document it was made in, before the server's state is
833 // fetched; what it writes is kept in unsaved (doc.on('update') below)
834 // and carried over.
835 while (fontGate.waiting) await free()
836 const { frames, seq } = await fetchFrames(updatesURL(base, { since: 0 }))
837 noteSeq(seq)
838 const doc = new Y.Doc()
839 for (const f of frames) Y.applyUpdate(doc, f, REMOTE)
840 const slides = doc.getArray('slides')
841 // The rebuilt deck may hold families nobody here has loaded (a
842 // collaborator's change this tab never received): they are made
843 // ready before anything is bound or fetched in them, committed past
844 // the timeout rather than held back.
845 if (fonts.web) await fonts.prepare(fonts.familiesOfView(view(doc)))
846
847 let lifecycleLive = null
848 const saveQueue = makeSaveQueue(() => lifecycleLive)
849 doc.on('update', (update, origin) => {
850 if (origin === REMOTE) return
851 if (resyncController.diverged) {
852 // Kept for the rebuilt document, not dropped (unsaved, above).
853 // A carried-over change applied to the rebuilt one is saved by
854 // the replay itself.
855 if (doc === ydoc && origin !== CARRIED) {
856 const replay = held || (mirrored && mirrored !== 'many' ? mirrored : undefined)
857 mirrored = null
858 unsaved.keep(doc, update, replay)
859 }
860 return
861 }
862 setStatus('saving')
863 saveQueue.enqueue(update)
864 })
865 // While diverged, each of this person's changes is made under the id
866 // the keeper gives it (carry.mjs's createKeeper): a ProseMirror change
867 // shares one per 500 ms window, anything else (an undo, a redo, an
868 // inspector change) takes one of its own.
869 doc.on('beforeTransaction', tr => {
870 if (doc !== ydoc || !resyncController.diverged) return
871 if (tr.origin === REMOTE || tr.origin === CARRIED) return
872 mirrored = null
873 unsaved.before(doc, tr.origin === ySyncPluginKey ? 'pm' : 'other')
874 })
875
876 // The same for a resync: it replaces every view, so it waits for a
877 // change of this person's that is waiting for its font, with no
878 // await between the check and the replacement.
879 while (fontGate.waiting) await free()
880 // The slide whose HTML is on the stage right now: the server's on
881 // the first mount, the previous stage's on a resync. The new stage
882 // binds to that DOM, so it has to be told which slide it is.
883 const shown = stage ? stage.slideId : root.dataset.slide
884 const selected = selection ? selection.current : parseHash(location.hash).block
885 // What this tab wrote while diverged goes into the rebuilt document
886 // now, before any view of it is mounted: the new stage binds with
887 // those words already in it, so they are never off the slide for a
888 // frame (Claude Fable, #27: the server's HTML was installed, and
889 // painted in the both view, before they were put back). The new undo
890 // manager is there first, so the carried change is one undo step.
891 const nextUndo = new Y.UndoManager(undoScope(doc), {
892 trackedOrigins: new Set([ySyncPluginKey, LOCAL, CARRIED]),
893 captureTimeout: UNDO_CAPTURE_MS
894 })
895 // The carried changes undo in the steps they were made in: a new step
896 // wherever two were made further apart than the capture window.
897 const undoSteps = (entry, previous) => {
898 if (!previous || entry.at - previous.at >= UNDO_CAPTURE_MS) nextUndo.stopCapturing()
899 }
900 const now = carry(doc, unsaved.take(), CARRIED, undoSteps)
901 // Everything mounted on the page's own long-lived elements — the
902 // strip's <ol>, the stage, the inspector's forms — is let go of
903 // before its replacement is mounted on the same element. Without
904 // this a resync leaves the previous mount's listeners behind, and
905 // a click reaches one handler per resync this session has had,
906 // each holding a Y.Doc nobody is editing any more.
907 if (stage) stage.destroy()
908 if (phoneStage) phoneStage.destroy()
909 if (canvas) canvas.destroy()
910 if (stageFocus) stageFocus.destroy()
911 if (strip) strip.destroy()
912 if (selection) selection.destroy()
913 if (inspector) inspector.destroy()
914 if (currentLive) currentLive.stop()
915 if (undoManager) undoManager.destroy()
916
917 ydoc = doc
918 undoManager = nextUndo
919 currentQueue = saveQueue
920 strip = mountStrip({
921 root: stripEl, ydoc: doc, thumbURL, slideLabel: text.slide,
922 template: root.querySelector('[slides-strip-item-template]'),
923 onCommand: (name, id) => commands.strip(name, id),
924 describe: () => { const v = view(doc); return new Map(v.slides.map(s => [s.id, { talk: s.talk || '', presses: presses(s, v.scenes).length }])) },
925 texts: talkText
926 })
927 strip.sync()
928 // Mounted as the desktop rendering the server painted; applyView
929 // below re-fetches if the stored view is another one.
930 // A slide the server rendered goes on the stage only once no change
931 // of this person's is waiting for its font, and once its own
932 // families are ready. Installing replaces every view on the stage,
933 // and a waiting change belongs to one of them: a refresh that landed
934 // mid-wait threw away a paste whose font then loaded (Astra, #27).
935 // So the install waits for the change, never the other way round,
936 // and nothing is deferred and replayed against a new view.
937 const beforeInstall = async html => {
938 for (;;) {
939 await free()
940 await fonts.prepareSection(html)
941 if (!fontGate.waiting) return
942 }
943 }
944 // The box focus is on, held across the install (onLoaded gives it back).
945 const beforeStageInstall = async html => {
946 await beforeInstall(html)
947 heldBox = stageFocus ? stageFocus.held() : ''
948 }
949 stage = mountStage({ root: stagePane, ydoc: doc, slideId: shown, fetchSlide, keys, onLoaded, onError: onLoadError, beforeInstall: beforeStageInstall, plugins: () => [fontGatePlugin(), formatBar.plugin()], notesPlugins: () => [formatBar.plugin('notes')], aroundDispatch })
950 phoneStage = mountStage({ el: phoneScreenEl, ydoc: doc, slideId: '', fetchSlide, keys, vp: 'phone', readOnly: true, beforeInstall })
951 selection = mountSelection({
952 stageEl,
953 getSlideId: () => stage.slideId,
954 // A refresh that only re-marked the same box is not a choice
955 // this person made: the card stays as it is (notes included).
956 onChange: (id, how) => { if (!how?.kept) inspect.selection(id ? [id] : []); formatBar.sync(); inspector.fill(); outline.fill(); canvas.place(); presenceView.place(); presence.changed(); syncScenes() }
957 })
958 inspector = mountInspector({
959 root, ydoc: doc, stageEl,
960 getSlideId: () => stage.slideId,
961 getSelected: () => selection.current,
962 getView: () => currentView,
963 commit,
964 onCommand: name => commands.run(name),
965 focusBox: id => stageFocus.focus(id),
966 labels: { upload: uploadText },
967 upload: (file, opts) => uploader.upload(file, opts),
968 // A scene's code (scene-code.mjs): saved as a picture is uploaded,
969 // previewed in the block's own frame.
970 scene: {
971 base: `/d/${sqid}`,
972 save: ({ text }) => saveSceneCode({ text, sign: body => assetJSON('/uploads', body), put: putBytes, register: body => assetJSON('/assets', body), hash: sha256Hex }),
973 preview: (id, submit) => sceneLayer.preview(id, submit)
974 }
975 })
976 canvas = mountCanvas({
977 stageEl,
978 getSelected: () => selection.current,
979 label: root.dataset.textCanvasSelected,
980 onPlace: () => { boxMenu.place(); stepMarks.place(); playThrough.place(); sceneLayer.place() },
981 onCommit: (id, box) => {
982 const block = blockJSON(stage.slideId, id)
983 if (block) commit([routeEdit({ view: currentView, slide: stage.slideId, block, field: 'box', value: box })])
984 }
985 })
986 stageFocus = mountStageFocus({
987 stageEl,
988 select: id => selection.select(id),
989 canvas,
990 isText: type => BOUND_TYPES.includes(type) || type === 'table',
991 labels: { types }
992 })
993 watchDoc(doc, slides, doc.getMap('meta'))
994 const wanted = wantedSlide()
995 if (wanted !== stage.slideId) await showSlide(wanted)
996 else onLoaded(wanted)
997 if (selected) selection.select(selected)
998 await applyView(currentView)
999
1000 lifecycleLive = createLiveUpdates({
1001 initialSeq: Number.isFinite(seq) ? seq : 0,
1002 openStream: (onEvent, onStreamError) => {
1003 const es = new EventSource(streamURL, { withCredentials: true })
1004 es.addEventListener('update', ev => onEvent(Number(ev.data)))
1005 es.addEventListener('error', ev => onStreamError(ev))
1006 // The same stream carries `event: presence` (live.go), the
1007 // whole set every time. live-updates.mjs is Docs' module,
1008 // copied verbatim, and knows nothing of it — this is the thin
1009 // wrapper the plan calls for, added onto the one EventSource
1010 // rather than a second connection.
1011 es.addEventListener('presence', ev => {
1012 let set = []
1013 try { set = JSON.parse(ev.data) } catch { /* a bad frame draws nothing, not an error */ }
1014 const diff = presence.applySet(set)
1015 presenceView.render(diff.people)
1016 presenceView.announce(diff)
1017 })
1018 return { close: () => es.close() }
1019 },
1020 fetchSince: async since => {
1021 const r = await fetchFrames(updatesURL(base, { since }))
1022 noteSeq(r.seq)
1023 return { bytes: r.frames, seq: r.seq }
1024 },
1025 // A collaborator's change waits for every family it would put on
1026 // a slide (font-session.mjs's prepare): one already on screen is
1027 // in; one that is not gets the timeout and is then committed to
1028 // its fallback, so the change is never held back for long and
1029 // never dropped. It also waits for a local wait to end, so the
1030 // deck does not move under the change being made. Batches stay in
1031 // order: live-updates.mjs awaits this before it fetches the next.
1032 onUpdates: async frames => {
1033 await free()
1034 if (resyncController.diverged || doc !== ydoc) return
1035 if (coldFamilies()) {
1036 let keys = []
1037 try {
1038 keys = familiesAfter(d => { for (const f of frames) Y.applyUpdate(d, f) })
1039 } catch {
1040 keys = []
1041 }
1042 await fonts.prepare(keys)
1043 while (fontGate.waiting) await free()
1044 if (resyncController.diverged || doc !== ydoc) return
1045 }
1046 for (const f of frames) Y.applyUpdate(doc, f, REMOTE)
1047 },
1048 onError: err => {
1049 // A dead stream is lost freshness, not a lost save: POST is a
1050 // separate path. EventSource also reports its ordinary close
1051 // during a page reload as an Event; that is expected teardown,
1052 // not a console error. A real fetch/decode Error is still
1053 // useful diagnostic evidence.
1054 if (err instanceof Error) console.error('live updates:', err)
1055 }
1056 })
1057 currentLive = lifecycleLive
1058 currentLive.start()
1059 if (document.hidden) currentLive.noteHidden()
1060 // Presence outlives a resync (it is mounted once, above), but a
1061 // reconnect is still the moment to say "I am here" again — the
1062 // same reasoning currentLive's own start() follows.
1063 presence.start()
1064 if (document.hidden) presence.noteHidden()
1065
1066 // Saved through the new queue: what was carried before the views
1067 // were mounted, and anything written on the rebuilt document since,
1068 // while this resync was still finishing (applying it again is a
1069 // no-op in Yjs). Only what took is posted, a replayed change as the
1070 // update its replay made; a change that could be neither carried nor
1071 // replayed is left out, and the save line already says some changes
1072 // were not saved, and stays saying it.
1073 const later = carry(doc, unsaved.take(), CARRIED, undoSteps)
1074 const post = now.post.concat(later.post)
1075 for (const u of post) saveQueue.enqueue(u)
1076 if (post.length) setStatus('saving')
1077 if (now.lost + later.lost) console.warn('resync: a change made on top of a refused one could not be carried over')
1078 }
1079
1080 const resyncController = createResyncController({
1081 attemptResync,
1082 // From the moment a batch is refused, this tab writes under a new
1083 // client id. Yjs applies one client's updates only in clock order,
1084 // so anything written after the refusal under the old id could
1085 // never be carried to the rebuilt document — it would wait forever
1086 // for the refused clocks the server never took (Astra, #27). Under a
1087 // fresh id it depends only on what it actually touches. Yjs gives a
1088 // document a fresh id the same way when it meets a collision.
1089 onDiverged: () => {
1090 if (ydoc) ydoc.clientID = freshClientID(ydoc)
1091 setStatus('retrying')
1092 },
1093 // 'saved' as the queue's word; the line still says failed after a
1094 // drop, because statusState ranks it first.
1095 onRecovered: () => setStatus('saved')
1096 })
1097
1098 // Reading localStorage AT ALL throws where site data is blocked, so
1099 // the access is guarded here as well as inside switcher.mjs — the
1100 // module's try/catch cannot help with an argument that threw before
1101 // the call was made.
1102 let storage = null
1103 try { storage = globalThis.localStorage } catch { /* the choice is for this session then */ }
1104 // The phone views draw a phone scaled to the stages (phone-frame.mjs);
1105 // a new scale moves whatever is placed over the stage in screen pixels.
1106 phoneFrame = mountPhoneFrame({
1107 stagesEl: stagePane.querySelector('[slides-stages]'),
1108 onChange: () => { if (canvas) canvas.place(); presenceView.place() }
1109 })
1110 mountSwitcher({ root: stagePane.querySelector('[slides-switcher]'), storage, onChange: v => { applyView(v) }, initial: shownBeforeMount ? 'desktop' : undefined })
1111 // A page shown again from the back/forward cache may have left with a
1112 // save on the wire, and WebKit never answers a keepalive save that
1113 // completed while the page was away (save-queue.mjs's own comment): the
1114 // queue sends it again rather than waiting on it forever. Registered
1115 // before the first mount so no save can precede it.
1116 addEventListener('pageshow', e => {
1117 if (e.persisted && currentQueue) currentQueue.resume()
1118 })
1119 await attemptResync()
1120 setStatus('saved')
1121
1122 // The font gate (fonts-gate.mjs) shows the slide once this has
1123 // mounted in the final faces: wait for the faces, have everything
1124 // that measured the slide measure again in them, and say so.
1125 await fonts.fontsReady
1126 if (selection) selection.reapply()
1127 if (canvas) canvas.place()
1128 presenceView.place()
1129 await nextFrame()
1130 fonts.settled()
1131
1132 // --- structural commands: the menu's, the inspector's, the strip's ---
1133
1134 // A follow-along code's audience link (qrlink.go): a share link made
1135 // for this deck, answered as its follow address, which the box then
1136 // holds. Only for somebody who may share the deck (data-qr-link is
1137 // there for them alone); null when the request does not succeed.
1138 const qrLinkAction = root.dataset.qrLink
1139 const qrLink = qrLinkAction
1140 ? async () => {
1141 const res = await fetch(qrLinkAction, { method: 'POST', credentials: 'same-origin' })
1142 if (!res.ok) return null
1143 const body = await res.json()
1144 return typeof body.url === 'string' ? body.url : null
1145 }
1146 : null
1147 const commands = createCommands({
1148 ydoc: () => ydoc,
1149 commit,
1150 flush: () => currentQueue.flush(),
1151 slideId: () => stage.slideId,
1152 selected: () => selection.current,
1153 slideJSON,
1154 blockJSON,
1155 undo: () => undo(),
1156 redo: () => redo(),
1157 present: () => presentForm && presentForm.requestSubmit(),
1158 select: id => selection.select(id),
1159 clearSelection: () => selection.clear(),
1160 showSlideOptions,
1161 // Insert → Clip opens the new clip's picker.
1162 pickClip: () => clipCard.pick(),
1163 // The box's menu into the card (Format; Position and size).
1164 showFormat: () => head.showInspector(true, { focus: true }),
1165 openPlace: () => {
1166 const first = inspector.openPlace()
1167 head.showInspector(true)
1168 if (first) first.focus()
1169 },
1170 confirmEl: inspectorEl.querySelector('[slides-confirm]'),
1171 qrLink
1172 })
1173 head = mountHead({ root, commands, notes: notesCard, outline, commitTitle: commands.setTitle })
1174
1175 // --- the card back on the slide's options (spec §4.1) ---
1176 // Nothing selected: a click on the desk's ground (the stage pane
1177 // outside any box or control, the phone screen's page included), a
1178 // slide picked in the strip, Escape in the notes, or Escape on a box
1179 // (selection.mjs; Escape in a box's options goes back to the box,
1180 // inspector.mjs).
1181 // A press that began
1182 // on a box or a control and ended on the ground (a text selection
1183 // dragged out of its block) is not a click on the ground.
1184 function showSlideOptions () {
1185 if (selection) selection.clear()
1186 inspect.reset()
1187 }
1188 const NOT_GROUND = '[slides-block], [slides-canvas-overlay], [slides-presence-marks], [slides-stage-bar], [slides-notes-pane], [slides-notes-open], a, button, input, select, textarea, label, summary, [contenteditable="true"]'
1189 const onGround = t => t instanceof Element && !t.closest(NOT_GROUND)
1190 let pressedGround = false
1191 stagePane.addEventListener('pointerdown', e => { pressedGround = onGround(e.target) })
1192 stagePane.addEventListener('click', e => {
1193 if (pressedGround && onGround(e.target)) showSlideOptions()
1194 })
1195 stripEl.addEventListener('click', e => {
1196 if (e.target.closest('[slides-strip-link]')) showSlideOptions()
1197 })
1198 // Escape while the card is on the notes: from the notes themselves,
1199 // or from nowhere, after a refresh has rebound the notes and taken
1200 // the caret with it. Heard first (capture), because the notes' own
1201 // editor marks every Escape handled and does nothing with it (as a
1202 // box's text does, selection.mjs), and selection.mjs's own Escape
1203 // marks it too. Not from what Escape closes or undoes itself: a
1204 // dialog, a menu, the assist panel, a field.
1205 document.addEventListener('keydown', e => {
1206 if (e.key !== 'Escape' || e.isComposing || inspect.current() !== 'notes') return
1207 const t = e.target instanceof Element ? e.target : null
1208 if (t && t.closest('dialog, [rst-dropdown], [popover], input, textarea, select')) return
1209 showSlideOptions()
1210 if (t instanceof HTMLElement && t.closest('[slides-notes]')) t.blur()
1211 }, true)
1212 mountAssist({
1213 root,
1214 assist: createAssist({ url: `/d/${sqid}/assist`, commit: commitAnswer, undoStep, flush: () => currentQueue.flush() }),
1215 getSlideId: () => (stage && stage.slideId) || '',
1216 go: id => { location.hash = '#' + id }
1217 })
1218 mountReorder({ root: stripEl, getIDs: () => slideIDs(ydoc), onMove: op => commit([op]), onNudge: commands.moveSlide })
1219
1220 root.addEventListener('click', e => {
1221 const btn = e.target.closest('[data-command]')
1222 // The card's buttons and the deck form's (its accent reset, in the
1223 // Deck settings dialog) are inspector.mjs's to run, once; the box
1224 // menu's rows, box-menu.mjs's.
1225 if (!btn || btn.closest('[slides-inspector], [slides-inspector-form], [slides-box-menu]') || !commands.has(btn.dataset.command)) return
1226 const menu = btn.closest('details')
1227 if (menu) menu.open = false
1228 commands.run(btn.dataset.command)
1229 })
1230
1231 // A native modal makes the page inert visually, but its key and
1232 // clipboard events still bubble to document. Stop them at window's
1233 // capture phase while a dialog is open so editor shortcuts cannot
1234 // write behind the link prompt. Do not prevent the default: typing,
1235 // Tab, Enter and Escape remain the dialog's native behaviour.
1236 // The one exception: undo and redo keys while Deck settings is the
1237 // open dialog, whose fields change the document as they are chosen,
1238 // so Cmd-Z there takes the change back. (Not in a text field, where
1239 // Cmd-Z is the field's own.)
1240 const isHistoryKey = e => e.type === 'keydown' && (e.ctrlKey || e.metaKey) && !e.altKey &&
1241 (e.key.toLowerCase() === 'z' || (e.key.toLowerCase() === 'y' && !e.shiftKey))
1242 const modalGuard = e => {
1243 const open = document.querySelector('dialog[open]')
1244 if (!open) return
1245 if (open.hasAttribute('slides-deck-dialog') && isHistoryKey(e) &&
1246 !(e.target.matches && e.target.matches('textarea, input:not([type="color"])'))) return
1247 e.stopPropagation()
1248 }
1249 for (const type of ['keydown', 'keyup', 'beforeinput', 'input', 'copy', 'cut', 'paste']) {
1250 addEventListener(type, modalGuard, { capture: true })
1251 }
1252
1253 // The document-level keys. Inside a text block ProseMirror has
1254 // already handled (and defaultPrevented) undo/redo; the slide keys
1255 // are not bound there, so they arrive here from anywhere.
1256 document.addEventListener('keydown', e => {
1257 if (e.defaultPrevented) return
1258 const mod = e.ctrlKey || e.metaKey
1259 if (!mod) return
1260 const key = e.key.toLowerCase()
1261 let cmd = null
1262 if (key === 'enter' && !e.shiftKey) cmd = 'new-slide'
1263 else if (key === 'd' && !e.shiftKey) cmd = 'duplicate-slide'
1264 else if (key === 'f' && e.shiftKey) cmd = 'present'
1265 else if (key === 'z' && !e.target.closest('.ProseMirror')) cmd = e.shiftKey ? 'redo' : 'undo'
1266 else if (key === 'y' && !e.target.closest('.ProseMirror')) cmd = 'redo'
1267 if (!cmd) return
1268 e.preventDefault()
1269 commands.run(cmd)
1270 })
1271
1272 // A hash naming another slide loads it; one naming a block on this
1273 // slide selects it (the strip's links name a slide only).
1274 addEventListener('hashchange', async () => {
1275 const wanted = wantedSlide()
1276 const { block } = parseHash(location.hash)
1277 if (wanted !== stage.slideId) await showSlide(wanted)
1278 if (block) selection.select(block)
1279 else if (location.hash === formatHash(stage.slideId)) selection.clear()
1280 })
1281
1282 // Activity keeps the stream open; a hidden tab lets it close sooner
1283 // (live-updates.mjs has the measurements).
1284 addEventListener('visibilitychange', () => {
1285 if (document.hidden) {
1286 if (currentLive) currentLive.noteHidden()
1287 presence.noteHidden()
1288 } else {
1289 if (currentLive) currentLive.noteActivity()
1290 presence.noteVisible()
1291 }
1292 })
1293 for (const name of ['pointermove', 'scroll', 'keydown', 'focus']) {
1294 addEventListener(name, () => currentLive && currentLive.noteActivity(), { passive: true, capture: true })
1295 }
1296
1297 // A close with unsent bytes beacons them (Docs' rule, and its
1298 // keepalive fallback for a beacon the browser refuses).
1299 addEventListener('beforeunload', () => {
1300 // What the queue owes, and what was written while diverged and is
1301 // waiting for the rebuild (Claude Fable, #27: closing the tab then
1302 // sent nothing for it). Under its fresh client id the server
1303 // integrates whatever of it does not depend on the refused batch;
1304 // a beacon racing a post of the same bytes is a no-op the second time.
1305 //
1306 // A save on the wire that went keepalive is left out: it outlives the
1307 // page and lands anyway, and keepalive requests and beacons share one
1308 // 64KiB quota, so repeating it refused the whole beacon, and with it
1309 // every edit queued behind it (Claude Fable on Docs #94). If that is
1310 // still refused, the queue alone, without a plain save on the wire.
1311 const extra = []
1312 for (const e of unsaved.entries) extra.push(...e.updates)
1313 const payload = owed => {
1314 const parts = owed ? [owed, ...extra] : extra
1315 if (!parts.length) return null
1316 return parts.length === 1 ? parts[0] : Y.mergeUpdates(parts)
1317 }
1318 const q = currentQueue
1319 const first = payload(q && q.pendingBytes({ wire: 'plain' }))
1320 if (!first) return
1321 const tries = [first]
1322 if (q && q.onWire === 'plain') {
1323 const second = payload(q.pendingBytes({ wire: 'none' }))
1324 if (second) tries.push(second)
1325 }
1326 for (const bytes of tries) {
1327 if (navigator.sendBeacon(base, new Blob([bytes], { type: 'application/octet-stream' }))) return
1328 }
1329 fetch(base, {
1330 method: 'POST',
1331 credentials: 'same-origin',
1332 keepalive: true,
1333 headers: { 'Content-Type': 'application/octet-stream' },
1334 body: tries[tries.length - 1]
1335 }).catch(() => {})
1336 })
1337}
1338
1339const nextFrame = () => new Promise(resolve => requestAnimationFrame(() => resolve()))
1340
1341const mount = document.querySelector('[slides-editor]')
1342if (mount) {
1343 mountEditor(mount).catch(err => {
1344 // The server-rendered page stays readable; only editing is lost.
1345 mount.setAttribute('data-editor-failed', '1')
1346 console.error(err)
1347 // And the font gate must not wait for a mount that is not coming.
1348 fontsFor().settled()
1349 })
1350}
1351