// fixtures/carry.mjs — what a resync does with the changes this tab wrote // while it was diverged (editor-entry.js's attemptResync). Slides has the // same module (oficina/slides fixtures/carry.mjs); keep the two the same. // // A save the server refused leaves the tab with a document the server will // never have. The resync rebuilds from the server's log; everything this // person wrote after the refusal was kept as the Y updates it produced // (createKeeper, below: the tab writes each change under a fresh Yjs // client id, so each depends only on what it touches, never on a change // before it that was held back), and each is carried onto the rebuilt // document here. What becomes of each: // // - every part of it integrates: applied, and posted; // - part of it integrates (a Backspace over the server's words and the // refused ones together; a paste into marked text, whose update also // rewrites the formatting around it): applied, and the part that // integrated is posted — skipping it would leave the page showing what // the server lacks, and posting all of it would leave the rest pending // in the server's log forever; // - none of it integrates (it was written on top of the refused text): // not posted, since the server would hold it pending in its log // forever (Claude Fable, #88) — unless it is a ProseMirror change, // which is replayed instead (below). // // Whether a part integrated is read from the update itself // (Y.decodeUpdate): a struct took when the document's state for its client // reaches the struct's end. A deleted range can take in part: Yjs deletes // up to the document's state for its client and holds the rest pending, so // a range took in part when that state is past its start, and did not // take in full while the state is short of its end (a Backspace over this // tab's own saved words and its refused ones together is one range of one // client; Claude Fable, #28). Y.encodeStateVectorFromUpdate is no // use here — it names a client only when the update's structs start at its // clock 0, and a delete-only update has none, so every update after a // client's first read as taken (Claude Fable, #27 and #88). // // The replay. A change made once the save was refused — a paste that // waited for its font, a keystroke, a delete — lands, in Yjs, against // whatever was beside it — often the refused text itself, which the server // never took; its update cannot integrate on the rebuilt document. But the // ProseMirror transactions that made it are kept (entry.replay.tr: tr.before // and every step), and so is where it was made (replay.locate, the // same text on the rebuilt document). The rebuilt text and tr.before differ // in one span, the refused change; the transaction's steps are mapped // through that span and applied with maybeStep, and the result is written // to the rebuilt text with y-prosemirror in one CARRIED transaction, whose // update is what is posted. ProseMirror checks every step: one that falls // inside the refused span, or cannot apply there (a paste into a paragraph // the refused change had made), gives up, and the change is left out, as // before — nothing posted, the save line already saying a change was not // saved, the clipboard as it was. Claude Fable's prototype for this kept // the paste in ten of eleven cases (carry.test.mjs holds them). // // The replay runs only when the change's own updates do not all take: a // change made elsewhere carries as its own Yjs updates, unchanged. import * as Y from 'yjs' import { EditorState } from 'prosemirror-state' import { StepMap, Mapping, ReplaceStep } from 'prosemirror-transform' import { yXmlFragmentToProseMirrorRootNode, prosemirrorToYXmlFragment } from 'y-prosemirror' // took reads, after u was applied to doc, how much of u is in it: 'all', // 'some' or 'none'. An update with nothing in it is 'all'. export function took (doc, u) { const { structs, ds } = Y.decodeUpdate(u) // The document's state for a client, read from its struct store: no // state vector is encoded per update, so carrying N updates is linear. const have = client => Y.getState(doc.store, client) let yes = 0 let no = 0 for (const s of structs) { if (s instanceof Y.Skip) continue if (have(s.id.client) >= s.id.clock + s.length) yes++ else no++ } for (const [client, ranges] of ds.clients) { for (const r of ranges) { // A range can take in part: Yjs deletes up to the document's state // for its client and holds the rest pending. const state = have(client) if (state > r.clock) yes++ if (state < r.clock + r.len) no++ } } if (!no) return 'all' return yes ? 'some' : 'none' } // integrated is what doc gained since the state vector before, without // anything Yjs holds pending: the structs that integrated, and the delete // set (whole, as Yjs always sends it; a delete applied twice is one). // encodeStateAsUpdate appends the pending structs and deletes otherwise, // so they are set aside for the call. function integrated (doc, before) { const { pendingStructs, pendingDs } = doc.store doc.store.pendingStructs = null doc.store.pendingDs = null try { return Y.encodeStateAsUpdate(doc, before) } finally { doc.store.pendingStructs = pendingStructs doc.store.pendingDs = pendingDs } } // replaySteps maps tr's steps from tr.before onto doc through the one span // in which the two differ, and applies them. It returns the new document, // or null when a step fell inside that span or ProseMirror refused it. export function replaySteps (tr, doc) { const before = tr.before const start = before.content.findDiffStart(doc.content) let ranges = [] if (start != null) { let { a: endA, b: endB } = before.content.findDiffEnd(doc.content) // The two ends overlap the start when the change repeats what is // beside it ("helllo" against "hello"); the span is moved past the // overlap so its sizes still differ by what was added or removed, as // prosemirror-view's findDiff does. Clamping it to the start instead // made it empty, and a paste after it landed a letter off (Claude // Fable, #28). const over = start - Math.min(endA, endB) if (over > 0) { endA += over endB += over } ranges = [start, endA - start, endB - start] } // prosemirror-collab's rebaseSteps, with the span in place of the remote // steps. A step after the first is in the coordinates of the document // the steps before it made, so each is mapped through the inverses of // those steps, the span, and their replayed forms, mirrored; mapping // every step through the one span map put a later step near the span's // edge off by what the earlier ones had moved, or refused it, and a mark // made over an insertion lost a letter (Claude Fable, #29). const steps = tr.steps const mapping = new Mapping() for (let i = steps.length - 1; i >= 0; i--) mapping.appendMap(steps[i].getMap().invert()) mapping.appendMap(new StepMap(ranges)) const next = EditorState.create({ doc, schema: doc.type.schema }).tr let mapFrom = steps.length for (const step of steps) { const mapped = step.map(mapping.slice(mapFrom)) mapFrom-- if (!mapped) return null if (next.maybeStep(mapped).failed) return null mapping.appendMap(mapped.getMap()) mapping.setMirror(mapFrom, mapping.maps.length - 1) } return next.doc } /** * derivedStep is one ReplaceStep that turns before into after, from the * one span in which they differ (the same overlap rule as replaySteps), or * null when they are the same. An undo or a redo reaches the editor as * ySync's mirror of a Yjs change, whose steps replace the whole document; * this is the change it made, as a step the resync can replay (Claude * Fable, #29/#90: an undo that put text back — a Backspace undone — was * lost when that text belonged to a replayed change, because Yjs anchors * the re-inserted text to the original, which the rebuilt document never * holds). */ export function derivedStep (before, after) { const start = before.content.findDiffStart(after.content) if (start == null) return null let { a: endA, b: endB } = before.content.findDiffEnd(after.content) const over = start - Math.min(endA, endB) if (over > 0) { endA += over endB += over } return new ReplaceStep(start, endA, after.slice(start, endB)) } // replay makes entry's change again on doc's text, in one transaction // under origin, and returns the updates it produced, or null when it could // not be made. function replay (doc, { tr, locate, schema }, origin) { let fragment = null try { fragment = locate(doc) } catch { fragment = null } if (!fragment) return null let after = null try { after = replaySteps(tr, yXmlFragmentToProseMirrorRootNode(fragment, schema)) } catch { after = null } if (!after) return null const out = [] const grab = u => out.push(u) doc.on('update', grab) try { doc.transact(() => prosemirrorToYXmlFragment(after, fragment), origin) } finally { doc.off('update', grab) } return out } // freshClientID is a Yjs client id: 32 random bits, as Y.Doc draws its // own, and never one doc already holds. export function freshClientID (doc, draw = randomID) { for (;;) { const id = draw() if (!doc || !doc.store.clients.has(id)) return id } } function randomID () { const a = new Uint32Array(1) globalThis.crypto.getRandomValues(a) return a[0] } /** * createKeeper keeps what a diverged tab writes, for carry: each update in * an entry of its own, or — while one change is held (held, its replay) — * in that change's entry, stamped with when it was made (at), so the * resync can group the carried changes into undo steps as they were made. * * Client ids. Yjs integrates one client's structs in clock order, so under * one id a change held back on the refused text held back every change * after it, wherever it was made (Claude Fable, #28). before(doc, kind) is * called before each transaction: a ProseMirror change ('pm') takes a fresh * id once per window (500 ms, the undo window) — a held one strands no * later ProseMirror change, since every one of those has its transaction * to replay; any other ('other': an undo, a redo, an inspector change, * which has nothing to replay) takes a fresh id of its own. A fresh id per * change was quadratic over a long divergence and left a client per * keystroke in the deck for good (Fable, #29: 4000 changes, 27 s). * * Undo and redo. Each is the undo manager's Yjs change, and the editor * keeps it with a replay derived from ySync's mirror of it (derivedStep), * so the resync makes it again on the rebuilt document as the person saw * it — taking text away, or putting it back — whatever ids the change it * undoes was replayed under. (Marking entries undone by item, as before, * could not reach text an undo put back, and doubled a type-over's undo * once the derived replay was in; Claude Fable, #29/#90.) */ export function createKeeper ({ newID = freshClientID, now = Date.now, window = 500 } = {}) { let entries = [] let since = null return { before (doc, kind) { const t = now() if (kind === 'pm' && since !== null && t - since < window) return doc.clientID = newID(doc) since = kind === 'pm' ? t : null }, keep (doc, update, held) { const last = entries[entries.length - 1] if (held && last && last.replay === held) last.updates.push(update) else entries.push({ updates: [update], replay: held || undefined, at: now() }) }, // take hands the entries over, and starts again. take () { const out = entries entries = [] return out }, get entries () { return entries } } } // inserts says whether an update adds anything. function inserts (u) { return Y.decodeUpdate(u).structs.some(s => !(s instanceof Y.Skip)) } /** * carry puts entries — [{ updates, replay? }], in the order they were * written — onto doc under origin. It returns the updates to post, in * order, and how many entries could not be carried in full. between, when * given, runs before each entry with it and the one before (or undefined): * the editor stops its undo manager capturing where the two were made * further apart than its capture window, so the carried changes undo in * the steps they were made in. * * Every local ProseMirror change made while diverged has a replay, not * only one that waited for its font (Paul: a lost edit is worse than a * flash). Once one change is replayed, the next one's Yjs updates may be * anchored to the original change's items, which never reach the rebuilt * document, so it is replayed in turn; the span is recomputed against the * rebuilt text each time, so what was carried or replayed before is on * both sides of it and only the refused, and what could not be kept, * remain in it. A replay that cannot be made falls back to the change's * own updates, of which what integrates is carried. */ export function carry (doc, entries, origin, between = () => {}) { const post = [] let lost = 0 let previous // copy is the running probe: a copy of doc that each entry's own // updates are tried on first. It follows doc while entries carry whole, // and is made again only after one did not, so carrying is linear. let copy = null for (const entry of entries) { const updates = entry.updates if (!updates.length) continue between(entry, previous) previous = entry if (!copy) { copy = new Y.Doc({ gc: false }) Y.applyUpdate(copy, Y.encodeStateAsUpdate(doc)) } const verdicts = updates.map(u => { Y.applyUpdate(copy, u) return took(copy, u) }) if (verdicts.every(t => t === 'all')) { for (const u of updates) Y.applyUpdate(doc, u, origin) post.push(...updates) continue } copy = null if (entry.replay) { const made = replay(doc, entry.replay, origin) if (made) { post.push(...made) continue } } // Nothing of it would take: leave it out, unapplied, so the rebuilt // document holds nothing pending for it. A delete of only what the // rebuilt document never held (an undo of the refused text alone) // loses nothing. if (verdicts.every(t => t === 'none')) { if (updates.some(inserts)) lost++ continue } lost++ for (const u of updates) { const before = Y.encodeStateVector(doc) Y.applyUpdate(doc, u, origin) const t = took(doc, u) if (t === 'all') post.push(u) else if (t === 'some') post.push(integrated(doc, before)) } } return { post, lost } }