oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/editor-entry.js — the vendored editor bundle's entire
2// source. fixtures/build-bundles.mjs bundles this one file (and
3// everything it imports) into internal/docs/static/editor.<hash>.js;
4// this is the whole program that runs in the browser, not a library
5// surface something else consumes — the app performs no build step
6// (spec §6.5), so what's committed here is what ships.
7//
8// yjs stays pinned at the exact version fixtures/package.json pins
9// for the wire fixtures (13.6.27, see that file's own comment) —
10// this bundle and core/'s Rust CRDT must agree on the same wire
11// format, and a bundle built against a different yjs would make that
12// agreement untested.
13import * as Y from 'yjs'
14import { carry, createKeeper, freshClientID, derivedStep } from './carry.mjs'
15import * as decoding from 'lib0/decoding'
16import { EditorState, Selection, TextSelection, Plugin, PluginKey } from 'prosemirror-state'
17import { EditorView, Decoration, DecorationSet } from 'prosemirror-view'
18import { sinkListItem, liftListItem, splitListItem } from 'prosemirror-schema-list'
19import { keymap } from 'prosemirror-keymap'
20import { baseKeymap, toggleMark, chainCommands } from 'prosemirror-commands'
21import { changeIndent } from './indent.mjs'
22import { autoformatRules } from './autoformat.mjs'
23import { pagesPlugin, PAGED, INFINITE, writeMode } from './pages.mjs'
24import { mountWordCount } from './wordcount.mjs'
25import { mountShortcuts } from './shortcuts.mjs'
26import { undoInputRule } from 'prosemirror-inputrules'
27import { ySyncPlugin, ySyncPluginKey, yUndoPlugin, undo, redo, defaultDeleteFilter, defaultProtectedNodes, absolutePositionToRelativePosition, relativePositionToAbsolutePosition } from 'y-prosemirror'
28import { createSaveQueue, createPoster, answerTimeoutMs, reachable, KEEPALIVE_BYTES } from './save-queue.mjs'
29import { createResyncController } from './resync-controller.mjs'
30import { blankLinesFromBreaks } from './paste.mjs'
31import { createToolbar } from './toolbar.mjs'
32import { mountMenu } from './menu.mjs'
33import { createLiveUpdates, updatesURL } from './live-updates.mjs'
34import { DEFAULT_FONT } from './fonts.mjs'
35import { createSystemSession, setImplicitFamilies, NEW_FAMILY_TIMEOUT_MS } from './font-session.mjs'
36import { fontStatus } from './font-status.mjs'
37
38// keptSelection draws the selection while the editor is not focused, which
39// a blurred contenteditable does not: the phone's Format sheet takes the
40// caret out of the document (so the keyboard goes) and its controls act on
41// the selection the person can still see (design/phone-web, P2). Its state
42// is one boolean, set by a transaction's meta; an empty selection is drawn
43// as a caret.
44const keptSelection = new PluginKey('docs-kept-selection')
45const keptSelectionPlugin = new Plugin({
46 key: keptSelection,
47 state: {
48 init: () => false,
49 apply: (tr, on) => {
50 const meta = tr.getMeta(keptSelection)
51 return meta === undefined ? on : meta
52 },
53 },
54 props: {
55 decorations(state) {
56 if (!keptSelection.getState(state)) return null
57 const { from, to, empty } = state.selection
58 if (empty) {
59 return DecorationSet.create(state.doc, [Decoration.widget(from, () => {
60 const caret = document.createElement('span')
61 caret.setAttribute('data-docs-kept-caret', '')
62 return caret
63 }, { side: 1 })])
64 }
65 return DecorationSet.create(state.doc, [Decoration.inline(from, to, { 'data-docs-kept': '' })])
66 },
67 },
68})
69
70// keptPositions and keepAgain carry a kept selection across a resync,
71// which replaces the EditorView and its Y.Doc (editor-entry's remount).
72// The relative positions follow the text through what the rebuilt
73// document kept. Where they resolve to nothing (the text was made by
74// the refused change itself: a style chip makes the paragraph anew),
75// the selection is looked for by its words: at its old positions if the
76// same words and the same block are there, which a change of block type
77// leaves them; else in the block with the same words nearest where it
78// was, since a change the page never saw can arrive with the rebuild
79// (live updates are not taken while diverged) and move everything;
80// else it is gone, and keepAgain says so (Fable's follow-up A on #181).
81function keptPositions(view) {
82 const { anchor, head, from, to } = view.state.selection
83 const doc = view.state.doc
84 const $anchor = doc.resolve(anchor)
85 const $head = doc.resolve(head)
86 const kept = {
87 at: { anchor, head },
88 rel: null,
89 text: doc.textBetween(from, to, '\n'),
90 anchorBlock: $anchor.parent.textContent,
91 anchorOffset: anchor - $anchor.start(),
92 headBlock: $head.parent.textContent,
93 headOffset: head - $head.start(),
94 oneBlock: $anchor.sameParent($head),
95 }
96 const ys = ySyncPluginKey.getState(view.state)
97 if (ys && ys.binding) {
98 kept.rel = {
99 anchor: absolutePositionToRelativePosition(anchor, ys.type, ys.binding.mapping),
100 head: absolutePositionToRelativePosition(head, ys.type, ys.binding.mapping),
101 }
102 }
103 return kept
104}
105
106// readsAsKept says whether anchor and head in doc hold the kept words,
107// with the anchor in a block that reads as the kept one did.
108function readsAsKept(doc, kept, anchor, head) {
109 if (anchor < 0 || head < 0 || anchor > doc.content.size || head > doc.content.size) return false
110 const $anchor = doc.resolve(anchor)
111 if (!$anchor.parent.isTextblock || $anchor.parent.textContent !== kept.anchorBlock) return false
112 return doc.textBetween(Math.min(anchor, head), Math.max(anchor, head), '\n') === kept.text
113}
114
115// findKept is where the kept words are in doc, or null.
116function findKept(doc, kept, ys) {
117 if (kept.rel && ys && ys.binding) {
118 const anchor = relativePositionToAbsolutePosition(ys.doc, ys.type, kept.rel.anchor, ys.binding.mapping)
119 const head = relativePositionToAbsolutePosition(ys.doc, ys.type, kept.rel.head, ys.binding.mapping)
120 if (anchor !== null && head !== null) return { anchor, head }
121 }
122 if (readsAsKept(doc, kept, kept.at.anchor, kept.at.head)) return kept.at
123 let best = null
124 doc.descendants((node, pos) => {
125 if (!node.isTextblock) return true
126 if (node.textContent !== kept.anchorBlock) return false
127 const anchor = pos + 1 + kept.anchorOffset
128 let head = pos + 1 + kept.headOffset
129 if (!kept.oneBlock) {
130 // The head's block: the first after this one that reads as it did.
131 head = -1
132 doc.nodesBetween(pos + node.nodeSize, doc.content.size, (n, p) => {
133 if (head >= 0) return false
134 if (!n.isTextblock) return true
135 if (n.textContent === kept.headBlock) head = p + 1 + kept.headOffset
136 return false
137 })
138 }
139 if (readsAsKept(doc, kept, anchor, head)) {
140 const distance = Math.abs(anchor - kept.at.anchor)
141 if (!best || distance < best.distance) best = { anchor, head, distance }
142 }
143 return false
144 })
145 return best && { anchor: best.anchor, head: best.head }
146}
147
148// keepAgain draws the kept selection in view, where it is found; it
149// reports whether it was.
150function keepAgain(view, kept) {
151 if (!kept) {
152 view.dispatch(view.state.tr.setMeta(keptSelection, true))
153 return true
154 }
155 const at = findKept(view.state.doc, kept, ySyncPluginKey.getState(view.state))
156 if (!at) return false
157 const tr = view.state.tr.setMeta(keptSelection, true)
158 view.dispatch(tr.setSelection(TextSelection.between(tr.doc.resolve(at.anchor), tr.doc.resolve(at.head))))
159 return true
160}
161
162// A collaborator's update is scanned for the names of every schema node
163// and mark whose family it does not name (the code block and code mark
164// are code's), so the scan follows the schema.
165setImplicitFamilies([
166 ...Object.values(schema.nodes).filter((t) => familyOfNode(t)).map((t) => [t.name, familyOfNode(t)]),
167 ...Object.values(schema.marks).filter((t) => !t.name.startsWith('font_') && familyOfMark(t)).map((t) => [t.name, familyOfMark(t)]),
168])
169
170import { schema, familyOfMark, familyOfNode, familiesOfFragment } from './schema.mjs'
171
172
173// Shift+Enter: a line break inside the current block, rather than a
174// new block.
175//
176// hard_break came with prosemirror-schema-basic from the beginning —
177// the node was always in the schema above — but nothing bound a key to
178// it, so there was no way to type one. The rest of the vocabulary is a
179// contract shared with core/src/fragment.rs (which renders the node as
180// <br> for a reader with no JavaScript, and reports it to
181// internal/export so both exporters can see it); the node's NAME is
182// what crosses the wire, because y-prosemirror stores every non-text
183// node as a Y.XmlElement named after its type.
184//
185// Written out rather than imported: prosemirror-commands exports no
186// insert-a-break command (checked against 1.7.2's own export list —
187// splitBlock, exitCode and the rest, nothing for this), so every
188// ProseMirror setup writes these same three lines. dispatch is checked
189// because a command can be called without one, to ask whether it
190// applies rather than to run it, and scrollIntoView because the new
191// line can be below the fold on a long document.
192function insertHardBreak(state, dispatch) {
193 if (dispatch) {
194 dispatch(state.tr.replaceSelectionWith(schema.nodes.hard_break.create()).scrollIntoView())
195 }
196 return true
197}
198
199// Coalesce a burst of typing into one request.
200//
201// This constant is the floor on how fast an edit can reach anyone
202// else: nothing leaves the tab that made it until the window closes,
203// so the stream, the fetch and the render all happen after it. 250ms
204// is chosen for that — under the ~300ms at which a delay stops
205// reading as "the app responded" and starts reading as "the app is
206// thinking" — rather than for any property of the server.
207//
208// It could not be chosen that way until recently, and the history is
209// worth keeping because the old value looked like a feel decision and
210// was not. Every accepted POST is one doc_updates row, and
211// core.Handle's maxRetainedUpdates (internal/core/core.go, 4096)
212// capped a document at that many, after which it refused edits
213// permanently. The value was therefore headroom against a cliff:
214// 400ms bought ~27 minutes of continuous typing, 2000ms bought about
215// 2h16m. Snapshots removed the cliff — replay now starts from a
216// snapshot plus a bounded tail — so this is free to be a number about
217// perception again.
218//
219// What it still costs, because this is not free and the next reader
220// should not have to rediscover it: eight times the row rate, roughly
221// 14,400 doc_updates rows an hour of continuous typing against the
222// old 1,800, each holding a character or two rather than a sentence.
223// Snapshots bound what that costs to REPLAY; nothing yet bounds what
224// it costs to STORE, because §4.1's compaction horizon is still
225// deferred, so the log and the WAL Litestream replicates grow eight
226// times faster than they did. The fix that would give back the rows
227// without giving back the latency is §4.1's other mechanism —
228// coalescing same-actor updates at the storage boundary — and it
229// belongs with the WebSocket transport, which needs it anyway.
230//
231// Nothing shows a "saving" indicator during an ordinary wait; only a
232// failure does, via the save queue's own status (see save-queue.mjs
233// and views/show.html's [estilo-save-status]). So this delay stays
234// invisible exactly when saving is going fine, which is the case that
235// matters for feel.
236const DEBOUNCE_MS = 250
237
238// CARRIED is a change this tab made while diverged, applied to the
239// rebuilt document by a resync (attemptResync). It is this person's own,
240// so the undo manager tracks it like the editor's own changes.
241const CARRIED = 'carried'
242
243// The undo manager's capture window: changes made within it of each other
244// are one undo step.
245const UNDO_CAPTURE_MS = 500
246
247
248// applyServerLog replays handlers.go's updatesGet response into ydoc.
249// That response is a raw concatenation of one encoded Yjs update per
250// accepted POST, back to back with no framing between them (its own
251// doc comment: "concatenated in seq order") — one row per update,
252// exactly like Store.replay applies them server-side. A single
253// Y.applyUpdate call cannot replay that correctly: its decoder reads
254// only the client count declared in the FIRST message's own header,
255// then returns, leaving every later message's bytes on the floor —
256// confirmed empirically (a second update silently vanishes) before
257// this fix went in. Y.readUpdate, looped over one shared lib0 decoder
258// until it is exhausted, replays every message the log actually
259// holds instead of just the first one.
260function applyServerLog(ydoc, log) {
261 if (!log.length) return
262 const decoder = decoding.createDecoder(log)
263 while (decoding.hasContent(decoder)) {
264 Y.readUpdate(decoder, ydoc, 'server')
265 }
266}
267
268// fontsFor is the tab's font session: the gate's (fonts-gate.mjs runs
269// first and leaves it on globalThis.docsFonts), or, if its script never
270// arrived, the system faces' session, under which nothing is loaded or
271// waited for and the editor shows the page itself once it has paginated.
272function fontsFor() {
273 return globalThis.docsFonts || createSystemSession(document.documentElement)
274}
275
276// layoutFrozen is whether the page was shown before the editor could
277// paginate it (fonts-gate.mjs, fonts-hold.js). Then the editor adds no
278// pages for the rest of the visit: the layout a reader first saw is the
279// one they keep, unless they choose a view themselves.
280function layoutFrozen() {
281 return document.documentElement.getAttribute('data-docs-layout') === 'frozen'
282}
283
284// familiesInFragment is every family a Yjs document references, read
285// off the schema as the transaction gate reads a slice: every node type
286// and mark whose family is not its surroundings' (schema.mjs's
287// familyOfNode and familyOfMark), and the default (export.FamiliesUsed).
288function familiesInFragment(fragment) {
289 const out = new Set([DEFAULT_FONT])
290 const walk = (node) => {
291 if (node instanceof Y.XmlText) {
292 for (const op of node.toDelta()) {
293 for (const name of Object.keys(op.attributes || {})) {
294 const f = familyOfMark(name)
295 if (f) out.add(f)
296 }
297 }
298 return
299 }
300 if (node instanceof Y.XmlElement) {
301 const f = familyOfNode(node.nodeName)
302 if (f) out.add(f)
303 }
304 for (const child of node.toArray()) walk(child)
305 }
306 walk(fragment)
307 return [...out]
308}
309
310// familiesIntroduced is every family a transaction would put text in:
311// the content its steps insert (a paste, a drop, an input rule, a typed
312// character, a block turned into code), the marks they add, and the
313// stored marks it sets. Undo, redo and collaborators' changes arrive
314// through Yjs and are checked before they reach Yjs (font-session.mjs's
315// prepareRemote); everything else passes here.
316function familiesIntroduced(tr) {
317 const out = new Set()
318 const markFamily = (m) => {
319 const f = familyOfMark(m.type)
320 if (f) out.add(f)
321 }
322 for (const step of tr.steps) {
323 if (step.slice) familiesOfFragment(step.slice.content, out)
324 if (step.mark) markFamily(step.mark)
325 }
326 if (tr.storedMarksSet && tr.storedMarks) tr.storedMarks.forEach(markFamily)
327 out.delete(undefined)
328 return [...out]
329}
330
331function nextFrame() {
332 return new Promise((resolve) => requestAnimationFrame(() => resolve()))
333}
334
335export async function mountEditor(el) {
336 const sqid = el.getAttribute('data-sqid')
337 const fonts = fontsFor()
338 const base = `/d/${sqid}/updates`
339 // The live-update stream (internal/docs/stream.go). A sibling of
340 // base rather than something derived from it: they are two routes
341 // on one document, not one route and a variation of it.
342 const streamURL = `/d/${sqid}/stream`
343
344 // The corner toast, by its placement: the page has more than one save
345 // status since the phone's large title (views/show.html), and the first
346 // in the page is the subtitle, which is display:none on a wide screen. A
347 // first-match selector mounted that one and a desktop never saw "Trouble
348 // saving" again (Fable on #179, B1).
349 const statusEl = document.querySelector('[estilo-save-status~="floating"]')
350 const statusURL = new URL(el.getAttribute('data-save-status-module'), location.href)
351 if (!statusEl || statusURL.origin !== location.origin) throw new Error('Invalid save-status module')
352 const { mount } = await import(statusURL.href)
353 const setToast = mount(statusEl)
354 // The phone says the same state under its large title (the subtitle,
355 // savestatus' "subtitle" placement) and, once that has scrolled away, in
356 // the folded bar's inline line ([docs-inline-state], aria-hidden: the
357 // subtitle is the live region there). Both are quiet as "Saved" where the
358 // toast rests empty, so the line never empties and nothing below it
359 // moves; a trouble state is said in both as it is in the toast.
360 const setSubtitles = Array.from(document.querySelectorAll('[estilo-save-status~="subtitle"]')).map(mount)
361 const subtitleEl = document.querySelector('[estilo-save-status~="subtitle"]')
362 const inlineEl = document.querySelector('[docs-inline-state]')
363 const setSaveState = (state) => {
364 setToast(state)
365 const quiet = state === 'retrying' || state === 'failed' ? state : 'saved'
366 for (const set of setSubtitles) set(quiet)
367 if (inlineEl && subtitleEl) {
368 const text = subtitleEl.getAttribute('data-text-' + quiet) || ''
369 if (inlineEl.getAttribute('data-state') !== quiet) inlineEl.setAttribute('data-state', quiet)
370 if (inlineEl.textContent !== text) inlineEl.textContent = text
371 }
372 }
373
374 // sessionFailed is stickier than any one save queue's own status
375 // (save-queue.mjs's own report() is only sticky within a single
376 // instance, and a resync replaces that instance): once a batch is
377 // ever dropped in this page's lifetime, the failed indicator must
378 // stay lit even after the editor is resynced and saving normally
379 // again — a person still needs to know something did not make it.
380 let sessionFailed = false
381 // currentQueue/currentView are read by beforeunload and by
382 // attemptResync below; both are reassigned wholesale on every
383 // resync, so anything that needs "whichever one is live right now"
384 // reads through these rather than closing over a value captured at
385 // mount time.
386 let currentQueue = null
387 let currentView = null
388 // The phone's quick format bar's height while it shows (docs:quickbar,
389 // below): the bottom of ProseMirror's scroll margin.
390 let quickbarHeight = 0
391 const scrollMargins = () => ({ top: 5, left: 5, right: 5, bottom: 5 + (quickbarHeight ? quickbarHeight + 8 : 0) })
392 // currentDoc is the Y.Doc the live view edits: onDiverged gives it a
393 // fresh client id, and its updates made while diverged are kept in
394 // unsaved (attemptResync).
395 let currentDoc = null
396 // What this tab writes while it is diverged — a paste that waited for
397 // its font and ran after a save was refused, or anything typed after
398 // the refusal — cannot go through the old save queue (the server
399 // refused a batch it may depend on), and must not be lost either: a
400 // resync used to rebuild from the server's log and throw it away
401 // (Claude Fable, #87). So it is kept here, as the Y updates it
402 // produced, and carried onto the rebuilt document and saved through its
403 // queue. These are the change's own bytes, not keys replayed.
404 // The keeper (carry.mjs) holds them as entries — { updates, replay? }:
405 // the updates one change made, and the transactions that made it (held,
406 // while a local change runs; mirrored, for an undo or a redo) — and
407 // gives the document its client ids, so one change held back cannot
408 // hold back the ones after it.
409 const unsaved = createKeeper()
410 let held = null
411 // mirrored is the replay of the undo or redo in this Yjs transaction:
412 // derived from ySync's mirror of it, which runs in Yjs's observer phase,
413 // before the update reaches keep.
414 let mirrored = null
415
416 // aroundDispatch runs every transaction the editor view makes. While a
417 // resync is pending, a local change is kept as the transactions that
418 // made it — the one dispatched and every one the plugins appended —
419 // beside its Yjs updates, so the resync can replay it when its updates
420 // cannot be carried: written on the refused text, or on a change of
421 // this tab's that could not be (carry.mjs; Paul ranks a lost edit worse
422 // than a flash). Transactions ySync makes to mirror Yjs, and ones that
423 // change nothing, are left alone — except an undo's or a redo's: the
424 // undo manager's Yjs change reaches the view as ySync's mirror, whose
425 // steps replace the whole document, so the change it made is derived
426 // from its before and after as one step (carry.mjs's derivedStep) and
427 // kept with its update. Without it an undo that put text back — a
428 // Backspace undone — was lost when that text belonged to a replayed
429 // change (Claude Fable, #90).
430 function aroundDispatch(tr, transactions, apply) {
431 if (held || !resyncController.diverged || !transactions.some((t) => t.docChanged)) return apply()
432 const ysync = transactions.map((t) => t.getMeta(ySyncPluginKey)).filter(Boolean)
433 if (ysync.length) {
434 if (ysync.some((m) => m.isUndoRedoOperation)) {
435 const step = derivedStep(tr.before, transactions[transactions.length - 1].doc)
436 if (step) mirrored = { tr: { before: tr.before, steps: [step] }, schema, locate: (d) => d.getXmlFragment('prosemirror') }
437 }
438 return apply()
439 }
440 held = {
441 tr: { before: tr.before, steps: transactions.flatMap((t) => t.steps) },
442 schema,
443 locate: (d) => d.getXmlFragment('prosemirror'),
444 }
445 try {
446 apply()
447 } finally {
448 held = null
449 }
450 }
451 // currentLive is the live-update subscriber (live-updates.mjs) for
452 // whichever Y.Doc is current. It belongs to that document, not to
453 // the page: a resync builds a new Y.Doc, so the subscriber feeding
454 // the old one is stopped and replaced along with the save queue and
455 // the view, or it would apply bytes into a document that has been
456 // discarded.
457 let currentLive = null
458
459 // The toolbar (fixtures/toolbar.mjs) is built once, before the first
460 // mount, because mountView needs its plugin. It reads the live view
461 // through this closure rather than being handed one: attemptResync
462 // destroys and rebuilds the EditorView wholesale, and a toolbar
463 // holding a captured view would dispatch into a dead one after a
464 // resync — the same reason placeCaretFromPage reads currentView at
465 // event time. views/show.html renders the markup; a page without it
466 // (or a future template that drops it) gets a toolbar with no
467 // plugin and an editor that works exactly as it did before.
468 // The menu bar (fixtures/menu.mjs) is mounted first but wired second,
469 // because the two point at each other: the menu dispatches through
470 // the toolbar's command table, and the toolbar's plugin is what
471 // drives the menu's sync. Declaring it here and filling it in below
472 // is the smaller of the two awkwardnesses — the alternative is a
473 // second ProseMirror plugin watching the same editor, and two
474 // watchers of one selection is how a menu item and the toolbar button
475 // beside it end up enabled differently.
476 //
477 // The bar works before any of this runs: it is six <details>
478 // elements, and its links and forms need no editor at all. Only the
479 // command items wait on a view.
480 let menu = null
481
482 // Paged or infinite. The server has already put its answer on
483 // [docs-canvas] from the cookie (handlers.go), so the first paint is
484 // already right and this only has to agree with it — reading the
485 // cookie again here would be a second source for one fact.
486 //
487 // The canvas carries the attribute rather than the editor, because
488 // what changes between the modes is the desk the paper sits on, and
489 // the gaps are drawn inside the page's own text flow.
490 const canvasEl = document.querySelector('[docs-canvas]')
491 let viewMode = canvasEl && canvasEl.getAttribute('data-view') === PAGED ? PAGED : INFINITE
492 // The page-number template ("Page {n}"), server-rendered from the
493 // catalog into a data attribute — the bundle carries no copy of its
494 // own, the same rule the save-status indicator and the toolbar
495 // already follow.
496 const pageLabelText = canvasEl ? canvasEl.getAttribute('data-page-label') : ''
497
498 // Pages are measured only in the final faces: until the gate says the
499 // faces are on, the view is laid out without them.
500 //
501 // And only while the sheet is still held. If it is already in view
502 // when the editor could first paginate (no hold: its script never
503 // arrived, or a gate that found no hold), the layout a reader is
504 // looking at is the final one: the editor freezes it for the visit
505 // rather than drawing page boundaries over text already on screen.
506 let facesFinal = false
507 fonts.fontsReady.then(() => {
508 if (document.documentElement.getAttribute('data-docs-fonts') !== 'pending') {
509 document.documentElement.setAttribute('data-docs-layout', 'frozen')
510 }
511 facesFinal = true
512 })
513 const effectiveMode = () => (facesFinal && !layoutFrozen() ? viewMode : INFINITE)
514
515 function setViewMode(mode) {
516 viewMode = mode
517 // A view the person chose is theirs: it unfreezes.
518 document.documentElement.removeAttribute('data-docs-layout')
519 if (canvasEl) canvasEl.setAttribute('data-view', mode)
520 writeMode(mode)
521 // Nudge the plugin: the mode is not part of editor state, so
522 // nothing else would tell it to re-measure.
523 const view = currentView
524 if (view) view.dispatch(view.state.tr)
525 }
526
527 // The Tools menu's two dialogs. Both read their copy from markup
528 // views/show.html rendered from the catalog, and both are null when
529 // that markup is absent — a template without them gets a menu whose
530 // items stay disabled rather than an error.
531 const wordCount = mountWordCount(document.querySelector('[docs-wordcount]'), {
532 getView: () => currentView,
533 })
534 const shortcuts = mountShortcuts(document.querySelector('[docs-shortcuts]'), {
535 menubar: document.querySelector('[estilo-menubar]'),
536 // The bindings no menu item carries — Tab, Shift+Tab, the
537 // autoformat undo and Shift+Enter — server-rendered into a hidden
538 // block as data so their labels stay in the catalog with every
539 // other string.
540 extraRows: Array.from(
541 document.querySelectorAll('[docs-shortcuts-extra] span'),
542 ).map((el) => ({
543 group: el.closest('[docs-shortcuts-extra]').getAttribute('data-group') || '',
544 label: el.getAttribute('data-label') || '',
545 keys: el.getAttribute('data-keys') || '',
546 })),
547 })
548
549 // The font gate every local change passes (branch reviews 6 and 7).
550 //
551 // A user action (typing, paste, drop, input rule, command, font pick,
552 // code toggle, undo, redo) that would put text in a family whose faces
553 // have not all settled is cancelled before it changes anything. Then,
554 // like a short modal: the editor, the formatting bar and the menu bar
555 // go inert, and the strip over the bar says a font is loading, at once.
556 // Input meanwhile goes nowhere, which a person can see; nothing is
557 // queued or replayed, because a replayed keystroke is not the keystroke
558 // (review 7). Other controls (the title, dialogs, comments) keep their
559 // own input. Once the family has loaded the action is performed, once,
560 // as it was made. If it fails or misses its deadline the action is
561 // dropped, editing comes back and the person is told.
562 //
563 // One wait at a time. Anything else that would change the document
564 // during it is refused, and the strip says so; so the document cannot
565 // move under the action. A collaborator's update waits for the wait to
566 // end before it reaches Yjs (onUpdates, free()).
567 //
568 // A wait never begins in an IME composition. A composition types in the
569 // marks already there, whose families are on screen and settled; if one
570 // ever is not, that family is drawn in its fallback rather than the
571 // composition being interrupted.
572 let waiting = false
573 let released = []
574 const free = () => (waiting ? new Promise((resolve) => released.push(resolve)) : Promise.resolve())
575
576 const status = fontStatus(document.querySelector('[docs-fonts-status]'))
577 // The chrome that drives the document, inert during a wait: the
578 // toolbar, the menu bar, both undo/redo pairs (the bar's lead and the
579 // strip's), the phone's quick format bar (design/phone-web, P2: its
580 // buttons are bound and kept current like the pairs, outside the
581 // role="toolbar") and the bar's Format toggle (spec I2).
582 const historyPairs = Array.from(document.querySelectorAll('[docs-history], [docs-quickbar]'))
583 const chrome = [
584 document.querySelector('[docs-toolbar]'),
585 document.querySelector('[estilo-menubar]'),
586 ...historyPairs,
587 document.querySelector('[data-estilo-toggle][aria-controls="docs-inspector"]'),
588 ].filter(Boolean)
589 const sheet = document.querySelector('[docs-page]')
590 // How long a font that could not be loaded is said, unless dismissed.
591 const UNAVAILABLE_NOTE_MS = 8000
592
593 const fontGatePlugin = new Plugin({
594 filterTransaction(tr) {
595 // Yjs's own changes (a collaborator, undo, redo, the first render)
596 // reach the editor as they are; they are checked before they reach
597 // Yjs.
598 if (tr.getMeta(ySyncPluginKey)) return true
599 if (waiting) {
600 if (!tr.docChanged && !tr.storedMarksSet) return true
601 status.say('refused')
602 return false
603 }
604 const keys = familiesIntroduced(tr)
605 const cold = keys.filter((k) => !fonts.ready(k))
606 if (!cold.length) {
607 fonts.use(keys)
608 return true
609 }
610 if (currentView && currentView.composing) {
611 fonts.commitFallback(cold)
612 fonts.use(keys)
613 return true
614 }
615 const view = currentView
616 wait(cold, () => {
617 if (view !== currentView || view.state.doc !== tr.before) return false
618 // Through the view's own dispatch, which keeps a change made while
619 // a resync is pending as its transactions too (aroundDispatch).
620 view.dispatch(tr)
621 return true
622 })
623 return false
624 },
625 })
626
627 // wait makes the editor inert while keys load, then runs the action
628 // once. run reports whether it could still be performed.
629 async function wait(keys, run) {
630 waiting = true
631 setInert(true)
632 let ok = false
633 try {
634 ok = (await fonts.waitFor(keys, NEW_FAMILY_TIMEOUT_MS)) && keys.every((k) => fonts.loaded(k) || fonts.committed(k))
635 } catch {
636 ok = false
637 }
638 waiting = false
639 // Editing back, and focus with it, before the action: so the action
640 // and its selection are painted in one frame, not the text and then
641 // its highlight.
642 setInert(false)
643 try {
644 ok = ok && run() !== false
645 } catch (err) {
646 console.error('fonts:', err)
647 ok = false
648 } finally {
649 if (ok) status.clear()
650 else status.say('unavailable', UNAVAILABLE_NOTE_MS)
651 const waiters = released
652 released = []
653 for (const r of waiters) r()
654 }
655 }
656
657 // While the editor is inert, focus is on the page itself, and there a
658 // key that would have edited is the browser's: Backspace goes back in
659 // history in WebKit (branch review 8, which lost the waiting paste),
660 // Space and the arrows scroll. Those keys do nothing during the wait.
661 // A real control (the title, a dialog, a comment) keeps them, and so
662 // does Tab. And leaving the page while an action waits asks first.
663 const HELD_KEYS = new Set(['Backspace', ' ', 'Spacebar', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'PageUp', 'PageDown', 'Home', 'End'])
664 const holdKeys = (e) => {
665 if (!HELD_KEYS.has(e.key)) return
666 const t = e.target
667 if (!t || t === document.body || t === document.documentElement || (t.closest && t.closest('[inert]'))) e.preventDefault()
668 }
669 const holdUnload = (e) => {
670 e.preventDefault()
671 e.returnValue = ''
672 }
673
674 // The phone's Format sheet, open or not (the docs:format-sheet
675 // listener below keeps it): while it is, the caret stays out of the
676 // document. Declared here, before setInert reads it.
677 const formatSheet = { open: false, hadFocus: false }
678
679 // setInert is the wait's modal state. Focus goes back to the document
680 // afterwards only if it was there, nobody has moved it elsewhere, and
681 // the Format sheet is not keeping the caret out (where the toolbar's
682 // refocus() says no, so does this).
683 let focusBack = false
684 function setInert(on) {
685 const listen = on ? 'addEventListener' : 'removeEventListener'
686 window[listen]('keydown', holdKeys)
687 window[listen]('beforeunload', holdUnload)
688 const v = currentView
689 const dom = v && v.dom
690 if (on) focusBack = !!dom && (dom.contains(document.activeElement) || chrome.some((el) => el.contains(document.activeElement)))
691 for (const el of [...chrome, dom]) if (el) el.inert = on
692 if (sheet) sheet.setAttribute('aria-busy', on ? 'true' : 'false')
693 if (on) status.say('loading')
694 else if (focusBack && v && !formatSheet.open && (!document.activeElement || document.activeElement === document.body)) v.focus()
695 }
696
697 // Undo and redo arrive through Yjs, so the gate cannot refuse them. What
698 // they bring back was on screen in this visit, in families that stay
699 // settled; if one somehow has not, they wait like any other action.
700 const guarded = (cmd) => (state, dispatch, view) => {
701 if (!dispatch) return cmd(state, dispatch, view)
702 if (waiting) {
703 status.say('refused')
704 return true
705 }
706 const cold = fonts.inUse.filter((k) => !fonts.ready(k))
707 if (!cold.length) return cmd(state, dispatch, view)
708 wait(cold, () => {
709 const v = currentView
710 if (!v) return false
711 cmd(v.state, v.dispatch, v)
712 return true
713 })
714 return true
715 }
716
717 const unavailable = () => status.say('unavailable', UNAVAILABLE_NOTE_MS)
718
719 // focusFormat moves focus to the bar's Format toggle, if it is drawn
720 // and enabled, and reports whether it did.
721 const focusFormat = () => {
722 const format = document.querySelector('[data-estilo-toggle][aria-controls="docs-inspector"]')
723 if (!format || format.disabled || format.inert) return false
724 const drawn = typeof format.checkVisibility === 'function' ? format.checkVisibility() : format.getClientRects().length > 0
725 if (!drawn) return false
726 format.focus()
727 return document.activeElement === format
728 }
729
730 // The phone's Format sheet (design/phone-web, P2; brand/phone.js opens
731 // and closes it and says so with a docs:format-sheet event). Opening it
732 // takes the caret out of the document, so the on-screen keyboard goes,
733 // and keeps the selection drawn as a decoration while the sheet is up,
734 // since a blurred editor draws none; it scrolls the selection clear of
735 // the sheet. Closing it brings the keyboard back only if it was up.
736 document.addEventListener('docs:format-sheet', (e) => {
737 const view = currentView
738 const open = !!(e.detail && e.detail.open)
739 if (open === formatSheet.open) return
740 formatSheet.open = open
741 if (!view) return
742 if (open) {
743 // Blur first, then draw the kept selection: drawn into a
744 // composition still open (Gboard, a Japanese or Chinese input
745 // method), the caret widget lands inside the words being composed.
746 // The blur ends a composition; one that outlasts it is waited for.
747 formatSheet.hadFocus = view.hasFocus()
748 const composing = view.composing
749 if (formatSheet.hadFocus) view.dom.blur()
750 const keep = () => {
751 const v = currentView
752 if (v && formatSheet.open && !keptSelection.getState(v.state)) v.dispatch(v.state.tr.setMeta(keptSelection, true))
753 }
754 if (!composing && !view.composing) keep()
755 else {
756 let done = false
757 const after = () => {
758 if (done) return
759 done = true
760 view.dom.removeEventListener('compositionend', after)
761 // ProseMirror reads the ended composition on a short timer of
762 // its own; the kept caret goes in after that.
763 setTimeout(keep, 50)
764 }
765 if (view.composing) {
766 view.dom.addEventListener('compositionend', after)
767 setTimeout(after, 500)
768 } else after()
769 }
770 const height = (e.detail && e.detail.height) || 0
771 try {
772 const at = view.coordsAtPos(view.state.selection.head)
773 const room = window.innerHeight - height - 16
774 if (at.bottom > room) window.scrollBy(0, at.bottom - room)
775 } catch { /* no layout to ask */ }
776 } else if (view.hasFocus()) {
777 // Closed by a tap in the document (brand/phone.js closes it on the
778 // editor's focusin): the tap places the caret, and ProseMirror
779 // reads it from the page a moment later. Dropping the kept
780 // selection now would write the old selection back over the tap,
781 // so it waits for that read; there is no keyboard to bring back.
782 setTimeout(() => {
783 const v = currentView
784 if (v && !formatSheet.open && keptSelection.getState(v.state)) v.dispatch(v.state.tr.setMeta(keptSelection, false))
785 }, 50)
786 } else {
787 view.dispatch(view.state.tr.setMeta(keptSelection, false))
788 if (formatSheet.hadFocus) view.focus()
789 }
790 })
791 // The quick format bar over the keyboard (brand/phone.js): ProseMirror
792 // keeps the caret this far above the window's foot while it shows.
793 document.addEventListener('docs:quickbar', (e) => {
794 quickbarHeight = Math.max(0, Math.round((e.detail && e.detail.height) || 0))
795 if (currentView) currentView.setProps({ scrollMargin: scrollMargins() })
796 })
797
798 const toolbar = createToolbar({
799 root: document.querySelector('[docs-toolbar]'),
800 history: historyPairs,
801 // While the phone's Format sheet is open the keyboard stays away:
802 // a control acts and leaves the caret where it is.
803 refocus: () => !formatSheet.open,
804 schema,
805 fonts,
806 onFontUnavailable: unavailable,
807 getView: () => currentView,
808 onSync: (view) => {
809 if (menu) menu.sync(view)
810 },
811 })
812
813 menu = mountMenu(document.querySelector('[estilo-menubar]'), {
814 getView: () => currentView,
815 commands: toolbar.commands,
816 // As the toolbar's: the Format sheet keeps the caret out.
817 refocus: () => !formatSheet.open,
818 // The check column: the view mode is this file's; the paragraph
819 // style and alignment are the toolbar's, read the same way its own
820 // pressed buttons and Style select are.
821 isPressed: (name, view) => {
822 if (name === 'view_paged') return viewMode === PAGED
823 if (name === 'view_infinite') return viewMode === INFINITE
824 return Boolean(view && toolbar.isPressed && toolbar.isPressed(view.state, name))
825 },
826 // The two View-menu commands. They are not editor commands — they
827 // change how the document is drawn, not what it contains — so they
828 // are passed in here rather than living in toolbar.mjs's table
829 // alongside Bold. menu.mjs treats them the way it treats Print: not
830 // dependent on a selection, and available whenever the page is.
831 extraCommands: {
832 view_paged: () => {
833 setViewMode(PAGED)
834 return true
835 },
836 view_infinite: () => {
837 setViewMode(INFINITE)
838 return true
839 },
840 // Both are null when the template renders no dialog, and
841 // mountMenu leaves an item with no command disabled — which is
842 // the right outcome rather than a crash.
843 ...(wordCount ? { word_count: wordCount } : {}),
844 ...(shortcuts ? { shortcuts } : {}),
845 },
846 })
847
848 function updateIndicator(state) {
849 setSaveState(sessionFailed ? 'failed' : state)
850 }
851
852 // getLive is a getter for THIS lifecycle's own subscriber, never
853 // the module-level currentLive. Whole-branch review found the
854 // difference matters: attemptResync stops the old subscriber but
855 // cannot stop the old save queue (save-queue.mjs has no stop, by
856 // design), so a POST issued before a resync can resolve after it.
857 // Reading currentLive at that moment would hand the seq of a
858 // pre-resync row to the FRESH subscriber, whose cursor was seeded
859 // from a GET that predates it — and if the contiguity check
860 // happened to pass, that cursor would step over a row the fresh
861 // Y.Doc never applied. Closing over the lifecycle's own reference
862 // means a late response lands on a stopped instance, which ignores
863 // it.
864 // sendSave posts a batch (createPoster): one for the page, not one per
865 // save queue, so a server found not to gunzip is remembered across a
866 // resync, which builds a new queue.
867 const sendSave = createPoster({ url: base })
868
869 function makeSaveQueue(getLive) {
870 // The save queue (fixtures/save-queue.mjs) owns the retry/drop
871 // decision — fix round 1's F1: a permanently-rejected batch (a
872 // 4xx) must be dropped, not retried forever and not merged into
873 // by whatever gets typed next, while a network failure or a 5xx
874 // is worth retrying. See that module's own doc comment for the
875 // bug this replaced and how fixtures/save-queue.test.mjs
876 // reproduces it.
877 return createSaveQueue({
878 // Wrapped rather than handed straight to fetch so this tab can
879 // read the seq the server assigned to its own write, which
880 // saves the round trip of hearing about it on the stream and
881 // fetching back bytes it already has. save-queue.mjs is
882 // untouched by this: it consumes only r.ok and r.status, and
883 // this returns the same response it always did.
884 //
885 // Only on a 2xx. A 4xx or 5xx carries no seq — the server
886 // broadcasts and sets the header only when ApplyUpdate returned
887 // no error — and noteOwnSeq's own contiguity check would ignore
888 // a stale number anyway.
889 //
890 // Keepalive, at most KEEPALIVE_BYTES a batch, and given up if it is
891 // not answered (saveRequest, answerTimeoutMs): WebKit sends no ordinary request
892 // while a link the page opened is still loading, and the page stays
893 // editable meanwhile — save-queue.mjs's own comment has the case.
894 post: async (bytes, onWire) => {
895 const res = await sendSave(bytes, onWire)
896 const live = getLive()
897 if (res.ok && live) {
898 const seq = Number(res.headers.get('Docs-Seq'))
899 if (Number.isFinite(seq)) live.noteOwnSeq(seq)
900 }
901 return res
902 },
903 mergeUpdates: Y.mergeUpdates,
904 debounceMs: DEBOUNCE_MS,
905 maxBatchBytes: KEEPALIVE_BYTES,
906 answerTimeoutMs,
907 // A save refused with no answer is "Trouble saving" only if the
908 // server cannot be reached either (reachable).
909 probe: () => reachable('/healthz'),
910 onStatus: (state) => {
911 if (state === 'failed') {
912 sessionFailed = true
913 resyncController.reportDivergence()
914 }
915 // Docs has no word for saving: the indicator rests while a save
916 // is out, as it always has.
917 updateIndicator(state === 'saving' ? 'ok' : state)
918 },
919 })
920 }
921
922 // placeCaretFromPage makes the whole sheet of paper behave like the
923 // document: a click in the page's 1in margin — outside the editable
924 // node, so neither the browser nor ProseMirror sees it as a click on
925 // text at all — puts the caret on the line nearest where the pointer
926 // landed, the way every word processor does. views/show.html grows
927 // the editable node to the full height of the page's text area, so
928 // the empty space below the last paragraph is already ProseMirror's
929 // own and needs none of this; the margins around it never can be,
930 // because they are [docs-page]'s padding and the editable node has
931 // no way to reach outside itself.
932 //
933 // Clamping the click's coordinates into the editable node's own
934 // rectangle before asking posAtCoords is what turns "beside the
935 // text" into "at the nearest end of the nearest line": posAtCoords
936 // answers null for a point outside the editor, and the clamped point
937 // is the closest one inside it. A null answer even after clamping
938 // falls back to the end of the document — not because any particular
939 // document is known to produce one (an empty document still holds an
940 // empty paragraph, which resolves fine), but because posAtCoords
941 // reads the live DOM and is documented to be able to return null,
942 // and the end of the document is the one position that always
943 // exists whatever it hands back.
944 //
945 // Reads currentView, not a view captured when the listener was
946 // registered: a resync destroys the whole EditorView and builds
947 // another (attemptResync), and a click after that must reach the
948 // live one rather than dispatching into a destroyed view.
949 function placeCaretFromPage(event) {
950 const view = currentView
951 if (!view || event.button !== 0) return
952 // Inside the editable node already: ProseMirror's own handling is
953 // better than anything reconstructed from coordinates here.
954 if (view.dom.contains(event.target)) return
955
956 const rect = view.dom.getBoundingClientRect()
957 const found = view.posAtCoords({
958 left: Math.min(Math.max(event.clientX, rect.left + 1), rect.right - 1),
959 top: Math.min(Math.max(event.clientY, rect.top + 1), rect.bottom - 1),
960 })
961 const pos = found ? found.pos : view.state.doc.content.size
962 // Selection.near, spelled on the base class rather than as
963 // TextSelection.near: TextSelection defines no static near of its
964 // own (prosemirror-state 1.4.4), so the latter silently resolves
965 // to this exact same inherited function while reading like a
966 // promise that the result is a TextSelection. It usually is, but
967 // near falls back to a NodeSelection or an AllSelection when no
968 // text position is reachable, and a name that overstates that is
969 // the kind of comment-shaped lie this file's own conventions
970 // exist to keep out. Every branch here yields some valid
971 // selection, which is all the dispatch below needs.
972 const selection = Selection.near(view.state.doc.resolve(pos))
973
974 // preventDefault before focusing: the default mousedown on a
975 // non-editable element blurs the editor and collapses the
976 // selection we are about to set, so the caret would appear and
977 // vanish in the same tick.
978 event.preventDefault()
979 view.dispatch(view.state.tr.setSelection(selection).scrollIntoView())
980 view.focus()
981 }
982
983 function mountView(mountEl, fragment, undoManager) {
984 // {mount: mountEl}, not plain mountEl: passed as a bare DOM node,
985 // EditorView only appends its own div as an extra child
986 // (prosemirror-view's own constructor —
987 // place.appendChild(this.dom)), leaving whatever was already
988 // there sitting beside it as inert, stale markup a click could
989 // land on instead of the real editable surface. {mount: mountEl}
990 // makes mountEl itself the editable DOM node, so ProseMirror takes
991 // over its existing children (this.mounted = true) instead of
992 // adding a sibling.
993 const plugins = [
994 ySyncPlugin(fragment),
995 yUndoPlugin({ undoManager }),
996 // Autoformat (fixtures/autoformat.mjs): "- " makes a bullet,
997 // "1. " a numbered list, "> " a quote, "# " a heading. Ahead of
998 // the keymaps because the rules act on typed TEXT rather than on
999 // keys, and because the Backspace binding below that reverts them
1000 // has to be able to see that one just fired.
1001 autoformatRules(schema),
1002 // Paged/infinite (fixtures/pages.mjs). Reads the mode through a
1003 // getter rather than being handed one, because the View menu can
1004 // change it at any moment and a plugin is configuration reused
1005 // across every state this page builds.
1006 pagesPlugin({ getMode: effectiveMode, pageLabel: pageLabelText }),
1007 fontGatePlugin,
1008 keymap({
1009 'Mod-z': guarded(undo), 'Mod-y': guarded(redo), 'Mod-Shift-z': guarded(redo),
1010 'Mod-b': toggleMark(schema.marks.strong),
1011 'Mod-i': toggleMark(schema.marks.em),
1012 // In this block rather than appended to baseKeymap below,
1013 // which is a shared module-level object every editor on the
1014 // page would see mutated. Nothing binds Shift-Enter today:
1015 // baseKeymap has Enter and Mod-Enter only, and
1016 // prosemirror-keymap looks up the full modified name for a
1017 // named key like Enter (its shift-less fallback is for
1018 // single-character keys), so the keystroke matched no binding,
1019 // was then captured and preventDefaulted by prosemirror-view,
1020 // which treats every Enter as handled (captureKeyDown returns
1021 // true for keyCode 13 whether or not shift is down, and its
1022 // caller preventDefaults whenever handleKeyDown fails and
1023 // captureKeyDown succeeds), and so did nothing at all.
1024 //
1025 // Worth stating precisely, because the plausible wrong reading
1026 // is that the keystroke fell through to the browser's own
1027 // contenteditable handling, inserted a native <br>, and was
1028 // re-parsed into this node by the schema's parseDOM — i.e.
1029 // that a break sometimes worked before this binding existed.
1030 // It never could: the event never reached the browser.
1031 'Shift-Enter': insertHardBreak,
1032 // Tab and Shift+Tab.
1033 //
1034 // chainCommands, so one key does the right thing in two
1035 // contexts without this file testing which one it is in: in a
1036 // list, Tab nests the item and Shift+Tab lifts it; anywhere
1037 // else it steps the block's own indent. sinkListItem is tried
1038 // FIRST and returns false when the selection is not in a list,
1039 // which is what hands the key to changeIndent.
1040 //
1041 // Tab inside an editable surface does not move focus, and that
1042 // is a deliberate exception to the usual rule rather than an
1043 // oversight. WCAG 2.1.2 forbids a keyboard trap, not a
1044 // repurposed Tab: Escape is not needed to leave because the
1045 // surrounding chrome — the menu bar, the formatting bar, the
1046 // sign-out control — is all reachable by Tab from outside, and
1047 // Shift+Tab at indent 0 in the first block returns false, so
1048 // the browser's own focus move takes over and a person tabs
1049 // backwards out of the document exactly as before. That last
1050 // part is why changeIndent reports honestly at the ends of its
1051 // range instead of returning true and swallowing the key.
1052 Tab: chainCommands(sinkListItem(schema.nodes.list_item), changeIndent(1)),
1053 'Shift-Tab': chainCommands(liftListItem(schema.nodes.list_item), changeIndent(-1)),
1054 // Backspace immediately after an input rule fired reverts the
1055 // transformation and leaves the typed characters — "- " goes
1056 // back to being "- " rather than becoming a list you have to
1057 // fight your way out of. This is the whole reason autoformat is
1058 // tolerable, and it has to be in THIS block rather than
1059 // appended to baseKeymap below, because baseKeymap binds
1060 // Backspace too and whichever comes first wins. Away from a
1061 // rule, undoInputRule returns false and baseKeymap's own
1062 // Backspace takes the key as it always did.
1063 Backspace: undoInputRule,
1064 // Escape leaves the document for the formatting bar.
1065 //
1066 // Tab is repurposed in here — it indents rather than moving
1067 // focus — and although Shift+Tab still escapes backwards
1068 // (changeIndent reports false at indent 0, handing the key
1069 // back to the browser), there is no forward exit below indent
1070 // 8. WCAG 2.1.2 permits a modified key provided the person is
1071 // told, and the shortcuts sheet tells them; but "you can only
1072 // leave backwards" is a poor thing to have to say, so Escape
1073 // leaves forwards onto the nearest chrome.
1074 //
1075 // Returns whether it moved focus rather than always true: with
1076 // nowhere to go, swallowing Escape would take the key away from
1077 // anything else that wants it while doing nothing.
1078 //
1079 // With the inspector closed (spec I2) none of the toolbar is
1080 // drawn and focusStop reports false; the nearest chrome is then
1081 // the bar's Format toggle, the way back to it (review on #106).
1082 Escape: () => toolbar.focusStop() || focusFormat(),
1083 // Enter in a list splits the item, and on an empty item lifts
1084 // out of the list — the idiom every editor has. Without this,
1085 // baseKeymap's splitBlock puts a bare paragraph inside the list
1086 // item and there is no way to end a list by pressing Enter
1087 // twice. Missing since lists were added; found in review.
1088 Enter: chainCommands(splitListItem(schema.nodes.list_item), baseKeymap.Enter),
1089 }),
1090 keymap(baseKeymap),
1091 ]
1092 // The toolbar's plugin keeps its buttons in step with the
1093 // selection. One Plugin instance is reused across every state this
1094 // page builds — a plugin is configuration, not state — so a resync
1095 // rebuilding the view does not need a new toolbar, and the toolbar
1096 // does not need to know a resync happened.
1097 if (toolbar.plugin) plugins.push(toolbar.plugin)
1098
1099 plugins.push(keptSelectionPlugin)
1100 return new EditorView({ mount: mountEl }, {
1101 state: EditorState.create({ schema, plugins }),
1102 scrollMargin: scrollMargins(),
1103 // Every transaction, with every one the plugins appended, goes
1104 // through aroundDispatch, which while a resync is pending keeps a
1105 // local change as the transactions that made it (carry.mjs).
1106 dispatchTransaction(tr) {
1107 const { state, transactions } = this.state.applyTransaction(tr)
1108 aroundDispatch(tr, transactions, () => this.updateState(state))
1109 },
1110 // A blank line pasted out of Google Docs arrives as a paragraph
1111 // holding one hard_break, which the editor draws two lines tall.
1112 // paste.mjs's header has the whole chain; the short version is
1113 // that this is the first point where a block-level <br> can be
1114 // told apart from one the author typed.
1115 transformPasted: blankLinesFromBreaks(schema),
1116 })
1117 }
1118
1119 // attemptResync fetches the server's own log fresh and rebuilds the
1120 // whole editor (Y.Doc, save queue, EditorView) from it — the same
1121 // thing this function also does for the very first mount below,
1122 // and the same truth a manual reload already reconstructs
1123 // correctly. Used both ways rather than duplicated: the initial
1124 // mount awaits it directly (a failure there means the editor never
1125 // mounted at all, handled by the outer .catch below), while a
1126 // later resync goes through resyncController, which retries on
1127 // failure instead of propagating one (fix round 2's own fix — see
1128 // resync-controller.mjs's header comment for why a resync that
1129 // silently gives up after one failure recreates the exact data
1130 // loss F1 was supposed to close).
1131 //
1132 // ySyncPlugin mirrors every local ProseMirror transaction into the
1133 // Y.Doc immediately, optimistically, before any network call even
1134 // starts, so once a batch is permanently rejected the local doc
1135 // already holds content the server never received — every update
1136 // produced after that point is encoded relative to that now-
1137 // fictional history, which core.Handle.Apply accepts (a real 204)
1138 // but can never actually integrate. The only way back to a state
1139 // new edits can build on is to discard the diverged document
1140 // entirely and rebuild from the server's own log — which is also
1141 // why this necessarily discards whatever was typed locally in the
1142 // interim: it was built on the same poisoned history and could
1143 // never have been saved either.
1144 // fetchLog does the whole-log GET that both the initial mount and
1145 // every later resync use (attemptResync below). raw, when true,
1146 // appends the literal query string `raw=1` — handlers.go matches
1147 // nothing else — which skips the snapshot lookup entirely and
1148 // serves exactly the doc_updates rows the server has always been
1149 // able to serve correctly. See applyServerLog's caller below for
1150 // why this exists.
1151 async function fetchLog(raw) {
1152 const url = updatesURL(base, { raw })
1153 const res = await fetch(url, { credentials: 'same-origin' })
1154 if (!res.ok) throw new Error(`load ${url}: ${res.status}`)
1155 return {
1156 log: new Uint8Array(await res.arrayBuffer()),
1157 // Docs-Seq names how far the bytes just received actually reach,
1158 // and the server derives it from those bytes rather than from a
1159 // separate query — so this cursor can never start out ahead of
1160 // what this document holds. A missing or unparseable header
1161 // (an older server, a proxy that strips it) becomes 0, which
1162 // costs one redundant full fetch on the first notification and
1163 // loses nothing.
1164 startSeq: Number(res.headers.get('Docs-Seq')),
1165 }
1166 }
1167
1168 async function attemptResync() {
1169 // A change of this person's that is waiting for its font runs first,
1170 // on the view and document it was made in; what it writes is kept in
1171 // unsaved and carried over below. Destroying the view under it made
1172 // the change impossible, and the strip said its font was unavailable.
1173 while (waiting) await free()
1174 let { log, startSeq } = await fetchLog(false)
1175
1176 let ydoc = new Y.Doc()
1177 try {
1178 applyServerLog(ydoc, log)
1179 } catch (decodeErr) {
1180 // This fetch happens before any live-update subscriber exists —
1181 // it IS the document, for the initial mount as much as for a
1182 // later resync — so a corrupt snapshot here has no cursor to
1183 // fall back through the way live-updates.mjs's drain() does; it
1184 // would simply stop the editor mounting at all. Same cause as
1185 // that module's own retry (its comment explains the "why" in
1186 // full): the server serves a snapshot without ever calling into
1187 // the CRDT core, so it cannot detect one corrupted on disk after
1188 // it was written and verified — only Y.readUpdate, here, can.
1189 // A fresh Y.Doc for the retry, not the one just poisoned by a
1190 // partial decode: applyServerLog can throw partway through the
1191 // loop, leaving ydoc in an unknown state that must not be built
1192 // on. A second throw is not caught again; it propagates like any
1193 // other attemptResync failure — to the outer .catch on the
1194 // initial mount, or to resyncController's own retry loop on a
1195 // later resync.
1196 ;({ log, startSeq } = await fetchLog(true))
1197 ydoc = new Y.Doc()
1198 applyServerLog(ydoc, log)
1199 }
1200 const fragment = ydoc.getXmlFragment('prosemirror')
1201 // Every style of every family the document uses loads before the
1202 // editor shows it: what the page was gated on, and any family a
1203 // change made since the page was rendered brought in.
1204 await fonts.prepare(familiesInFragment(fragment))
1205
1206 // lifecycleLive is this resync's own subscriber — see
1207 // makeSaveQueue's own comment for why the queue must not read the
1208 // module-level currentLive instead. Assigned below, once
1209 // createLiveUpdates has built it; until then the getter returns
1210 // null and a POST simply records no seq, which costs one fetch.
1211 let lifecycleLive = null
1212 const saveQueue = makeSaveQueue(() => lifecycleLive)
1213 // Send only what originated here, and only once the document is
1214 // known consistent with the server. The 'server' origin above
1215 // marks replayed bytes (echoing those back would grow the log
1216 // without adding information); resyncController.diverged marks
1217 // everything produced while a previous rejection is still being
1218 // recovered from — sending THAT would only earn more silently-
1219 // unintegrated 204s (fix round 2's blocking finding) and spend
1220 // core.go's maxRetainedUpdates cap for nothing. It is kept instead
1221 // (unsaved, above) and carried onto the rebuilt document, where only
1222 // what integrates is posted. Once a resync actually replaces this
1223 // ydoc with a fresh one, diverged is false again and this check
1224 // simply passes every update through.
1225 const doc = ydoc
1226 doc.on('update', (update, origin) => {
1227 if (origin === 'server') return
1228 if (resyncController.diverged) {
1229 if (doc === currentDoc && origin !== CARRIED) {
1230 const replay = held || mirrored || undefined
1231 mirrored = null
1232 unsaved.keep(doc, update, replay)
1233 }
1234 return
1235 }
1236 saveQueue.enqueue(update)
1237 })
1238 // While diverged, each of this person's changes is made under the id
1239 // the keeper gives it (carry.mjs's createKeeper): a ProseMirror change
1240 // shares one per 500 ms window, anything else (an undo, a redo) takes
1241 // one of its own.
1242 doc.on('beforeTransaction', (tr) => {
1243 if (doc !== currentDoc || !resyncController.diverged) return
1244 if (tr.origin === 'server' || tr.origin === CARRIED) return
1245 mirrored = null
1246 unsaved.before(doc, tr.origin === ySyncPluginKey ? 'pm' : 'other')
1247 })
1248
1249 // And again with no await between this check and the view's
1250 // replacement: a paste that began waiting while the log was fetched
1251 // runs on its own view first.
1252 while (waiting) await free()
1253 // What this tab wrote while diverged goes into the rebuilt document
1254 // now, before its view is mounted: the new view renders with those
1255 // words already in it, so they are never off the sheet for a frame.
1256 // The undo manager is made first, so the carried change is one undo
1257 // step; it is yUndoPlugin's own, with 'carried' tracked too.
1258 const undoManager = new Y.UndoManager(fragment, {
1259 trackedOrigins: new Set([ySyncPluginKey, CARRIED]),
1260 captureTimeout: UNDO_CAPTURE_MS,
1261 deleteFilter: (item) => defaultDeleteFilter(item, defaultProtectedNodes),
1262 captureTransaction: (tr) => tr.meta.get('addToHistory') !== false,
1263 })
1264 // The carried changes undo in the steps they were made in: a new step
1265 // wherever two were made further apart than the capture window.
1266 const undoSteps = (entry, previous) => {
1267 if (!previous || entry.at - previous.at >= UNDO_CAPTURE_MS) undoManager.stopCapturing()
1268 }
1269 const now = carry(doc, unsaved.take(), CARRIED, undoSteps)
1270
1271 // Destroy the old view BEFORE creating the new one, not after:
1272 // {mount: el} makes an EditorView take exclusive ownership of
1273 // el's own DOM node, so two views both pointed at the same el at
1274 // once corrupted that node instead of cleanly handing it off —
1275 // found when a resync's own follow-up edit landed nowhere: the
1276 // click after resync hit a DOM ProseMirror no longer recognised
1277 // as its own.
1278 // The Format sheet's selection, as Yjs relative positions, so the
1279 // view built below can draw it kept again: the person still sees
1280 // what the sheet acts on. The rebuilt document keeps the server's
1281 // items under their ids, so the positions resolve in it; one that
1282 // does not (it was in a refused change) leaves the new view's own.
1283 const kept = formatSheet.open && currentView ? keptPositions(currentView) : null
1284 if (currentView) currentView.destroy()
1285 currentQueue = saveQueue
1286 currentDoc = doc
1287 currentView = mountView(el, fragment, undoManager)
1288 // Where its words are gone, the sheet closes: what it would act on
1289 // is no longer anywhere. The keyboard does not come back for it.
1290 if (formatSheet.open && !keepAgain(currentView, kept)) {
1291 formatSheet.hadFocus = false
1292 document.dispatchEvent(new CustomEvent('docs:format-sheet-close'))
1293 }
1294
1295 // The live subscriber is replaced wholesale with everything else.
1296 // Stopping the old one first matters for the same reason
1297 // destroying the old view first does: it may have a fetch in
1298 // flight, and its own stop() is what makes that response land
1299 // nowhere instead of in the document that just replaced it.
1300 if (currentLive) currentLive.stop()
1301 lifecycleLive = createLiveUpdates({
1302 initialSeq: Number.isFinite(startSeq) ? startSeq : 0,
1303 openStream: (onEvent, onStreamError) => {
1304 const es = new EventSource(streamURL, { withCredentials: true })
1305 es.addEventListener('update', (ev) => onEvent(Number(ev.data)))
1306 es.addEventListener('error', (ev) => onStreamError(ev))
1307 return { close: () => es.close() }
1308 },
1309 // raw must reach the server as the literal query string `raw=1`
1310 // — handlers.go matches nothing else, not `raw=true` or a bare
1311 // `raw` — or the escape hatch fails silently and drain() ends up
1312 // refetching the same corrupt snapshot forever.
1313 fetchSince: async (since, { raw } = {}) => {
1314 const url = updatesURL(base, { since, raw })
1315 const r = await fetch(url, { credentials: 'same-origin' })
1316 if (!r.ok) throw new Error(`fetch ${url}: ${r.status}`)
1317 return {
1318 bytes: new Uint8Array(await r.arrayBuffer()),
1319 seq: Number(r.headers.get('Docs-Seq')),
1320 }
1321 },
1322 onUpdates: async (bytes) => {
1323 // A collaborator's change waits for every face it could paint
1324 // in (font-session.mjs's prepare): any family it names, and
1325 // every family in use with the default's and code's, since a
1326 // change in bold or code names none (review finding 1). Their
1327 // text appears once, in its own face. A family new to this tab
1328 // that takes more than three seconds is committed to its
1329 // fallback; one already on screen is waited for. Updates stay in
1330 // order: live-updates.mjs awaits this before the next.
1331 await fonts.prepareRemote(bytes)
1332 // And for a local action waiting for its font: the document must
1333 // not move under it. Updates keep their order; nothing local is
1334 // held for them.
1335 await free()
1336 // While diverged the local document is known poisoned and a
1337 // rebuild is already being retried; applying remote bytes to
1338 // it would only build more history on top of a fiction. The
1339 // resync replaces this whole subscriber, and its fresh
1340 // cursor picks these same rows up again. The same if a resync
1341 // replaced this subscriber while the font was loading.
1342 if (resyncController.diverged || currentLive !== lifecycleLive) return
1343 applyServerLog(ydoc, bytes)
1344 },
1345 onError: (err) => {
1346 // Deliberately not updateIndicator('failed'): [estilo-save-status]
1347 // means "your edit did not save", and that is still false —
1348 // POST is a separate path and is unaffected by a dead stream.
1349 // What is lost is freshness, which heals on the next activity.
1350 console.error('live updates:', err)
1351 },
1352 })
1353 currentLive = lifecycleLive
1354 currentLive.start()
1355
1356 // A tab that LOADS hidden never fires visibilitychange, so the
1357 // listener below cannot close its stream and only the idle timer
1358 // would — leaving a background tab holding a connection for two
1359 // minutes it never needed. Cheap to check once, here, where the
1360 // stream has just been opened.
1361 if (typeof document !== 'undefined' && document.hidden) currentLive.noteHidden()
1362
1363 // Saved through the new queue: what was carried before the view was
1364 // mounted, and anything written on the rebuilt document since, while
1365 // this resync was still finishing (applying it again is a no-op in
1366 // Yjs). Only what took is posted, a replayed change as the update its
1367 // replay made; a change that could be neither carried nor replayed is
1368 // left out, and the save line already says something was not saved.
1369 // Edits made between a batch leaving and its refusal arriving are not
1370 // here: they were under the old client id, after the refused clocks,
1371 // and went with that batch.
1372 const later = carry(doc, unsaved.take(), CARRIED, undoSteps)
1373 for (const u of now.post.concat(later.post)) saveQueue.enqueue(u)
1374 if (now.lost + later.lost) console.warn('resync: a change made on top of a refused one could not be carried over')
1375 }
1376
1377 // resyncController (fix round 2) owns "the local document has
1378 // diverged and needs rebuilding" as its own retried-until-it-
1379 // succeeds state machine — see resync-controller.mjs's own header
1380 // comment for the bug this replaced: round 1's resync gave up
1381 // silently after one failure, and nothing ever told it to try
1382 // again, so a single dropped connection at the wrong moment
1383 // recreated the exact silent-204 loss F1 exists to prevent.
1384 // onDiverged/onRecovered keep the visible indicator in step with
1385 // the state machine's own truth rather than with whatever the
1386 // (possibly still-diverged) save queue's own status happens to
1387 // report — sessionFailed's own stickiness (updateIndicator) means
1388 // onRecovered never actually clears the indicator once something
1389 // has been lost, but it does matter the first time: onDiverged is
1390 // what lights the indicator up if a batch is ever dropped without
1391 // save-queue.mjs's own onStatus('failed') having already done so.
1392 const resyncController = createResyncController({
1393 attemptResync,
1394 // From the moment a batch is refused, this tab writes under a new
1395 // client id. Yjs integrates one client's updates only in clock order,
1396 // so anything written after the refusal under the old id could never
1397 // be carried to the rebuilt document: it would wait forever for the
1398 // refused clocks the server never took. Under a fresh id it depends
1399 // only on what it actually touches. Yjs gives a document a fresh id
1400 // the same way when it meets a collision.
1401 onDiverged: () => {
1402 if (currentDoc) currentDoc.clientID = freshClientID(currentDoc)
1403 updateIndicator('failed')
1404 },
1405 onRecovered: () => updateIndicator(sessionFailed ? 'failed' : 'ok'),
1406 })
1407
1408 // A page shown again from the back/forward cache may have left with a
1409 // save on the wire, and WebKit never answers a keepalive save that
1410 // completed while the page was away (save-queue.mjs's own comment): the
1411 // queue sends it again rather than waiting on it forever. Registered
1412 // before the first mount so no save can precede it.
1413 addEventListener('pageshow', (e) => {
1414 if (e.persisted && currentQueue) currentQueue.resume()
1415 })
1416
1417 // Initial mount: attemptResync's own failure here is NOT retried —
1418 // it propagates to the outer .catch below, which leaves the
1419 // server-rendered read view in place. Retrying belongs to a
1420 // document the person is already editing (resyncController's own
1421 // job); a document that never opened has nothing to retry into.
1422 await attemptResync()
1423
1424 // The font gate (fonts-gate.mjs) shows the sheet once this has
1425 // paginated in the final faces: wait for the faces, have the pages
1426 // plugin measure again (and the toolbar sync, which opens the font
1427 // control once its previews are in), give it the frame it measures in,
1428 // then say so.
1429 await fonts.fontsReady
1430 if (currentView) currentView.dispatch(currentView.state.tr.setMeta('docs-fonts-ready', true))
1431 // The font control opens once its previews have settled: tell the
1432 // toolbar, which re-reads that on every update.
1433 fonts.previewsDone.then(() => currentView && currentView.dispatch(currentView.state.tr.setMeta('docs-previews-ready', true)))
1434 await nextFrame()
1435 await nextFrame()
1436 fonts.settled()
1437
1438 // An empty document opens ready to type: the caret is already in it,
1439 // the way a blank page waits for its first word. Only an empty one,
1440 // so a document somebody came to read does not scroll or raise a
1441 // phone's keyboard, and only when nothing else has focus yet, so a
1442 // person who already reached for the title or the toolbar keeps
1443 // their place. After the reveal, because an inert editor cannot take
1444 // focus.
1445 const first = currentView
1446 if (first && first.editable && first.state.doc.textContent === '' && first.state.doc.childCount <= 1 &&
1447 (!document.activeElement || document.activeElement === document.body)) {
1448 first.focus()
1449 }
1450
1451
1452 // The live subscriber's window on whether anybody is here. It owns
1453 // no DOM of its own (live-updates.mjs is testable under plain Node
1454 // precisely because of that), so every listener it needs is
1455 // registered here, once, reading currentLive rather than a
1456 // subscriber captured at mount time — a resync replaces that
1457 // object, and these listeners outlive every one of them.
1458 //
1459 // A hidden tab shortens its deadline rather than closing on the
1460 // spot: platform hibernation is default-on and this app holds one
1461 // stream per open editor, so a document left open on Friday must not
1462 // keep its instance awake all weekend — but closing the instant a
1463 // tab goes to the background made every switch back paint the old
1464 // document for a frame before the reconnect caught it up, which is
1465 // the flash Paul kept seeing. live-updates.mjs's HIDDEN_MS carries
1466 // the measurement and the arithmetic.
1467 //
1468 // Everything else is "activity", and the breadth is the point. The
1469 // obvious three — visibility, focus, and typing — all miss the
1470 // commonest case there is: someone READING a long document, on a
1471 // tab that is already visible and already focused. That person
1472 // fires none of them, so an idle close would never be undone and
1473 // the tab would go quietly stale — which is exactly the watching
1474 // half of "type in one tab, watch the other". A pointer moving or
1475 // a page scrolling is what says they are still there.
1476 //
1477 // All passive, and none of them does work per event: noteActivity
1478 // only re-arms a timer, or reopens a stream that is already closed.
1479 addEventListener('visibilitychange', () => {
1480 if (document.hidden) currentLive && currentLive.noteHidden()
1481 else currentLive && currentLive.noteActivity()
1482 })
1483 // Leaving the page, and coming back to it from the back/forward cache,
1484 // are live-updates.mjs's own: it listens from the moment it loads.
1485 for (const name of ['pointermove', 'scroll', 'keydown', 'focus']) {
1486 addEventListener(name, () => currentLive && currentLive.noteActivity(), { passive: true, capture: true })
1487 }
1488
1489 // Registered on [docs-page] rather than on the editable node (which
1490 // never receives these clicks) and after the first mount rather than
1491 // before it, so placeCaretFromPage always has a live view to
1492 // dispatch into. Once, not once per resync: it reads currentView,
1493 // and the page element outlives every EditorView mounted into it.
1494 const page = el.closest('[docs-page]')
1495 if (page) page.addEventListener('mousedown', placeCaretFromPage)
1496
1497 // The caret is this editor's focus indicator — views/show.html drops
1498 // the browser's focus ring, on the argument that a text cursor says
1499 // more than a box around the paper does. That argument only holds
1500 // while the caret is actually on screen, and one route in breaks it:
1501 // Tab in from the sign-out button, on a document scrolled away from
1502 // wherever the selection was last left, and ProseMirror restores that
1503 // selection without scrolling to it (its focus() does not scroll on
1504 // purpose), so focus lands with no visible indicator anywhere in the
1505 // viewport. The ring, whose edges would have been on screen, used to
1506 // cover that case. AGENTS.md's rule is WCAG 2.2 AA with no
1507 // exemptions, so the ring's replacement has to be visible on every
1508 // path that reaches focus, not just on the click that scrolls itself
1509 // into view. An empty transaction carries the scroll: it changes no
1510 // content, so ySyncPlugin emits no Y update and the save queue never
1511 // sees it (this must not cost a row against core.go's
1512 // maxRetainedUpdates for merely tabbing into a document).
1513 //
1514 // Only for focus that did NOT arrive by pointer, which is the whole
1515 // subtlety here. A focus event fires before ProseMirror has set the
1516 // selection the click asked for, so scrolling on every focus would
1517 // scroll to wherever the selection happened to be left instead —
1518 // click into the third page of a document and the view yanks back to
1519 // the first, which is a worse bug than the one this is closing.
1520 // :focus-visible cannot make the distinction: a contenteditable
1521 // takes keyboard input, so it matches whatever the modality was.
1522 // Hence the flag: a pointer press sets it, and clearing it on the
1523 // next macrotask leaves it set for exactly the focus that press
1524 // causes (focus is dispatched synchronously inside the press's own
1525 // default action) and clear for every later one.
1526 let focusFromPointer = false
1527 const notePointer = () => {
1528 focusFromPointer = true
1529 setTimeout(() => { focusFromPointer = false }, 0)
1530 }
1531 document.addEventListener('mousedown', notePointer, true)
1532 document.addEventListener('touchstart', notePointer, true)
1533
1534 el.addEventListener('focus', () => {
1535 if (focusFromPointer) return
1536 const view = currentView
1537 if (view) view.dispatch(view.state.tr.scrollIntoView())
1538 })
1539
1540 // A close or reload with unsent bytes must not lose the edit.
1541 // pendingBytes() covers both what is still queued AND what is
1542 // already in flight, unless that went keepalive (fix round 1's LOW
1543 // finding: a flush's own fetch, awaited but not yet resolved, held
1544 // bytes that a same-tick unload would otherwise abandon with nothing
1545 // beaconed at all, since they had already been cleared out of the
1546 // queue proper; a keepalive save is not abandoned).
1547 // Reads currentQueue, not a queue captured at mount time, so a
1548 // close during/after a resync still beacons the live queue.
1549 addEventListener('beforeunload', () => {
1550 // What the queue owes, and what was written while diverged and is
1551 // waiting for the rebuild. Under its fresh client id the server
1552 // integrates whatever of it does not depend on the refused batch.
1553 //
1554 // A save on the wire that went keepalive is left out: it outlives the
1555 // page and lands anyway, and keepalive requests and beacons share one
1556 // 64KiB quota, so repeating it refused the whole beacon, and with it
1557 // every edit queued behind it (Claude Fable on #94). If that is still
1558 // refused, the queue alone, without a plain save on the wire.
1559 const extra = []
1560 for (const e of unsaved.entries) extra.push(...e.updates)
1561 const payload = (owed) => {
1562 const parts = owed ? [owed, ...extra] : extra
1563 if (!parts.length) return null
1564 return parts.length === 1 ? parts[0] : Y.mergeUpdates(parts)
1565 }
1566 const q = currentQueue
1567 const first = payload(q && q.pendingBytes({ wire: 'plain' }))
1568 if (!first) return
1569 const tries = [first]
1570 if (q && q.onWire === 'plain') {
1571 const second = payload(q.pendingBytes({ wire: 'none' }))
1572 if (second) tries.push(second)
1573 }
1574 for (const bytes of tries) {
1575 if (navigator.sendBeacon(base, new Blob([bytes], { type: 'application/octet-stream' }))) return
1576 }
1577 // sendBeacon refuses outright once the quota is spent, and a fetch
1578 // with keepalive:true shares it — not a bigger-payload workaround
1579 // (fix round 2: 100KB refused by both, 30KB through both). It is
1580 // still tried, with the smallest payload, because the quota is shared
1581 // across every keepalive request the page makes, and one may have
1582 // finished since. What this cannot do is get a paste-sized edit out
1583 // during an immediate close; the debounce stays short so most edits
1584 // have long gone.
1585 console.error('beforeunload: sendBeacon refused the pending edit, retrying via keepalive fetch')
1586 fetch(base, {
1587 method: 'POST',
1588 credentials: 'same-origin',
1589 keepalive: true,
1590 headers: { 'Content-Type': 'application/octet-stream' },
1591 body: tries[tries.length - 1],
1592 }).catch(() => {})
1593 })
1594
1595 return currentView
1596}
1597
1598const mount = document.querySelector('[docs-editor]')
1599if (mount) mountEditor(mount).catch(err => {
1600 // The sheet must not stay held for an editor that never came.
1601 fontsFor().settled()
1602 // Leave the server-rendered read view in place rather than replacing
1603 // it with a blank editor: unreadable is worse than uneditable.
1604 mount.setAttribute('data-editor-failed', '1')
1605 console.error(err)
1606})
1607