| 1 | // fixtures/carry.mjs — what a resync does with the changes this tab wrote |
| 2 | // while it was diverged (editor-entry.js's attemptResync). Slides has the |
| 3 | // same module (oficina/slides fixtures/carry.mjs); keep the two the same. |
| 4 | // |
| 5 | // A save the server refused leaves the tab with a document the server will |
| 6 | // never have. The resync rebuilds from the server's log; everything this |
| 7 | // person wrote after the refusal was kept as the Y updates it produced |
| 8 | // (createKeeper, below: the tab writes each change under a fresh Yjs |
| 9 | // client id, so each depends only on what it touches, never on a change |
| 10 | // before it that was held back), and each is carried onto the rebuilt |
| 11 | // document here. What becomes of each: |
| 12 | // |
| 13 | // - every part of it integrates: applied, and posted; |
| 14 | // - part of it integrates (a Backspace over the server's words and the |
| 15 | // refused ones together; a paste into marked text, whose update also |
| 16 | // rewrites the formatting around it): applied, and the part that |
| 17 | // integrated is posted — skipping it would leave the page showing what |
| 18 | // the server lacks, and posting all of it would leave the rest pending |
| 19 | // in the server's log forever; |
| 20 | // - none of it integrates (it was written on top of the refused text): |
| 21 | // not posted, since the server would hold it pending in its log |
| 22 | // forever (Claude Fable, #88) — unless it is a ProseMirror change, |
| 23 | // which is replayed instead (below). |
| 24 | // |
| 25 | // Whether a part integrated is read from the update itself |
| 26 | // (Y.decodeUpdate): a struct took when the document's state for its client |
| 27 | // reaches the struct's end. A deleted range can take in part: Yjs deletes |
| 28 | // up to the document's state for its client and holds the rest pending, so |
| 29 | // a range took in part when that state is past its start, and did not |
| 30 | // take in full while the state is short of its end (a Backspace over this |
| 31 | // tab's own saved words and its refused ones together is one range of one |
| 32 | // client; Claude Fable, #28). Y.encodeStateVectorFromUpdate is no |
| 33 | // use here — it names a client only when the update's structs start at its |
| 34 | // clock 0, and a delete-only update has none, so every update after a |
| 35 | // client's first read as taken (Claude Fable, #27 and #88). |
| 36 | // |
| 37 | // The replay. A change made once the save was refused — a paste that |
| 38 | // waited for its font, a keystroke, a delete — lands, in Yjs, against |
| 39 | // whatever was beside it — often the refused text itself, which the server |
| 40 | // never took; its update cannot integrate on the rebuilt document. But the |
| 41 | // ProseMirror transactions that made it are kept (entry.replay.tr: tr.before |
| 42 | // and every step), and so is where it was made (replay.locate, the |
| 43 | // same text on the rebuilt document). The rebuilt text and tr.before differ |
| 44 | // in one span, the refused change; the transaction's steps are mapped |
| 45 | // through that span and applied with maybeStep, and the result is written |
| 46 | // to the rebuilt text with y-prosemirror in one CARRIED transaction, whose |
| 47 | // update is what is posted. ProseMirror checks every step: one that falls |
| 48 | // inside the refused span, or cannot apply there (a paste into a paragraph |
| 49 | // the refused change had made), gives up, and the change is left out, as |
| 50 | // before — nothing posted, the save line already saying a change was not |
| 51 | // saved, the clipboard as it was. Claude Fable's prototype for this kept |
| 52 | // the paste in ten of eleven cases (carry.test.mjs holds them). |
| 53 | // |
| 54 | // The replay runs only when the change's own updates do not all take: a |
| 55 | // change made elsewhere carries as its own Yjs updates, unchanged. |
| 56 | import * as Y from 'yjs' |
| 57 | import { EditorState } from 'prosemirror-state' |
| 58 | import { StepMap, Mapping, ReplaceStep } from 'prosemirror-transform' |
| 59 | import { yXmlFragmentToProseMirrorRootNode, prosemirrorToYXmlFragment } from 'y-prosemirror' |
| 60 | |
| 61 | // took reads, after u was applied to doc, how much of u is in it: 'all', |
| 62 | // 'some' or 'none'. An update with nothing in it is 'all'. |
| 63 | export function took (doc, u) { |
| 64 | const { structs, ds } = Y.decodeUpdate(u) |
| 65 | // The document's state for a client, read from its struct store: no |
| 66 | // state vector is encoded per update, so carrying N updates is linear. |
| 67 | const have = client => Y.getState(doc.store, client) |
| 68 | let yes = 0 |
| 69 | let no = 0 |
| 70 | for (const s of structs) { |
| 71 | if (s instanceof Y.Skip) continue |
| 72 | if (have(s.id.client) >= s.id.clock + s.length) yes++ |
| 73 | else no++ |
| 74 | } |
| 75 | for (const [client, ranges] of ds.clients) { |
| 76 | for (const r of ranges) { |
| 77 | // A range can take in part: Yjs deletes up to the document's state |
| 78 | // for its client and holds the rest pending. |
| 79 | const state = have(client) |
| 80 | if (state > r.clock) yes++ |
| 81 | if (state < r.clock + r.len) no++ |
| 82 | } |
| 83 | } |
| 84 | if (!no) return 'all' |
| 85 | return yes ? 'some' : 'none' |
| 86 | } |
| 87 | |
| 88 | // integrated is what doc gained since the state vector before, without |
| 89 | // anything Yjs holds pending: the structs that integrated, and the delete |
| 90 | // set (whole, as Yjs always sends it; a delete applied twice is one). |
| 91 | // encodeStateAsUpdate appends the pending structs and deletes otherwise, |
| 92 | // so they are set aside for the call. |
| 93 | function integrated (doc, before) { |
| 94 | const { pendingStructs, pendingDs } = doc.store |
| 95 | doc.store.pendingStructs = null |
| 96 | doc.store.pendingDs = null |
| 97 | try { |
| 98 | return Y.encodeStateAsUpdate(doc, before) |
| 99 | } finally { |
| 100 | doc.store.pendingStructs = pendingStructs |
| 101 | doc.store.pendingDs = pendingDs |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | // replaySteps maps tr's steps from tr.before onto doc through the one span |
| 106 | // in which the two differ, and applies them. It returns the new document, |
| 107 | // or null when a step fell inside that span or ProseMirror refused it. |
| 108 | export function replaySteps (tr, doc) { |
| 109 | const before = tr.before |
| 110 | const start = before.content.findDiffStart(doc.content) |
| 111 | let ranges = [] |
| 112 | if (start != null) { |
| 113 | let { a: endA, b: endB } = before.content.findDiffEnd(doc.content) |
| 114 | // The two ends overlap the start when the change repeats what is |
| 115 | // beside it ("helllo" against "hello"); the span is moved past the |
| 116 | // overlap so its sizes still differ by what was added or removed, as |
| 117 | // prosemirror-view's findDiff does. Clamping it to the start instead |
| 118 | // made it empty, and a paste after it landed a letter off (Claude |
| 119 | // Fable, #28). |
| 120 | const over = start - Math.min(endA, endB) |
| 121 | if (over > 0) { |
| 122 | endA += over |
| 123 | endB += over |
| 124 | } |
| 125 | ranges = [start, endA - start, endB - start] |
| 126 | } |
| 127 | // prosemirror-collab's rebaseSteps, with the span in place of the remote |
| 128 | // steps. A step after the first is in the coordinates of the document |
| 129 | // the steps before it made, so each is mapped through the inverses of |
| 130 | // those steps, the span, and their replayed forms, mirrored; mapping |
| 131 | // every step through the one span map put a later step near the span's |
| 132 | // edge off by what the earlier ones had moved, or refused it, and a mark |
| 133 | // made over an insertion lost a letter (Claude Fable, #29). |
| 134 | const steps = tr.steps |
| 135 | const mapping = new Mapping() |
| 136 | for (let i = steps.length - 1; i >= 0; i--) mapping.appendMap(steps[i].getMap().invert()) |
| 137 | mapping.appendMap(new StepMap(ranges)) |
| 138 | const next = EditorState.create({ doc, schema: doc.type.schema }).tr |
| 139 | let mapFrom = steps.length |
| 140 | for (const step of steps) { |
| 141 | const mapped = step.map(mapping.slice(mapFrom)) |
| 142 | mapFrom-- |
| 143 | if (!mapped) return null |
| 144 | if (next.maybeStep(mapped).failed) return null |
| 145 | mapping.appendMap(mapped.getMap()) |
| 146 | mapping.setMirror(mapFrom, mapping.maps.length - 1) |
| 147 | } |
| 148 | return next.doc |
| 149 | } |
| 150 | |
| 151 | /** |
| 152 | * derivedStep is one ReplaceStep that turns before into after, from the |
| 153 | * one span in which they differ (the same overlap rule as replaySteps), or |
| 154 | * null when they are the same. An undo or a redo reaches the editor as |
| 155 | * ySync's mirror of a Yjs change, whose steps replace the whole document; |
| 156 | * this is the change it made, as a step the resync can replay (Claude |
| 157 | * Fable, #29/#90: an undo that put text back — a Backspace undone — was |
| 158 | * lost when that text belonged to a replayed change, because Yjs anchors |
| 159 | * the re-inserted text to the original, which the rebuilt document never |
| 160 | * holds). |
| 161 | */ |
| 162 | export function derivedStep (before, after) { |
| 163 | const start = before.content.findDiffStart(after.content) |
| 164 | if (start == null) return null |
| 165 | let { a: endA, b: endB } = before.content.findDiffEnd(after.content) |
| 166 | const over = start - Math.min(endA, endB) |
| 167 | if (over > 0) { |
| 168 | endA += over |
| 169 | endB += over |
| 170 | } |
| 171 | return new ReplaceStep(start, endA, after.slice(start, endB)) |
| 172 | } |
| 173 | |
| 174 | // replay makes entry's change again on doc's text, in one transaction |
| 175 | // under origin, and returns the updates it produced, or null when it could |
| 176 | // not be made. |
| 177 | function replay (doc, { tr, locate, schema }, origin) { |
| 178 | let fragment = null |
| 179 | try { |
| 180 | fragment = locate(doc) |
| 181 | } catch { |
| 182 | fragment = null |
| 183 | } |
| 184 | if (!fragment) return null |
| 185 | let after = null |
| 186 | try { |
| 187 | after = replaySteps(tr, yXmlFragmentToProseMirrorRootNode(fragment, schema)) |
| 188 | } catch { |
| 189 | after = null |
| 190 | } |
| 191 | if (!after) return null |
| 192 | const out = [] |
| 193 | const grab = u => out.push(u) |
| 194 | doc.on('update', grab) |
| 195 | try { |
| 196 | doc.transact(() => prosemirrorToYXmlFragment(after, fragment), origin) |
| 197 | } finally { |
| 198 | doc.off('update', grab) |
| 199 | } |
| 200 | return out |
| 201 | } |
| 202 | |
| 203 | // freshClientID is a Yjs client id: 32 random bits, as Y.Doc draws its |
| 204 | // own, and never one doc already holds. |
| 205 | export function freshClientID (doc, draw = randomID) { |
| 206 | for (;;) { |
| 207 | const id = draw() |
| 208 | if (!doc || !doc.store.clients.has(id)) return id |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | function randomID () { |
| 213 | const a = new Uint32Array(1) |
| 214 | globalThis.crypto.getRandomValues(a) |
| 215 | return a[0] |
| 216 | } |
| 217 | |
| 218 | /** |
| 219 | * createKeeper keeps what a diverged tab writes, for carry: each update in |
| 220 | * an entry of its own, or — while one change is held (held, its replay) — |
| 221 | * in that change's entry, stamped with when it was made (at), so the |
| 222 | * resync can group the carried changes into undo steps as they were made. |
| 223 | * |
| 224 | * Client ids. Yjs integrates one client's structs in clock order, so under |
| 225 | * one id a change held back on the refused text held back every change |
| 226 | * after it, wherever it was made (Claude Fable, #28). before(doc, kind) is |
| 227 | * called before each transaction: a ProseMirror change ('pm') takes a fresh |
| 228 | * id once per window (500 ms, the undo window) — a held one strands no |
| 229 | * later ProseMirror change, since every one of those has its transaction |
| 230 | * to replay; any other ('other': an undo, a redo, an inspector change, |
| 231 | * which has nothing to replay) takes a fresh id of its own. A fresh id per |
| 232 | * change was quadratic over a long divergence and left a client per |
| 233 | * keystroke in the deck for good (Fable, #29: 4000 changes, 27 s). |
| 234 | * |
| 235 | * Undo and redo. Each is the undo manager's Yjs change, and the editor |
| 236 | * keeps it with a replay derived from ySync's mirror of it (derivedStep), |
| 237 | * so the resync makes it again on the rebuilt document as the person saw |
| 238 | * it — taking text away, or putting it back — whatever ids the change it |
| 239 | * undoes was replayed under. (Marking entries undone by item, as before, |
| 240 | * could not reach text an undo put back, and doubled a type-over's undo |
| 241 | * once the derived replay was in; Claude Fable, #29/#90.) |
| 242 | */ |
| 243 | export function createKeeper ({ newID = freshClientID, now = Date.now, window = 500 } = {}) { |
| 244 | let entries = [] |
| 245 | let since = null |
| 246 | return { |
| 247 | before (doc, kind) { |
| 248 | const t = now() |
| 249 | if (kind === 'pm' && since !== null && t - since < window) return |
| 250 | doc.clientID = newID(doc) |
| 251 | since = kind === 'pm' ? t : null |
| 252 | }, |
| 253 | keep (doc, update, held) { |
| 254 | const last = entries[entries.length - 1] |
| 255 | if (held && last && last.replay === held) last.updates.push(update) |
| 256 | else entries.push({ updates: [update], replay: held || undefined, at: now() }) |
| 257 | }, |
| 258 | // take hands the entries over, and starts again. |
| 259 | take () { |
| 260 | const out = entries |
| 261 | entries = [] |
| 262 | return out |
| 263 | }, |
| 264 | get entries () { return entries } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | // inserts says whether an update adds anything. |
| 269 | function inserts (u) { |
| 270 | return Y.decodeUpdate(u).structs.some(s => !(s instanceof Y.Skip)) |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * carry puts entries — [{ updates, replay? }], in the order they were |
| 275 | * written — onto doc under origin. It returns the updates to post, in |
| 276 | * order, and how many entries could not be carried in full. between, when |
| 277 | * given, runs before each entry with it and the one before (or undefined): |
| 278 | * the editor stops its undo manager capturing where the two were made |
| 279 | * further apart than its capture window, so the carried changes undo in |
| 280 | * the steps they were made in. |
| 281 | * |
| 282 | * Every local ProseMirror change made while diverged has a replay, not |
| 283 | * only one that waited for its font (Paul: a lost edit is worse than a |
| 284 | * flash). Once one change is replayed, the next one's Yjs updates may be |
| 285 | * anchored to the original change's items, which never reach the rebuilt |
| 286 | * document, so it is replayed in turn; the span is recomputed against the |
| 287 | * rebuilt text each time, so what was carried or replayed before is on |
| 288 | * both sides of it and only the refused, and what could not be kept, |
| 289 | * remain in it. A replay that cannot be made falls back to the change's |
| 290 | * own updates, of which what integrates is carried. |
| 291 | */ |
| 292 | export function carry (doc, entries, origin, between = () => {}) { |
| 293 | const post = [] |
| 294 | let lost = 0 |
| 295 | let previous |
| 296 | // copy is the running probe: a copy of doc that each entry's own |
| 297 | // updates are tried on first. It follows doc while entries carry whole, |
| 298 | // and is made again only after one did not, so carrying is linear. |
| 299 | let copy = null |
| 300 | for (const entry of entries) { |
| 301 | const updates = entry.updates |
| 302 | if (!updates.length) continue |
| 303 | between(entry, previous) |
| 304 | previous = entry |
| 305 | if (!copy) { |
| 306 | copy = new Y.Doc({ gc: false }) |
| 307 | Y.applyUpdate(copy, Y.encodeStateAsUpdate(doc)) |
| 308 | } |
| 309 | const verdicts = updates.map(u => { |
| 310 | Y.applyUpdate(copy, u) |
| 311 | return took(copy, u) |
| 312 | }) |
| 313 | if (verdicts.every(t => t === 'all')) { |
| 314 | for (const u of updates) Y.applyUpdate(doc, u, origin) |
| 315 | post.push(...updates) |
| 316 | continue |
| 317 | } |
| 318 | copy = null |
| 319 | if (entry.replay) { |
| 320 | const made = replay(doc, entry.replay, origin) |
| 321 | if (made) { |
| 322 | post.push(...made) |
| 323 | continue |
| 324 | } |
| 325 | } |
| 326 | // Nothing of it would take: leave it out, unapplied, so the rebuilt |
| 327 | // document holds nothing pending for it. A delete of only what the |
| 328 | // rebuilt document never held (an undo of the refused text alone) |
| 329 | // loses nothing. |
| 330 | if (verdicts.every(t => t === 'none')) { |
| 331 | if (updates.some(inserts)) lost++ |
| 332 | continue |
| 333 | } |
| 334 | lost++ |
| 335 | for (const u of updates) { |
| 336 | const before = Y.encodeStateVector(doc) |
| 337 | Y.applyUpdate(doc, u, origin) |
| 338 | const t = took(doc, u) |
| 339 | if (t === 'all') post.push(u) |
| 340 | else if (t === 'some') post.push(integrated(doc, before)) |
| 341 | } |
| 342 | } |
| 343 | return { post, lost } |
| 344 | } |
| 345 | |