foldkit-richtext 0.5.3 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clipboard.d.ts +224 -0
- package/dist/clipboard.d.ts.map +1 -0
- package/dist/clipboard.js +208 -0
- package/dist/clipboard.js.map +1 -0
- package/dist/code.d.ts +27 -0
- package/dist/code.d.ts.map +1 -0
- package/dist/code.js +45 -0
- package/dist/code.js.map +1 -0
- package/dist/command.d.ts +300 -0
- package/dist/command.d.ts.map +1 -0
- package/dist/command.js +1438 -0
- package/dist/command.js.map +1 -0
- package/dist/decoration.d.ts +44 -0
- package/dist/decoration.d.ts.map +1 -0
- package/dist/decoration.js +96 -0
- package/dist/decoration.js.map +1 -0
- package/dist/document.d.ts +1045 -0
- package/dist/document.d.ts.map +1 -0
- package/dist/document.js +544 -0
- package/dist/document.js.map +1 -0
- package/dist/footnote.d.ts +35 -0
- package/dist/footnote.d.ts.map +1 -0
- package/dist/footnote.js +100 -0
- package/dist/footnote.js.map +1 -0
- package/dist/history.d.ts +470 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +81 -0
- package/dist/history.js.map +1 -0
- package/dist/html.d.ts +27 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +99 -0
- package/dist/html.js.map +1 -0
- package/dist/indent.d.ts +16 -0
- package/dist/indent.d.ts.map +1 -0
- package/dist/indent.js +101 -0
- package/dist/indent.js.map +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +24 -0
- package/dist/input.d.ts +54 -0
- package/dist/input.d.ts.map +1 -0
- package/dist/input.js +37 -0
- package/dist/input.js.map +1 -0
- package/dist/kit.d.ts +179 -0
- package/dist/kit.d.ts.map +1 -0
- package/dist/kit.js +202 -0
- package/dist/kit.js.map +1 -0
- package/dist/marks.d.ts +79 -0
- package/dist/marks.d.ts.map +1 -0
- package/dist/marks.js +127 -0
- package/dist/marks.js.map +1 -0
- package/dist/media.d.ts +30 -0
- package/dist/media.d.ts.map +1 -0
- package/dist/media.js +148 -0
- package/dist/media.js.map +1 -0
- package/dist/migration.d.ts +55 -0
- package/dist/migration.d.ts.map +1 -0
- package/dist/migration.js +124 -0
- package/dist/migration.js.map +1 -0
- package/dist/outline.d.ts +15 -0
- package/dist/outline.d.ts.map +1 -0
- package/dist/outline.js +39 -0
- package/dist/outline.js.map +1 -0
- package/dist/rendering.d.ts +96 -0
- package/dist/rendering.d.ts.map +1 -0
- package/dist/rendering.js +106 -0
- package/dist/rendering.js.map +1 -0
- package/dist/replicated.d.ts +340 -0
- package/dist/replicated.d.ts.map +1 -0
- package/dist/replicated.js +1727 -0
- package/dist/replicated.js.map +1 -0
- package/dist/search.d.ts +28 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +61 -0
- package/dist/search.js.map +1 -0
- package/dist/standard.d.ts +61 -0
- package/dist/standard.d.ts.map +1 -0
- package/dist/standard.js +231 -0
- package/dist/standard.js.map +1 -0
- package/dist/table.d.ts +38 -0
- package/dist/table.d.ts.map +1 -0
- package/dist/table.js +160 -0
- package/dist/table.js.map +1 -0
- package/dist/transaction.d.ts +712 -0
- package/dist/transaction.d.ts.map +1 -0
- package/dist/transaction.js +993 -0
- package/dist/transaction.js.map +1 -0
- package/dist/transform.d.ts +48 -0
- package/dist/transform.d.ts.map +1 -0
- package/dist/transform.js +94 -0
- package/dist/transform.js.map +1 -0
- package/dist/url.d.ts +16 -0
- package/dist/url.d.ts.map +1 -0
- package/dist/url.js +32 -0
- package/dist/url.js.map +1 -0
- package/package.json +7 -7
- package/dist/index.d.mts +0 -3787
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -6688
- package/dist/index.mjs.map +0 -1
- package/dist/rolldown-runtime-D8jQpDG7.mjs +0 -12
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"replicated.js","names":["markName","locateRun"],"sources":["../src/replicated.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport {\n nodeIndex,\n NodeId,\n RunMark,\n type Block,\n type Document,\n type Position,\n type Selection,\n type Text,\n} from './document.js'\nimport { markName, sameMark, sameMarkSet } from './marks.js'\nimport { apply, RetypeTarget, type Operation, type TransactionResult } from './transaction.js'\n\n/**\n * A document shared by several replicas, where every character has an identity that\n * outlives the edits around it.\n *\n * The editor keeps working on a plain `Document`: `project` derives one from this state.\n * An edit runs as an ordinary command against that projection, `translate` restates the\n * transactions it applied as `ReplicatedOp`s that name characters and blocks rather than\n * offsets and indices, and `applyOps` folds those ops into the state. Replicas converge\n * because a server gives every op one order and `applyOps` is a deterministic, total\n * function of the state and the ops: it never throws.\n */\n\n/**\n * An identity this state minted: segments joined by `:`, at least two of them. The colon\n * keeps an id from ever naming an `Object.prototype` key, which is why the block record is\n * indexed directly, and the absent `.` is what separates an id from a character reference\n * built on it.\n */\nexport const ReplicatedId = Schema.String.check(\n Schema.isPattern(/^[A-Za-z0-9_-]+(?::[A-Za-z0-9_-]+)+$/),\n).pipe(Schema.brand('foldkit-richtext/ReplicatedId'))\nexport type ReplicatedId = typeof ReplicatedId.Type\n\n/** A character: the insert that created it, and its index within that insert's text. */\nexport const CharRef = Schema.String.check(\n Schema.isPattern(/^[A-Za-z0-9_-]+(?::[A-Za-z0-9_-]+)+\\.(?:0|[1-9][0-9]*)$/),\n).pipe(Schema.brand('foldkit-richtext/CharRef'))\nexport type CharRef = typeof CharRef.Type\n\nconst Index = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\n/** Characters `from` up to, not including, `to` of one insert. */\nexport const CharRange = Schema.Struct({ id: ReplicatedId, from: Index, to: Index })\nexport type CharRange = typeof CharRange.Type\n\n/** What a block is, apart from its content and place. */\nexport const BlockShape = Schema.Union([\n Schema.Struct({ type: Schema.Literal('Paragraph') }),\n Schema.Struct({ type: Schema.Literal('Heading'), level: Schema.Literals([1, 2, 3, 4, 5, 6]) }),\n Schema.Struct({\n type: Schema.Literal('Node'),\n kind: Schema.NonEmptyString,\n props: Schema.JsonObject,\n /** What the node holds: runs, nested blocks, or nothing (an atom such as an image). */\n holds: Schema.Literals(['text', 'blocks', 'none']),\n }),\n Schema.Struct({\n type: Schema.Literal('Unknown'),\n originalType: Schema.NonEmptyString,\n props: Schema.JsonObject,\n }),\n])\nexport type BlockShape = typeof BlockShape.Type\n\n/** A stretch of one insert's characters with one mark set, visible or deleted. */\nconst Span = Schema.Struct({\n id: ReplicatedId,\n offset: Index,\n text: Schema.NonEmptyString,\n marks: Schema.Array(RunMark),\n deleted: Schema.Boolean,\n /** Deleted when a `Collect` ran, so the next one removes it. */\n swept: Schema.optionalKey(Schema.Boolean),\n /**\n * The last character of a collected stretch, kept only so its insert's indexes are never\n * reused. It is never shown again, not even by an undo.\n */\n kept: Schema.optionalKey(Schema.Literal(true)),\n})\ntype Span = typeof Span.Type\n\nconst Entry = Schema.Struct({\n shape: BlockShape,\n parent: Schema.NullOr(ReplicatedId),\n spans: Schema.Array(Span),\n /** Nested blocks in order, deleted ones included, so a sibling anchor still resolves. */\n children: Schema.Array(ReplicatedId),\n deleted: Schema.Boolean,\n /** Deleted when a `Collect` ran, so the next one removes the text it holds. */\n swept: Schema.optionalKey(Schema.Boolean),\n /** Where a joined block's start now is: after this character of `into`, or its start. */\n joined: Schema.optionalKey(Schema.Struct({ into: ReplicatedId, after: Schema.NullOr(CharRef) })),\n})\ntype Entry = typeof Entry.Type\n\nexport const ReplicatedState = Schema.Struct({\n version: Schema.Literal(1),\n root: Schema.Array(ReplicatedId),\n blocks: Schema.Record(ReplicatedId, Entry),\n})\nexport type ReplicatedState = typeof ReplicatedState.Type\n\n/**\n * One change, naming what it touches by identity. Inserts and splits anchor after a\n * character, or at a block's start when `after` is null; block ops anchor after a sibling,\n * or at the start of the container when `after` is null.\n */\nexport const ReplicatedOp = Schema.Union([\n Schema.Struct({\n type: Schema.Literal('Insert'),\n id: ReplicatedId,\n /** The block the anchor was in when the op was made: where a lost anchor falls back to. */\n block: ReplicatedId,\n after: Schema.NullOr(CharRef),\n text: Schema.NonEmptyString,\n marks: Schema.Array(RunMark),\n /**\n * The index of its first character, when it continues an insert of the same id rather\n * than starting one: `id.from` onwards. Absent means 0.\n */\n from: Schema.optionalKey(Index),\n }),\n Schema.Struct({ type: Schema.Literal('Delete'), ranges: Schema.Array(CharRange) }),\n Schema.Struct({ type: Schema.Literal('Mark'), ranges: Schema.Array(CharRange), mark: RunMark }),\n Schema.Struct({\n type: Schema.Literal('Unmark'),\n ranges: Schema.Array(CharRange),\n name: Schema.NonEmptyString,\n }),\n Schema.Struct({\n type: Schema.Literal('InsertBlock'),\n id: ReplicatedId,\n shape: BlockShape,\n parent: Schema.NullOr(ReplicatedId),\n after: Schema.NullOr(ReplicatedId),\n }),\n Schema.Struct({ type: Schema.Literal('DeleteBlock'), id: ReplicatedId }),\n Schema.Struct({\n type: Schema.Literal('MoveBlock'),\n id: ReplicatedId,\n parent: Schema.NullOr(ReplicatedId),\n after: Schema.NullOr(ReplicatedId),\n }),\n Schema.Struct({\n type: Schema.Literal('Split'),\n block: ReplicatedId,\n after: Schema.NullOr(CharRef),\n into: ReplicatedId,\n }),\n Schema.Struct({\n type: Schema.Literal('Join'),\n into: ReplicatedId,\n removed: ReplicatedId,\n /**\n * The last character of `into` when the op was made, or null when it had none: the\n * removed block's text goes right after it, wherever it has gone since, so a join still\n * lands where it was made after `into` is split or joined itself.\n */\n after: Schema.NullOr(CharRef),\n /**\n * `'end'` puts the text at the end of the block holding `after` (of `into` when null) as\n * that block is when the join applies, so text typed at its end since stays before it.\n * Only undo makes it: rejoining halves someone has typed into since.\n */\n at: Schema.optionalKey(Schema.Literal('end')),\n }),\n Schema.Struct({ type: Schema.Literal('Retype'), id: ReplicatedId, to: RetypeTarget }),\n Schema.Struct({ type: Schema.Literal('SetProps'), id: ReplicatedId, props: Schema.JsonObject }),\n // The inverses `invert` makes, for undo. Only `Collect` removes deleted text, so until\n // then each of these finds what it restores where it was.\n Schema.Struct({ type: Schema.Literal('Undelete'), ranges: Schema.Array(CharRange) }),\n Schema.Struct({ type: Schema.Literal('UndeleteBlock'), id: ReplicatedId }),\n Schema.Struct({\n type: Schema.Literal('Unjoin'),\n /** The block a join removed, restored where it stood. */\n id: ReplicatedId,\n /** The characters it held, taken back from wherever they are now. */\n ranges: Schema.Array(CharRange),\n /** The nested blocks it held, taken back from the container they were joined into. */\n children: Schema.Array(ReplicatedId),\n }),\n /**\n * Tombstone collection, in two phases so a deletion is kept for one whole interval:\n * removes the deleted text the previous `Collect` found, then marks what is deleted now.\n */\n Schema.Struct({ type: Schema.Literal('Collect') }),\n])\nexport type ReplicatedOp = typeof ReplicatedOp.Type\n\nconst charRef = (id: string, index: number): CharRef => `${id}.${index}` as CharRef\nconst parseChar = (ref: string): { readonly id: string; readonly index: number } => {\n const dot = ref.lastIndexOf('.')\n return { id: ref.slice(0, dot), index: Number(ref.slice(dot + 1)) }\n}\n\n/** The run a text block with no visible characters shows, so a caret has somewhere to be. */\nconst emptyRunId = (block: string): NodeId => NodeId.make(`${block}.0`)\n\nexport const empty: ReplicatedState = { version: 1, root: [], blocks: {} }\n\nconst lookup = (state: ReplicatedState, id: string): Entry | undefined =>\n state.blocks[id as ReplicatedId]\n\n// ---------------------------------------------------------------------------------------\n// Applying ops\n// ---------------------------------------------------------------------------------------\n\n/**\n * Which blocks hold spans of each insert. Built once for a state that needs it, then carried\n * to each state `applyOps` makes from it as a layer of only what that call changed, so\n * finding a character costs a lookup rather than a scan of every block. Layers are merged\n * back into one map every so often, so a lookup walks a short chain.\n */\ninterface Holders {\n readonly parent: Holders | undefined\n readonly own: ReadonlyMap<string, ReadonlyArray<ReplicatedId>>\n readonly depth: number\n}\nconst MAX_HOLDER_LAYERS = 16\n\nconst holdersIn = (holders: Holders, id: string): ReadonlyArray<ReplicatedId> | undefined => {\n for (let at: Holders | undefined = holders; at !== undefined; at = at.parent) {\n const found = at.own.get(id)\n if (found !== undefined) return found\n }\n return undefined\n}\n\nconst insertIdsOf = (entry: Entry | undefined): ReadonlySet<string> =>\n new Set(entry?.spans.map(span => span.id) ?? [])\n\nconst holderIndexes = new WeakMap<ReplicatedState, Holders>()\nconst holdersOf = (state: ReplicatedState): Holders => {\n const cached = holderIndexes.get(state)\n if (cached !== undefined) return cached\n const own = new Map<string, Array<ReplicatedId>>()\n for (const [block, entry] of Object.entries(state.blocks) as Array<[ReplicatedId, Entry]>) {\n for (const id of insertIdsOf(entry)) {\n const list = own.get(id)\n if (list === undefined) own.set(id, [block])\n else list.push(block)\n }\n }\n const holders = { parent: undefined, own, depth: 0 }\n holderIndexes.set(state, holders)\n return holders\n}\n\n/** The holders after `changed` blocks were rewritten from `before` to `after`. */\nconst nextHolders = (\n holders: Holders,\n before: ReplicatedState,\n after: ReplicatedState,\n changed: Iterable<string>,\n): Holders => {\n const own = new Map<string, Array<ReplicatedId>>()\n const listFor = (id: string): Array<ReplicatedId> => {\n let list = own.get(id)\n if (list === undefined) {\n list = [...(holdersIn(holders, id) ?? [])]\n own.set(id, list)\n }\n return list\n }\n for (const block of changed as Iterable<ReplicatedId>) {\n const was = insertIdsOf(lookup(before, block))\n const is = insertIdsOf(lookup(after, block))\n for (const id of was) {\n if (is.has(id)) continue\n const list = listFor(id)\n list.splice(list.indexOf(block), 1)\n }\n for (const id of is) if (!was.has(id)) listFor(id).push(block)\n }\n if (own.size === 0) return holders\n if (holders.depth < MAX_HOLDER_LAYERS) return { parent: holders, own, depth: holders.depth + 1 }\n // Merged into one map: a copy of the whole index, once every so many edits.\n const merged = new Map<string, ReadonlyArray<ReplicatedId>>()\n const layers: Array<Holders> = []\n for (let at: Holders | undefined = holders; at !== undefined; at = at.parent) layers.push(at)\n for (const layer of layers.reverse()) for (const [id, list] of layer.own) merged.set(id, list)\n for (const [id, list] of own) merged.set(id, list)\n return { parent: undefined, own: merged, depth: 0 }\n}\n\n/**\n * A working copy of the state for one `applyOps`: the block record is copied on the first\n * write, and each entry the ops touch once, so a batch of ops costs one copy of what it\n * touches, and a read-only walk (`resolve`'s) copies nothing.\n */\nconst draft = (state: ReplicatedState) => {\n let blocks: Record<string, Entry | undefined> = state.blocks\n let blocksCopied = false\n let root = state.root\n let rootCopied = false\n const copied = new Set<string>()\n /** Blocks each insert's spans have been put into by this draft, beyond the index's. */\n const moved = new Map<string, Set<ReplicatedId>>()\n type Writable = { -readonly [K in keyof Entry]: Entry[K] } & {\n spans: Array<Span>\n children: Array<ReplicatedId>\n }\n const own = (id: string, entry: Writable): void => {\n if (!blocksCopied) {\n blocks = { ...blocks }\n blocksCopied = true\n }\n blocks[id] = entry\n copied.add(id)\n }\n const read = (id: string): Entry | undefined => blocks[id]\n const write = (id: string): Writable | undefined => {\n const entry = read(id)\n if (entry === undefined) return undefined\n if (copied.has(id)) return entry as Writable\n const copy: Writable = { ...entry, spans: [...entry.spans], children: [...entry.children] }\n own(id, copy)\n return copy\n }\n /** Records that `spans` were put into `block`, so `holding` finds them there. */\n const hold = (block: string, spans: ReadonlyArray<Span>): void => {\n for (const span of spans) {\n const set = moved.get(span.id)\n if (set === undefined) moved.set(span.id, new Set([block as ReplicatedId]))\n else set.add(block as ReplicatedId)\n }\n }\n const siblings = (parent: string | null): Array<ReplicatedId> | undefined => {\n if (parent === null) {\n if (!rootCopied) {\n root = [...root]\n rootCopied = true\n }\n return root as Array<ReplicatedId>\n }\n const entry = write(parent)\n return entry !== undefined && holdsBlocks(entry.shape) ? entry.children : undefined\n }\n const create = (id: string, entry: Entry): void => {\n own(id, { ...entry, spans: [...entry.spans], children: [...entry.children] })\n hold(id, entry.spans)\n }\n /**\n * The blocks that may hold spans of an insert: those that did before this `applyOps`, and\n * those it has put spans of it into since.\n */\n const holding = (id: string): ReadonlySet<ReplicatedId> => {\n const since = moved.get(id)\n const before = holdersIn(holdersOf(state), id) ?? []\n return since === undefined ? new Set(before) : new Set([...before, ...since])\n }\n const finish = (): ReplicatedState => {\n const next: ReplicatedState = {\n version: 1,\n root,\n blocks: blocks as Record<ReplicatedId, Entry>,\n }\n const holders = holderIndexes.get(state)\n if (holders !== undefined) holderIndexes.set(next, nextHolders(holders, state, next, copied))\n return next\n }\n const ids = (): ReadonlyArray<string> => Object.keys(blocks)\n return { read, write, hold, siblings, create, finish, holding, ids }\n}\ntype Draft = ReturnType<typeof draft>\n\n/** Marks with `mark` set: a same-named one replaced where it stands, or `mark` added last. */\nconst withMark = (marks: ReadonlyArray<RunMark>, mark: RunMark): Array<RunMark> =>\n marks.some(held => markName(held) === markName(mark))\n ? marks.map(held => (markName(held) === markName(mark) ? mark : held))\n : [...marks, mark]\n\nconst holdsText = (shape: BlockShape): boolean =>\n shape.type === 'Paragraph' ||\n shape.type === 'Heading' ||\n (shape.type === 'Node' && shape.holds === 'text')\n\nconst holdsBlocks = (shape: BlockShape): boolean =>\n shape.type === 'Node' && shape.holds === 'blocks'\n\n/** Whether an id already names a block or an insert anywhere in the state. */\nconst taken = (work: Draft, id: string): boolean =>\n work.read(id) !== undefined ||\n [...work.holding(id)].some(block => work.read(block)!.spans.some(span => span.id === id))\n\n/** Whether any of characters `from` up to `to` of an insert are already in the state. */\nconst charsTaken = (\n read: (block: string) => Entry | undefined,\n holders: Iterable<ReplicatedId>,\n id: string,\n from: number,\n to: number,\n): boolean =>\n read(id) !== undefined ||\n [...holders].some(block =>\n read(block)!.spans.some(\n span => span.id === id && span.offset < to && from < span.offset + span.text.length,\n ),\n )\n\n/** Where a character is: its block, and the span index and offset within that span. */\ninterface Found {\n readonly block: ReplicatedId\n readonly span: number\n readonly within: number\n}\n\nconst findChar = (work: Draft, ref: string, hint: ReplicatedId | undefined): Found | undefined => {\n const { id, index } = parseChar(ref)\n const search = (block: ReplicatedId): Found | undefined => {\n const spans = work.read(block)?.spans ?? []\n for (const [span, candidate] of spans.entries()) {\n if (\n candidate.id === id &&\n index >= candidate.offset &&\n index < candidate.offset + candidate.text.length\n ) {\n return { block, span, within: index - candidate.offset }\n }\n }\n return undefined\n }\n const hinted = hint === undefined ? undefined : search(hint)\n if (hinted !== undefined) return hinted\n for (const block of work.holding(id)) {\n const found = search(block)\n if (found !== undefined) return found\n }\n return undefined\n}\n\n/** Splits a block's span so a boundary falls `within` characters into it. */\nconst cut = (spans: Array<Span>, span: number, within: number): void => {\n const target = spans[span]!\n if (within <= 0 || within >= target.text.length) return\n spans.splice(\n span,\n 1,\n { ...target, text: target.text.slice(0, within) },\n { ...target, offset: target.offset + within, text: target.text.slice(within) },\n )\n}\n\n/** A place between characters: a block, and how many of its spans come before it. */\ninterface Place {\n readonly block: ReplicatedId\n readonly index: number\n}\n\n/** The start of a block; a joined block's start is where its characters went. */\nconst startOf = (work: Draft, block: ReplicatedId, seen = new Set<string>()): Place | undefined => {\n const entry = work.read(block)\n if (entry === undefined || seen.has(block)) return undefined\n if (entry.joined === undefined) return { block, index: 0 }\n seen.add(block)\n return entry.joined.after === null\n ? startOf(work, entry.joined.into, seen)\n : (afterChar(work, entry.joined.after, entry.joined.into) ?? endOf(work, entry.joined.into))\n}\n\n/**\n * The end of a block, or of the block a joined one went into: where text whose anchor is\n * gone (rejected, or collected) is kept, near where it was typed and shown.\n */\nconst endOf = (work: Draft, block: ReplicatedId): Place | undefined => {\n const live = liveContainer(work, block)\n if (live === undefined) return undefined\n return { block: live, index: work.read(live)!.spans.length }\n}\n\n/** The place right after a character, cutting its span so a boundary falls there. */\nconst afterChar = (work: Draft, ref: string, hint: ReplicatedId | undefined): Place | undefined => {\n const found = findChar(work, ref, hint)\n if (found === undefined) return undefined\n const spans = work.write(found.block)!.spans\n cut(spans, found.span, found.within + 1)\n return { block: found.block, index: found.span + 1 }\n}\n\n/** Every stretch of spans a set of ranges covers, cut so each lies wholly inside or out. */\nconst eachCovered = (\n work: Draft,\n ranges: ReadonlyArray<CharRange>,\n visit: (span: Span) => Span,\n): void => {\n const ids = new Set(ranges.map(range => range.id))\n const candidates = new Set([...ids].flatMap(id => [...work.holding(id)]))\n for (const block of candidates) {\n if (!work.read(block)!.spans.some(span => ids.has(span.id))) continue\n const spans = work.write(block)!.spans\n for (const range of ranges) {\n for (let index = 0; index < spans.length; index++) {\n const span = spans[index]!\n if (span.id !== range.id) continue\n const end = span.offset + span.text.length\n if (range.to <= span.offset || range.from >= end) continue\n cut(spans, index, range.from - span.offset)\n const inside = spans[index]!\n if (inside.offset < range.from) continue\n cut(spans, index, range.to - inside.offset)\n spans[index] = visit(spans[index]!)\n }\n }\n }\n}\n\n/**\n * Takes the spans a set of ranges covers out of whatever blocks hold them, cut so each lies\n * wholly inside, and gives them back in range order, and each range's in character order:\n * the order of the blocks holding them depends on how the state was reached, not on what\n * it holds, so it would give two replicas different text.\n */\nconst takeCovered = (work: Draft, ranges: ReadonlyArray<CharRange>): Array<Span> => {\n const taken: Array<Span> = []\n for (const range of ranges) {\n const ofRange: Array<Span> = []\n for (const block of work.holding(range.id)) {\n if (!work.read(block)!.spans.some(span => span.id === range.id)) continue\n const spans = work.write(block)!.spans\n for (let index = 0; index < spans.length; index++) {\n const span = spans[index]!\n if (span.id !== range.id) continue\n const end = span.offset + span.text.length\n if (range.to <= span.offset || range.from >= end) continue\n cut(spans, index, range.from - span.offset)\n const inside = spans[index]!\n if (inside.offset < range.from) continue\n cut(spans, index, range.to - inside.offset)\n ofRange.push(...spans.splice(index, 1))\n index--\n }\n }\n taken.push(...ofRange.sort((left, right) => left.offset - right.offset))\n }\n return taken\n}\n\n/**\n * Where a block was last inserted into each sibling list. A paste inserts each block after the\n * one before it, so the next anchor is usually found there rather than by a scan of the list,\n * which made applying a paste quadratic in its blocks. A hint that no longer names the anchor\n * falls back to the scan.\n */\nconst lastInserted = new WeakMap<Array<ReplicatedId>, number>()\n\nconst insertAfterSibling = (\n list: Array<ReplicatedId>,\n id: ReplicatedId,\n after: string | null,\n): void => {\n const hint = lastInserted.get(list)\n const at =\n after === null\n ? 0\n : (hint !== undefined && list[hint] === after ? hint : list.indexOf(after as ReplicatedId)) +\n 1\n // A sibling that has left this container puts the block at the container's end.\n const place = after !== null && at === 0 ? list.length : at\n list.splice(place, 0, id)\n lastInserted.set(list, place)\n}\n\n/**\n * The container a block's children are in now: a container joined into another passed its\n * children on, so an op naming it means the one it was joined into. Undefined when gone.\n */\nconst liveContainer = (work: Draft, id: ReplicatedId): ReplicatedId | undefined => {\n const seen = new Set<string>()\n for (let at = id; !seen.has(at);) {\n seen.add(at)\n const entry = work.read(at)\n if (entry === undefined) return undefined\n if (entry.joined === undefined) return at\n at = entry.joined.into\n }\n return undefined\n}\n\nconst isWithin = (work: Draft, block: string, ancestor: string): boolean => {\n for (let at: string | null = block; at !== null; at = work.read(at)?.parent ?? null) {\n if (at === ancestor) return true\n }\n return false\n}\n\nconst applyOp = (work: Draft, op: ReplicatedOp): void => {\n switch (op.type) {\n case 'Insert': {\n const from = op.from ?? 0\n if (charsTaken(work.read, work.holding(op.id), op.id, from, from + op.text.length)) return\n // A lost anchor (its insert was rejected, or collected) falls back to the end of the\n // block the op was made in, or of the one that block was joined into.\n const place =\n (op.after === null ? startOf(work, op.block) : afterChar(work, op.after, op.block)) ??\n endOf(work, op.block)\n // A block that holds no text keeps the characters unshown, which is all a refusal\n // would do.\n if (place === undefined) return\n const span: Span = { id: op.id, offset: from, text: op.text, marks: op.marks, deleted: false }\n work.write(place.block)!.spans.splice(place.index, 0, span)\n work.hold(place.block, [span])\n return\n }\n case 'Delete':\n eachCovered(work, op.ranges, span => ({ ...span, deleted: true }))\n return\n case 'Mark':\n eachCovered(work, op.ranges, span => ({\n ...span,\n marks: withMark(span.marks, op.mark),\n }))\n return\n case 'Unmark':\n eachCovered(work, op.ranges, span => ({\n ...span,\n marks: span.marks.filter(mark => markName(mark) !== op.name),\n }))\n return\n case 'InsertBlock': {\n if (taken(work, op.id)) return\n const parent = op.parent === null ? null : liveContainer(work, op.parent)\n if (parent === undefined) return\n const list = work.siblings(parent)\n if (list === undefined) return\n insertAfterSibling(list, op.id, op.after)\n work.create(op.id, {\n shape: op.shape,\n parent,\n spans: [],\n children: [],\n deleted: false,\n })\n return\n }\n case 'DeleteBlock': {\n const entry = work.read(op.id)\n if (entry === undefined) return\n work.write(op.id)!.deleted = true\n return\n }\n case 'MoveBlock': {\n const entry = work.read(op.id)\n if (entry === undefined) return\n const parent = op.parent === null ? null : liveContainer(work, op.parent)\n if (parent === undefined || (parent !== null && isWithin(work, parent, op.id))) return\n const destination = work.siblings(parent)\n if (destination === undefined) return\n const source = work.siblings(entry.parent)!\n source.splice(source.indexOf(op.id), 1)\n insertAfterSibling(destination, op.id, op.after)\n work.write(op.id)!.parent = parent\n return\n }\n case 'Split': {\n if (taken(work, op.into)) return\n // A lost anchor splits at the end, so the block the split made is there for what is\n // typed into it next.\n const place =\n (op.after === null ? startOf(work, op.block) : afterChar(work, op.after, op.block)) ??\n endOf(work, op.block)\n if (place === undefined) return\n const source = work.read(place.block)!\n if (!holdsText(source.shape)) return\n const list = work.siblings(source.parent)!\n const moved = work.write(place.block)!.spans.splice(place.index)\n insertAfterSibling(list, op.into, place.block)\n work.create(op.into, {\n shape: source.shape,\n parent: source.parent,\n spans: moved,\n children: [],\n deleted: source.deleted,\n })\n return\n }\n case 'Join': {\n const removed = work.read(op.removed)\n if (removed === undefined || removed.deleted) return\n if (holdsText(removed.shape)) {\n // Right after the character `into` ended with, or at the end of the block holding it\n // now, wherever a split or another join has taken it since.\n const place =\n op.at === 'end'\n ? endOf(\n work,\n (op.after === null ? undefined : findChar(work, op.after, op.into)?.block) ??\n op.into,\n )\n : op.after === null\n ? startOf(work, op.into)\n : afterChar(work, op.after, op.into)\n if (place === undefined || place.block === op.removed) return\n const target = work.read(place.block)!\n // A block deleted rather than joined takes nothing: the text would vanish with it.\n if (target.deleted || !holdsText(target.shape)) return\n const before = target.spans[place.index - 1]\n const gone = work.write(op.removed)!\n work.write(place.block)!.spans.splice(place.index, 0, ...gone.spans)\n work.hold(place.block, gone.spans)\n gone.spans = []\n gone.deleted = true\n gone.joined = {\n into: place.block,\n after:\n before === undefined\n ? null\n : charRef(before.id, before.offset + before.text.length - 1),\n }\n return\n }\n const into = liveContainer(work, op.into)\n if (into === undefined) return\n const target = work.read(into)!\n if (target.deleted) return\n if (isWithin(work, into, op.removed) || isWithin(work, op.removed, into)) return\n if (!holdsBlocks(target.shape) || !holdsBlocks(removed.shape)) return\n const gone = work.write(op.removed)!\n for (const child of gone.children) work.write(child)!.parent = into\n work.write(into)!.children.push(...gone.children)\n gone.children = []\n gone.deleted = true\n gone.joined = { into, after: null }\n return\n }\n case 'Retype': {\n // Its spans or its children stay where they are, so what anyone typed into the block\n // stays with it. A container becomes only another container.\n const entry = work.read(op.id)\n if (entry === undefined) return\n if (holdsText(entry.shape)) {\n work.write(op.id)!.shape = op.to.type === 'Node' ? { ...op.to, holds: 'text' } : op.to\n } else if (holdsBlocks(entry.shape) && op.to.type === 'Node') {\n work.write(op.id)!.shape = { ...op.to, holds: 'blocks' }\n }\n return\n }\n case 'Undelete':\n eachCovered(work, op.ranges, span => {\n if (span.kept === true) return span\n const { swept: _, ...shown } = span\n return { ...shown, deleted: false }\n })\n return\n case 'UndeleteBlock': {\n // A joined block comes back by `Unjoin`, which returns what it held too.\n const entry = work.read(op.id)\n if (entry === undefined || !entry.deleted || entry.joined !== undefined) return\n const restored = work.write(op.id)!\n restored.deleted = false\n delete restored.swept\n return\n }\n case 'Collect':\n collect(work)\n return\n case 'Unjoin': {\n const entry = work.read(op.id)\n if (entry?.joined === undefined) return\n // Where its children are now: the container it joined, or the one that was joined into.\n const home = liveContainer(work, entry.joined.into)\n const restored = work.write(op.id)!\n restored.deleted = false\n delete restored.swept\n delete restored.joined\n restored.spans = takeCovered(work, op.ranges)\n work.hold(op.id, restored.spans)\n for (const child of op.children) {\n const moved = work.read(child)\n // A child that is the block itself, or holds it since a move, would make a cycle.\n if (moved === undefined || moved.parent !== home || isWithin(work, op.id, child)) continue\n const list = work.write(home!)!.children\n list.splice(list.indexOf(child), 1)\n work.write(child)!.parent = op.id\n restored.children.push(child)\n }\n return\n }\n case 'SetProps': {\n const entry = work.read(op.id)\n if (entry?.shape.type !== 'Node') return\n work.write(op.id)!.shape = { ...entry.shape, props: { ...entry.shape.props, ...op.props } }\n return\n }\n }\n}\n\n/**\n * Removes the text the last `Collect` found deleted, deleted characters and those of a\n * deleted block alike, then marks what is deleted now for the next one. A late op that\n * names a removed character takes the fallback a lost anchor does.\n *\n * An insert keeps its highest index: where a removed stretch ended it, its last character\n * stays, deleted. Otherwise `translate` could continue the insert from a lower index, and a\n * late op naming the removed character would find the new one.\n */\nconst collect = (work: Draft): void => {\n const ends = new Map<string, number>()\n for (const block of work.ids()) {\n for (const span of work.read(block)?.spans ?? []) {\n const end = span.offset + span.text.length\n if (end > (ends.get(span.id) ?? 0)) ends.set(span.id, end)\n }\n }\n for (const block of work.ids()) {\n const entry = work.read(block)\n if (entry === undefined) continue\n const blockGone = entry.deleted && entry.swept === true\n const collected = (span: Span) =>\n span.kept !== true && (blockGone || (span.deleted && span.swept === true))\n const unmarked = (span: Span) => span.deleted && span.swept !== true\n if (!entry.spans.some(span => collected(span) || unmarked(span))) {\n if (entry.deleted && entry.swept !== true) work.write(block)!.swept = true\n continue\n }\n const spans: Array<Span> = []\n for (const span of entry.spans) {\n const end = span.offset + span.text.length\n if (!collected(span)) {\n spans.push(unmarked(span) ? { ...span, swept: true } : span)\n } else if (end === ends.get(span.id)) {\n const last = span.text.slice(-1)\n spans.push({ ...span, offset: end - 1, text: last, deleted: true, swept: true, kept: true })\n }\n }\n const written = work.write(block)!\n written.spans = spans\n if (entry.deleted) written.swept = true\n }\n}\n\nconst applied = new WeakMap<\n ReplicatedState,\n WeakMap<ReadonlyArray<ReplicatedOp>, ReplicatedState>\n>()\n\n/**\n * Folds ops into the state in order. Total: an op whose target is gone, whose ids are\n * already taken, or that would make the tree cyclic changes nothing, and an insert or split\n * anchored on a character that is gone (never arrived, or collected) lands at the end of the\n * block it names, or of the block that one was joined into. It trusts the\n * state to be one these functions made (the ops are the untrusted input): a state decoded\n * from elsewhere is not checked for a block listed twice or a cycle of parents.\n *\n * The same ops on the same state give back the same state object, so the edit that made\n * the ops and the durable Message that replays them agree on identity, and whatever is\n * derived from it (`project`, an editor host's key) is derived once. The ops array is\n * remembered by identity, so do not change one after applying it.\n */\nexport const applyOps = (\n state: ReplicatedState,\n ops: ReadonlyArray<ReplicatedOp>,\n): ReplicatedState => {\n if (ops.length === 0) return state\n const known = applied.get(state)?.get(ops)\n if (known !== undefined) return known\n const work = draft(state)\n for (const op of ops) applyOp(work, op)\n const next = work.finish()\n const byOps = applied.get(state) ?? new WeakMap()\n byOps.set(ops, next)\n applied.set(state, byOps)\n return next\n}\n\n/**\n * The same ops with each insert that continues the one right before it folded into that one:\n * a run of typing `translate` carried on as one insert becomes one op again. For ops\n * `translate` made, which never reuse a character, applying the result shows what applying\n * `ops` does.\n */\nexport const coalesce = (ops: ReadonlyArray<ReplicatedOp>): ReadonlyArray<ReplicatedOp> => {\n const out: Array<ReplicatedOp> = []\n for (const op of ops) {\n const last = out[out.length - 1]\n if (op.type === 'Insert' && last?.type === 'Insert') {\n const end = (last.from ?? 0) + last.text.length\n if (\n op.id === last.id &&\n op.block === last.block &&\n (op.from ?? 0) === end &&\n op.after === charRef(last.id, end - 1) &&\n sameMarkSet(op.marks, last.marks)\n ) {\n out[out.length - 1] = { ...last, text: last.text + op.text }\n continue\n }\n }\n out.push(op)\n }\n return out\n}\n\n// ---------------------------------------------------------------------------------------\n// Undoing\n// ---------------------------------------------------------------------------------------\n\n/**\n * The stretches of `state`'s spans each range covers, with where each span is: in range\n * order, and each range's in character order, whatever order the blocks are indexed in.\n */\nconst coveredParts = (\n state: ReplicatedState,\n ranges: ReadonlyArray<CharRange>,\n): ReadonlyArray<{\n readonly block: ReplicatedId\n readonly index: number\n readonly span: Span\n readonly range: CharRange\n}> =>\n ranges.flatMap(range =>\n (holdersIn(holdersOf(state), range.id) ?? [])\n .flatMap(block =>\n lookup(state, block)!.spans.flatMap((span, index) => {\n if (span.id !== range.id) return []\n const from = Math.max(range.from, span.offset)\n const to = Math.min(range.to, span.offset + span.text.length)\n return from < to ? [{ block, index, span, range: { id: range.id, from, to } }] : []\n }),\n )\n .sort((left, right) => left.span.offset - right.span.offset),\n )\n\n/** What a block that holds text or blocks is, as a retype names it. */\nconst retypeTargetOf = (shape: BlockShape): RetypeTarget | undefined =>\n shape.type === 'Paragraph' || shape.type === 'Heading'\n ? shape\n : shape.type === 'Node' && shape.holds !== 'none'\n ? { type: 'Node', kind: shape.kind, props: shape.props }\n : undefined\n\n/** The ops that take back one op, made against the state it was applied to. */\nconst invertOne = (state: ReplicatedState, op: ReplicatedOp): ReadonlyArray<ReplicatedOp> => {\n switch (op.type) {\n case 'Insert': {\n // An insert whose characters were taken changed nothing.\n const from = op.from ?? 0\n const to = from + op.text.length\n const holders = holdersIn(holdersOf(state), op.id) ?? []\n return charsTaken(id => lookup(state, id), holders, op.id, from, to)\n ? []\n : [{ type: 'Delete', ranges: [{ id: op.id, from, to }] }]\n }\n case 'Delete': {\n // Only what this op deleted: characters already gone before it stay gone.\n const ranges = coveredParts(state, op.ranges)\n .filter(part => !part.span.deleted)\n .map(part => part.range)\n return ranges.length === 0 ? [] : [{ type: 'Undelete', ranges }]\n }\n case 'Undelete': {\n const ranges = coveredParts(state, op.ranges)\n .filter(part => part.span.deleted)\n .map(part => part.range)\n return ranges.length === 0 ? [] : [{ type: 'Delete', ranges }]\n }\n case 'Mark':\n case 'Unmark': {\n const name = op.type === 'Mark' ? markName(op.mark) : op.name\n const inverse: Array<ReplicatedOp> = []\n const unmarked: Array<CharRange> = []\n for (const { span, range } of coveredParts(state, op.ranges)) {\n const prior = span.marks.find(mark => markName(mark) === name)\n if (prior === undefined) {\n if (op.type === 'Mark') unmarked.push(range)\n } else inverse.push({ type: 'Mark', ranges: [range], mark: prior })\n }\n return unmarked.length === 0\n ? inverse\n : [{ type: 'Unmark', ranges: unmarked, name }, ...inverse]\n }\n case 'InsertBlock':\n return lookup(state, op.id) !== undefined ? [] : [{ type: 'DeleteBlock', id: op.id }]\n case 'DeleteBlock': {\n const entry = lookup(state, op.id)\n return entry === undefined || entry.deleted ? [] : [{ type: 'UndeleteBlock', id: op.id }]\n }\n case 'UndeleteBlock': {\n const entry = lookup(state, op.id)\n return entry?.deleted === true && entry.joined === undefined\n ? [{ type: 'DeleteBlock', id: op.id }]\n : []\n }\n case 'MoveBlock': {\n const entry = lookup(state, op.id)\n if (entry === undefined) return []\n const siblings =\n entry.parent === null ? state.root : (lookup(state, entry.parent)?.children ?? [])\n const at = siblings.indexOf(op.id)\n return [\n {\n type: 'MoveBlock',\n id: op.id,\n parent: entry.parent,\n after: at > 0 ? siblings[at - 1]! : null,\n },\n ]\n }\n case 'Split':\n // At the end of the half holding the character split after, so what was typed at the\n // end of that half since stays before the text rejoined.\n return lookup(state, op.into) !== undefined\n ? []\n : [{ type: 'Join', into: op.block, removed: op.into, after: op.after, at: 'end' }]\n case 'Join': {\n const removed = lookup(state, op.removed)\n if (removed === undefined || removed.deleted) return []\n return [\n {\n type: 'Unjoin',\n id: op.removed,\n ranges: removed.spans.map(span => ({\n id: span.id,\n from: span.offset,\n to: span.offset + span.text.length,\n })),\n children: [...removed.children],\n },\n ]\n }\n case 'Unjoin': {\n const joined = lookup(state, op.id)?.joined\n if (joined === undefined) return []\n // Joined again right after the character now before its text, deleted or not. When\n // its text ends that block, at the block's end instead, as an undone split is: text\n // typed there once it was split out stays before it.\n const parts = coveredParts(state, op.ranges)\n const first = parts[0]\n if (first === undefined)\n return [{ type: 'Join', into: joined.into, removed: op.id, after: joined.after }]\n // Spans are cut but never merged, so the text starts where a span does.\n const spans = lookup(state, first.block)!.spans\n const before = spans[first.index - 1]\n const after =\n before === undefined ? null : charRef(before.id, before.offset + before.text.length - 1)\n const last = Math.max(\n ...parts.filter(part => part.block === first.block).map(part => part.index),\n )\n return [\n {\n type: 'Join',\n into: first.block,\n removed: op.id,\n after,\n ...(last === spans.length - 1 ? { at: 'end' as const } : {}),\n },\n ]\n }\n case 'Collect':\n // What it removed is gone for good; undoing an edit made before it finds less.\n return []\n case 'Retype': {\n const entry = lookup(state, op.id)\n const prior = entry === undefined ? undefined : retypeTargetOf(entry.shape)\n return prior === undefined ? [] : [{ type: 'Retype', id: op.id, to: prior }]\n }\n case 'SetProps': {\n const shape = lookup(state, op.id)?.shape\n if (shape?.type !== 'Node') return []\n // A prop the op added cannot be taken away (SetProps sets, it does not delete), so\n // only the ones it changed go back.\n const prior = Object.fromEntries(\n Object.keys(op.props)\n .filter(key => Object.hasOwn(shape.props, key))\n .map(key => [key, shape.props[key]!]),\n )\n return Object.keys(prior).length === 0 ? [] : [{ type: 'SetProps', id: op.id, props: prior }]\n }\n }\n}\n\n/**\n * The ops that undo `ops`, made against `state`, the state `ops` were applied to. Applied\n * after `ops` and after whatever else has happened since, they take back what `ops` did\n * and leave the rest alone. Characters it inserted are deleted, and characters it deleted\n * come back. Marks, block types and props return to what they were, a split is joined and\n * a join split out, and a moved block goes back beside the sibling it followed. A prop it\n * added where there was none stays, since `SetProps` cannot delete one. Inverting the\n * result gives the ops that redo it.\n */\nexport const invert = (\n state: ReplicatedState,\n ops: ReadonlyArray<ReplicatedOp>,\n): ReadonlyArray<ReplicatedOp> => {\n const inverses: Array<ReadonlyArray<ReplicatedOp>> = []\n let current = state\n for (const op of ops) {\n inverses.push(invertOne(current, op))\n current = applyOps(current, [op])\n }\n return inverses.reverse().flat()\n}\n\n// ---------------------------------------------------------------------------------------\n// Projection\n// ---------------------------------------------------------------------------------------\n\n/** A projected run and the characters it shows, in order. */\ninterface ProjectedRun {\n readonly id: NodeId\n readonly chars: ReadonlyArray<CharRange>\n}\n\ninterface Projection {\n readonly document: Document\n /** The runs of every visible block that holds text, in order. */\n readonly runs: ReadonlyMap<string, ReadonlyArray<ProjectedRun>>\n}\n\nconst appendChars = (chars: Array<CharRange>, id: ReplicatedId, from: number, to: number) => {\n const last = chars[chars.length - 1]\n if (last !== undefined && last.id === id && last.to === from) {\n chars[chars.length - 1] = { id, from: last.from, to }\n } else {\n chars.push({ id, from, to })\n }\n}\n\nconst projectRuns = (\n block: string,\n entry: Entry,\n): { runs: Array<Text>; shown: Array<ProjectedRun> } => {\n const runs: Array<Text> = []\n const shown: Array<ProjectedRun> = []\n for (const span of entry.spans) {\n if (span.deleted) continue\n const previous = runs[runs.length - 1]\n if (previous !== undefined && sameMarkSet(previous.marks, span.marks)) {\n runs[runs.length - 1] = { ...previous, text: previous.text + span.text }\n appendChars(\n shown[shown.length - 1]!.chars as Array<CharRange>,\n span.id,\n span.offset,\n span.offset + span.text.length,\n )\n continue\n }\n const id = NodeId.make(charRef(span.id, span.offset))\n runs.push({ type: 'Text', id, text: span.text, marks: span.marks })\n shown.push({\n id,\n chars: [{ id: span.id, from: span.offset, to: span.offset + span.text.length }],\n })\n }\n if (runs.length === 0) {\n const id = emptyRunId(block)\n runs.push({ type: 'Text', id, text: '', marks: [] })\n shown.push({ id, chars: [] })\n }\n return { runs, shown }\n}\n\nconst projections = new WeakMap<ReplicatedState, Projection>()\n\n/**\n * A block's projection, by the entry it was made from. `applyOps` copies only the entries it\n * touches, so an untouched block projects to the same object in the next state: the work is\n * the changed blocks, and whatever keys on a block's identity (validation, the DOM patch)\n * sees it unchanged. A container is reused while its entry and every child's are.\n */\ninterface ProjectedBlock {\n readonly block: Block\n readonly shown: ReadonlyArray<ProjectedRun> | undefined\n readonly nested: ReadonlyArray<Block>\n}\nconst projectedBlocks = new WeakMap<Entry, ProjectedBlock>()\n\nconst projection = (state: ReplicatedState): Projection => {\n const cached = projections.get(state)\n if (cached !== undefined) return cached\n const runs = new Map<string, ReadonlyArray<ProjectedRun>>()\n const blocks = (ids: ReadonlyArray<string>): Array<Block> =>\n ids.flatMap((id): ReadonlyArray<Block> => {\n const entry = lookup(state, id)\n if (entry === undefined || entry.deleted) return []\n const nested = holdsBlocks(entry.shape) ? blocks(entry.children) : []\n const known = projectedBlocks.get(entry)\n if (\n known !== undefined &&\n known.nested.length === nested.length &&\n known.nested.every((child, at) => child === nested[at])\n ) {\n if (known.shown !== undefined) runs.set(id, known.shown)\n return [known.block]\n }\n const made = projectBlock(id, entry, nested)\n projectedBlocks.set(entry, { ...made, nested })\n if (made.shown !== undefined) runs.set(id, made.shown)\n return [made.block]\n })\n const result: Projection = { document: { version: 1, children: blocks(state.root) }, runs }\n projections.set(state, result)\n return result\n}\n\nconst projectBlock = (\n id: string,\n entry: Entry,\n nested: ReadonlyArray<Block>,\n): { readonly block: Block; readonly shown: ReadonlyArray<ProjectedRun> | undefined } => {\n const nodeId = NodeId.make(id)\n const shape = entry.shape\n if (shape.type === 'Unknown') {\n return {\n block: {\n type: 'Unknown',\n id: nodeId,\n originalType: shape.originalType,\n props: shape.props,\n children: [],\n },\n shown: undefined,\n }\n }\n if (shape.type === 'Node' && shape.holds !== 'text') {\n return {\n block: {\n type: 'Node',\n kind: shape.kind,\n id: nodeId,\n props: shape.props,\n children: [],\n ...(shape.holds === 'blocks' ? { blocks: nested } : {}),\n },\n shown: undefined,\n }\n }\n const { runs: children, shown } = projectRuns(id, entry)\n if (shape.type === 'Paragraph')\n return { block: { type: 'Paragraph', id: nodeId, children }, shown }\n if (shape.type === 'Heading')\n return { block: { type: 'Heading', id: nodeId, level: shape.level, children }, shown }\n return {\n block: { type: 'Node', kind: shape.kind, id: nodeId, props: shape.props, children },\n shown,\n }\n}\n\n/** The document a state shows: visible blocks and characters, with runs merged by marks. */\nexport const project = (state: ReplicatedState): Document => projection(state).document\n\n// ---------------------------------------------------------------------------------------\n// Starting from a document\n// ---------------------------------------------------------------------------------------\n\nconst shapeOf = (block: Block): BlockShape => {\n switch (block.type) {\n case 'Paragraph':\n return { type: 'Paragraph' }\n case 'Heading':\n return { type: 'Heading', level: block.level }\n case 'Unknown':\n return { type: 'Unknown', originalType: block.originalType, props: block.props }\n case 'Node':\n return {\n type: 'Node',\n kind: block.kind,\n props: block.props,\n holds: block.blocks !== undefined ? 'blocks' : block.children.length > 0 ? 'text' : 'none',\n }\n }\n}\n\n/** The ops that build these blocks, and their text, inside `parent` after `after`. */\nconst buildOps = (\n blocks: ReadonlyArray<Block>,\n parent: ReplicatedId | null,\n after: ReplicatedId | null,\n mint: () => ReplicatedId,\n named: (block: Block, id: ReplicatedId) => void = () => {},\n): Array<ReplicatedOp> => {\n const ops: Array<ReplicatedOp> = []\n let previous = after\n for (const block of blocks) {\n const id = mint()\n named(block, id)\n ops.push({ type: 'InsertBlock', id, shape: shapeOf(block), parent, after: previous })\n let last: CharRef | null = null\n for (const run of block.children) {\n if (run.text.length === 0) continue\n const key = mint()\n ops.push({\n type: 'Insert',\n id: key,\n block: id,\n after: last,\n text: run.text,\n marks: run.marks,\n })\n last = charRef(key, run.text.length - 1)\n }\n if (block.type === 'Node' && block.blocks !== undefined) {\n ops.push(...buildOps(block.blocks, id, null, mint, named))\n }\n previous = id\n }\n return ops\n}\n\n/** A minter of fresh ids under one key: `key:0`, `key:1`, and so on. */\nconst minter = (key: string): (() => ReplicatedId) => {\n const prefix = ReplicatedId.make(`${key}:x`).slice(0, -2)\n let next = 0\n return () => `${prefix}:${next++}` as ReplicatedId\n}\n\n/**\n * A state that shows `document`, with every block and character given a new identity\n * under `key`, which must be unique among the keys this state's ops are minted under.\n */\nexport const fromDocument = (document: Document, key: string): ReplicatedState =>\n applyOps(empty, buildOps(document.children, null, null, minter(key)))\n\n// ---------------------------------------------------------------------------------------\n// Translating an edit\n// ---------------------------------------------------------------------------------------\n\n/** A caret or selection end held by what it sits after, so it survives others' edits. */\nexport const AnchoredPosition = Schema.Struct({\n block: ReplicatedId,\n /** The character just before the position, or null at the block's start. */\n after: Schema.NullOr(CharRef),\n affinity: Schema.Literals(['before', 'after']),\n})\nexport type AnchoredPosition = typeof AnchoredPosition.Type\n\nexport const AnchoredSelection = Schema.Union([\n Schema.Struct({\n type: Schema.Literal('Range'),\n anchor: AnchoredPosition,\n focus: AnchoredPosition,\n }),\n Schema.Struct({ type: Schema.Literal('Node'), node: ReplicatedId }),\n])\nexport type AnchoredSelection = typeof AnchoredSelection.Type\n\nconst charsLength = (chars: ReadonlyArray<CharRange>): number =>\n chars.reduce((total, range) => total + range.to - range.from, 0)\n\nconst sliceChars = (\n chars: ReadonlyArray<CharRange>,\n from: number,\n to: number,\n): Array<CharRange> => {\n const out: Array<CharRange> = []\n let at = 0\n for (const range of chars) {\n const length = range.to - range.from\n const start = Math.max(from, at)\n const end = Math.min(to, at + length)\n if (start < end) appendChars(out, range.id, range.from + start - at, range.from + end - at)\n at += length\n }\n return out\n}\n\nconst concatChars = (...lists: ReadonlyArray<ReadonlyArray<CharRange>>): Array<CharRange> => {\n const out: Array<CharRange> = []\n for (const list of lists)\n for (const range of list) appendChars(out, range.id, range.from, range.to)\n return out\n}\n\nconst charAt = (chars: ReadonlyArray<CharRange>, index: number): CharRef => {\n const [range] = sliceChars(chars, index, index + 1)\n return charRef(range!.id, range!.from)\n}\n\ninterface ShadowRun {\n id: string\n chars: Array<CharRange>\n marks: ReadonlyArray<RunMark>\n}\n\n/**\n * The document an edit is working on, with each run's characters: the translation replays\n * the edit's operations here to learn which characters each one touches. Block ids new to\n * the edit are renamed to minted ones, recorded in `names`.\n */\ninterface Shadow {\n readonly document: Document\n readonly runs: Lazy<string, Array<ShadowRun>>\n readonly children: Lazy<string | null, Array<string>>\n readonly parents: Lazy<string, string | null>\n readonly names: Map<string, ReplicatedId>\n}\n\n/**\n * A map that derives each key on first read and keeps what it derived, so a translation\n * builds only the part of the shadow it touches.\n */\nclass Lazy<K, V> {\n readonly own = new Map<K, V>()\n constructor(private readonly derive: (key: K) => V | undefined) {}\n get(key: K): V | undefined {\n if (this.own.has(key)) return this.own.get(key)\n const value = this.derive(key)\n if (value !== undefined) this.own.set(key, value)\n return value\n }\n has(key: K): boolean {\n return this.get(key) !== undefined\n }\n set(key: K, value: V): void {\n this.own.set(key, value)\n }\n /** Forgets a block the edit joined away, whose runs another block now holds. */\n delete(key: K): void {\n this.own.delete(key)\n }\n}\n\nconst ROOT = null\n\n/** Each block's characters, in order. */\ntype BlockChars = (block: string) => ReadonlyArray<CharRange>\n\n/** The shadow for `document`, each block keeping the characters `chars` says it held. */\nconst shadowOf = (\n document: Document,\n chars: BlockChars,\n names: Map<string, ReplicatedId>,\n): Shadow => {\n const index = nodeIndex(document)\n const blockNamed = (id: string): Block | undefined => {\n const node = index.nodes.get(id as NodeId)\n return node === undefined || node.type === 'Text' ? undefined : node\n }\n return {\n document,\n names,\n runs: new Lazy(id => {\n const block = blockNamed(id)\n if (block === undefined) return undefined\n const held = chars(id)\n let at = 0\n return block.children.map(run => {\n const slice = sliceChars(held, at, at + run.text.length)\n at += run.text.length\n return { id: run.id, chars: slice, marks: run.marks }\n })\n }),\n children: new Lazy(parent => {\n if (parent === ROOT) return document.children.map(block => block.id)\n const block = blockNamed(parent)\n return block?.type === 'Node' && block.blocks !== undefined\n ? block.blocks.map(child => child.id)\n : undefined\n }),\n parents: new Lazy(block => index.parentOf.get(block as NodeId)),\n }\n}\n\n/** The characters each block holds once a shadow's edits are done. */\nconst charsAfter =\n (shadow: Shadow, before: BlockChars): BlockChars =>\n block => {\n const runs = shadow.runs.own.get(block)\n return runs === undefined ? before(block) : concatChars(...runs.map(run => run.chars))\n }\n\n/**\n * Restates an edit's transactions as ops against `state`, which the edit ran on the\n * projection of. `key` must be unique to this edit among everything the state has seen: it\n * names the edit's new characters and blocks. Also anchors the edit's resulting selection.\n * Throws if the transactions do not apply to the projection, which is a caller's bug. The\n * transactions are replayed with `apply`'s default transforms, as `RichText.run` applies\n * them; an edit normalized by other transforms does not translate.\n *\n * Text typed right after the last character of an insert `continues` accepts carries on that\n * insert (`from` its next index) instead of starting one, so `coalesce` can fold a run of\n * typing into one op. Accept only inserts this replica minted: two replicas continuing one\n * insert at once would both claim its next characters, and the later would be dropped.\n */\nexport const translate = (\n state: ReplicatedState,\n result: Pick<Extract<TransactionResult, { readonly ok: true }>, 'transactions' | 'state'>,\n key: string,\n options: { readonly continues?: (id: ReplicatedId) => boolean } = {},\n): { readonly ops: ReadonlyArray<ReplicatedOp>; readonly selection: AnchoredSelection | null } => {\n const mint = minter(key)\n const continues = options.continues ?? (() => false)\n // How many characters each insert has, counting what this edit adds: an insert may be\n // continued only from its end.\n const lengths = new Map<string, number>()\n const lengthOf = (id: string): number => {\n const known = lengths.get(id)\n if (known !== undefined) return known\n let length = 0\n for (const block of holdersIn(holdersOf(state), id) ?? []) {\n for (const span of lookup(state, block)!.spans) {\n if (span.id === id) length = Math.max(length, span.offset + span.text.length)\n }\n }\n lengths.set(id, length)\n return length\n }\n const next: NextInsert = (after, length) => {\n if (after !== null) {\n const { id, index } = parseChar(after)\n if (continues(id as ReplicatedId) && lengthOf(id) === index + 1) {\n lengths.set(id, index + 1 + length)\n return { id: id as ReplicatedId, from: index + 1 }\n }\n }\n const id = mint()\n lengths.set(id, length)\n return { id, from: 0 }\n }\n const ops: Array<ReplicatedOp> = []\n const names = new Map<string, ReplicatedId>()\n const start = projection(state)\n let chars = projectedChars(start)\n let current: { document: Document; selection: Selection | null } = {\n document: start.document,\n selection: null,\n }\n // Each transaction is replayed on a shadow rebuilt from the document before it: the\n // normalization between transactions merges runs, which only that document shows.\n for (const transaction of result.transactions) {\n // Applied first, so a transaction that does not fit is reported as such rather than as\n // whatever lookup the translation meets first.\n const applied = apply(current, transaction)\n if (!applied.ok) throw new Error(`translate: a transaction was refused (${applied.error})`)\n const shadow = shadowOf(current.document, chars, names)\n for (const operation of transaction) translateOne(shadow, operation, ops, mint, next)\n current = applied.state\n chars = charsAfter(shadow, chars)\n }\n return {\n ops,\n selection: anchorIn(shadowOf(current.document, chars, names), result.state.selection),\n }\n}\n\nconst replicated = (shadow: Shadow, block: string): ReplicatedId =>\n shadow.names.get(block) ?? (block as ReplicatedId)\n\n/**\n * A run and where it is. The blocks this translation has already touched come first, since\n * a run may have moved between them; any other run is where the document has it.\n */\nconst locateRun = (shadow: Shadow, run: string) => {\n const inBlock = (block: string, runs: Array<ShadowRun>) => {\n const index = runs.findIndex(candidate => candidate.id === run)\n return index === -1 ? undefined : { block, runs, index, run: runs[index]! }\n }\n for (const [block, runs] of shadow.runs.own) {\n const found = inBlock(block, runs)\n if (found !== undefined) return found\n }\n const block = nodeIndex(shadow.document).blockOf.get(run as NodeId)?.id\n const runs = block === undefined ? undefined : shadow.runs.get(block)\n const found = runs === undefined ? undefined : inBlock(block!, runs)\n if (found === undefined) throw new Error(`translate: no run ${run}`)\n return found\n}\n\n/** Each block's characters as a projection shows them. */\nconst projectedChars =\n (start: Projection): BlockChars =>\n block =>\n concatChars(...(start.runs.get(block) ?? []).map(run => run.chars))\n\n/** The character before `offset` in a run, looking back through earlier runs of its block. */\nconst charBefore = (\n runs: ReadonlyArray<ShadowRun>,\n index: number,\n offset: number,\n): CharRef | null => {\n if (offset > 0) return charAt(runs[index]!.chars, offset - 1)\n for (let earlier = index - 1; earlier >= 0; earlier--) {\n const chars = runs[earlier]!.chars\n const length = charsLength(chars)\n if (length > 0) return charAt(chars, length - 1)\n }\n return null\n}\n\nconst siblingBefore = (\n shadow: Shadow,\n parent: string | null,\n index: number,\n): ReplicatedId | null =>\n index === 0 ? null : replicated(shadow, shadow.children.get(parent)![index - 1]!)\n\nconst removeFromParent = (shadow: Shadow, block: string): void => {\n const list = shadow.children.get(shadow.parents.get(block) ?? ROOT)!\n list.splice(list.indexOf(block), 1)\n}\n\n/** Records a block subtree the edit inserted, with minted names for its blocks. */\nconst addSubtree = (shadow: Shadow, block: Block, parent: string | null): void => {\n shadow.parents.set(block.id, parent)\n shadow.runs.set(\n block.id,\n block.children.map(run => ({ id: run.id, chars: [], marks: run.marks })),\n )\n if (block.type === 'Node' && block.blocks !== undefined) {\n shadow.children.set(\n block.id,\n block.blocks.map(child => child.id),\n )\n for (const child of block.blocks) addSubtree(shadow, child, block.id)\n }\n}\n\n/** The id and first index for new text after a character: a continued insert, or a new one. */\ntype NextInsert = (\n after: CharRef | null,\n length: number,\n) => { readonly id: ReplicatedId; readonly from: number }\n\nconst translateOne = (\n shadow: Shadow,\n operation: Operation,\n ops: Array<ReplicatedOp>,\n mint: () => ReplicatedId,\n next: NextInsert,\n): void => {\n switch (operation.type) {\n case 'SetSelection':\n return\n case 'InsertText': {\n if (operation.text.length === 0) return\n const { block, runs, index, run } = locateRun(shadow, operation.at.node)\n const after = charBefore(runs, index, operation.at.offset)\n const { id, from } = next(after, operation.text.length)\n ops.push({\n type: 'Insert',\n id,\n block: replicated(shadow, block),\n after,\n text: operation.text,\n marks: run.marks,\n ...(from === 0 ? {} : { from }),\n })\n run.chars = concatChars(\n sliceChars(run.chars, 0, operation.at.offset),\n [{ id, from, to: from + operation.text.length }],\n sliceChars(run.chars, operation.at.offset, charsLength(run.chars)),\n )\n return\n }\n case 'DeleteText': {\n const { run } = locateRun(shadow, operation.node)\n const removed = sliceChars(run.chars, operation.from, operation.to)\n if (removed.length > 0) ops.push({ type: 'Delete', ranges: removed })\n run.chars = concatChars(\n sliceChars(run.chars, 0, operation.from),\n sliceChars(run.chars, operation.to, charsLength(run.chars)),\n )\n return\n }\n case 'AddMark': {\n const { run } = locateRun(shadow, operation.node)\n // `apply` skips a mark the run already has exactly; an op for it would re-mark text\n // another replica unmarked meanwhile.\n if (run.marks.some(mark => sameMark(mark, operation.mark))) return\n if (run.chars.length > 0) ops.push({ type: 'Mark', ranges: run.chars, mark: operation.mark })\n run.marks = withMark(run.marks, operation.mark)\n return\n }\n case 'RemoveMark': {\n const { run } = locateRun(shadow, operation.node)\n if (!run.marks.some(mark => markName(mark) === operation.mark)) return\n if (run.chars.length > 0)\n ops.push({ type: 'Unmark', ranges: run.chars, name: operation.mark })\n run.marks = run.marks.filter(mark => markName(mark) !== operation.mark)\n return\n }\n case 'SplitRun': {\n if (operation.offset === 0) return\n const { runs, index, run } = locateRun(shadow, operation.node)\n const rest = sliceChars(run.chars, operation.offset, charsLength(run.chars))\n run.chars = sliceChars(run.chars, 0, operation.offset)\n runs.splice(index + 1, 0, { id: operation.textId, chars: rest, marks: run.marks })\n return\n }\n case 'SplitNode': {\n const { block, runs, index, run } = locateRun(shadow, operation.node)\n const into = mint()\n shadow.names.set(operation.blockId, into)\n ops.push({\n type: 'Split',\n block: replicated(shadow, block),\n after: charBefore(runs, index, operation.offset),\n into,\n })\n const moved: Array<ShadowRun> = [\n {\n id: operation.textId,\n chars: sliceChars(run.chars, operation.offset, charsLength(run.chars)),\n marks: run.marks,\n },\n ...runs.slice(index + 1),\n ]\n run.chars = sliceChars(run.chars, 0, operation.offset)\n runs.splice(index + 1)\n shadow.runs.set(operation.blockId, moved)\n const parent = shadow.parents.get(block) ?? ROOT\n const list = shadow.children.get(parent)!\n list.splice(list.indexOf(block) + 1, 0, operation.blockId)\n shadow.parents.set(operation.blockId, parent)\n return\n }\n case 'JoinNode': {\n const intoRuns = shadow.runs.get(operation.into)!\n const lastRun = intoRuns.length - 1\n ops.push({\n type: 'Join',\n into: replicated(shadow, operation.into),\n removed: replicated(shadow, operation.removed),\n after:\n lastRun < 0 ? null : charBefore(intoRuns, lastRun, charsLength(intoRuns[lastRun]!.chars)),\n })\n shadow.runs.get(operation.into)!.push(...shadow.runs.get(operation.removed)!)\n shadow.runs.delete(operation.removed)\n const nested = shadow.children.get(operation.removed)\n if (nested !== undefined) {\n for (const child of nested) shadow.parents.set(child, operation.into)\n shadow.children.get(operation.into)!.push(...nested)\n shadow.children.delete(operation.removed)\n }\n removeFromParent(shadow, operation.removed)\n return\n }\n case 'MoveNode': {\n const parent = operation.parent ?? ROOT\n const from = shadow.parents.get(operation.node) ?? ROOT\n // `apply` skips a move to where the block already is; so does the op it would make.\n if (from === parent && shadow.children.get(parent)!.indexOf(operation.node) === operation.to)\n return\n removeFromParent(shadow, operation.node)\n ops.push({\n type: 'MoveBlock',\n id: replicated(shadow, operation.node),\n parent: parent === ROOT ? null : replicated(shadow, parent),\n after: siblingBefore(shadow, parent, operation.to),\n })\n shadow.children.get(parent)!.splice(operation.to, 0, operation.node)\n shadow.parents.set(operation.node, parent)\n return\n }\n case 'RetypeBlock':\n ops.push({ type: 'Retype', id: replicated(shadow, operation.node), to: operation.to })\n return\n case 'SetProps':\n ops.push({ type: 'SetProps', id: replicated(shadow, operation.node), props: operation.props })\n return\n case 'InsertNode': {\n const parent = operation.parent ?? ROOT\n const after = siblingBefore(shadow, parent, operation.at)\n const built = buildOps(\n [operation.block],\n parent === ROOT ? null : replicated(shadow, parent),\n after,\n mint,\n (block, id) => shadow.names.set(block.id, id),\n )\n ops.push(...built)\n shadow.children.get(parent)!.splice(operation.at, 0, operation.block.id)\n addSubtree(shadow, operation.block, parent)\n // The inserted runs' characters are the Insert ops just built, in the same order.\n const inserts = built.filter(\n (op): op is Extract<ReplicatedOp, { type: 'Insert' }> => op.type === 'Insert',\n )\n let next = 0\n const fill = (block: Block) => {\n const runs = shadow.runs.get(block.id)!\n for (const [index, run] of block.children.entries()) {\n if (run.text.length === 0) continue\n runs[index]!.chars = [{ id: inserts[next++]!.id, from: 0, to: run.text.length }]\n }\n if (block.type === 'Node' && block.blocks !== undefined) block.blocks.forEach(fill)\n }\n fill(operation.block)\n return\n }\n case 'DeleteNode':\n ops.push({ type: 'DeleteBlock', id: replicated(shadow, operation.node) })\n removeFromParent(shadow, operation.node)\n return\n }\n}\n\nconst anchorPosition = (shadow: Shadow, position: Position): AnchoredPosition => {\n const { block, runs, index } = locateRun(shadow, position.node)\n return {\n block: replicated(shadow, block),\n after: charBefore(runs, index, position.offset),\n affinity: position.affinity,\n }\n}\n\nconst anchorIn = (shadow: Shadow, selection: Selection | null): AnchoredSelection | null => {\n if (selection === null) return null\n if (selection.type === 'Node') {\n return shadow.parents.has(selection.node)\n ? { type: 'Node', node: replicated(shadow, selection.node) }\n : null\n }\n return {\n type: 'Range',\n anchor: anchorPosition(shadow, selection.anchor),\n focus: anchorPosition(shadow, selection.focus),\n }\n}\n\n/**\n * Anchors a selection on the projection of `state`, so it can be resolved again after\n * other replicas' ops change the text around it.\n */\nexport const anchor = (\n state: ReplicatedState,\n selection: Selection | null,\n): AnchoredSelection | null => {\n const start = projection(state)\n return anchorIn(shadowOf(start.document, projectedChars(start), new Map()), selection)\n}\n\n// ---------------------------------------------------------------------------------------\n// Resolving a selection\n// ---------------------------------------------------------------------------------------\n\nconst visible = (state: ReplicatedState, block: string): boolean => {\n for (let at: string | null = block; at !== null;) {\n const entry = lookup(state, at)\n if (entry === undefined || entry.deleted) return false\n at = entry.parent\n }\n return true\n}\n\n/** Where a position resolves in the projection: after the nearest visible character. */\nconst resolvePosition = (\n state: ReplicatedState,\n position: AnchoredPosition,\n): Position | undefined => {\n const runs = projection(state).runs\n const atStart = (block: string): Position | undefined => {\n const first = runs.get(block)?.[0]\n return first === undefined\n ? undefined\n : { node: first.id, offset: 0, affinity: position.affinity }\n }\n if (position.after === null) {\n const place = startOf(draft(state), position.block)\n if (place === undefined || !visible(state, place.block)) return undefined\n // A joined block starts after the text of the one it was joined into.\n const before = lookup(state, place.block)?.spans[place.index - 1]\n return before === undefined\n ? atStart(place.block)\n : resolvePosition(state, {\n ...position,\n block: place.block as ReplicatedId,\n after: charRef(before.id, before.offset + before.text.length - 1),\n })\n }\n const { id, index } = parseChar(position.after)\n // The block's visible characters in order; the anchor, or the last visible one before it.\n for (const block of holdersIn(holdersOf(state), id) ?? []) {\n const entry = lookup(state, block)!\n const spanIndex = entry.spans.findIndex(\n span => span.id === id && index >= span.offset && index < span.offset + span.text.length,\n )\n if (spanIndex === -1) continue\n const span = entry.spans[spanIndex]!\n let target: { id: string; index: number } | undefined = span.deleted ? undefined : { id, index }\n for (let earlier = spanIndex - 1; target === undefined && earlier >= 0; earlier--) {\n const candidate = entry.spans[earlier]!\n if (!candidate.deleted) {\n target = { id: candidate.id, index: candidate.offset + candidate.text.length - 1 }\n }\n }\n if (target === undefined) return atStart(block)\n let offset = 0\n for (const run of runs.get(block) ?? []) {\n for (const range of run.chars) {\n if (range.id === target.id && target.index >= range.from && target.index < range.to) {\n return {\n node: run.id,\n offset: offset + target.index - range.from + 1,\n affinity: position.affinity,\n }\n }\n offset += range.to - range.from\n }\n offset = 0\n }\n }\n return visible(state, position.block) ? atStart(position.block) : undefined\n}\n\n/**\n * The selection an anchored one names in the projection of `state`. A position whose\n * character was deleted moves back to the nearest character still shown; one whose block\n * is gone resolves to nothing, and so does the selection.\n */\nexport const resolve = (\n state: ReplicatedState,\n selection: AnchoredSelection | null,\n): Selection | null => {\n if (selection === null) return null\n if (selection.type === 'Node') {\n return visible(state, selection.node)\n ? { type: 'Node', node: NodeId.make(selection.node) }\n : null\n }\n const anchorAt = resolvePosition(state, selection.anchor)\n const focusAt = resolvePosition(state, selection.focus)\n return anchorAt === undefined || focusAt === undefined\n ? null\n : { type: 'Range', anchor: anchorAt, focus: focusAt }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,eAAe,OAAO,OAAO,MACxC,OAAO,UAAU,sCAAsC,CACzD,CAAC,CAAC,KAAK,OAAO,MAAM,+BAA+B,CAAC;;AAIpD,MAAa,UAAU,OAAO,OAAO,MACnC,OAAO,UAAU,yDAAyD,CAC5E,CAAC,CAAC,KAAK,OAAO,MAAM,0BAA0B,CAAC;AAG/C,MAAM,QAAQ,OAAO,OAAO,MAAM,OAAO,MAAM,GAAG,OAAO,uBAAuB,CAAC,CAAC;;AAGlF,MAAa,YAAY,OAAO,OAAO;CAAE,IAAI;CAAc,MAAM;CAAO,IAAI;AAAM,CAAC;;AAInF,MAAa,aAAa,OAAO,MAAM;CACrC,OAAO,OAAO,EAAE,MAAM,OAAO,QAAQ,WAAW,EAAE,CAAC;CACnD,OAAO,OAAO;EAAE,MAAM,OAAO,QAAQ,SAAS;EAAG,OAAO,OAAO,SAAS;GAAC;GAAG;GAAG;GAAG;GAAG;GAAG;EAAC,CAAC;CAAE,CAAC;CAC7F,OAAO,OAAO;EACZ,MAAM,OAAO,QAAQ,MAAM;EAC3B,MAAM,OAAO;EACb,OAAO,OAAO;;EAEd,OAAO,OAAO,SAAS;GAAC;GAAQ;GAAU;EAAM,CAAC;CACnD,CAAC;CACD,OAAO,OAAO;EACZ,MAAM,OAAO,QAAQ,SAAS;EAC9B,cAAc,OAAO;EACrB,OAAO,OAAO;CA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** The kind a search decoration carries, which is what a stylesheet reaches it by. */
|
|
4
|
+
export declare const SEARCH_DECORATION = "search";
|
|
5
|
+
/** The kind the match a find bar is on carries instead, so it can be drawn apart. */
|
|
6
|
+
export declare const SEARCH_CURRENT_DECORATION = "search-current";
|
|
7
|
+
export interface SearchOptions {
|
|
8
|
+
/** Whether case counts; by default it does not. */
|
|
9
|
+
readonly caseSensitive?: boolean | undefined;
|
|
10
|
+
}
|
|
11
|
+
/** One occurrence: its block, its offset in the block's text, and its ends as positions. */
|
|
12
|
+
export interface SearchMatch {
|
|
13
|
+
readonly block: NodeId;
|
|
14
|
+
readonly at: number;
|
|
15
|
+
readonly length: number;
|
|
16
|
+
readonly from: Position;
|
|
17
|
+
readonly to: Position;
|
|
18
|
+
}
|
|
19
|
+
/** Every occurrence of `query`, in document order; none for an empty query. */
|
|
20
|
+
export declare const findMatches: (document: Document, query: string, options?: SearchOptions) => ReadonlyArray<SearchMatch>;
|
|
21
|
+
/**
|
|
22
|
+
* Every occurrence of `query` in the document, as decorations a renderer can draw; the one at
|
|
23
|
+
* index `current`, when given, carries `search-current` instead of `search`.
|
|
24
|
+
*/
|
|
25
|
+
export declare const searchDecorations: (document: Document, query: string, options?: SearchOptions & {
|
|
26
|
+
readonly current?: number | undefined;
|
|
27
|
+
}) => DecorationSet;
|
|
28
|
+
//# sourceMappingURL=search.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search.d.ts","names":[],"sources":["../src/search.ts"],"mappings":";;;qBAqBa;;qBAEA;iBAEI;;WAEN;;;iBAIM;WACN,OAAO;WACP;WACA;WACA,MAAM;WACN,IAAI;;;qBAcF,cAAW,UACZ,UAAQ,eACL,UACJ,kBACR,cAAc;;;;;qBAuBJ,oBAAiB,UAClB,UAAQ,eACL,UACJ;WAA2B;MACnC"}
|
package/dist/search.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { eachBlock, positionInBlock } from "./document.js";
|
|
2
|
+
// src/search.ts
|
|
3
|
+
/**
|
|
4
|
+
* Search: every occurrence of a query in a document's text, as matches a find bar steps through
|
|
5
|
+
* and as decorations a renderer draws, without changing anything. The producer lives here rather
|
|
6
|
+
* than in an application because it is a pure read of a document and nothing else, and the
|
|
7
|
+
* interpreter that draws the result is the caller's choice — the read-only view renders these as
|
|
8
|
+
* `span[data-decoration="search"]` (§126), and the editable one takes them when its overlay lands.
|
|
9
|
+
*
|
|
10
|
+
* A match never spans two blocks, because what a document has between blocks is a structural
|
|
11
|
+
* boundary rather than text. It may span two *runs*, though, which is why a block's runs are
|
|
12
|
+
* read as one string and the endpoints are mapped back to positions.
|
|
13
|
+
*/
|
|
14
|
+
/** The kind a search decoration carries, which is what a stylesheet reaches it by. */
|
|
15
|
+
const SEARCH_DECORATION = "search";
|
|
16
|
+
/** The kind the match a find bar is on carries instead, so it can be drawn apart. */
|
|
17
|
+
const SEARCH_CURRENT_DECORATION = "search-current";
|
|
18
|
+
/**
|
|
19
|
+
* Text as it is compared: lowercased when case does not count, unless lowercasing would change
|
|
20
|
+
* its length (a dotted capital I does), which would put every offset after it out of step.
|
|
21
|
+
*/
|
|
22
|
+
const comparable = (text, caseSensitive) => {
|
|
23
|
+
if (caseSensitive) return text;
|
|
24
|
+
const lower = text.toLowerCase();
|
|
25
|
+
return lower.length === text.length ? lower : text;
|
|
26
|
+
};
|
|
27
|
+
/** Every occurrence of `query`, in document order; none for an empty query. */
|
|
28
|
+
const findMatches = (document, query, options = {}) => {
|
|
29
|
+
const found = [];
|
|
30
|
+
if (query.length === 0) return found;
|
|
31
|
+
const caseSensitive = options.caseSensitive === true;
|
|
32
|
+
const needle = comparable(query, caseSensitive);
|
|
33
|
+
eachBlock(document.children, (block) => {
|
|
34
|
+
if (block.type === "Unknown" || block.children.length === 0) return;
|
|
35
|
+
const text = comparable(block.children.map((run) => run.text).join(""), caseSensitive);
|
|
36
|
+
for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
|
|
37
|
+
const from = positionInBlock(block, at);
|
|
38
|
+
const to = positionInBlock(block, at + needle.length);
|
|
39
|
+
if (from !== void 0 && to !== void 0) found.push({
|
|
40
|
+
block: block.id,
|
|
41
|
+
at,
|
|
42
|
+
length: needle.length,
|
|
43
|
+
from,
|
|
44
|
+
to
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
return found;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Every occurrence of `query` in the document, as decorations a renderer can draw; the one at
|
|
52
|
+
* index `current`, when given, carries `search-current` instead of `search`.
|
|
53
|
+
*/
|
|
54
|
+
const searchDecorations = (document, query, options = {}) => findMatches(document, query, options).map((match, index) => ({
|
|
55
|
+
from: match.from,
|
|
56
|
+
to: match.to,
|
|
57
|
+
kind: index === options.current ? SEARCH_CURRENT_DECORATION : SEARCH_DECORATION
|
|
58
|
+
}));
|
|
59
|
+
export { SEARCH_CURRENT_DECORATION, SEARCH_DECORATION, findMatches, searchDecorations };
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=search.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search.js","names":[],"sources":["../src/search.ts"],"sourcesContent":["/**\n * Search: every occurrence of a query in a document's text, as matches a find bar steps through\n * and as decorations a renderer draws, without changing anything. The producer lives here rather\n * than in an application because it is a pure read of a document and nothing else, and the\n * interpreter that draws the result is the caller's choice — the read-only view renders these as\n * `span[data-decoration=\"search\"]` (§126), and the editable one takes them when its overlay lands.\n *\n * A match never spans two blocks, because what a document has between blocks is a structural\n * boundary rather than text. It may span two *runs*, though, which is why a block's runs are\n * read as one string and the endpoints are mapped back to positions.\n */\nimport {\n eachBlock,\n positionInBlock,\n type Document,\n type NodeId,\n type Position,\n} from './document.js'\nimport type { Decoration, DecorationSet } from './decoration.js'\n\n/** The kind a search decoration carries, which is what a stylesheet reaches it by. */\nexport const SEARCH_DECORATION = 'search'\n/** The kind the match a find bar is on carries instead, so it can be drawn apart. */\nexport const SEARCH_CURRENT_DECORATION = 'search-current'\n\nexport interface SearchOptions {\n /** Whether case counts; by default it does not. */\n readonly caseSensitive?: boolean | undefined\n}\n\n/** One occurrence: its block, its offset in the block's text, and its ends as positions. */\nexport interface SearchMatch {\n readonly block: NodeId\n readonly at: number\n readonly length: number\n readonly from: Position\n readonly to: Position\n}\n\n/**\n * Text as it is compared: lowercased when case does not count, unless lowercasing would change\n * its length (a dotted capital I does), which would put every offset after it out of step.\n */\nconst comparable = (text: string, caseSensitive: boolean): string => {\n if (caseSensitive) return text\n const lower = text.toLowerCase()\n return lower.length === text.length ? lower : text\n}\n\n/** Every occurrence of `query`, in document order; none for an empty query. */\nexport const findMatches = (\n document: Document,\n query: string,\n options: SearchOptions = {},\n): ReadonlyArray<SearchMatch> => {\n const found: Array<SearchMatch> = []\n if (query.length === 0) return found\n const caseSensitive = options.caseSensitive === true\n const needle = comparable(query, caseSensitive)\n eachBlock(document.children, block => {\n if (block.type === 'Unknown' || block.children.length === 0) return\n const text = comparable(block.children.map(run => run.text).join(''), caseSensitive)\n for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {\n const from = positionInBlock(block, at)\n const to = positionInBlock(block, at + needle.length)\n if (from !== undefined && to !== undefined) {\n found.push({ block: block.id, at, length: needle.length, from, to })\n }\n }\n })\n return found\n}\n\n/**\n * Every occurrence of `query` in the document, as decorations a renderer can draw; the one at\n * index `current`, when given, carries `search-current` instead of `search`.\n */\nexport const searchDecorations = (\n document: Document,\n query: string,\n options: SearchOptions & { readonly current?: number | undefined } = {},\n): DecorationSet =>\n findMatches(document, query, options).map((match, index): Decoration => ({\n from: match.from,\n to: match.to,\n kind: index === options.current ? SEARCH_CURRENT_DECORATION : SEARCH_DECORATION,\n }))\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAa,oBAAoB;;AAEjC,MAAa,4BAA4B;;;;;AAoBzC,MAAM,cAAc,MAAc,kBAAmC;CACnE,IAAI,eAAe,OAAO;CAC1B,MAAM,QAAQ,KAAK,YAAY;CAC/B,OAAO,MAAM,WAAW,KAAK,SAAS,QAAQ;AAChD;;AAGA,MAAa,eACX,UACA,OACA,UAAyB,CAAC,MACK;CAC/B,MAAM,QAA4B,CAAC;CACnC,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,MAAM,gBAAgB,QAAQ,kBAAkB;CAChD,MAAM,SAAS,WAAW,OAAO,aAAa;CAC9C,UAAU,SAAS,WAAU,UAAS;EACpC,IAAI,MAAM,SAAS,aAAa,MAAM,SAAS,WAAW,GAAG;EAC7D,MAAM,OAAO,WAAW,MAAM,SAAS,KAAI,QAAO,IAAI,IAAI,CAAC,CAAC,KAAK,EAAE,GAAG,aAAa;EACnF,KAAK,IAAI,KAAK,KAAK,QAAQ,MAAM,GAAG,MAAM,GAAG,KAAK,KAAK,QAAQ,QAAQ,KAAK,OAAO,MAAM,GAAG;GAC1F,MAAM,OAAO,gBAAgB,OAAO,EAAE;GACtC,MAAM,KAAK,gBAAgB,OAAO,KAAK,OAAO,MAAM;GACpD,IAAI,SAAS,KAAA,KAAa,OAAO,KAAA,GAC/B,MAAM,KAAK;IAAE,OAAO,MAAM;IAAI;IAAI,QAAQ,OAAO;IAAQ;IAAM;GAAG,CAAC;EAEvE;CACF,CAAC;CACD,OAAO;AACT;;;;;AAMA,MAAa,qBACX,UACA,OACA,UAAqE,CAAC,MAEtE,YAAY,UAAU,OAAO,OAAO,CAAC,CAAC,KAAK,OAAO,WAAuB;CACvE,MAAM,MAAM;CACZ,IAAI,MAAM;CACV,MAAM,UAAU,QAAQ,UAAU,4BAA4B;AAChE,EAAE"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
import { Document, Selection } from "./document.js";
|
|
3
|
+
import { MarkDef } from "./marks.js";
|
|
4
|
+
import { NodeDefinition } from "./kit.js";
|
|
5
|
+
import { Rendering } from "./rendering.js";
|
|
6
|
+
/**
|
|
7
|
+
* A struck-through span. It expands `after`, so typing at its edge continues it, as
|
|
8
|
+
* bold and italic do.
|
|
9
|
+
*/
|
|
10
|
+
export declare const Strikethrough: MarkDef<undefined>;
|
|
11
|
+
/**
|
|
12
|
+
* A hyperlink. Its `href` is a prop rather than a mark name, which is what lets the
|
|
13
|
+
* serializer render a real `<a href>` (§121); it expands `none`, because text typed
|
|
14
|
+
* after a link is new text, not a continuation of the link.
|
|
15
|
+
*/
|
|
16
|
+
export declare const Link: MarkDef<Schema.Struct<{
|
|
17
|
+
readonly href: Schema.String;
|
|
18
|
+
}>>;
|
|
19
|
+
/** The link a selection starts in: its `href`, and the range of runs it spans. */
|
|
20
|
+
export interface LinkAt {
|
|
21
|
+
/** The stored `href`, or `''` when the stored one is not a string. */
|
|
22
|
+
readonly href: string;
|
|
23
|
+
readonly selection: Extract<Selection, {
|
|
24
|
+
readonly type: 'Range';
|
|
25
|
+
}>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The link a selection starts in, which is what a link editor opens on: at a caret, the
|
|
29
|
+
* link around it; over a range, the link its start is in. Undefined outside a link, and for
|
|
30
|
+
* a node selection, which covers blocks rather than text.
|
|
31
|
+
*/
|
|
32
|
+
export declare const linkAt: (document: Document, selection: Selection | null) => LinkAt | undefined;
|
|
33
|
+
/** Every mark the standard vocabulary names, in menu order. */
|
|
34
|
+
export declare const standardMarks: ReadonlyArray<MarkDef>;
|
|
35
|
+
/**
|
|
36
|
+
* The standard node kinds. Constraints are what make a kind more than a name: a
|
|
37
|
+
* `List` accepts only `ListItem`s and a `Table` only `TableRow`s, so `validate`
|
|
38
|
+
* reports a document that says otherwise (§125); a `CodeBlock` carries text with no
|
|
39
|
+
* formatting, and its `language` is a prop, not a mark.
|
|
40
|
+
*/
|
|
41
|
+
export declare const standardNodes: ReadonlyArray<NodeDefinition>;
|
|
42
|
+
/**
|
|
43
|
+
* An `Image`'s `width` and `height` attributes from its props' `asset`, at its drawn `width`
|
|
44
|
+
* when it has one, so a page keeps the box before the file arrives; none without facts. The
|
|
45
|
+
* standard rendering writes them; a rendering of its own (a figure) spreads them on its `img`.
|
|
46
|
+
* The facts are trusted to be `src`'s: whatever changes `src` replaces or clears `asset`.
|
|
47
|
+
*/
|
|
48
|
+
export declare const imageBox: (props: Readonly<Record<string, unknown>>) => Readonly<Record<string, string>>;
|
|
49
|
+
/**
|
|
50
|
+
* How the standard vocabulary renders (§121): the element each kind is, with the props
|
|
51
|
+
* that belong in attributes read from the block, so a `Link` is an `<a href>`, an `Image`
|
|
52
|
+
* carries its source, and a `List` is an `<ol>` or a `<ul>`. The shipped marks already
|
|
53
|
+
* nest in `strong`/`em`/`code`; this adds the two that do not. An application composes it
|
|
54
|
+
* with `renderingOver` and names its own kinds beside it:
|
|
55
|
+
*
|
|
56
|
+
* ```ts
|
|
57
|
+
* renderingOver(RichText.standardRendering, { nodes: { Callout: { tag: 'aside' } } })
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export declare const standardRendering: Rendering;
|
|
61
|
+
//# sourceMappingURL=standard.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard.d.ts","names":[],"sources":["../src/standard.ts"],"mappings":";;;;;;;;;qBA+Ba,eAAa;;;;;;qBAOb,MAAI,QAAA,OAAA;;;;iBAMA;;WAEN;WACA,WAAW,QAAQ;aAAsB;;;;;;;;qBAQvC,SAAM,UAAc,UAAQ,WAAa,qBAAmB;;qBAU5D,eAAe,cAAc;;;;;;;qBAQ7B,eAAe,cAAc;;;;;;;qBAiE7B,WAAQ,OACZ,SAAS,6BACf,SAAS;;;;;;;;;;;;qBAkCC,mBAAmB"}
|