// revertible — undo for a Yjs document, on Yjs's public API: the shell. // // It keeps a draft of each local transaction as it happens (from `prepare`, // `afterBatch` and the event bridge), builds the record in normal form when // the transaction ends (`./normal.js`), and plans a revert of one: gather // what it names from the document, plan purely (`./plan.js`); applied, the // plan is one authored batch, and what the restores landed with is read // back. Two records compose through the normal form. The record is // `./record.js`, capture `./capture.js`, and what is read of the Y.Doc // `./document.js`, whose Yjs calls `yjs-surface.test.ts` pins. // // Where a transaction's record goes is the transaction's own `capture`, // given when the substrate opens it: a sink (a revert's redo), nowhere (a // revert's annotation), or commit listeners. A transaction nothing wants is // not drafted. // // A draft holds only what undo records. An authored op is split as // `partitionOps` splits it, a direct write's ops are partitioned, and a text // event is read only at a recorded path, so a write to an unrecorded log is // in no record, and a transaction that wrote only logs makes none. import { applicablePlan, type BatchOutcome, type Capture, type ChangeBase, findOpaqueBoundary, footprintOf, freezeTree, howMuchStands, isReplaceChange, isRichTextChange, isSequenceChange, isTextChange, isUnrecordedPath, type Op, type Owned, type Path, partitionOps, pathSchema, type Revertible, type RevertibleCommit, type RevertPlan, type RichTextSpan, type SchemaBinding, type Schema as SchemaNode, type StateCell, sequenceChange, trustAsOwned, type WritableContext, } from "@kyneta/schema" import * as Y from "yjs" import { yjsPathToKynetaPath } from "../change-mapping.js" import { charMarks, type Draft, deletedItems, itemOf, kindAt, markWrites, nestedIds, newDraft, type Stage, textChanges, valueWrites, } from "./capture.js" import { clockOf, destabilize, gapAfter, idAt, locate, stabilize, type Tree, typeAt, } from "./document.js" import { composeYjsRecords, normalizeYjsRecord } from "./normal.js" import { contentLength, type GatheredContainer, type Landed, type Located, planYjsRevert, recoveredYjsRedo, remapOfLanded, type YjsGathered, type YjsPlan, } from "./plan.js" import { codec, expandRuns, type Id, type IdRun, idKey, isEmpty, type NestedIds, positionalPath, rewriteYjsRecord, type Slot, type StablePath, samePath, toRuns, type YjsRecord, } from "./record.js" // --------------------------------------------------------------------------- // The shell // --------------------------------------------------------------------------- export interface YjsRevertibleHost { /** The document, read through the substrate's slot: it throws * `DocumentClosedError` once the substrate is disposed. */ readonly doc: Y.Doc readonly rootMap: Y.Map readonly schema: SchemaNode readonly binding: SchemaBinding | undefined readonly shadow: StateCell context(): WritableContext } /** A Yjs substrate's undo, plus the hooks the substrate calls. */ export interface YjsRevertible extends Revertible { /** Whether anything wants `transaction`'s record: hooks do nothing for a * transaction nothing wants. */ recording(transaction: Y.Transaction): boolean /** An authored transaction opened, with where its record goes. */ opened(transaction: Y.Transaction, capture: Capture | undefined): void /** An authored op, before it applies. */ preparing(path: Path, change: ChangeBase): void /** The authored op `preparing` saw, after it applied. */ prepared(path: Path, change: ChangeBase): void /** An authored batch ended. */ ended(outcome: BatchOutcome): void /** Stop listening to the document. The substrate calls it as it is * disposed, while the document is still there to stop listening to. */ dispose(): void /** Events on the root map, for any transaction, before the bridge syncs σ. */ observed( events: Y.YEvent[], transaction: Y.Transaction, ops: readonly Op[] | null, ): void } export function createYjsRevertible(host: YjsRevertibleHost): YjsRevertible { const tree: Tree = host const listeners = new Set<(commit: RevertibleCommit) => void>() const drafts = new Map() let authored: Y.Transaction | undefined // Each authored transaction's capture, until it ends. const captures = new Map() const recording = (tr: Y.Transaction): boolean => { const capture = captures.get(tr) if (capture === undefined) return listeners.size > 0 return capture !== "none" } const draftFor = (tr: Y.Transaction): Draft => { let draft = drafts.get(tr) if (draft === undefined) { draft = newDraft() drafts.set(tr, draft) } return draft } // The ops of each transaction, for grouping. const draftOps = new Map() const afterTransaction = (tr: Y.Transaction): void => { const capture = captures.get(tr) captures.delete(tr) const draft = drafts.get(tr) if (draft === undefined) return drafts.delete(tr) const ops = draftOps.get(tr) ?? [] draftOps.delete(tr) if (!tr.local || draft.aborted) return const made: YjsRecord = { inserted: draft.inserted, deleted: draft.deleted, values: draft.values, marks: draft.marks, } // A transaction that wrote nothing undo records is not a commit; one // whose writes cancel out is, and its record names nothing. if (isEmpty(made)) return const record = normalizeYjsRecord(made) if (capture !== undefined && capture !== "none") { capture.sink(record) return } // `ops` are the recorded ops already (`ended`, `observed`). const footprint = footprintOf(host.schema, ops) for (const listener of [...listeners]) { listener({ record, ops, footprint }) } } host.doc.on("afterTransaction", afterTransaction) // The client's clock before the authored op `prepared` will see. let clockBefore = 0 /** * What an op wrote, read against `pre`, σ at its path before it: its * values, the list runs it deleted, and its marks. */ function capture( draft: Draft, path: Path, change: ChangeBase, pre: unknown, stage: Stage, ): void { for (const w of valueWrites(tree, path, change, pre)) { const at = stabilize(tree, w.path) if (at !== null) { draft.values.push({ path: at, wrote: w.wrote, previous: w.previous }) } } const stable = stabilize(tree, path) if (stable === null) return const target = typeAt(tree, path) if (isSequenceChange(change) && target instanceof Y.Array) { draft.deleted.push( ...deletedItems( tree, stable, path, change, (pre ?? []) as unknown[], target, stage, ), ) } if (isRichTextChange(change) && target instanceof Y.Text) { draft.marks.push( ...markWrites(stable, change, (pre ?? []) as RichTextSpan[], stage, i => idAt(target, i), ), ) } } /** * `change` at `path` as Yjs stores it. A replace at a list index (`.set` on * a list item) deletes the item and inserts a new one * (`applyReplaceChange`), so it is gathered as that sequence change on the * list: the old item's run, and the new item's id. A replace inside a * `.json()` value, and any other change, is stored as written. */ function asStored( path: Path, change: ChangeBase, ): { path: Path; change: ChangeBase } { if (!isReplaceChange(change)) return { path, change } const last = path.segments.at(-1) if (last?.role !== "index") return { path, change } if (findOpaqueBoundary(tree.schema, path, tree.binding) !== null) { return { path, change } } const list = path.slice(0, path.segments.length - 1) if (!(typeAt(tree, list) instanceof Y.Array)) return { path, change } const index = last.resolve() as number return { path: list, change: sequenceChange>([ ...(index > 0 ? [{ retain: index }] : []), { delete: 1 }, // A replace's value is owned already (`ref/write.ts`). { insert: [trustAsOwned(change.value)] }, ]), } } /** What an authored op at `path` wrote over, read before it applies. */ function gatherBefore(draft: Draft, path: Path, change: ChangeBase): void { // Inside a `.json()` value the whole value is one register, written // as a whole when the batch ends: record it as one value. const boundary = findOpaqueBoundary(tree.schema, path, tree.binding) if (boundary !== null) { const at = path.slice(0, boundary.prefixLength + 1) const stableAt = stabilize(tree, at) if (stableAt === null) return const key = JSON.stringify(stableAt) if (!draft.boundaries.has(key)) { draft.boundaries.set(key, { path: stableAt, at, previous: readSlot(at), }) } return } const pre = shadowAt(path) if (isRichTextChange(change)) { const stable = stabilize(tree, path) const key = JSON.stringify(stable) if (stable !== null && !draft.texts.has(key)) { draft.texts.set(key, (pre ?? []) as RichTextSpan[]) } } // Capture reads coordinates as they are now, and derives paths below // `path`: by coordinate, since `path` is live only as far as refs were // made, and deriving a live path would create coordinates. capture(draft, path.toRaw(), change, pre, "before") } const revertible: YjsRevertible = { recording, opened(transaction, capture) { authored = transaction if (capture !== undefined) captures.set(transaction, capture) }, preparing(path, change) { if (authored === undefined || !recording(authored)) return clockBefore = clockOf(host.doc, host.doc.clientID) const draft = draftFor(authored) const { recorded } = partitionOps(tree.schema, [ { path: path.toRaw(), change }, ]) for (const part of recorded) { // An op that is not split keeps its live path. const at = part.change === change ? path : part.path const stored = asStored(at, part.change) gatherBefore(draft, stored.path, stored.change) } }, prepared(written, writtenChange) { if (authored === undefined || !recording(authored)) return // Only a root op is split, and a root op inserts nothing positional. if (isUnrecordedPath(tree.schema, written)) return const { path, change } = asStored(written, writtenChange) const positional = isTextChange(change) || isSequenceChange(change) || isRichTextChange(change) if (!positional || !change.instructions.some(i => "insert" in i)) return const stable = stabilize(tree, path) if (stable === null) return let ids: IdRun[] if (isRichTextChange(change) || isSequenceChange(change)) { // Read the units at the indices the change inserted: a rich text's // marks are format items of their own, which an undo must leave for // the mark rule, and a list item's content has ids of its own, which // the item's id stands for. const type = typeAt(tree, path) if (!(type instanceof Y.Text || type instanceof Y.Array)) return const units: Id[] = [] let target = 0 for (const op of change.instructions) { if ("insert" in op) { for (let k = 0; k < op.insert.length; k++) { const id = idAt(type, target + k) if (id !== null) units.push(id) } target += op.insert.length } else if ("retain" in op) target += op.retain else if ("format" in op) target += op.format } ids = toRuns(units) } else { const clockAfter = clockOf(host.doc, host.doc.clientID) if (clockAfter === clockBefore) return ids = [ { client: host.doc.clientID, clock: clockBefore, length: clockAfter - clockBefore, }, ] } if (ids.length > 0) { draftFor(authored).inserted.push({ container: stable, ids }) } }, ended(outcome) { if (authored === undefined) return const draft = drafts.get(authored) const transaction = authored authored = undefined if (draft === undefined) return if (outcome.aborted) { draft.aborted = true return } draftOps.set(transaction, partitionOps(tree.schema, outcome.ops).recorded) for (const { path, at, previous } of draft.boundaries.values()) { draft.values.push({ path, wrote: readSlot(at), previous }) } }, observed(events, transaction, ops) { if (!transaction.local || !recording(transaction)) return const draft = draftFor(transaction) // What happened to texts: deletions for authored and direct writes // alike, insertions for direct writes (an authored insert is known // from the clock around it). for (const event of events) { const target = event.target if (!(target instanceof Y.Text)) continue const path = pathOf(event) // For authored and direct transactions alike: an authored one's text // deletions are read only from its events. if (path === null || isUnrecordedPath(tree.schema, path)) continue const stable = stabilize(tree, path) if (stable === null) continue // σ still holds a direct write's before-state here; an authored // batch noted it as it began. const before = kindAt(tree, path) !== "richtext" ? null : (draft.texts.get(JSON.stringify(stable)) ?? ((shadowAt(path) ?? []) as RichTextSpan[])) const { deleted, inserted } = textChanges( host.doc, target, stable, transaction, before, ) draft.deleted.push(...deleted) if (ops !== null && inserted.length > 0) { draft.inserted.push({ container: stable, ids: inserted }) } } if (ops === null) return // The rest of a direct write: what `prepare` gathers for an authored // op, read after the write, with σ still before it. const recorded = partitionOps(tree.schema, ops).recorded draftOps.set(transaction, recorded) for (const event of events) { const target = event.target if (!(target instanceof Y.Array)) continue const path = pathOf(event) if (path === null || isUnrecordedPath(tree.schema, path)) continue const stable = stabilize(tree, path) if (stable === null) continue const ids: Id[] = [] for (const item of event.changes.added) { for (let k = 0; k < item.length; k++) { ids.push({ client: item.id.client, clock: item.id.clock + k }) } } ids.sort((a, b) => a.client - b.client || a.clock - b.clock) if (ids.length > 0) { draft.inserted.push({ container: stable, ids: toRuns(ids) }) } } for (const op of recorded) { capture(draft, op.path, op.change, shadowAt(op.path), "after") } }, subscribeCommits(listener) { listeners.add(listener) return () => { listeners.delete(listener) } }, plan(record): RevertPlan { const plan = planYjsRevert(record, gather(record)) const { tally } = plan if (howMuchStands(tally) === "none") return { tally, apply: undefined } const ctx = host.context() return applicablePlan(ctx, { tally, record, revert(options) { if (plan.ops.length === 0) return "nothing" ctx.runBatch(() => { for (const { path, change } of plan.ops) { ctx.dispatch(path, change) } }, options) return remapOfLanded(landed(plan)) }, }) }, compose: composeYjsRecords, recovered(record, position) { const from = decodePosition(position) const now = clockOf(host.doc, from.client) const fresh: IdRun[] = now > from.clock ? [ { client: from.client, clock: from.clock, length: now - from.clock, }, ] : [] // The revert's insertions are the fresh ids each restored container // holds: the annotation's, map values' and delete-clock ticks' ids lie // elsewhere. const deletedNow = Y.snapshot(host.doc).ds const located: Located[] = [] for (const run of record.deleted) { if (located.some(l => samePath(l.container, run.container))) continue const path = destabilize(tree, run.container, deletedNow) const type = path === null ? undefined : typeAt(tree, path) located.push({ container: run.container, ids: type === undefined ? [] : aliveIn(host.doc, type, fresh, deletedNow).map(u => u.id), }) } return recoveredYjsRedo(record, located) }, rewrite: rewriteYjsRecord, position() { return encodePosition({ client: host.doc.clientID, clock: clockOf(host.doc, host.doc.clientID), }) }, authoredSince(position) { const from = decodePosition(position) return clockOf(host.doc, from.client) > from.clock }, codec, dispose() { host.doc.off("afterTransaction", afterTransaction) listeners.clear() drafts.clear() draftOps.clear() }, } function pathOf(event: Y.YEvent): Path | null { try { return yjsPathToKynetaPath(event.path, tree.schema, tree.binding) } catch { return null } } /** Read what `record` names as the document holds it now. */ function gather(record: YjsRecord): YjsGathered { const deletedNow = Y.snapshot(host.doc).ds const alive = (id: Id) => isAlive(deletedNow, id) const containers = new Map() /** A container's key, noting its kind and length, or null if gone. */ const container = (stable: StablePath): string | null => { const path = destabilize(tree, stable, deletedNow) if (path === null) return null if (!containers.has(path.key)) { const kind = kindAt(tree, path) const current = shadowAt(path) const length = kind === "text" ? String(current ?? "").length : kind === "richtext" ? ((current ?? []) as RichTextSpan[]).reduce( (n, span) => n + span.text.length, 0, ) : ((current ?? []) as unknown[]).length const spans = kind === "richtext" ? (current as RichTextSpan[]) : [] containers.set(path.key, { path, kind, length, marks: charMarks(spans ?? []), }) } return path.key } /** Where each id still alive in the container sits. */ const indices = (key: string | null, ids: readonly IdRun[]) => { const at = key === null ? undefined : containers.get(key) if (at === undefined) return [] return aliveIn(host.doc, typeAt(tree, at.path), ids, deletedNow) } return { containers, inserted: record.inserted.map(run => { const key = container(run.container) return { container: key, indices: indices(key, run.ids).map(u => u.index), } }), deleted: record.deleted.map(run => ({ container: container(run.container), back: [...expandRuns(run.ids)].some(alive), gap: gapAfter(host.doc, run.after), })), marks: record.marks.map(mark => { const key = container(mark.container) return { container: key, indices: indices(key, mark.ids).map(u => u.index), } }), values: record.values.map(write => { const path = destabilize(tree, write.path, deletedNow) return { path, current: path === null ? null : readSlot(path) } }), } } /** What the revert gave each run it restored, read where it landed. */ function landed(plan: YjsPlan): Landed[] { return plan.placed.map(({ container, run, at }) => { const type = typeAt(tree, container) const fresh: Id[] = [] if (type instanceof Y.Text || type instanceof Y.Array) { for (let k = 0; k < contentLength(run.content); k++) { const id = idAt(type, at + k) if (id !== null) fresh.push(id) } } const itemSchema = type instanceof Y.Array ? itemOf(pathSchema(tree.schema, container, tree.binding)) : undefined // Each text and list inside a restored item, paired with the one the // record named by where it sits among the item's containers. const nested: Landed["nested"][number][] = [] if (itemSchema !== undefined) { const items = new Set(run.nested.map(n => n.item)) for (const item of items) { const was = run.nested.filter(n => n.item === item) const now: NestedIds[] = nestedIds( tree, container.item(at + item), itemSchema, ).map(n => ({ item, ...n })) for (const n of was) { const where = positionalPath(was, n.path) const fresh = now.find(m => positionalPath(now, m.path) === where) nested.push({ nested: n, ids: fresh?.ids ?? [] }) } } } return { run, fresh, nested } }) } /** * σ at `path`, frozen. A draft keeps what it reads until the transaction * ends, and the batch goes on writing σ meanwhile: a write changes an * unfrozen node in place, and copies a frozen one (`applyChange`). */ function shadowAt(path: Path): unknown { return freezeTree(path.read(host.shadow.current)) } function readSlot(path: Path): Slot { const segments = path.segments const last = segments.at(-1) if (last === undefined) return { value: shadowAt(path) } const parent = path.slice(0, segments.length - 1).read(host.shadow.current) const key = last.resolve() if (parent === null || typeof parent !== "object") return null return Object.hasOwn(parent as object, key as string) ? { value: freezeTree((parent as Record)[key as string]), } : null } return revertible } type DeleteSet = ReturnType["ds"] function isAlive(deleted: DeleteSet, id: Id): boolean { return !Y.isDeleted(deleted, Y.createID(id.client, id.clock)) } /** The ids of `ids` alive and sitting in `type` now, with their indices, in * the order given. */ function aliveIn( doc: Y.Doc, type: unknown, ids: readonly IdRun[], deleted: DeleteSet, ): { id: Id; index: number }[] { const out: { id: Id; index: number }[] = [] for (const id of expandRuns(ids)) { if (!isAlive(deleted, id)) continue const where = locate(doc, id) if (where !== null && where.type === type) { out.push({ id, index: where.index }) } } return out } function encodePosition(position: Id): Uint8Array { return new TextEncoder().encode(idKey(position)) } function decodePosition(bytes: Uint8Array): Id { const [client, clock] = new TextDecoder().decode(bytes).split(":").map(Number) return { client, clock } }