// fixtures/carry.test.mjs — what a resync carries onto the rebuilt // document (carry.mjs), with the real Yjs, ProseMirror and y-prosemirror. // // The server holds two paragraphs. The tab made a change the server // refused (client 2), took a fresh client id (3), and then wrote more; the // rebuilt document is the server's, sometimes with a colleague's words that // arrived meanwhile. Claude Fable's probes on #27 and #88: carry-probe.mjs // (which updates took) and pm-replay-probe.mjs (the eleven replay cases). import { test } from 'node:test' import assert from 'node:assert/strict' import * as Y from 'yjs' import { EditorState, TextSelection } from 'prosemirror-state' import { Slice, Fragment } from 'prosemirror-model' import { yXmlFragmentToProseMirrorRootNode, prosemirrorToYXmlFragment } from 'y-prosemirror' import { schema } from './schema.mjs' import { carry, took, createKeeper, freshClientID, replaySteps, derivedStep } from './carry.mjs' const CARRIED = 'carried' const P = schema.nodes.paragraph const mk = (...paras) => schema.nodes.doc.create(null, paras.map(t => P.create(null, t ? schema.text(t) : null))) const paras = doc => { const out = []; doc.forEach(n => out.push(n.textContent)); return out } const frag = d => d.getXmlFragment('t') const pmOf = d => yXmlFragmentToProseMirrorRootNode(frag(d), schema) const endOf = (doc, i) => { let pos = 0; for (let k = 0; k <= i; k++) { if (k === i) return pos + 1 + doc.child(k).content.size; pos += doc.child(k).nodeSize } } const code = schema.marks.code.create() const pasteSlice = new Slice(Fragment.from(P.create(null, [schema.text('REVIEW_RESYNC_PASTE '), schema.text('codeword', [code])])), 1, 1) const twoParas = new Slice(Fragment.from([P.create(null, [schema.text('ONE '), schema.text('c1', [code])]), P.create(null, schema.text('TWO'))]), 1, 1) // write puts pm into d's text as one transaction and returns its updates. function write (d, pm) { const out = [] const grab = u => out.push(u) d.on('update', grab) d.transact(() => prosemirrorToYXmlFragment(pm, frag(d))) d.off('update', grab) return out } // world builds the server, the tab after its refused change, and the // rebuilt document (the server's, with colleague's words when given). function world (refused, colleague) { const server = new Y.Doc(); server.clientID = 1 write(server, mk('First paragraph.', 'Second paragraph.')) const tab = new Y.Doc(); tab.clientID = 2 Y.applyUpdate(tab, Y.encodeStateAsUpdate(server)) write(tab, refused) tab.clientID = 3 if (colleague) { const peer = new Y.Doc(); peer.clientID = 5 Y.applyUpdate(peer, Y.encodeStateAsUpdate(server)) for (const u of write(peer, colleague)) Y.applyUpdate(server, u) } const rebuilt = new Y.Doc(); rebuilt.clientID = 4 Y.applyUpdate(rebuilt, Y.encodeStateAsUpdate(server)) return { server, tab, rebuilt } } // pasteOn makes the paste on the tab as the editor would — a ProseMirror // transaction on its text — and returns the entry the resync keeps. function pasteOn (tab, from, to, slice = pasteSlice) { const before = pmOf(tab) const tr = EditorState.create({ doc: before, schema }).tr tr.setSelection(TextSelection.create(before, from(before), (to || from)(before))).replaceSelection(slice) const updates = write(tab, tr.doc) return { updates, replay: { tr, locate: frag, schema } } } // posted applies what carry would post to a copy of the server: it must // integrate there whole, and give the page's text. function posted (server, post) { const copy = new Y.Doc() Y.applyUpdate(copy, Y.encodeStateAsUpdate(server)) for (const u of post) Y.applyUpdate(copy, u) return copy } const replayCases = [ { name: '(a) the paste right after the refused x (Fable\'s probe)', refused: mk('First paragraph.', 'Second paragraph.x'), at: d => endOf(d, 1), want: ['First paragraph.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword'] }, { name: '(b) the refused x elsewhere, before the paste', refused: mk('First paragraph.x', 'Second paragraph.'), at: d => endOf(d, 1), want: ['First paragraph.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword'] }, { name: '(g) the refused x after the paste point', refused: mk('First paragraph.', 'Second paragraph.x'), at: d => endOf(d, 0), want: ['First paragraph.REVIEW_RESYNC_PASTE codeword', 'Second paragraph.'] }, { name: '(c) two refused x, the paste after the second', refused: mk('First paragraph.x', 'Second paragraph.x'), at: d => endOf(d, 1), want: ['First paragraph.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword'] }, { name: '(i) the refused x mid-paragraph, the paste at its end', refused: mk('First paragraph.', 'Second xparagraph.'), at: d => endOf(d, 1), want: ['First paragraph.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword'] }, { name: '(e) the paste over "paragraph.x"', refused: mk('First paragraph.', 'Second paragraph.x'), at: d => endOf(d, 1) - 11, to: d => endOf(d, 1), want: ['First paragraph.', 'Second REVIEW_RESYNC_PASTE codeword'] }, { name: '(f) a refused deletion elsewhere', refused: mk('First .', 'Second paragraph.'), at: d => endOf(d, 1), want: ['First paragraph.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword'] }, { name: '(h) two paragraphs pasted after the refused x', refused: mk('First paragraph.', 'Second paragraph.x'), at: d => endOf(d, 1), slice: twoParas, want: ['First paragraph.', 'Second paragraph.ONE c1', 'TWO'] }, { name: '(j) a colleague\'s words before, the refused x after', refused: mk('First paragraph.', 'Second paragraph.x'), colleague: mk('First paragraph. More from a colleague.', 'Second paragraph.'), at: d => endOf(d, 1), want: ['First paragraph. More from a colleague.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword'] }, { name: '(k) a colleague appended where the x was refused', refused: mk('First paragraph.', 'Second paragraph.x'), colleague: mk('First paragraph.', 'Second paragraph. Colleague.'), at: d => endOf(d, 1), want: ['First paragraph.', 'Second paragraph. Colleague.REVIEW_RESYNC_PASTE codeword'] } ] for (const c of replayCases) { test(`a paste that waited for its font is kept: ${c.name}`, () => { const { server, tab, rebuilt } = world(c.refused, c.colleague) const entry = pasteOn(tab, c.at, c.to, c.slice) const { post, lost } = carry(rebuilt, [entry], CARRIED) assert.equal(lost, 0) assert.deepEqual(paras(pmOf(rebuilt)), c.want, 'the rebuilt page') assert.equal(rebuilt.store.pendingStructs, null, 'nothing held pending on the page') const there = posted(server, post) assert.deepEqual(paras(pmOf(there)), c.want, 'the server, once it has what was posted') assert.equal(there.store.pendingStructs, null, 'nothing held pending on the server') assert.equal(there.store.pendingDs, null) // The code mark came through. let marked = false pmOf(rebuilt).descendants(n => { if (n.isText && code.isInSet(n.marks)) marked = true }) assert.ok(marked, 'the pasted code is still code') }) } test('a paste into a paragraph the refused change made cannot be kept: nothing is posted, the page is the server\'s', () => { const { server, tab, rebuilt } = world(mk('First paragraph.', 'Second paragraph.', '')) const entry = pasteOn(tab, d => endOf(d, 2)) const { post, lost } = carry(rebuilt, [entry], CARRIED) assert.equal(lost, 1) assert.deepEqual(post, []) assert.deepEqual(paras(pmOf(rebuilt)), paras(pmOf(server))) assert.equal(rebuilt.store.pendingStructs, null, 'its updates were never applied') }) test('a paste made elsewhere carries as its own updates, not a replay', () => { const { tab, rebuilt } = world(mk('First paragraph.x', 'Second paragraph.')) const entry = pasteOn(tab, d => endOf(d, 1)) // Not anchored to the refused x: its own updates integrate. const { post } = carry(rebuilt, [{ ...entry, replay: { ...entry.replay, locate: () => { throw new Error('replayed') } } }], CARRIED) assert.deepEqual(post, entry.updates) }) test('the replay is one change for an undo manager tracking the carried origin', () => { const { tab, rebuilt } = world(mk('First paragraph.', 'Second paragraph.x')) const undo = new Y.UndoManager(frag(rebuilt), { trackedOrigins: new Set([CARRIED]) }) carry(rebuilt, [pasteOn(tab, d => endOf(d, 1))], CARRIED) assert.equal(undo.undoStack.length, 1) undo.undo() assert.deepEqual(paras(pmOf(rebuilt)), ['First paragraph.', 'Second paragraph.']) }) // Which updates took (Claude Fable's carry-probe.mjs). The server holds // "hello"; the tab typed "x" (refused), took a fresh id and wrote more. function textWorld () { const server = new Y.Doc(); server.clientID = 1 server.getText('t').insert(0, 'hello') const tab = new Y.Doc(); tab.clientID = 2 Y.applyUpdate(tab, Y.encodeStateAsUpdate(server)) tab.getText('t').insert(5, 'x') tab.clientID = 3 const unsaved = [] tab.on('update', u => unsaved.push(u)) const rebuilt = new Y.Doc(); rebuilt.clientID = 4 Y.applyUpdate(rebuilt, Y.encodeStateAsUpdate(server)) return { server, tab, rebuilt, unsaved } } const entries = us => us.map(u => ({ updates: [u] })) test('every update written on top of the refused text is held back, not only the first', () => { const { tab, rebuilt, unsaved } = textWorld() tab.getText('t').insert(6, 'a') tab.getText('t').insert(7, 'b') const { post, lost } = carry(rebuilt, entries(unsaved), CARRIED) assert.deepEqual(post, [], 'the second keystroke was posted') assert.equal(lost, 2) }) test('a Backspace over the refused text is held back', () => { const { tab, rebuilt, unsaved } = textWorld() tab.getText('t').delete(5, 1) const { post } = carry(rebuilt, entries(unsaved), CARRIED) assert.deepEqual(post, [], 'a delete-only update over refused text was posted') }) test('of an update that partly took, the part that took is posted, and nothing the server would hold pending', () => { const { server, tab, rebuilt, unsaved } = textWorld() tab.getText('t').delete(3, 3) // "lo" and the refused x together const { post, lost } = carry(rebuilt, entries(unsaved), CARRIED) assert.equal(post.length, 1) assert.equal(lost, 1) assert.equal(rebuilt.getText('t').toString(), 'hel') const there = posted(server, post) assert.equal(there.getText('t').toString(), 'hel') assert.equal(there.store.pendingDs, null, 'the delete of the refused x was posted') }) test('an update that rewrites formatting and writes on top of the refused text posts the formatting, not the words', () => { // What the editor's binding writes for a paste into marked text: the // formatting around the server's words rewritten (it integrates) and // the words after the refused ones (they cannot) in one update. const { server, tab, rebuilt, unsaved } = textWorld() tab.transact(() => { tab.getText('t').format(0, 5, { b: true }) tab.getText('t').insert(6, 'ONTOP') }) const { post } = carry(rebuilt, entries(unsaved), CARRIED) assert.equal(post.length, 1) const there = posted(server, post) assert.equal(there.store.pendingStructs, null, 'the words were posted, to sit pending on the server') assert.deepEqual(there.getText('t').toDelta(), [{ insert: 'hello', attributes: { b: true } }]) }) test('a paste elsewhere is posted and a keystroke after the refused x is not', () => { const { tab, rebuilt, unsaved } = textWorld() tab.getText('t').insert(0, 'PASTE ') tab.getText('t').insert(12, 'a') const { post } = carry(rebuilt, entries(unsaved), CARRIED) assert.deepEqual(post, [unsaved[0]]) assert.equal(rebuilt.getText('t').toString(), 'PASTE hello') }) test('took reads all, some and none from the update itself', () => { const { tab, rebuilt, unsaved } = textWorld() tab.getText('t').insert(0, 'A') tab.getText('t').insert(7, 'B') // after the refused x tab.getText('t').delete(4, 3) // "o", the refused x, and B for (const u of unsaved) Y.applyUpdate(rebuilt, u) assert.deepEqual(unsaved.map(u => took(rebuilt, u)), ['all', 'none', 'some']) }) // Claude Fable's review of #28/#89 (rv-carry-review.test.mjs). test('a Backspace over this tab\'s own saved words and its refused ones together posts the saved part (one delete range, one client)', () => { // The tab (client 2) typed "llo" (saved) and "x" (refused), then deleted // "ox": one range of one client, which Yjs applies up to the doc's state // and holds pending past it. const server = new Y.Doc(); server.clientID = 1 server.getText('t').insert(0, 'he') const tab = new Y.Doc(); tab.clientID = 2 Y.applyUpdate(tab, Y.encodeStateAsUpdate(server)) const saved = []; tab.on('update', u => saved.push(u)) tab.getText('t').insert(2, 'llo') for (const u of saved) Y.applyUpdate(server, u) tab.getText('t').insert(5, 'x') tab.clientID = 3 const unsaved = []; tab.on('update', u => unsaved.push({ updates: [u] })) tab.getText('t').delete(4, 2) const rebuilt = new Y.Doc(); rebuilt.clientID = 4 Y.applyUpdate(rebuilt, Y.encodeStateAsUpdate(server)) const { post } = carry(rebuilt, unsaved, CARRIED) assert.equal(took(rebuilt, unsaved[0].updates[0]), 'some') assert.equal(rebuilt.getText('t').toString(), 'hell') assert.equal(posted(server, post).getText('t').toString(), 'hell', 'the server has what the page shows') }) test('a paste right after a refused repeated letter lands where it was made', () => { // "hell|o" + a refused "l": the paste after that l belongs before the o. const server = new Y.Doc(); server.clientID = 1 write(server, mk('hello world')) const tab = new Y.Doc(); tab.clientID = 2 Y.applyUpdate(tab, Y.encodeStateAsUpdate(server)) write(tab, mk('helllo world')) tab.clientID = 3 const before = pmOf(tab) const tr = EditorState.create({ doc: before, schema }).tr tr.setSelection(TextSelection.create(before, 6)).replaceSelection(new Slice(Fragment.from(P.create(null, schema.text('PASTE'))), 1, 1)) const updates = write(tab, tr.doc) const rebuilt = new Y.Doc(); rebuilt.clientID = 4 Y.applyUpdate(rebuilt, Y.encodeStateAsUpdate(server)) const { post, lost } = carry(rebuilt, [{ updates, replay: { tr, locate: frag, schema } }], CARRIED) assert.equal(lost, 0) assert.deepEqual(paras(pmOf(rebuilt)), ['hellPASTEo world']) assert.deepEqual(paras(pmOf(posted(server, post))), ['hellPASTEo world']) }) // What the editor keeps while diverged goes through a keeper, which gives // the document a fresh client id after every change: Yjs integrates a // client's structs in clock order, so one change held back would // otherwise hold back every later one, wherever it was made. for (const order of ['on the refused text, then elsewhere', 'elsewhere, then on the refused text']) { test(`a change made in a clean spot is not lost with one held back on the refused text (${order})`, () => { const server = new Y.Doc(); server.clientID = 1 server.getText('t').insert(0, 'hello') const tab = new Y.Doc(); tab.clientID = 2 Y.applyUpdate(tab, Y.encodeStateAsUpdate(server)) tab.getText('t').insert(5, 'x') tab.clientID = 3 const keeper = createKeeper() // Raw Yjs edits, as an inspector change or an undo is: each takes a // fresh id before it is made. tab.on('beforeTransaction', () => keeper.before(tab, 'other')) tab.on('update', u => keeper.keep(tab, u)) if (order.startsWith('on')) { tab.getText('t').insert(6, 'a') // on the refused x tab.getText('t').insert(0, 'PASTE ') // elsewhere, afterwards } else { tab.getText('t').insert(0, 'PASTE ') tab.getText('t').insert(12, 'a') } const rebuilt = new Y.Doc(); rebuilt.clientID = 4 Y.applyUpdate(rebuilt, Y.encodeStateAsUpdate(server)) const { post, lost } = carry(rebuilt, keeper.take(), CARRIED) assert.equal(lost, 1) assert.equal(rebuilt.getText('t').toString(), 'PASTE hello', 'the paste elsewhere is on the page') assert.equal(posted(server, post).getText('t').toString(), 'PASTE hello') }) } test('the keeper groups the updates of one held change into one entry, and hands the entries over once', () => { const doc = new Y.Doc() const keeper = createKeeper() const held = { tr: null } doc.on('update', u => keeper.keep(doc, u, held)) doc.getText('t').insert(0, 'a') doc.getText('t').insert(1, 'b') doc.getText('t').insert(2, 'c') assert.equal(keeper.entries.length, 1) assert.equal(keeper.entries[0].updates.length, 3) assert.equal(keeper.entries[0].replay, held) assert.equal(keeper.take().length, 1) assert.deepEqual(keeper.take(), []) }) // The general replay (feat/replay-while-diverged): every local ProseMirror // change made while diverged is kept with its transaction (Claude Fable's // rv-general-probe.mjs). Each runs on the tab under its own client id, as // the keeper gives it. const startOf = (doc, i) => endOf(doc, i) - doc.child(i).content.size const text = s => new Slice(Fragment.from(P.create(null, schema.text(s))), 1, 1) function change (tab, keeper, make) { const before = pmOf(tab) const tr = EditorState.create({ doc: before, schema }).tr make(tr, before) const held = { tr, locate: frag, schema } const grab = u => keeper.keep(tab, u, held) keeper.before(tab, 'pm') tab.on('update', grab) tab.transact(() => prosemirrorToYXmlFragment(tr.doc, frag(tab))) tab.off('update', grab) } test('every change made while diverged is kept, whatever it was written on', () => { const { server, tab, rebuilt } = world(mk('First paragraph.', 'Second paragraph.x')) const keeper = createKeeper() // On the refused x, elsewhere, on the a, across the server's words, the // refused x and the new ones, and elsewhere again. change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 1))).replaceSelection(text('a'))) change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, startOf(d, 0))).replaceSelection(text('ELSEWHERE '))) change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 1))).replaceSelection(text('b'))) change(tab, keeper, (tr, d) => tr.delete(endOf(d, 1) - 13, endOf(d, 1))) change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 0))).replaceSelection(text('c'))) const { post, lost } = carry(rebuilt, keeper.take(), CARRIED) assert.equal(lost, 0) const want = ['ELSEWHERE First paragraph.c', 'Second '] assert.deepEqual(paras(pmOf(rebuilt)), want) const there = posted(server, post) assert.deepEqual(paras(pmOf(there)), want) assert.equal(there.store.pendingStructs, null) assert.equal(there.store.pendingDs, null) }) test('a change that cannot be kept in the middle loses nothing after it', () => { // A refused Enter made a third paragraph; typing inside it cannot be // kept, typing elsewhere afterwards is, and inside again is not. const { server, tab, rebuilt } = world(mk('First paragraph.', 'Second paragraph.', '')) const keeper = createKeeper() change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 2))).replaceSelection(text('INSIDE'))) change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 0))).replaceSelection(text(' after'))) change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 2))).replaceSelection(text('!'))) const { post, lost } = carry(rebuilt, keeper.take(), CARRIED) assert.equal(lost, 2) assert.deepEqual(paras(pmOf(rebuilt)), ['First paragraph. after', 'Second paragraph.']) assert.deepEqual(paras(pmOf(posted(server, post))), ['First paragraph. after', 'Second paragraph.']) assert.equal(rebuilt.store.pendingStructs, null) }) test("a replay that cannot be made falls back to what of the change's own updates integrates", () => { const { server, tab, rebuilt, unsaved } = textWorld() tab.getText('t').delete(3, 3) // "lo" and the refused x together const entries = unsaved.map(u => ({ updates: [u], replay: { tr: null, locate: () => null, schema } })) const { post } = carry(rebuilt, entries, CARRIED) assert.equal(rebuilt.getText('t').toString(), 'hel') assert.equal(posted(server, post).getText('t').toString(), 'hel') }) test('the carried changes undo in the steps they were made in', () => { const { tab, rebuilt } = world(mk('First paragraph.', 'Second paragraph.x')) let clock = 0 const keeper = createKeeper({ now: () => clock }) // "a" and "b" a moment apart; "c" a second later. change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 1))).replaceSelection(text('a'))) clock = 100 change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 1))).replaceSelection(text('b'))) clock = 1100 change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 0))).replaceSelection(text('c'))) const undo = new Y.UndoManager(frag(rebuilt), { trackedOrigins: new Set([CARRIED]), captureTimeout: 500 }) carry(rebuilt, keeper.take(), CARRIED, (e, p) => { if (!p || e.at - p.at >= 500) undo.stopCapturing() }) assert.deepEqual(paras(pmOf(rebuilt)), ['First paragraph.c', 'Second paragraph.ab']) undo.undo() assert.deepEqual(paras(pmOf(rebuilt)), ['First paragraph.', 'Second paragraph.ab'], 'one undo took back more than the last change') undo.undo() assert.deepEqual(paras(pmOf(rebuilt)), ['First paragraph.', 'Second paragraph.'], 'a and b, made a moment apart, are one step') }) // Claude Fable's review of #29/#90 (feat/replay-while-diverged at 72f74b0). // A multi-step transaction: each later step is in the coordinates of the // document the earlier steps made, so it is mapped through their inverses, // the span, and their replayed forms (prosemirror-collab's rebase), not // through the one span map (rv-multistep-probe.mjs). const multi = [ ['an insert, then an insert just before the refused text', 'abcdefghxij', 'abcdefghij', tr => { tr.insertText('ZZZ', 3); tr.insertText('Q', 10) }, ['abZZZcdefQghij']], ['an insert, then a mark over it, the refused text two letters on', 'abcdefxgh', 'abcdefgh', tr => { tr.insertText('ZZZ', 5); tr.addMark(5, 8, code) }, ['abcdZZZefgh']], ['a delete, then an insert past the refused text', 'abcdefghxij', 'abcdefghij', tr => { tr.delete(2, 5); tr.insertText('Q', 8) }, ['aefghiQj']] ] for (const [name, had, rebuiltText, build, want] of multi) { test(`a multi-step change replays each step where it was made: ${name}`, () => { const tr = EditorState.create({ doc: mk(had), schema }).tr build(tr) const got = replaySteps(tr, mk(rebuiltText)) assert.ok(got, 'the replay was refused') assert.deepEqual(paras(got), want) }) } test('a mark made over an insertion in the same change covers all of it', () => { const tr = EditorState.create({ doc: mk('abcdefxgh'), schema }).tr tr.insertText('ZZZ', 5); tr.addMark(5, 8, code) const marked = d => { const out = []; d.descendants(n => { if (n.isText && n.marks.length) out.push(n.text) }); return out.join('|') } assert.equal(marked(replaySteps(tr, mk('abcdefgh'))), 'ZZZ') }) test('a multi-step change on the refused text is replayed where it was made, on the page and the server', () => { const server = new Y.Doc(); server.clientID = 1 write(server, mk('abcdefghij')) const tab = new Y.Doc(); tab.clientID = 2 Y.applyUpdate(tab, Y.encodeStateAsUpdate(server)) write(tab, mk('abcdefghxij')) tab.clientID = 3 const before = pmOf(tab) const tr = EditorState.create({ doc: before, schema }).tr tr.insertText('ZZZ', 3); tr.insertText('Q', 12) // the Q right before the refused x const updates = write(tab, tr.doc) const rebuilt = new Y.Doc(); rebuilt.clientID = 4 Y.applyUpdate(rebuilt, Y.encodeStateAsUpdate(server)) const { post } = carry(rebuilt, [{ updates, replay: { tr, locate: frag, schema } }], CARRIED) assert.deepEqual(paras(pmOf(rebuilt)), ['abZZZcdefghQij']) assert.deepEqual(paras(pmOf(posted(server, post))), ['abZZZcdefghQij']) }) // Undo and redo while diverged (Claude Fable's rv-undo-delete-probe.mjs, // #29/#90). Each is the undo manager's Yjs change; 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, taking text away or // putting it back, whatever ids the change it undoes was replayed under. // The refused x is gone afterwards unless an undo or a redo put it back, // as the person saw. Item matching (watchUndo, before this) lost an undo // that put text back — a Backspace undone — when that text was typed on // the refused x: Yjs anchors the re-inserted text to the original, which // the rebuilt document never holds. function undoWorld (oneStep = false) { const server = new Y.Doc(); server.clientID = 1 write(server, mk('First paragraph.', 'Second paragraph.')) const tab = new Y.Doc(); tab.clientID = 2 Y.applyUpdate(tab, Y.encodeStateAsUpdate(server)) let clock = 0 // The editor's undo manager; the refused x is in its own step unless // oneStep, where the x and what follows are one. const um = new Y.UndoManager(frag(tab), { captureTimeout: oneStep ? 100000 : 0, trackedOrigins: new Set([null]) }) write(tab, mk('First paragraph.', 'Second paragraph.x')) tab.clientID = 3 const keeper = createKeeper({ now: () => clock }) const pm = make => change(tab, keeper, make) // An undo or a redo, kept as the editor keeps it: its update with the // step derived from ySync's mirror (before, and the document after). const other = fn => { keeper.before(tab, 'other') const before = pmOf(tab) const got = [] const grab = u => got.push(u) tab.on('update', grab) fn() tab.off('update', grab) const step = derivedStep(before, pmOf(tab)) const held = step ? { tr: { before, steps: [step] }, locate: frag, schema } : undefined for (const u of got) keeper.keep(tab, u, held) } const resync = () => { const rebuilt = new Y.Doc(); rebuilt.clientID = 4 Y.applyUpdate(rebuilt, Y.encodeStateAsUpdate(server)) const { post, lost } = carry(rebuilt, keeper.take(), CARRIED) assert.equal(rebuilt.store.pendingStructs, null, 'something was left pending on the page') return { page: paras(pmOf(rebuilt)), server: paras(pmOf(posted(server, post))), lost } } return { tab, pm, undo: () => other(() => um.undo()), redo: () => other(() => um.redo()), tick: (ms = 600) => { clock += ms }, resync } } const on1 = (tr, d, back = 0) => tr.setSelection(TextSelection.create(d, endOf(d, 1) - back)) const del1 = n => (tr, d) => tr.delete(endOf(d, 1) - n, endOf(d, 1)) // Each case: what is done, and what the page and the server must hold // afterwards — the tab's own text, the refused x gone unless an undo or a // redo put it back. const undoCases = [ ['A: "abc" on the x; Backspace; undo the Backspace', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('abc'))); w.tick(); w.pm(del1(1)); w.tick(); w.undo() }, 'Second paragraph.abc'], ['B: "a" on the x; select it, type "b"; undo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.pm((tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 1) - 1, endOf(d, 1))).replaceSelection(text('b'))); w.tick(); w.undo() }, 'Second paragraph.a'], ['C: "a" on the x; Backspace; undo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.pm(del1(1)); w.tick(); w.undo() }, 'Second paragraph.a'], ['D: "a" on the x; Backspace; undo; "b" typed', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.pm(del1(1)); w.tick(); w.undo(); w.tick(); w.pm((tr, d) => on1(tr, d).replaceSelection(text('b'))) }, 'Second paragraph.ab'], ['E: "a" on the x; Backspace; undo; redo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.pm(del1(1)); w.tick(); w.undo(); w.redo() }, 'Second paragraph.'], ['F: "a" elsewhere; Backspace; undo', w => { w.pm((tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 0))).replaceSelection(text('a'))); w.tick(); w.pm((tr, d) => tr.delete(endOf(d, 0) - 1, endOf(d, 0))); w.tick(); w.undo() }, 'Second paragraph.', 'First paragraph.a'], ['G: "a" on the x; undo; redo; undo; redo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.undo(); w.redo(); w.undo(); w.redo() }, 'Second paragraph.a'], ['H: "a" on the x; "b"; undo; undo; redo; redo; "c"', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.pm((tr, d) => on1(tr, d).replaceSelection(text('b'))); w.tick(); w.undo(); w.undo(); w.redo(); w.redo(); w.tick(); w.pm((tr, d) => on1(tr, d).replaceSelection(text('c'))) }, 'Second paragraph.abc'], ['I: "a" on the x; Backspace over "xa"; undo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.pm(del1(2)); w.tick(); w.undo() }, 'Second paragraph.xa'], ['J: "a" on the x; Backspace over ".xa"; undo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.pm(del1(3)); w.tick(); w.undo() }, 'Second paragraph.xa'], ['K: the x and "a" one undo step; undo; redo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.undo(); w.redo() }, 'Second paragraph.xa', undefined, true], ['L: "a" on the x; undo; "b"; undo; redo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.undo(); w.tick(); w.pm((tr, d) => on1(tr, d).replaceSelection(text('b'))); w.tick(); w.undo(); w.redo() }, 'Second paragraph.b'], ['M: two words pasted on the x; the first deleted; undo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text(' one two'))); w.tick(); w.pm((tr, d) => tr.delete(endOf(d, 1) - 8, endOf(d, 1) - 4)); w.tick(); w.undo() }, 'Second paragraph. one two'], ['N: "a" on the x; undo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.undo() }, 'Second paragraph.'], ['O: "a" on the x; undo; "b"', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.undo(); w.tick(); w.pm((tr, d) => on1(tr, d).replaceSelection(text('b'))) }, 'Second paragraph.b'], ['P: "a" on the x; "b" elsewhere; undo; undo', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.pm((tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 0))).replaceSelection(text('b'))); w.tick(); w.undo(); w.undo() }, 'Second paragraph.'], ['Q: "a" on the x; undo; redo; "c"', w => { w.pm((tr, d) => on1(tr, d).replaceSelection(text('a'))); w.tick(); w.undo(); w.redo(); w.tick(); w.pm((tr, d) => on1(tr, d).replaceSelection(text('c'))) }, 'Second paragraph.ac'] ] for (const [name, run, second, first = 'First paragraph.', oneStep = false] of undoCases) { test(`an undo or a redo while diverged ends as the person saw it: ${name}`, () => { const w = undoWorld(oneStep) run(w) const want = [first, second] const r = w.resync() assert.deepEqual(r.page, want, 'the page') assert.deepEqual(r.server, want, 'the server') }) } test('an undo of a change saved before the refusal is still carried', () => { const server = new Y.Doc(); server.clientID = 1 write(server, mk('First paragraph.', 'Second paragraph.')) const tab = new Y.Doc(); tab.clientID = 2 Y.applyUpdate(tab, Y.encodeStateAsUpdate(server)) const um = new Y.UndoManager(frag(tab), { captureTimeout: 0, trackedOrigins: new Set([null]) }) // "s" typed and saved, then "x" refused, then the x and the s undone. for (const u of write(tab, mk('First paragraph.s', 'Second paragraph.'))) Y.applyUpdate(server, u) um.stopCapturing() write(tab, mk('First paragraph.s', 'Second paragraph.x')) tab.clientID = 3 const keeper = createKeeper() for (let i = 0; i < 2; i++) { keeper.before(tab, 'other') const before = pmOf(tab) const got = [] const grab = u => got.push(u) tab.on('update', grab) um.undo() tab.off('update', grab) const step = derivedStep(before, pmOf(tab)) for (const u of got) keeper.keep(tab, u, step ? { tr: { before, steps: [step] }, locate: frag, schema } : undefined) } const rebuilt = new Y.Doc(); rebuilt.clientID = 4 Y.applyUpdate(rebuilt, Y.encodeStateAsUpdate(server)) const { post, lost } = carry(rebuilt, keeper.take(), CARRIED) assert.deepEqual(paras(pmOf(rebuilt)), ['First paragraph.', 'Second paragraph.']) assert.deepEqual(paras(pmOf(posted(server, post))), ['First paragraph.', 'Second paragraph.']) assert.equal(lost, 0, 'an undo of only the refused x counted as a loss') }) test('derivedStep turns one document into the other, and is null for the same one', () => { const a = mk('First paragraph.', 'Second paragraph.') const b = mk('First paragraph.', 'Second paragraph.ab') const step = derivedStep(a, b) assert.deepEqual(paras(step.apply(a).doc), paras(b)) assert.equal(derivedStep(a, a), null) // A repeated letter: the overlap rule keeps the step's size right. const c = mk('hello'); const d = mk('helllo') assert.deepEqual(paras(derivedStep(c, d).apply(c).doc), ['helllo']) }) // The cost of a long divergence: ProseMirror changes share one client id // per 500 ms window, and carry reads clocks directly and keeps one running // copy, so it is linear (rv-cost-probe.mjs: 2000 changes took 6.1 s and // 4000 took 27 s, every change leaving a client in the deck for good). function longWorld () { const body = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '.repeat(4) const doc0 = schema.nodes.doc.create(null, Array.from({ length: 60 }, (_, i) => P.create(null, schema.text(`${i} ${body}`)))) const server = new Y.Doc(); server.clientID = 1 write(server, doc0) const tab = new Y.Doc(); tab.clientID = 2 Y.applyUpdate(tab, Y.encodeStateAsUpdate(server)) let d = pmOf(tab) write(tab, EditorState.create({ doc: d, schema }).tr.insertText('x', endOf(d, 59)).doc) tab.clientID = 3 return { server, tab } } // carryTime types n changes (elsewhere, or on the refused text) into a // long document and returns how long carrying them took, with the deck's // client count, checking page and server agree. function carryTime (where, n) { const { server, tab } = longWorld() let clock = 0 const keeper = createKeeper({ now: () => clock }) // Typing straight into the tab's Yjs text, as a keystroke reaches it; // the transaction is kept as the editor keeps it. let pm = pmOf(tab) for (let i = 0; i < n; i++) { clock += 25 const at = where === 'elsewhere' ? endOf(pm, 0) : endOf(pm, 59) const tr = EditorState.create({ doc: pm, schema }).tr.insertText(String.fromCharCode(97 + (i % 26)), at) const held = { tr, locate: frag, schema } keeper.before(tab, 'pm') const grab = u => keeper.keep(tab, u, held) tab.on('update', grab) tab.transact(() => prosemirrorToYXmlFragment(tr.doc, frag(tab))) tab.off('update', grab) pm = tr.doc } const rebuilt = new Y.Doc(); rebuilt.clientID = 4 Y.applyUpdate(rebuilt, Y.encodeStateAsUpdate(server)) const entries = keeper.take() // CPU time, not wall time: a loaded machine stretches the second and // barely the first. const t0 = process.cpuUsage() const { post, lost } = carry(rebuilt, entries, CARRIED) const used = process.cpuUsage(t0) const ms = (used.user + used.system) / 1000 assert.equal(lost, 0) const there = posted(server, post) assert.equal(pmOf(there).textContent, pmOf(rebuilt).textContent) return { ms, clients: new Set(Y.decodeStateVector(Y.encodeStateVector(there)).keys()).size } } // The bound is on growth, not on a time, so a loaded runner does not fail // it: four times the changes may take at most eight times the CPU time // (linear is four; the quadratic version this replaced took about twenty, // 6.1 s for 2000 and 27 s for 4000), with a generous ceiling as well. The // best of three runs of the smaller size and two of the larger is compared, against noise. for (const [where, small, big, ceiling] of [['elsewhere', 1000, 4000, 10000], ['on the refused text', 500, 2000, 20000]]) { test(`carrying grows linearly over a long divergence: changes typed ${where}, ${small} against ${big}, under few client ids`, () => { const a = Math.min(...[0, 1, 2].map(() => carryTime(where, small).ms)) const bigs = [0, 1].map(() => carryTime(where, big)) const b = Math.min(...bigs.map(r => r.ms)) assert.ok(b < Math.max(a, 40) * 8, `${small} changes took ${Math.round(a)} ms of CPU and ${big} took ${Math.round(b)} ms`) assert.ok(b < ceiling, `${big} changes took ${Math.round(b)} ms`) // One id per 500 ms window: changes 25 ms apart, so n / 20 of them. const { clients } = bigs[0] assert.ok(clients <= Math.ceil(big * 25 / 500) + 3, `${clients} client ids in the deck`) }) } test('a client id never collides with one the document already holds', () => { const doc = new Y.Doc(); doc.clientID = 7 doc.getText('t').insert(0, 'a') const draws = [7, 7, 9] assert.equal(freshClientID(doc, () => draws.shift()), 9) }) test('ProseMirror changes inside one window share an id; one held back there does not strand the next', () => { const { server, tab, rebuilt } = world(mk('First paragraph.', 'Second paragraph.x')) let clock = 0 const keeper = createKeeper({ now: () => clock }) change(tab, keeper, (tr, d) => on1(tr, d).replaceSelection(text('a'))) // on the refused x const first = tab.clientID clock += 100 change(tab, keeper, (tr, d) => tr.setSelection(TextSelection.create(d, endOf(d, 0))).replaceSelection(text('c'))) // elsewhere assert.equal(tab.clientID, first, 'two changes in one window took two ids') const { post, lost } = carry(rebuilt, keeper.take(), CARRIED) assert.equal(lost, 0) const want = ['First paragraph.c', 'Second paragraph.a'] assert.deepEqual(paras(pmOf(rebuilt)), want) assert.deepEqual(paras(pmOf(posted(server, post))), want) })