foldkit-richtext 0.4.0 → 0.5.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["pathKey","resolve","pathKey","textOf","holdsBlocks","pathKey","locateRun"],"sources":["../src/document.ts","../src/marks.ts","../src/rendering.ts","../src/html.ts","../src/clipboard.ts","../src/kit.ts","../src/transform.ts","../src/transaction.ts","../src/indent.ts","../src/search.ts","../src/footnote.ts","../src/table.ts","../src/command.ts","../src/input.ts","../src/history.ts","../src/decoration.ts","../src/code.ts","../src/url.ts","../src/standard.ts","../src/migration.ts","../src/replicated.ts","../src/outline.ts","../src/media.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Caller-assigned identity, unique across blocks and text runs in a document. */\nexport const NodeId = Schema.NonEmptyString.pipe(Schema.brand('foldkit-richtext/NodeId'))\nexport type NodeId = typeof NodeId.Type\n\n/** The mark names this vocabulary defines; a document may hold others verbatim. */\nexport const Mark = Schema.Literals(['Bold', 'Italic', 'Code'])\nexport type Mark = typeof Mark.Type\n\n/** A schema this version can hand to `decodeUnknownSync` at a Kit boundary. */\nexport type PropsSchema = Schema.Codec<any, any, never>\n\n/**\n * A mark with props: which mark, plus the JSON data it carries. Props are JSON\n * here for the same reason a node's are: the document codec cannot know an\n * application's schemas, so a Kit validates them at that boundary (§12).\n */\nexport const MarkValue = Schema.Struct({\n name: Schema.NonEmptyString,\n props: Schema.optionalKey(Schema.JsonObject),\n})\nexport type MarkValue = typeof MarkValue.Type\n\n/**\n * A mark as a text run stores it: a bare name for a mark with no props, or a\n * value when it has them. Loading preserves the form it found, so a names-only\n * document round-trips byte-equal, and because a run carries a name at most once\n * it never holds both forms of one mark.\n */\nexport const RunMark = Schema.Union([Schema.NonEmptyString, MarkValue])\nexport type RunMark = typeof RunMark.Type\n\n/** A mark's name: a bare string is a mark with no props, an object carries them. */\nexport const markName = (mark: RunMark): string => (typeof mark === 'string' ? mark : mark.name)\n\n/**\n * The content a block holds: runs, or nested blocks (§13). A document does not\n * declare which a block kind accepts — its Kit does — so these are the words a\n * declaration and a migration both use.\n */\nexport const textContent = 'text' as const\nexport const blockContent = 'blocks' as const\nexport type ContentMode = typeof textContent | typeof blockContent\n\n/**\n * The wire shape of a value: the same structure with identities unbranded. A\n * branded `NodeId` encodes as a plain string, so an annotated schema whose type\n * mentions one cannot claim its encoded form is the type itself; this names the\n * wire side, which the recursive block schema needs to break its type cycle.\n */\ntype Wire<T> = T extends NodeId\n ? string\n : T extends ReadonlyArray<infer E>\n ? ReadonlyArray<Wire<E>>\n : T extends object\n ? { readonly [K in keyof T]: Wire<T[K]> }\n : T\n\nexport const Text = Schema.Struct({\n type: Schema.Literal('Text'),\n id: NodeId,\n text: Schema.String,\n // A mark name this version does not define loads verbatim; `Edit.addMark`\n // still accepts only what the caller's vocabulary declares. A run carries a\n // name at most once; see `findUnknownMarks` for the publishing gate.\n marks: Schema.Array(RunMark).check(\n Schema.makeFilter(\n marks => new Set(marks.map(markName)).size === marks.length || 'Invalid marks',\n ),\n ),\n})\nexport type Text = typeof Text.Type\n\nexport const Paragraph = Schema.Struct({\n type: Schema.Literal('Paragraph'),\n id: NodeId,\n children: Schema.Array(Text),\n})\nexport type Paragraph = typeof Paragraph.Type\n\nexport const Heading = Schema.Struct({\n type: Schema.Literal('Heading'),\n id: NodeId,\n level: Schema.Literals([1, 2, 3, 4, 5, 6]),\n children: Schema.Array(Text),\n})\nexport type Heading = typeof Heading.Type\n\n/**\n * A block whose `type` this version does not implement, retained verbatim for\n * recovery and migration: the original type, its remaining JSON fields, and no\n * text runs (its subtree lives in `props`, opaque). Unknown blocks are\n * read-only content: address them structurally, never edit their text.\n */\nexport const UnknownBlock = Schema.Struct({\n type: Schema.Literal('Unknown'),\n id: NodeId,\n originalType: Schema.NonEmptyString,\n props: Schema.JsonObject,\n children: Schema.Array(Text).check(\n Schema.makeFilter(runs => runs.length === 0 || 'Unknown blocks keep no text runs'),\n ),\n})\nexport type UnknownBlock = typeof UnknownBlock.Type\n\n/**\n * A block whose kind the application declares: a Callout, an Image, an embed.\n * `props` is JSON at the codec level because the document codec cannot know an\n * application's schemas; a Kit's node definition validates it at that boundary,\n * and runtime declarations stay outside the codec (§12). `children` are text\n * runs, so positions, operations, and selection work on it unchanged.\n *\n * `blocks` holds nested blocks, and its presence is what says the kind accepts\n * them (§116): a List holds ListItems, a Quote holds paragraphs. A kind with\n * nested blocks has no direct runs, which is why `children` stays `Text[]` on\n * every block kind — a container simply leaves it empty, as `UnknownBlock` does.\n *\n * The shape is written by hand because `Block` and this type are mutually\n * recursive, and TypeScript cannot infer through that cycle: the schema's\n * nested field names the interface, and the interface names the union.\n */\nexport interface NodeBlock {\n readonly type: 'Node'\n readonly kind: string\n readonly id: NodeId\n readonly props: Schema.JsonObject\n readonly children: ReadonlyArray<Text>\n readonly blocks?: ReadonlyArray<Block>\n}\n\nexport const NodeBlock = Schema.Struct({\n type: Schema.Literal('Node'),\n kind: Schema.NonEmptyString,\n id: NodeId,\n props: Schema.JsonObject,\n children: Schema.Array(Text),\n blocks: Schema.optionalKey(\n Schema.suspend((): Schema.Codec<ReadonlyArray<Block>, Wire<ReadonlyArray<Block>>> =>\n Schema.Array(Block),\n ),\n ),\n}).check(\n Schema.makeFilter(\n block =>\n block.blocks === undefined ||\n block.children.length === 0 ||\n 'A block with nested blocks keeps no direct runs',\n ),\n)\n\nexport type Block = Paragraph | Heading | NodeBlock | UnknownBlock\nexport const Block = Schema.Union([Paragraph, Heading, NodeBlock, UnknownBlock])\n\n/** Every identity a block subtree owns, block and run alike, in document order. */\nconst subtreeIds = (block: Block): ReadonlyArray<NodeId> => [\n block.id,\n ...block.children.map(run => run.id),\n ...(block.type === 'Node' && block.blocks !== undefined ? block.blocks.flatMap(subtreeIds) : []),\n]\n\n/** Version 1's initial block vocabulary, with document-wide identity validation. */\nexport const Document = Schema.Struct({\n version: Schema.Literal(1),\n children: Schema.Array(Block),\n}).check(\n Schema.makeFilter(document => {\n const ids = new Set<NodeId>()\n for (const block of document.children) {\n for (const id of subtreeIds(block)) {\n if (ids.has(id)) return 'Duplicate node identity'\n ids.add(id)\n }\n }\n return true\n }),\n)\nexport type Document = typeof Document.Type\n\nconst isKnownBlockType = (type: unknown): boolean =>\n type === 'Paragraph' || type === 'Heading' || type === 'Node'\n\n/**\n * Converts a block whose type this version does not implement into an `Unknown`\n * node, and does the same inside a known node block's nested blocks. Everything\n * except `type` and `id` becomes opaque JSON props; the raw subtree is preserved\n * there verbatim.\n */\nconst preserveBlock = (input: unknown): unknown => {\n if (typeof input !== 'object' || input === null) return input\n const block = input as Record<string, unknown>\n if (!isKnownBlockType(block.type) && block.type !== 'Unknown') {\n const { type, id, ...props } = block\n return { type: 'Unknown', id, originalType: type, props, children: [] }\n }\n return Array.isArray(block.blocks) ? { ...block, blocks: block.blocks.map(preserveBlock) } : block\n}\n\n/**\n * Converts blocks whose type this version does not implement into `Unknown`\n * nodes before structural decoding, so persisted content survives a deploy\n * that lost a node implementation. Nested blocks are walked for the same reason.\n */\nconst preserveUnknownBlocks = (input: unknown): unknown => {\n if (typeof input !== 'object' || input === null) return input\n const document = input as { children?: unknown }\n if (!Array.isArray(document.children)) return input\n return { ...document, children: document.children.map(preserveBlock) }\n}\n\n/** Strict boundary for persisted content. Throws a Schema error on invalid input. */\nconst decodeStructure = Schema.decodeUnknownSync(Document, { onExcessProperty: 'error' })\n\nconst PositiveCount = Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0))\n\n/** Bounds for decoded documents: blocks, text runs, and total UTF-16 text units. */\nexport const DocumentLimits = Schema.Struct({\n maxBlocks: PositiveCount,\n maxTextRuns: PositiveCount,\n maxTextLength: PositiveCount,\n})\nexport type DocumentLimits = typeof DocumentLimits.Type\n\n/** Generous DoS guardrails, not application quotas; tighten per document with a spread. */\nexport const DefaultDocumentLimits: DocumentLimits = DocumentLimits.make({\n maxBlocks: 10_000,\n maxTextRuns: 50_000,\n maxTextLength: 5_000_000,\n})\n\n/** Every block a subtree holds, nested ones included. */\nconst countBlocks = (blocks: ReadonlyArray<Block>): number => {\n let count = 0\n eachBlock(blocks, () => {\n count += 1\n })\n return count\n}\n\n/**\n * Strict boundary for persisted content. Decodes structure first, then enforces\n * `limits`. Throws a Schema error on invalid input, or an Error naming the\n * first exceeded bound.\n */\nexport const decodeDocument = (\n input: unknown,\n limits: DocumentLimits = DefaultDocumentLimits,\n): Document => {\n const document = decodeStructure(preserveUnknownBlocks(input))\n const summary = inspect(document)\n const blocks = countBlocks(document.children)\n const runs = summary.nodeCount - blocks\n if (blocks > limits.maxBlocks)\n throw new Error(`Document exceeds maxBlocks: ${blocks} > ${limits.maxBlocks}`)\n if (runs > limits.maxTextRuns)\n throw new Error(`Document exceeds maxTextRuns: ${runs} > ${limits.maxTextRuns}`)\n if (summary.textLength > limits.maxTextLength)\n throw new Error(\n `Document exceeds maxTextLength: ${summary.textLength} > ${limits.maxTextLength}`,\n )\n return document\n}\n\n/**\n * A block's address: root-first container indices. `[2]` is the third top-level\n * block, `[2, 0]` is the first block nested inside it (§116). A block's depth is\n * its path's length.\n */\nexport type BlockPath = ReadonlyArray<number>\n\n/** A stable key for a block path, so paths can key maps and compare cheaply. */\nexport const pathKey = (path: BlockPath): string => path.join('.')\n\n/** Walks every block subtree in document order, visiting each with its path. */\nexport const eachBlock = (\n blocks: ReadonlyArray<Block>,\n visit: (block: Block, path: BlockPath) => void,\n prefix: BlockPath = [],\n): void => {\n for (const [index, block] of blocks.entries()) {\n const path = [...prefix, index]\n visit(block, path)\n if (block.type === 'Node' && block.blocks !== undefined) eachBlock(block.blocks, visit, path)\n }\n}\n\n/** A run's place in document order: its block's path, then its index in that block. */\nexport interface RunPlace {\n readonly path: BlockPath\n readonly index: number\n}\n\n/** A run with the identity it was found by. */\nexport interface LocatedRun extends RunPlace {\n readonly run: Text\n}\n\n/** Document order over run places: path first, then the run's index. */\nexport const compareRunPlaces = (left: RunPlace, right: RunPlace): number => {\n const shared = Math.min(left.path.length, right.path.length)\n for (let index = 0; index < shared; index++) {\n if (left.path[index] !== right.path[index]) return left.path[index]! - right.path[index]!\n }\n if (left.path.length !== right.path.length) return left.path.length - right.path.length\n return left.index - right.index\n}\n\n/** A position's place in document order: its run's place, then its offset in that run. */\nexport interface PositionPlace extends RunPlace {\n readonly offset: number\n}\n\n/** Document order over position places: the run first, then the offset within it. */\nexport const comparePositionPlaces = (left: PositionPlace, right: PositionPlace): number =>\n compareRunPlaces(left, right) || left.offset - right.offset\n\n/** The block a path addresses, or undefined when the path does not resolve. */\nexport const blockAtPath = (document: Document, path: BlockPath): Block | undefined => {\n let blocks: ReadonlyArray<Block> = document.children\n let found: Block | undefined\n for (const index of path) {\n found = blocks[index]\n if (found === undefined) return undefined\n blocks = found.type === 'Node' && found.blocks !== undefined ? found.blocks : []\n }\n return found\n}\n\n/** The block with this identity, wherever it sits. */\nexport const locateBlock = (\n document: Document,\n node: NodeId,\n): { readonly path: BlockPath; readonly block: Block } | undefined => {\n let found: { readonly path: BlockPath; readonly block: Block } | undefined\n eachBlock(document.children, (block, path) => {\n if (found === undefined && block.id === node) found = { path, block }\n })\n return found\n}\n\n/**\n * The blocks either side of a block in its own container, which a handle's up and down move it\n * past; both absent when the document does not hold it.\n */\nexport const siblingsOf = (\n document: Document,\n node: NodeId,\n): { readonly previous?: Block | undefined; readonly next?: Block | undefined } => {\n const found = locateBlock(document, node)\n if (found === undefined) return {}\n const index = found.path[found.path.length - 1]!\n const container = found.path.slice(0, -1)\n const parent = container.length === 0 ? undefined : blockAtPath(document, container)\n const blocks = parent?.type === 'Node' ? (parent.blocks ?? []) : document.children\n return { previous: blocks[index - 1], next: blocks[index + 1] }\n}\n\n/** The run with this identity, wherever it sits. */\nexport const locateRun = (document: Document, node: NodeId): LocatedRun | undefined => {\n let found: LocatedRun | undefined\n eachBlock(document.children, (block, path) => {\n if (found !== undefined) return\n const index = block.children.findIndex(run => run.id === node)\n if (index >= 0) found = { path, index, run: block.children[index]! }\n })\n return found\n}\n\n/**\n * Whether a reader would see nothing: no blocks, or a lone paragraph or heading whose runs\n * hold no text. What an editor shows its placeholder for; a lone empty list or code block is\n * content a writer made, so it is not blank.\n */\nexport const isBlank = (document: Document): boolean => {\n const first = document.children[0]\n if (first === undefined) return true\n return (\n document.children.length === 1 &&\n (first.type === 'Paragraph' || first.type === 'Heading') &&\n first.children.every(run => run.text.length === 0)\n )\n}\n\n/**\n * The text of the block a position addresses, up to that position, in run order.\n * A menu reads this: what a query is typed into is the block's text between its\n * start and the caret, and a query never spans blocks. Affinity is not consulted — a\n * prefix ends between characters whatever side the caret leans to — an offset past a\n * run's end clamps to it, a negative one reads as none of it, and a position that\n * resolves to nothing gives an empty string.\n */\nexport const textBefore = (document: Document, position: Position): string => {\n const found = locateRun(document, position.node)\n if (found === undefined) return ''\n const block = blockAtPath(document, found.path)\n if (block === undefined) return ''\n const lead = block.children\n .slice(0, found.index)\n .map(earlier => earlier.text)\n .join('')\n return lead + found.run.text.slice(0, Math.max(0, position.offset))\n}\n\n/**\n * Whichever end of a range comes first in the document, whatever direction it was made in,\n * or `undefined` when either end does not resolve. What replaces a range starts here, so a\n * read of the text before an edit reads from this end rather than the anchor.\n */\nexport const rangeStart = (\n document: Document,\n range: Extract<Selection, { readonly type: 'Range' }>,\n): Position | undefined => {\n const anchor = locateRun(document, range.anchor.node)\n const focus = locateRun(document, range.focus.node)\n if (anchor === undefined || focus === undefined) return undefined\n return comparePositionPlaces(\n { ...anchor, offset: range.anchor.offset },\n { ...focus, offset: range.focus.offset },\n ) <= 0\n ? range.anchor\n : range.focus\n}\n\n/**\n * The position a block's text offset addresses, or `undefined` when it is negative or past\n * the end. The inverse of `textBefore` for one block: a rule, a search match, or any producer\n * working in a block's own text needs it to say where what it found is.\n */\nexport const positionInBlock = (block: Block, offset: number): Position | undefined => {\n if (offset < 0) return undefined\n let consumed = 0\n for (const run of block.children) {\n const next = consumed + run.text.length\n if (offset <= next) {\n return {\n node: run.id,\n offset: offset - consumed,\n affinity: offset === next ? 'after' : 'before',\n }\n }\n consumed = next\n }\n return undefined\n}\n\n/**\n * The range covering the `length` characters before `position` in its block, or\n * `undefined` when the position does not resolve, `length` is not positive, or fewer\n * characters precede it. The inverse of `textBefore`: an input rule or a menu deletes\n * what it matched with this range, so removing the match and acting on it commit as one\n * action (§124 §5). Endpoints land at run boundaries with `after` affinity, which is\n * where a caret that typed that character would sit.\n */\nexport const textRangeBefore = (\n document: Document,\n position: Position,\n length: number,\n): Selection | undefined => {\n if (length <= 0) return undefined\n const found = locateRun(document, position.node)\n if (found === undefined) return undefined\n const block = blockAtPath(document, found.path)\n if (block === undefined) return undefined\n const lead = block.children\n .slice(0, found.index)\n .reduce((total, run) => total + run.text.length, 0)\n // Clamped to the run as `textBefore` clamps, so an overlong offset never reads into the next run.\n const end = lead + Math.min(found.run.text.length, Math.max(0, position.offset))\n const start = end - length\n if (start < 0) return undefined\n const anchor = positionInBlock(block, start)\n const focus = positionInBlock(block, end)\n return anchor === undefined || focus === undefined ? undefined : { type: 'Range', anchor, focus }\n}\n\n/** Every node a block subtree owns, block and run alike, keyed by identity. */\nconst indexNodes = (blocks: ReadonlyArray<Block>, nodes: Map<NodeId, Block | Text>): void => {\n eachBlock(blocks, block => {\n nodes.set(block.id, block)\n for (const run of block.children) nodes.set(run.id, run)\n })\n}\n\nconst isKnownMarkName = Schema.is(Mark)\n\n/** A mark this vocabulary does not define, kept verbatim on its text run. */\nexport interface UnknownMark {\n readonly node: NodeId\n /** The mark's name; its props, if any, stay on the run. */\n readonly mark: string\n}\n\n/** Lists unknown marks per text run; empty means the document publishes cleanly. */\nexport const findUnknownMarks = (document: Document): ReadonlyArray<UnknownMark> => {\n const unknown: Array<UnknownMark> = []\n eachBlock(document.children, block => {\n for (const text of block.children) {\n for (const mark of text.marks) {\n const name = markName(mark)\n if (!isKnownMarkName(name)) unknown.push({ node: text.id, mark: name })\n }\n }\n })\n return unknown\n}\n\n/** A block this vocabulary does not implement, retained for migration. */\nexport interface UnknownNode {\n readonly node: NodeId\n readonly originalType: string\n}\n\n/** Lists preserved unknown blocks; empty means the document publishes cleanly. */\nexport const findUnknownNodes = (document: Document): ReadonlyArray<UnknownNode> => {\n const unknown: Array<UnknownNode> = []\n eachBlock(document.children, block => {\n if (block.type === 'Unknown') {\n unknown.push({ node: block.id, originalType: block.originalType })\n }\n })\n return unknown\n}\n\n/** UTF-16 offset in one text run, with insertion affinity at that offset. */\nexport const Position = Schema.Struct({\n node: NodeId,\n offset: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),\n affinity: Schema.Literals(['before', 'after']),\n})\nexport type Position = typeof Position.Type\n\n/** A reusable identity resolved against an explicit document, without owning its content. */\nexport interface NodeReference {\n readonly id: NodeId\n /** Returns the current node, or undefined if this document does not contain it. */\n readonly read: (document: Document) => Block | Text | undefined\n /** Describes a text position; application of an edit checks the target and bounds. */\n readonly at: (offset: number, affinity: Position['affinity']) => Position\n}\n\nexport const Node = {\n /** Declares an immutable reference. Does not insert a node or reserve its ID. */\n make: (id: string): NodeReference => {\n const nodeId = NodeId.make(id)\n return Object.freeze({\n id: nodeId,\n read: (document: Document): Block | Text | undefined => {\n const nodes = new Map<NodeId, Block | Text>()\n indexNodes(document.children, nodes)\n return nodes.get(nodeId)\n },\n at: (offset: number, affinity: Position['affinity']): Position =>\n Position.make({ node: nodeId, offset, affinity }),\n })\n },\n}\n\nexport const Selection = Schema.Union([\n Schema.Struct({ type: Schema.Literal('Range'), anchor: Position, focus: Position }),\n Schema.Struct({ type: Schema.Literal('Node'), node: NodeId }),\n])\nexport type Selection = typeof Selection.Type\n\n/** Every node of a document by identity, with where each block and run sits. */\nexport interface NodeIndex {\n readonly nodes: ReadonlyMap<NodeId, Block | Text>\n /** Each run's block. */\n readonly blockOf: ReadonlyMap<NodeId, Block>\n /** Each block's parent block, `null` at the top level. */\n readonly parentOf: ReadonlyMap<NodeId, NodeId | null>\n}\nconst nodeIndexes = new WeakMap<Document, NodeIndex>()\n/** The document's `NodeIndex`, built once per document: documents are immutable. */\nexport const nodeIndex = (document: Document): NodeIndex => {\n const cached = nodeIndexes.get(document)\n if (cached !== undefined) return cached\n const nodes = new Map<NodeId, Block | Text>()\n const blockOf = new Map<NodeId, Block>()\n const parentOf = new Map<NodeId, NodeId | null>()\n const visit = (blocks: ReadonlyArray<Block>, parent: NodeId | null): void => {\n for (const block of blocks) {\n nodes.set(block.id, block)\n parentOf.set(block.id, parent)\n for (const run of block.children) {\n nodes.set(run.id, run)\n blockOf.set(run.id, block)\n }\n if (block.type === 'Node' && block.blocks !== undefined) visit(block.blocks, block.id)\n }\n }\n visit(document.children, null)\n const index = { nodes, blockOf, parentOf }\n nodeIndexes.set(document, index)\n return index\n}\n\n/** Validates references without sorting range endpoints or changing direction. */\nexport const selectionIsValid = (document: Document, selection: Selection | null): boolean => {\n if (selection === null) return true\n const { nodes } = nodeIndex(document)\n if (selection.type === 'Node') return nodes.has(selection.node)\n return [selection.anchor, selection.focus].every(position => {\n const node = nodes.get(position.node)\n return (\n node?.type === 'Text' &&\n Number.isInteger(position.offset) &&\n position.offset >= 0 &&\n position.offset <= node.text.length\n )\n })\n}\n\nexport const EditorState = Schema.Struct({\n document: Document,\n selection: Schema.NullOr(Selection),\n}).check(\n Schema.makeFilter(\n state => selectionIsValid(state.document, state.selection) || 'Unresolved selection',\n ),\n)\nexport type EditorState = typeof EditorState.Type\n\nconst decodeBlock = Schema.decodeUnknownSync(Block, { onExcessProperty: 'error' })\nconst decodeSelection = Schema.decodeUnknownSync(Schema.NullOr(Selection), {\n onExcessProperty: 'error',\n})\n/**\n * Blocks and documents that have passed validation. They are immutable, and an edit copies\n * only the blocks on the path to what it touches, so a keystroke re-validates that path\n * rather than the document or a whole container.\n */\nconst validBlocks = new WeakSet<Block>()\nconst validDocuments = new WeakSet<Document>()\n\n/**\n * Throws unless `block` decodes as a `Block`, caching every block that passes, nested ones\n * included. A block's validity does not depend on where it sits (the codec has no placement\n * or depth rules; identity is checked document-wide by the caller), so a node block is valid\n * exactly when its own fields are and each nested block is: those are checked separately, the\n * fields by decoding the block with its nested blocks emptied.\n */\nconst assertBlock = (block: unknown): void => {\n if (typeof block !== 'object' || block === null) return void decodeBlock(block)\n if (validBlocks.has(block as Block)) return\n const nested = Object.getOwnPropertyDescriptor(block, 'blocks')\n if ((block as { type?: unknown }).type === 'Node' && Array.isArray(nested?.value)) {\n // Every other own key, enumerable or not, symbol or not, stays, so the decoder sees\n // what it would see in `block` itself; a spread would drop some of them.\n decodeBlock(\n Object.create(Object.getPrototypeOf(block), {\n ...Object.getOwnPropertyDescriptors(block),\n blocks: { ...nested, value: [] },\n }),\n )\n for (const child of nested.value) assertBlock(child)\n } else decodeBlock(block)\n validBlocks.add(block as Block)\n}\n\nconst hasOnlyKeys = (value: object, keys: ReadonlyArray<string>): boolean =>\n Object.keys(value).every(key => keys.includes(key))\n\n/**\n * Whether `input` decodes as an `EditorState`, with no excess properties, as\n * `Schema.decodeUnknownSync(EditorState, { onExcessProperty: 'error' })` decides, but\n * remembering each block and document that passed. Throws on invalid input.\n */\nexport const assertEditorState = (input: unknown): void => {\n if (typeof input !== 'object' || input === null || !hasOnlyKeys(input, ['document', 'selection']))\n throw new Error('Invalid editor state')\n const { document, selection } = input as { document?: unknown; selection?: unknown }\n if (typeof document !== 'object' || document === null) throw new Error('Invalid document')\n if (!validDocuments.has(document as Document)) {\n const { version, children } = document as { version?: unknown; children?: unknown }\n if (\n version !== 1 ||\n !Array.isArray(children) ||\n !hasOnlyKeys(document, ['version', 'children'])\n )\n throw new Error('Invalid document')\n for (const block of children) assertBlock(block)\n const ids = new Set<NodeId>()\n for (const block of children as ReadonlyArray<Block>) {\n for (const id of subtreeIds(block)) {\n if (ids.has(id)) throw new Error('Duplicate node identity')\n ids.add(id)\n }\n }\n validDocuments.add(document as Document)\n }\n decodeSelection(selection)\n if (!selectionIsValid(document as Document, selection as Selection | null))\n throw new Error('Unresolved selection')\n}\n\n/**\n * Counts semantic nodes and UTF-16 text units, and reports nesting depth. Depth\n * counts levels of content: an empty document is 0, blocks are 1, runs inside a\n * block are 2, and a block nested inside a block adds a level (§116).\n */\nexport const inspect = (document: Document) => {\n let nodeCount = 0\n let textLength = 0\n let depth = 0\n eachBlock(document.children, (block, path) => {\n nodeCount += 1 + block.children.length\n for (const text of block.children) textLength += text.text.length\n depth = Math.max(depth, path.length + (block.children.length > 0 ? 1 : 0))\n })\n return { nodeCount, textLength, depth }\n}\n\nconst words = new Intl.Segmenter(undefined, { granularity: 'word' })\nconst graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\n\n/**\n * What a reader would count: words and user-perceived characters, as `Intl.Segmenter` splits\n * them in the default locale, so a word in a script without spaces still counts. Runs are\n * joined within a block, so a word that changes mark midway is one word, and blocks never\n * join, so the last word of one block and the first of the next are two.\n */\nexport const count = (document: Document): { words: number; characters: number } => {\n let wordCount = 0\n let characterCount = 0\n eachBlock(document.children, block => {\n const text = block.children.map(run => run.text).join('')\n for (const segment of words.segment(text)) if (segment.isWordLike) wordCount += 1\n for (const _ of graphemes.segment(text)) characterCount += 1\n })\n return { words: wordCount, characters: characterCount }\n}\n","import { Equal, Schema } from 'effect'\nimport {\n eachBlock,\n markName,\n type Document,\n type MarkValue,\n type Position,\n type PropsSchema,\n type RunMark,\n} from './document.js'\n\nexport { markName }\n\n/** Which edges a mark continues across when typing at a run boundary. */\nexport type MarkExpansion = 'before' | 'after' | 'both' | 'none'\n\nconst decodeJsonProps = Schema.decodeUnknownSync(Schema.JsonObject)\n\n/**\n * A mark definition: its name, where it continues across a boundary, and the\n * schema its props must satisfy when it has any. A Kit declares the vocabulary\n * an editor accepts, so an application can say that its own mark behaves like a\n * link (nothing expands, an `href` prop) or like bold (it continues).\n */\nexport interface MarkDef<Props extends PropsSchema | undefined = PropsSchema | undefined> {\n readonly name: string\n readonly expand: MarkExpansion\n /** Validates a mark value's props at the Kit boundary, not in the codec. */\n readonly Props: Props\n /** Encodes decoded props into the JSON value stored on a text run. */\n readonly of: Props extends Schema.Codec<infer A, any, any>\n ? (props: A) => MarkValue\n : () => MarkValue\n}\n\n/**\n * Declares a mark. Expansion defaults to `both`: the conservative choice for a\n * name no policy knows. A definition with `Props` gets an `of` that builds the\n * value; a definition without props builds a value that carries only its name.\n */\nexport const mark = <Props extends PropsSchema | undefined = undefined>(\n name: string,\n options: { readonly Props?: Props; readonly expand?: MarkExpansion } = {},\n): MarkDef<Props> => {\n if (name.length === 0) throw new Error('RichText.mark: a mark needs a name')\n const encodeProps =\n options.Props === undefined\n ? undefined\n : Schema.encodeUnknownSync(options.Props, { onExcessProperty: 'error' })\n return {\n name,\n expand: options.expand ?? 'both',\n Props: options.Props as Props,\n of: ((props?: unknown): MarkValue => {\n if (encodeProps === undefined) return { name }\n // The stored value is the schema's *encoded* form: a transforming codec\n // (`NumberFromString`) must persist `'42'`, which is what Kit validation\n // decodes. Decoding the result against JSON keeps the boundary honest.\n return { name, props: decodeJsonProps(encodeProps(props)) }\n }) as MarkDef<Props>['of'],\n }\n}\n\nexport const Bold: MarkDef = mark('Bold', { expand: 'after' })\nexport const Italic: MarkDef = mark('Italic', { expand: 'after' })\nexport const Code: MarkDef = mark('Code', { expand: 'none' })\n\n/** The marks this vocabulary defines, and the policy a document without a Kit gets. */\nexport const shippedMarks: ReadonlyArray<MarkDef> = [Bold, Italic, Code]\n\n/**\n * Whether props fail to decode against a node's or a mark's declared schema. The\n * diagnostic is deliberately stable: a schema's own message can name internals\n * an API boundary should not leak, so only the verdict travels.\n */\nexport const propsFailure = (props: PropsSchema | undefined, value: unknown): boolean => {\n if (props === undefined) return false\n try {\n // Strict, like the persisted-content boundary: a field the schema does not\n // declare is a failure, not something silently kept beside the props.\n Schema.decodeUnknownSync(props, { onExcessProperty: 'error' })(value)\n return false\n } catch {\n return true\n }\n}\n\n/**\n * The expansion policy of a set of definitions, and which names it declares. A\n * mark the registry does not declare expands both ways: preservation never\n * retargets it away. Declared names are what an edit may add.\n */\nexport interface MarkRegistry {\n readonly expansionOf: (name: string) => MarkExpansion\n readonly declares: (name: string) => boolean\n /** Whether an edit may add this mark: its name is declared and its props decode. */\n readonly accepts: (mark: RunMark) => boolean\n}\n\nexport const markRegistry = (definitions: ReadonlyArray<MarkDef>): MarkRegistry => {\n const byName = new Map(definitions.map(definition => [definition.name, definition]))\n return {\n expansionOf: name => byName.get(name)?.expand ?? 'both',\n declares: name => byName.has(name),\n accepts: mark => {\n const definition = byName.get(markName(mark))\n return definition !== undefined && !propsFailure(definition.Props, markProps(mark))\n },\n }\n}\n\n/** The policy of the shipped vocabulary. */\nexport const shippedRegistry: MarkRegistry = markRegistry(shippedMarks)\n\n/** A mark's props, or undefined when it carries none. */\nexport const markProps = (mark: RunMark): MarkValue['props'] | undefined =>\n typeof mark === 'string' ? undefined : mark.props\n\n/**\n * Whether two marks are the same mark with the same props. This is the\n * equivalence normalization merges on, so props compare structurally and key\n * order does not matter.\n */\nexport const sameMark = (left: RunMark, right: RunMark): boolean =>\n markName(left) === markName(right) && Equal.equals(markProps(left), markProps(right))\n\n/** Order-insensitive mark-set equality; a run carries a name at most once. */\nexport const sameMarkSet = (left: ReadonlyArray<RunMark>, right: ReadonlyArray<RunMark>): boolean =>\n left.length === right.length && left.every(mark => right.some(other => sameMark(mark, other)))\n\n/**\n * Retargets a boundary insertion to the neighboring run when the current run\n * carries marks that forbid the edge and the neighbor carries exactly the\n * marks that remain. Interior positions, missing neighbors, and mismatched\n * neighbors return the input reference unchanged; unknown node ids are left\n * for `apply` to diagnose. Never invents runs: mixed-mark edges stay put.\n */\nexport const resolveInsertion = (\n document: Document,\n position: Position,\n registry: MarkRegistry = shippedRegistry,\n): Position => {\n let resolved = position\n // Nested blocks too: a list item's or a table cell's runs follow the same rule.\n eachBlock(document.children, block => {\n const index = block.children.findIndex(run => run.id === position.node)\n const run = block.children[index]\n if (run === undefined) return\n const leavingLeft = position.affinity === 'before' && position.offset === 0\n const leavingRight = position.affinity === 'after' && position.offset === run.text.length\n if (!leavingLeft && !leavingRight) return\n const neighbor = leavingLeft ? block.children[index - 1] : block.children[index + 1]\n if (neighbor === undefined) return\n const desired = extending(run.marks, leavingLeft ? 'before' : 'after', registry)\n if (!sameMarkSet(desired, neighbor.marks)) return\n resolved = {\n node: neighbor.id,\n offset: leavingLeft ? neighbor.text.length : 0,\n affinity: position.affinity,\n }\n })\n return resolved\n}\n\n/** The marks of a run that extend past its edge in this direction. */\nconst extending = (\n marks: ReadonlyArray<RunMark>,\n direction: 'before' | 'after',\n registry: MarkRegistry,\n): ReadonlyArray<RunMark> =>\n marks.filter(mark => {\n const expand = registry.expansionOf(markName(mark))\n return expand === 'both' || expand === direction\n })\n\n/**\n * The marks text typed at the outer edge of a block should carry, when they differ from its run's:\n * a mark that does not extend past that edge (a link, a footnote reference) stops there. There is\n * no neighbouring run to type into instead, as `resolveInsertion` finds inside a block, so the\n * text needs a run of its own. Undefined anywhere else, and where every mark extends.\n */\nexport const edgeMarks = (\n document: Document,\n position: Position,\n registry: MarkRegistry = shippedRegistry,\n): ReadonlyArray<RunMark> | undefined => {\n let found: ReadonlyArray<RunMark> | undefined\n eachBlock(document.children, block => {\n const index = block.children.findIndex(run => run.id === position.node)\n const run = block.children[index]\n if (run === undefined || run.text.length === 0) return\n const atEnd = index === block.children.length - 1 && position.offset === run.text.length\n const atStart = index === 0 && position.offset === 0\n if (!atEnd && !atStart) return\n const desired = extending(run.marks, atEnd ? 'after' : 'before', registry)\n if (desired.length !== run.marks.length) found = desired\n })\n return found\n}\n","import type { NodeBlock, RunMark, Text } from './document.js'\nimport { markName } from './marks.js'\n\n/**\n * How an element is rendered: a tag and its attributes. Data, not a view (§121),\n * so the DOM-free serializer writes it and the DOM interpreters build it without\n * the core learning about Foldkit or the DOM.\n */\nexport interface ElementRendering {\n readonly tag: string\n /** Values are escaped when written; a name that would end the markup is refused. */\n readonly attributes: Readonly<Record<string, string>>\n /**\n * An element the nested blocks go inside, where HTML's parser would insert one anyway: a\n * `table`'s rows go in a `tbody`. Without it, markup sent from a server parses to a tree\n * the renderer did not write, and Foldkit refuses to serialize it.\n */\n readonly inner?: string | undefined\n /**\n * Elements drawn inside the block before its content that are not content: a task's\n * checkbox, an image's picture and caption, a callout's icon. They hold no position, are\n * never edited as text, and an HTML import skips them, so a block's text stays its runs'.\n */\n readonly adornments?: ReadonlyArray<Adornment> | undefined\n}\n\n/**\n * One element of a block's adornments. `toggles` names a boolean prop of the block that a click\n * on the element flips, through the editor's own Message (a task's `checked`, a toggle's\n * `open`), so the document stays the one place that state lives. `action` names something a\n * click on it asks the application for that is not an edit, a code block's Copy or its language\n * menu: the editor reports it, with the block, and changes nothing.\n */\nexport interface Adornment {\n readonly tag: string\n readonly attributes: Readonly<Record<string, string>>\n readonly text?: string | undefined\n readonly toggles?: string | undefined\n readonly action?: string | undefined\n}\n\n/** The attribute that marks an element as an adornment, which every interpreter skips as content. */\nexport const ADORNMENT_ATTRIBUTE = 'data-adornment'\n/** The attribute naming the prop an adornment's click flips. */\nexport const TOGGLES_ATTRIBUTE = 'data-toggles'\n/** The attribute naming what an adornment's click asks the application for. */\nexport const ACTION_ATTRIBUTE = 'data-action'\n\n/** An adornment's attributes as every interpreter writes them: its own, then the markers. */\nexport const adornmentAttributes = (\n adornment: Adornment,\n): ReadonlyArray<readonly [string, string]> => [\n ...Object.entries(adornment.attributes).filter(\n ([name]) =>\n name !== ADORNMENT_ATTRIBUTE && name !== TOGGLES_ATTRIBUTE && name !== ACTION_ATTRIBUTE,\n ),\n [ADORNMENT_ATTRIBUTE, ''],\n ...(adornment.toggles === undefined ? [] : [[TOGGLES_ATTRIBUTE, adornment.toggles] as const]),\n ...(adornment.action === undefined ? [] : [[ACTION_ATTRIBUTE, adornment.action] as const]),\n]\n\n/** Whether two renderings draw the same element: tag, attributes, holder and adornments. */\nexport const sameElementRendering = (left: ElementRendering, right: ElementRendering): boolean =>\n left.tag === right.tag &&\n left.inner === right.inner &&\n sameRecord(left.attributes, right.attributes) &&\n (left.adornments ?? []).length === (right.adornments ?? []).length &&\n (left.adornments ?? []).every((adornment, at) => {\n const other = right.adornments![at]!\n return (\n adornment.tag === other.tag &&\n adornment.text === other.text &&\n adornment.toggles === other.toggles &&\n adornment.action === other.action &&\n sameRecord(adornment.attributes, other.attributes)\n )\n })\n\nconst sameRecord = (\n left: Readonly<Record<string, string>>,\n right: Readonly<Record<string, string>>,\n): boolean => {\n const names = Object.keys(left)\n return (\n names.length === Object.keys(right).length &&\n names.every(name => Object.hasOwn(right, name) && left[name] === right[name])\n )\n}\n\n/**\n * A rendering entry: fixed data, or computed from the value being rendered, which\n * is how a mark's attributes reach its props. `undefined` means the entry does not\n * apply, so the name falls back the way an entry-less name does.\n */\nexport type RenderingEntry<Value> =\n | ElementRendering\n | ((value: Value) => ElementRendering | undefined)\n\n/**\n * A vocabulary of renderings built *over* a Kit, never inside it (§34, §121). A\n * name with no entry renders the shipped way: its mark nests in `strong`, `em`, or\n * `code`, an application node keeps its default element, and any other name rides\n * on `data-marks` — which is what keeps the slice format and an HTML round trip\n * lossless rather than lossy.\n */\nexport interface Rendering {\n readonly marks: Readonly<Record<string, RenderingEntry<RunMark>>>\n readonly nodes: Readonly<Record<string, RenderingEntry<NodeBlock>>>\n}\n\n/** The nesting the shipped marks get, innermost first. */\nconst BUILT_IN_MARK_TAGS: ReadonlyArray<readonly [string, string]> = [\n ['Bold', 'strong'],\n ['Italic', 'em'],\n ['Code', 'code'],\n]\n\n/**\n * Own-property lookup: a mark or node name is document content, so a plain or\n * hand-built `Rendering` must not let `__proto__` resolve to a prototype.\n */\nconst entryFor = <Value>(\n entries: Readonly<Record<string, RenderingEntry<Value>>>,\n name: string,\n): RenderingEntry<Value> | undefined => (Object.hasOwn(entries, name) ? entries[name] : undefined)\n\nconst resolve = <Value>(\n entry: RenderingEntry<Value>,\n value: Value,\n): ElementRendering | undefined => (typeof entry === 'function' ? entry(value) : entry)\n\n/** A name's own entry map, with no prototype for a content-chosen name to reach. */\nconst entryMap = <Value>(\n entries: Readonly<Record<string, RenderingEntry<Value>>> | undefined,\n): Readonly<Record<string, RenderingEntry<Value>>> => {\n const map: Record<string, RenderingEntry<Value>> = Object.create(null)\n for (const [name, entry] of Object.entries(entries ?? {})) map[name] = entry\n return Object.freeze(map)\n}\n\nexport const rendering = (\n definition: {\n readonly marks?: Readonly<Record<string, RenderingEntry<RunMark>>>\n readonly nodes?: Readonly<Record<string, RenderingEntry<NodeBlock>>>\n } = {},\n): Rendering =>\n Object.freeze({ marks: entryMap(definition.marks), nodes: entryMap(definition.nodes) })\n\n/** The behaviour without a renderer: shipped tags for shipped marks, names otherwise. */\nexport const noRendering: Rendering = rendering()\n\n/**\n * A registry built over another: an entry named here wins, and every name the base\n * renders keeps its entry, so an application extends a vocabulary like the standard one\n * without restating it.\n */\nexport const renderingOver = (\n base: Rendering,\n definition: {\n readonly marks?: Readonly<Record<string, RenderingEntry<RunMark>>>\n readonly nodes?: Readonly<Record<string, RenderingEntry<NodeBlock>>>\n } = {},\n): Rendering =>\n rendering({\n marks: { ...base.marks, ...definition.marks },\n nodes: { ...base.nodes, ...definition.nodes },\n })\n\n/** What a run's marks nest in, and which names nest nowhere. */\nexport interface RunRendering {\n /** Elements to wrap the run's text in, innermost first. */\n readonly nest: ReadonlyArray<ElementRendering>\n /** Names with neither an entry nor a shipped tag, sorted so output is stable. */\n readonly unrendered: ReadonlyArray<string>\n}\n\nconst byName = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0)\n\n/**\n * Resolves a run's marks to elements. Order is the vocabulary's, then names\n * alphabetically, never the order marks happen to be stored in — the same set of\n * marks must serialize the same way however it was assembled. An entry for a\n * shipped name replaces that name's tag but keeps its place in the nesting.\n */\nexport const runRendering = (definition: Rendering, run: Text): RunRendering => {\n const nest: Array<ElementRendering> = []\n const unrendered: Array<string> = []\n for (const [name, tag] of BUILT_IN_MARK_TAGS) {\n const mark = run.marks.find(candidate => markName(candidate) === name)\n if (mark === undefined) continue\n const entry = entryFor(definition.marks, name)\n nest.push(\n entry === undefined\n ? { tag, attributes: {} }\n : (resolve(entry, mark) ?? { tag, attributes: {} }),\n )\n }\n const others = run.marks\n .filter(mark => !BUILT_IN_MARK_TAGS.some(([name]) => name === markName(mark)))\n .sort((left, right) => byName(markName(left), markName(right)))\n for (const mark of others) {\n const name = markName(mark)\n const entry = entryFor(definition.marks, name)\n const element = entry === undefined ? undefined : resolve(entry, mark)\n if (element === undefined) unrendered.push(name)\n else nest.push(element)\n }\n return { nest, unrendered }\n}\n\n/** The element a node kind renders as, or undefined when no entry applies. */\nexport const nodeRendering = (\n definition: Rendering,\n block: NodeBlock,\n): ElementRendering | undefined => {\n const entry = entryFor(definition.nodes, block.kind)\n return entry === undefined ? undefined : resolve(entry, block)\n}\n","import type { Block, Document, Text } from './document.js'\nimport {\n adornmentAttributes,\n noRendering,\n nodeRendering,\n runRendering,\n type ElementRendering,\n type Rendering,\n} from './rendering.js'\n\n/**\n * HTML is an interchange format, not the document model (§70). This serializer\n * exists so a copy can offer HTML to other applications and a preview can be\n * read by anything; nothing here is ever parsed back into authority. Unknown\n * marks survive as `data-marks` on a span and unknown blocks as a placeholder\n * carrying their original type, so a round trip through HTML cannot silently\n * invent formatting the document never had.\n *\n * A renderer (§121) decides which element a declared mark or node kind produces,\n * which is how a Link's `href` becomes a real attribute. Without one, this\n * fallback still carries mark *names*, and a mark's props travel in the slice\n * format, which is the lossless path.\n */\nexport type BlockList = ReadonlyArray<Block>\n\nconst escapeText = (text: string): string =>\n text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n\nconst escapeAttribute = (value: string): string =>\n escapeText(value).replace(/\"/g, '&quot;').replace(/'/g, '&#39;')\n\nconst TAG = /^[A-Za-z][-A-Za-z0-9]*$/\nconst ATTRIBUTE = /^[A-Za-z_:][-A-Za-z0-9_:.]*$/\n\n/**\n * HTML void elements: they have no closing tag, so a rendering that names one — a\n * standard `Image` is an `img`, a `ThematicBreak` an `hr` — writes one tag and no\n * children rather than `<img></img>`.\n */\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n])\n\n/**\n * Writes an element. An attribute *value* is content and is escaped; a tag or\n * attribute *name* is refused rather than written when malformed, because a name\n * cannot be escaped — one holding a quote, a space, or `>` would end the attribute\n * and inject markup. A well-formed but unwise name (an event handler built from a\n * mark's props, say) is the application's own decision to make.\n */\nconst renderElement = (element: ElementRendering, inner: string): string => {\n if (!TAG.test(element.tag)) throw new Error(`RichText.toHtml: invalid tag \"${element.tag}\"`)\n const attributes = Object.entries(element.attributes)\n .map(([name, value]) => {\n if (!ATTRIBUTE.test(name))\n throw new Error(`RichText.toHtml: invalid attribute name \"${name}\"`)\n return ` ${name}=\"${escapeAttribute(value)}\"`\n })\n .join('')\n if (VOID_ELEMENTS.has(element.tag.toLowerCase())) return `<${element.tag}${attributes}>`\n return `<${element.tag}${attributes}>${inner}</${element.tag}>`\n}\n\nconst renderRun = (run: Text, renderer: Rendering): string => {\n const { nest, unrendered } = runRendering(renderer, run)\n let html = escapeText(run.text)\n for (const element of nest) html = renderElement(element, html)\n return unrendered.length === 0\n ? html\n : `<span data-marks=\"${escapeAttribute(unrendered.join(' '))}\">${html}</span>`\n}\n\nconst blockTag = (block: Block): string => {\n if (block.type === 'Heading') return `h${block.level}`\n return block.type === 'Node' ? 'div' : 'p'\n}\n\nconst renderBlock = (block: Block, renderer: Rendering): string => {\n if (block.type === 'Unknown')\n return `<div data-unknown=\"${escapeAttribute(block.originalType)}\"></div>`\n const runs = block.children.map(run => renderRun(run, renderer)).join('')\n // A node that accepts nested blocks renders them inside it, so a list keeps\n // its items.\n const nested =\n block.type === 'Node' && block.blocks !== undefined ? toHtml(block.blocks, renderer) : ''\n // An application node carries its kind so a stylesheet can reach it; a renderer\n // entry replaces this default element entirely.\n const element = (block.type === 'Node' ? nodeRendering(renderer, block) : undefined) ?? {\n tag: blockTag(block),\n attributes: block.type === 'Node' ? { 'data-node': block.kind } : {},\n }\n const adornment = (element.adornments ?? [])\n .map(piece =>\n renderElement(\n { tag: piece.tag, attributes: Object.fromEntries(adornmentAttributes(piece)) },\n escapeText(piece.text ?? ''),\n ),\n )\n .join('')\n return renderElement(\n element,\n element.inner === undefined\n ? `${adornment}${runs}${nested}`\n : `${adornment}${runs}${renderElement({ tag: element.inner, attributes: {} }, nested)}`,\n )\n}\n\n/** Serializes blocks as HTML, with text and attributes escaped. */\nexport const toHtml = (blocks: BlockList, renderer: Rendering = noRendering): string =>\n blocks.map(block => renderBlock(block, renderer)).join('')\n\n/**\n * Plain text of blocks, one line per text block; unknown blocks keep a\n * placeholder and a container contributes its children's lines.\n */\nexport const toText = (blocks: BlockList): string => {\n const lines: Array<string> = []\n const walk = (current: BlockList): void => {\n for (const block of current) {\n if (block.type === 'Unknown') {\n lines.push(`[${block.originalType}]`)\n continue\n }\n if (block.type === 'Node' && block.blocks !== undefined) {\n walk(block.blocks)\n continue\n }\n lines.push(block.children.map(run => run.text).join(''))\n }\n }\n walk(blocks)\n return lines.join('\\n')\n}\n\n/** Convenience for a whole document, whose blocks are its children. */\nexport const documentToHtml = (document: Document, renderer?: Rendering): string =>\n toHtml(document.children, renderer)\nexport const documentToText = (document: Document): string => toText(document.children)\n","import { Schema } from 'effect'\nimport { toText } from './html.js'\nimport {\n Block,\n NodeId,\n blockAtPath,\n compareRunPlaces,\n comparePositionPlaces,\n eachBlock,\n locateBlock,\n locateRun,\n pathKey,\n type BlockPath,\n type Document,\n type RunPlace,\n type Selection,\n type Text,\n} from './document.js'\n\n/**\n * Clipboard content is semantic, not HTML (§69). A slice is a versioned,\n * identity-carrying fragment of a document: it round-trips through an\n * application's own format, and a paste mints fresh identities so nothing\n * collides with the document it lands in. HTML and plain text are interchange\n * fallbacks the adapter adds; they are not the slice.\n */\nexport const Slice = Schema.Struct({\n version: Schema.Literal(1),\n blocks: Schema.Array(Block),\n}).check(\n Schema.makeFilter(slice => {\n const ids = new Set<NodeId>()\n let duplicate = false\n eachBlock(slice.blocks, block => {\n for (const id of [block.id, ...block.children.map(run => run.id)]) {\n if (ids.has(id)) duplicate = true\n ids.add(id)\n }\n })\n return !duplicate || 'Duplicate slice identity'\n }),\n)\nexport type Slice = typeof Slice.Type\n\nexport const emptySlice: Slice = Object.freeze({ version: 1, blocks: [] })\n\nconst decodeSlice = Schema.decodeUnknownSync(Slice, { onExcessProperty: 'error' })\nconst encodeSlice = Schema.encodeSync(Slice)\n\nconst trim = (run: Text, from: number, to: number): Text => ({\n ...run,\n text: run.text.slice(from, to),\n})\n\n/** A covered span: the two endpoints, ordered, each with its offset in its run. */\ninterface CoveredSpan {\n readonly start: RunPlace & { readonly offset: number }\n readonly end: RunPlace & { readonly offset: number }\n}\n\n/** Whether a block's subtree contains an endpoint, or sits between the two. */\nconst inRange = (blockPath: BlockPath, span: CoveredSpan): boolean => {\n const contains = (place: RunPlace): boolean =>\n blockPath.length <= place.path.length &&\n blockPath.every((index, depth) => place.path[depth] === index)\n if (contains(span.start) || contains(span.end)) return true\n const first = { path: blockPath, index: 0 }\n return compareRunPlaces(first, span.start) > 0 && compareRunPlaces(first, span.end) < 0\n}\n\n/** The runs of one block that the span covers, trimmed to it. */\nconst coveredRuns = (\n block: Block,\n blockPath: BlockPath,\n span: CoveredSpan,\n): ReadonlyArray<Text> => {\n const atStart = pathKey(blockPath) === pathKey(span.start.path)\n const atEnd = pathKey(blockPath) === pathKey(span.end.path)\n if (!atStart && !atEnd) return block.children\n const from = atStart ? span.start.index : 0\n const to = atEnd ? span.end.index : block.children.length - 1\n const children: Array<Text> = []\n for (const [index, run] of block.children.entries()) {\n if (index < from || index > to) continue\n const trimFrom = index === from && atStart ? span.start.offset : 0\n const trimTo = index === to && atEnd ? span.end.offset : run.text.length\n if (trimFrom >= trimTo) continue\n children.push(trim(run, trimFrom, trimTo))\n }\n return children\n}\n\n/**\n * The covered part of a block list: the blocks the span reaches, each trimmed to\n * it. A container is kept with the children the span reaches, so copying across\n * two list items carries the list rather than two loose paragraphs.\n */\nconst coveredBlocks = (\n blocks: ReadonlyArray<Block>,\n prefix: BlockPath,\n span: CoveredSpan,\n): ReadonlyArray<Block> => {\n const covered: Array<Block> = []\n for (const [index, block] of blocks.entries()) {\n const path = [...prefix, index]\n if (!inRange(path, span)) continue\n if (block.type === 'Unknown') {\n covered.push(block)\n continue\n }\n const children = coveredRuns(block, path, span)\n if (block.type === 'Node' && block.blocks !== undefined) {\n const nested = coveredBlocks(block.blocks, path, span)\n if (children.length === 0 && nested.length === 0) continue\n covered.push({ ...block, children, blocks: nested })\n continue\n }\n if (children.length === 0) continue\n covered.push({ ...block, children })\n }\n return covered\n}\n\n/**\n * The semantic content a copy would take: a whole block for a node selection,\n * and for a range only the covered part of what it reaches, with runs trimmed to\n * the selection. Blocks the range never enters are left out, so a partial copy\n * never drags a paragraph along.\n */\nexport const sliceOf = (document: Document, selection: Selection | null): Slice | undefined => {\n if (selection === null) return undefined\n if (selection.type === 'Node') {\n const located = locateBlock(document, selection.node)\n return located === undefined ? undefined : { version: 1, blocks: [located.block] }\n }\n const anchor = locateRun(document, selection.anchor.node)\n const focus = locateRun(document, selection.focus.node)\n if (anchor === undefined || focus === undefined) return undefined\n const anchorPlace = { ...anchor, offset: selection.anchor.offset }\n const focusPlace = { ...focus, offset: selection.focus.offset }\n const span: CoveredSpan =\n comparePositionPlaces(anchorPlace, focusPlace) <= 0\n ? { start: anchorPlace, end: focusPlace }\n : { start: focusPlace, end: anchorPlace }\n // A span inside one block copies that block, as it does at the top level; a\n // span across blocks keeps the containers that hold them, so copying across\n // two list items carries the list.\n if (pathKey(span.start.path) === pathKey(span.end.path)) {\n const block = blockAtPath(document, span.start.path)\n if (block === undefined || block.type === 'Unknown') return { version: 1, blocks: [] }\n const children = coveredRuns(block, span.start.path, span)\n return { version: 1, blocks: children.length === 0 ? [] : [{ ...block, children }] }\n }\n return { version: 1, blocks: coveredBlocks(document.children, [], span) }\n}\n\n/**\n * Plain text of a slice, one line per text block. A slice and a block list have\n * the same shape, so the serializer's walk serves both.\n */\nexport const plainTextOf = (slice: Slice): string => toText(slice.blocks)\n\n/**\n * A slice from pasted plain text: one paragraph per line. Identities come from\n * the caller, like every other identity a live edit mints.\n */\nexport const sliceFromText = (text: string, mint: () => string): Slice => ({\n version: 1,\n blocks: text.split(/\\r\\n|\\r|\\n/).map(line => ({\n type: 'Paragraph' as const,\n id: NodeId.make(mint()),\n children: [\n {\n type: 'Text' as const,\n id: NodeId.make(mint()),\n text: line,\n marks: [],\n },\n ],\n })),\n})\n\n/** The same content under fresh identities, so a paste can never collide. */\nexport const withFreshIds = (slice: Slice, mint: () => string): Slice => {\n // Pre-order: a block's identity, then its runs, then its nested blocks.\n const freshBlock = (block: Block): Block => {\n const id = NodeId.make(mint())\n const children = block.children.map(run => ({ ...run, id: NodeId.make(mint()) }))\n if (block.type === 'Node' && block.blocks !== undefined) {\n return { ...block, id, children, blocks: block.blocks.map(freshBlock) }\n }\n return { ...block, id, children }\n }\n return { version: 1, blocks: slice.blocks.map(freshBlock) }\n}\n\n/** Encodes a slice for the clipboard. */\nexport const serializeSlice = (slice: Slice): string => JSON.stringify(encodeSlice(slice))\n\n/** Decodes a slice, or undefined when the payload is not one this version wrote. */\nexport const deserializeSlice = (input: unknown): Slice | undefined => {\n try {\n return decodeSlice(typeof input === 'string' ? JSON.parse(input) : input)\n } catch {\n return undefined\n }\n}\n","import type { Schema } from 'effect'\nimport {\n blockAtPath,\n blockContent,\n eachBlock,\n textContent,\n type Block,\n type ContentMode,\n type Document,\n type NodeBlock,\n type NodeId,\n type PropsSchema,\n} from './document.js'\nimport { markName, markProps, propsFailure, type MarkDef } from './marks.js'\n\n/** Whether a kind's runs may carry formatting marks; `all` unless declared otherwise. */\nexport type MarksPolicy = 'all' | 'none'\n\n/**\n * Block content that accepts only the named kinds, so a `List` can declare that its\n * children are `ListItem`s and `validate` can report one that is not (§13, §125).\n */\nexport interface BlockConstraint {\n readonly mode: typeof blockContent\n readonly of: ReadonlyArray<string>\n}\n\n/** Declares that a node holds nested blocks, only of the named kinds. */\nexport const blocksOf = (...kinds: ReadonlyArray<string>): BlockConstraint =>\n Object.freeze({ mode: blockContent, of: [...kinds] })\n\n/** A kind's declared content: a mode, or block content restricted to named kinds. */\nexport type ChildrenDeclaration = ContentMode | BlockConstraint\n\n/**\n * The node shapes this version can declare: a `block` is one of the built-in\n * text blocks, an `atom` is an addressable node holding nothing (with optional\n * props), and an application `node` holds runs or nested blocks plus props its own\n * schema validates (§13).\n */\nexport type NodeDefinition =\n | { readonly name: string; readonly kind: 'block'; readonly children: 'text' }\n | {\n readonly name: string\n readonly kind: 'atom'\n readonly children: 'none'\n /** An atom's props decode at this boundary too, so an `Image` carries a source. */\n readonly props?: PropsSchema | undefined\n }\n | {\n readonly name: string\n readonly kind: 'node'\n /** `textContent` holds runs; `blockContent` or `blocksOf(…)` holds nested blocks. */\n readonly children: ChildrenDeclaration\n /** `none` forbids marks on this kind's runs, as a `CodeBlock` needs. */\n readonly marks: MarksPolicy\n /** Validates a `Node` block's `props` at this boundary, not in the codec. */\n readonly props?: PropsSchema | undefined\n /**\n * A boundary a lift never crosses: a table cell's content stays in the cell, where a\n * quote's or a list item's would be lifted out.\n */\n readonly isolating?: boolean | undefined\n /** Props a copy split off this node starts with, over the original's (§135). */\n readonly splitProps?: NodeBlock['props'] | undefined\n /**\n * The kinds this one may stand in (§149); absent, any that holds it. A kind that names\n * them never stands at the top level, as a `ListItem` stands only in a `List`.\n */\n readonly within?: ReadonlyArray<string> | undefined\n /** Its text keeps line breaks: Enter inserts one rather than splitting, as in code. */\n readonly lineBreaks?: boolean | undefined\n /** Tab indents its lines, and a new line starts as indented as the last, as in code. */\n readonly indents?: boolean | undefined\n }\n\n/**\n * A declared application node, with the caller's name, prop schema, and content\n * mode kept in the type: the erasure to `any` happens only where heterogeneous\n * definitions are collected, not at the authoring call.\n */\nexport interface NodeDefinitionOf<\n Name extends string,\n Props extends PropsSchema | undefined,\n Children extends ChildrenDeclaration = typeof textContent,\n> {\n readonly name: Name\n readonly kind: 'node'\n readonly children: Children\n readonly marks: MarksPolicy\n readonly props: Props\n readonly isolating: boolean\n readonly splitProps: NodeBlock['props'] | undefined\n readonly within: ReadonlyArray<string> | undefined\n readonly lineBreaks: boolean\n readonly indents: boolean\n}\n\n/** Declares a block node kind: a top-level node containing text runs. */\nexport const block = (name: string): NodeDefinition => ({\n name,\n kind: 'block',\n children: 'text',\n})\n\n/**\n * Declares an atom: an addressable node with no text content. Its optional props\n * decode at the same boundary as a `node`'s, so an `Image` is an atom carrying a\n * source rather than a run holder.\n */\nexport const atom = (\n name: string,\n options: { readonly Props?: PropsSchema | undefined } = {},\n): NodeDefinition => ({ name, kind: 'atom', children: 'none', props: options.Props })\n\n/**\n * Declares an application node kind: a `Node` block whose props this schema\n * validates and whose content the `children` declaration states — a mode, or block\n * content restricted to the kinds `blocksOf` names. `marks: 'none'` forbids marks on\n * its runs. The document codec keeps those props as JSON; the Kit is where an\n * application's types meet them.\n */\nexport const node = <\n const Name extends string,\n Props extends PropsSchema | undefined = undefined,\n Children extends ChildrenDeclaration = typeof textContent,\n>(\n name: Name,\n options: {\n readonly Props?: Props\n readonly children?: Children\n readonly marks?: MarksPolicy\n /** A boundary a lift never crosses, as a table cell is. */\n readonly isolating?: boolean\n /**\n * Props a copy split off this node starts with, laid over the original's: Enter in a\n * checked task item starts an unchecked one.\n */\n readonly splitProps?: Props extends PropsSchema\n ? Partial<Schema.Schema.Type<Props>>\n : NodeBlock['props']\n /** The kinds this one may stand in; it then never stands at the top level (§149). */\n readonly within?: ReadonlyArray<string>\n /**\n * Its text keeps line breaks, as code does: Enter inserts a newline instead of splitting\n * the block, and Enter on an empty last line leaves it for a paragraph after. A callout's\n * text can keep them too, for a note of several lines.\n */\n readonly lineBreaks?: boolean\n /**\n * Its lines are indented, as code's are: Tab and Shift+Tab indent and outdent them, and a\n * line broken with Enter starts as indented as the one before.\n */\n readonly indents?: boolean\n } = {},\n): NodeDefinitionOf<Name, Props, Children> => ({\n name,\n kind: 'node',\n children: (options.children ?? textContent) as Children,\n marks: options.marks ?? 'all',\n props: options.Props as Props,\n isolating: options.isolating ?? false,\n splitProps: options.splitProps,\n within: options.within,\n lineBreaks: options.lineBreaks ?? false,\n indents: options.indents ?? false,\n})\n\n/**\n * The vocabulary one editor accepts: which node kinds and marks are available.\n * A Kit is a definition, never document state, and it never holds renderers or\n * executable code. Transforms and metadata arrive later.\n */\nexport interface Kit {\n readonly nodes: ReadonlyArray<NodeDefinition>\n /** Mark definitions, not just names: a Kit carries each mark's boundary policy. */\n readonly marks: ReadonlyArray<MarkDef>\n}\n\nexport const kit = (definition: {\n readonly nodes: ReadonlyArray<NodeDefinition>\n readonly marks: ReadonlyArray<MarkDef>\n}): Kit => Object.freeze({ nodes: [...definition.nodes], marks: [...definition.marks] })\n\nexport interface Diagnostic {\n readonly code:\n | 'UnknownNode'\n | 'UnsupportedNode'\n | 'UnknownMark'\n | 'InvalidProps'\n | 'MismatchedDefinition'\n | 'UnexpectedChild'\n | 'MisplacedNode'\n | 'ForbiddenMark'\n readonly message: string\n readonly node?: NodeId\n readonly detail?: string\n}\n\n/** Whether a block is held as a built-in block or as an application node. */\nconst heldShape = (block: Block): 'block' | 'node' => (block.type === 'Node' ? 'node' : 'block')\n\n/**\n * The content a block actually holds. An empty application node is `either`: the\n * document cannot say whether it is an atom or a run holder that happens to have\n * no runs, so a declaration of either kind agrees with it.\n */\nconst heldContent = (block: Block): 'text' | 'blocks' | 'either' => {\n if (block.type !== 'Node') return 'text'\n if (block.blocks !== undefined) return 'blocks'\n return block.children.length > 0 ? 'text' : 'either'\n}\n\n/** The content mode a declaration names, or `'none'` for an atom. */\nconst declaredContent = (definition: NodeDefinition): ContentMode | 'none' =>\n definition.kind === 'atom'\n ? 'none'\n : typeof definition.children === 'string'\n ? definition.children\n : blockContent\n\n/**\n * Whether a declared definition agrees with the block it is declared for, and\n * why not. A `block` declaration expects a built-in block and a `node` or `atom`\n * one expects an application node; then the declared content mode must match what\n * the block holds, which is what makes an atom's no-children rule real.\n */\nconst definitionMismatch = (definition: NodeDefinition, block: Block): string | undefined => {\n const expected = definition.kind === 'block' ? 'block' : 'node'\n const held = heldShape(block)\n if (held !== expected) {\n return `\"${definition.name}\" is declared as ${definition.kind}, but the document holds it as ${held}`\n }\n const declared = declaredContent(definition)\n const content = heldContent(block)\n const agrees = content === 'either' ? declared !== 'blocks' : declared === content\n return agrees\n ? undefined\n : `\"${definition.name}\" is declared to hold ${declared}, but the document holds ${content}`\n}\n\n/**\n * A block's semantic kind: an application node's declared kind, a preserved node's\n * original type, or a built-in block's own type. This is what a `blocksOf`\n * constraint names, and what a `NodeRegistry` is looked up by.\n */\nexport const blockKind = (block: Block): string =>\n block.type === 'Node' ? block.kind : block.type === 'Unknown' ? block.originalType : block.type\n\n/**\n * The children a constrained kind does not accept. A declaration without a\n * constraint accepts any block, and a block that holds runs has no children to\n * check; `definitionMismatch` is what reports the mode itself.\n */\nconst childKindDiagnostics = (\n definition: NodeDefinition,\n block: Block,\n): ReadonlyArray<Diagnostic> => {\n if (definition.kind !== 'node' || typeof definition.children === 'string') return []\n if (block.type !== 'Node' || block.blocks === undefined) return []\n const allowed = definition.children.of\n const permitted = new Set(allowed)\n return block.blocks\n .filter(child => !permitted.has(blockKind(child)))\n .map(child => ({\n code: 'UnexpectedChild' as const,\n node: child.id,\n detail: blockKind(child),\n message: `\"${block.kind}\" accepts only ${allowed.join(', ')}`,\n }))\n}\n\n/**\n * Whether a kind may stand in a parent of `parentKind`, or at the top level when that is\n * undefined: anywhere, unless its declaration names where (§149).\n */\nexport const standsWithin = (\n declared: NodeDefinition | undefined,\n parentKind: string | undefined,\n): boolean =>\n declared?.kind !== 'node' ||\n declared.within === undefined ||\n (parentKind !== undefined && declared.within.includes(parentKind))\n\n/** Structural summary of a Kit, for tooling and tests. */\nexport const inspectKit = (definition: Kit) => ({\n blocks: definition.nodes.filter(node => node.kind === 'block').length,\n atoms: definition.nodes.filter(node => node.kind === 'atom').length,\n nodes: definition.nodes.filter(node => node.kind === 'node').length,\n marks: definition.marks.length,\n})\n\n/**\n * The node vocabulary an edit may target, the way `MarkRegistry` is the mark\n * vocabulary a mark edit consults. `run` reads a kind's declaration from it to refuse\n * an edit a constraint forbids (§117, §125); `apply` still takes none, so a durable\n * transaction never depends on a vocabulary that may have moved.\n */\nexport interface NodeRegistry {\n /** The declaration for a block kind, or undefined when this vocabulary has none. */\n readonly definitionFor: (kind: string) => NodeDefinition | undefined\n}\n\n/** Builds the registry an edit consults. A later declaration for a name wins, as a Map does. */\nexport const nodeRegistry = (definitions: ReadonlyArray<NodeDefinition>): NodeRegistry => {\n const byName = new Map(definitions.map(definition => [definition.name, definition]))\n return Object.freeze({ definitionFor: (kind: string) => byName.get(kind) })\n}\n\n/**\n * Checks a document against a Kit's vocabulary without changing it, walking\n * nested blocks so a container's children are checked too. Reports preserved\n * unknown blocks, known blocks the Kit does not declare, declarations that\n * disagree with how the document holds a block, application nodes whose props\n * their schema refuses, and marks outside the Kit or whose props their definition\n * refuses. Content diagnostics never strip or repair the document; callers decide\n * whether to block publishing or surface a placeholder.\n */\nexport const validate = (document: Document, definition: Kit): ReadonlyArray<Diagnostic> => {\n const byName = new Map(definition.nodes.map(node => [node.name, node]))\n const declaredMarks = new Map(definition.marks.map(mark => [mark.name, mark]))\n const diagnostics: Array<Diagnostic> = []\n eachBlock(document.children, (block, path) => {\n if (block.type === 'Unknown') {\n diagnostics.push({\n code: 'UnknownNode',\n node: block.id,\n detail: block.originalType,\n message: `Unimplemented node type \"${block.originalType}\"`,\n })\n return\n }\n const kind = blockKind(block)\n const declared = byName.get(kind)\n if (declared === undefined) {\n diagnostics.push({\n code: 'UnsupportedNode',\n node: block.id,\n detail: kind,\n message: `The Kit does not declare ${block.type === 'Node' ? 'node ' : ''}\"${kind}\"`,\n })\n } else {\n const mismatch = definitionMismatch(declared, block)\n if (mismatch !== undefined) {\n diagnostics.push({\n code: 'MismatchedDefinition',\n node: block.id,\n detail: kind,\n message: mismatch,\n })\n } else {\n if (\n block.type === 'Node' &&\n declared.kind !== 'block' &&\n propsFailure(declared.props, block.props)\n ) {\n diagnostics.push({\n code: 'InvalidProps',\n node: block.id,\n detail: kind,\n message: `\"${kind}\" props do not match its declared schema`,\n })\n }\n diagnostics.push(...childKindDiagnostics(declared, block))\n const parent = path.length > 1 ? blockAtPath(document, path.slice(0, -1)) : undefined\n const parentKind = parent === undefined ? undefined : blockKind(parent)\n if (!standsWithin(declared, parentKind)) {\n diagnostics.push({\n code: 'MisplacedNode',\n node: block.id,\n detail: kind,\n message: `\"${kind}\" cannot stand ${parentKind === undefined ? 'at the top level' : `in \"${parentKind}\"`}`,\n })\n }\n }\n }\n // A kind declared mark-free has no formatting to carry, so any mark it does is\n // reported as well as checked against the vocabulary that declared it.\n const forbidsMarks = declared?.kind === 'node' && declared.marks === 'none'\n for (const run of block.children) {\n for (const mark of run.marks) {\n const name = markName(mark)\n if (forbidsMarks) {\n diagnostics.push({\n code: 'ForbiddenMark',\n node: run.id,\n detail: name,\n message: `\"${kind}\" accepts no marks`,\n })\n }\n const declaredMark = declaredMarks.get(name)\n if (declaredMark === undefined) {\n diagnostics.push({\n code: 'UnknownMark',\n node: run.id,\n detail: name,\n message: `The Kit does not declare mark \"${name}\"`,\n })\n } else if (propsFailure(declaredMark.Props, markProps(mark))) {\n diagnostics.push({\n code: 'InvalidProps',\n node: run.id,\n detail: name,\n message: `\"${name}\" props do not match its declared schema`,\n })\n }\n }\n }\n })\n return diagnostics\n}\n","import { NodeId, type Block, type Document, type Text } from './document.js'\nimport { sameMarkSet } from './marks.js'\nimport type { CollapseStep, PositionStep, RelocateStep, SplitStep } from './transaction.js'\n\n/**\n * Transforms normalize or derive semantic structure after edits (§23). A\n * transform is a pure function of the document plus what the transaction\n * touched: it returns a whole new document and the position steps and identity\n * bookkeeping that go with it, so `apply` can fold it into the same ChangeSet\n * and position map it was already building.\n *\n * Two rules make a registry safe to run in a loop (§24): a transform must be\n * deterministic, and it must be idempotent on normalized state — so running it\n * again after it has run changes nothing, which is how the loop knows it has\n * settled.\n */\nexport interface TransformContext {\n /** Blocks the transaction touched, plus whatever earlier transforms touched. */\n readonly dirtyNodes: ReadonlySet<NodeId>\n /** Runs already spent, so a transform can bail out rather than spin. */\n readonly pass: number\n}\n\nexport interface TransformReport {\n readonly document: Document\n /** The same step vocabulary a transaction uses, so `apply` can fold either. */\n readonly steps: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>\n readonly insertedNodes: ReadonlySet<NodeId>\n readonly removedNodes: ReadonlySet<NodeId>\n readonly dirtyNodes: ReadonlySet<NodeId>\n /** Runs whose text a transform rewrote, such as a merge's accumulator. */\n readonly textChanged: ReadonlySet<NodeId>\n /** Whether the block list changed shape, not just the runs inside a block. */\n readonly structureChanged: boolean\n}\n\nexport interface Transform {\n readonly name: string\n readonly apply: (document: Document, context: TransformContext) => TransformReport\n}\n\n/** A transform that found nothing to do. */\nexport const unchanged = (document: Document): TransformReport => ({\n document,\n steps: [],\n insertedNodes: new Set(),\n removedNodes: new Set(),\n dirtyNodes: new Set(),\n textChanged: new Set(),\n structureChanged: false,\n})\n\nconst mergeRunInto = (accumulator: Text, run: Text): Text => ({\n ...accumulator,\n text: accumulator.text + run.text,\n})\n\n/**\n * Merges adjacent runs whose mark sets match, within the blocks the transaction\n * touched, at any depth. Merging strictly reduces the run count, so one pass reaches\n * a stable state and a second pass finds nothing: the rule is idempotent, and only\n * equal mark sets merge, so an unknown mark never drops.\n */\nexport const mergeAdjacentRuns: Transform = {\n name: 'mergeAdjacentRuns',\n apply: (document, context) => {\n const steps: Array<RelocateStep> = []\n const removedNodes = new Set<NodeId>()\n const dirtyNodes = new Set<NodeId>()\n const textChanged = new Set<NodeId>()\n const mergeRuns = (block: Block): Block => {\n const first = block.children[0]\n if (!context.dirtyNodes.has(block.id) || first === undefined) return block\n let accumulator = first\n let changed = false\n const kept: Array<Text> = [accumulator]\n for (const run of block.children.slice(1)) {\n if (sameMarkSet(accumulator.marks, run.marks)) {\n steps.push({\n node: run.id,\n into: accumulator.id,\n at: 0,\n base: accumulator.text.length,\n })\n accumulator = mergeRunInto(accumulator, run)\n kept[kept.length - 1] = accumulator\n removedNodes.add(run.id)\n dirtyNodes.add(accumulator.id)\n textChanged.add(accumulator.id)\n changed = true\n } else {\n accumulator = run\n kept.push(run)\n }\n }\n return changed ? { ...block, children: kept } : block\n }\n // Returns the same array when nothing inside changed, so untouched containers keep\n // their identity and `apply` can tell that this transform found nothing.\n const mergeWithin = (blocks: ReadonlyArray<Block>): ReadonlyArray<Block> => {\n let changed = false\n const next = blocks.map(block => {\n let merged = mergeRuns(block)\n if (merged.type === 'Node' && merged.blocks !== undefined) {\n const nested = mergeWithin(merged.blocks)\n if (nested !== merged.blocks) merged = { ...merged, blocks: nested }\n }\n if (merged !== block) changed = true\n return merged\n })\n return changed ? next : blocks\n }\n const children = mergeWithin(document.children)\n return {\n document: children === document.children ? document : { ...document, children },\n steps,\n insertedNodes: new Set(),\n removedNodes,\n dirtyNodes,\n textChanged,\n structureChanged: false,\n }\n },\n}\n\n/** The transforms every transaction runs, in order, unless a caller says otherwise. */\nexport const defaultTransforms: ReadonlyArray<Transform> = [mergeAdjacentRuns]\n","import { Equal, Schema } from 'effect'\nimport { markName, sameMark } from './marks.js'\nimport {\n assertEditorState,\n Block,\n eachBlock,\n EditorState,\n NodeId,\n Position,\n RunMark,\n Selection,\n compareRunPlaces,\n type BlockPath,\n type Document,\n type NodeReference,\n type RunPlace,\n type Text,\n} from './document.js'\nimport { defaultTransforms, type Transform } from './transform.js'\n\n/** How many normalization passes a transaction may spend before it gives up. */\nexport const MAX_NORMALIZATION_PASSES = 10\n\nconst Offset = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\nconst InsertTextOperation = Schema.Struct({\n type: Schema.Literal('InsertText'),\n at: Position,\n text: Schema.String,\n})\nconst DeleteTextOperation = Schema.Struct({\n type: Schema.Literal('DeleteText'),\n node: NodeId,\n from: Offset,\n to: Offset,\n})\nconst AddMarkOperation = Schema.Struct({\n type: Schema.Literal('AddMark'),\n node: NodeId,\n mark: RunMark,\n})\nconst RemoveMarkOperation = Schema.Struct({\n type: Schema.Literal('RemoveMark'),\n node: NodeId,\n mark: Schema.String,\n})\nconst SetSelectionOperation = Schema.Struct({\n type: Schema.Literal('SetSelection'),\n selection: Schema.NullOr(Selection),\n})\nconst SplitNodeOperation = Schema.Struct({\n type: Schema.Literal('SplitNode'),\n block: NodeId,\n node: NodeId,\n offset: Offset,\n blockId: NodeId,\n textId: NodeId,\n})\nconst JoinNodeOperation = Schema.Struct({\n type: Schema.Literal('JoinNode'),\n into: NodeId,\n removed: NodeId,\n})\nconst MoveNodeOperation = Schema.Struct({\n type: Schema.Literal('MoveNode'),\n node: NodeId,\n to: Offset,\n /** The block list to move into: a node block's, or the document's when absent. */\n parent: Schema.optionalKey(NodeId),\n})\n/**\n * What a text block retypes to: a paragraph, or a heading at a level. Its runs are\n * its own and survive the change; only the block's type does not.\n */\nexport const TextBlock = 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])\nexport type TextBlock = typeof TextBlock.Type\n\n/**\n * What a block becomes, under its own identity and with its own content: a block that holds\n * text becomes a paragraph, a heading, or an application node kind that holds text, such as a\n * code block, keeping its runs; a node that holds blocks becomes another node kind, keeping\n * its nested blocks, as a list item becomes a task.\n */\nexport const RetypeTarget = 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 }),\n])\nexport type RetypeTarget = typeof RetypeTarget.Type\n\nconst RetypeBlockOperation = Schema.Struct({\n type: Schema.Literal('RetypeBlock'),\n node: NodeId,\n to: RetypeTarget,\n})\nconst SetPropsOperation = Schema.Struct({\n type: Schema.Literal('SetProps'),\n node: NodeId,\n props: Schema.JsonObject,\n})\nconst InsertNodeOperation = Schema.Struct({\n type: Schema.Literal('InsertNode'),\n block: Block,\n at: Offset,\n /** The block list to insert into: a node block's, or the document's when absent. */\n parent: Schema.optionalKey(NodeId),\n})\nconst DeleteNodeOperation = Schema.Struct({\n type: Schema.Literal('DeleteNode'),\n node: NodeId,\n})\nconst SplitRunOperation = Schema.Struct({\n type: Schema.Literal('SplitRun'),\n node: NodeId,\n offset: Offset,\n textId: NodeId,\n})\n\nexport const Operation = Schema.Union([\n InsertTextOperation,\n DeleteTextOperation,\n AddMarkOperation,\n RemoveMarkOperation,\n SetSelectionOperation,\n SplitNodeOperation,\n JoinNodeOperation,\n MoveNodeOperation,\n RetypeBlockOperation,\n SetPropsOperation,\n InsertNodeOperation,\n DeleteNodeOperation,\n SplitRunOperation,\n])\nexport type Operation = typeof Operation.Type\nexport const Transaction = Schema.Array(Operation)\nexport type Transaction = typeof Transaction.Type\n\n/** A text-run target: a validated id or a reusable node reference. */\nexport type TextTarget = NodeId | NodeReference\n\nconst targetId = (target: TextTarget): NodeId => (typeof target === 'string' ? target : target.id)\n\n/** Accepts a raw string or validated id; empty strings throw via `NodeId`. */\nconst freshId = (id: string | NodeId): NodeId => (typeof id === 'string' ? NodeId.make(id) : id)\n\n/**\n * Typesafe constructors for transaction operations. Each builder accepts a\n * `NodeId` or a `Node.make` reference and validates shape immediately\n * (misuse throws), while document-dependent checks — node kind, existence,\n * bounds, selection resolution — remain `apply` diagnostics. Compose with\n * `Node.at` for positions: `Edit.insertText(Text.at(5, 'after'), '!')`.\n */\nexport const Edit = {\n insertText: (at: Position, text: string): Extract<Operation, { readonly type: 'InsertText' }> =>\n InsertTextOperation.make({ type: 'InsertText', at, text }),\n\n deleteText: (\n node: TextTarget,\n from: number,\n to: number,\n ): Extract<Operation, { readonly type: 'DeleteText' }> => {\n if (from > to) throw new Error(`Edit.deleteText: from (${from}) must not exceed to (${to})`)\n return DeleteTextOperation.make({ type: 'DeleteText', node: targetId(node), from, to })\n },\n\n addMark: (node: TextTarget, mark: RunMark): Extract<Operation, { readonly type: 'AddMark' }> =>\n AddMarkOperation.make({ type: 'AddMark', node: targetId(node), mark }),\n\n removeMark: (\n node: TextTarget,\n mark: string,\n ): Extract<Operation, { readonly type: 'RemoveMark' }> =>\n RemoveMarkOperation.make({ type: 'RemoveMark', node: targetId(node), mark }),\n\n setSelection: (\n selection: Selection | null,\n ): Extract<Operation, { readonly type: 'SetSelection' }> =>\n SetSelectionOperation.make({ type: 'SetSelection', selection }),\n\n splitBlock: (\n block: TextTarget,\n node: TextTarget,\n offset: number,\n newBlock: string | NodeId,\n newRun: string | NodeId,\n ): Extract<Operation, { readonly type: 'SplitNode' }> =>\n SplitNodeOperation.make({\n type: 'SplitNode',\n block: targetId(block),\n node: targetId(node),\n offset,\n blockId: freshId(newBlock),\n textId: freshId(newRun),\n }),\n\n joinBlocks: (\n survivor: TextTarget,\n removed: TextTarget,\n ): Extract<Operation, { readonly type: 'JoinNode' }> =>\n JoinNodeOperation.make({\n type: 'JoinNode',\n into: targetId(survivor),\n removed: targetId(removed),\n }),\n\n moveBlock: (\n node: TextTarget,\n to: number,\n parent?: TextTarget,\n ): Extract<Operation, { readonly type: 'MoveNode' }> =>\n MoveNodeOperation.make({\n type: 'MoveNode',\n node: targetId(node),\n to,\n ...(parent === undefined ? {} : { parent: targetId(parent) }),\n }),\n\n retypeBlock: (\n node: TextTarget,\n to: RetypeTarget,\n ): Extract<Operation, { readonly type: 'RetypeBlock' }> =>\n RetypeBlockOperation.make({ type: 'RetypeBlock', node: targetId(node), to }),\n\n /** Sets the named props of a node block; props it does not name keep their values. */\n setProps: (\n node: TextTarget,\n props: Schema.JsonObject,\n ): Extract<Operation, { readonly type: 'SetProps' }> =>\n SetPropsOperation.make({ type: 'SetProps', node: targetId(node), props }),\n\n insertBlock: (\n block: Block,\n at: number,\n parent?: TextTarget,\n ): Extract<Operation, { readonly type: 'InsertNode' }> =>\n InsertNodeOperation.make({\n type: 'InsertNode',\n block,\n at,\n ...(parent === undefined ? {} : { parent: targetId(parent) }),\n }),\n\n deleteBlock: (node: TextTarget): Extract<Operation, { readonly type: 'DeleteNode' }> =>\n DeleteNodeOperation.make({ type: 'DeleteNode', node: targetId(node) }),\n\n splitRun: (\n node: TextTarget,\n offset: number,\n newRun: string | NodeId,\n ): Extract<Operation, { readonly type: 'SplitRun' }> =>\n SplitRunOperation.make({\n type: 'SplitRun',\n node: targetId(node),\n offset,\n textId: freshId(newRun),\n }),\n}\n\nexport interface ChangeSet {\n readonly dirtyNodes: ReadonlySet<NodeId>\n readonly insertedNodes: ReadonlySet<NodeId>\n readonly removedNodes: ReadonlySet<NodeId>\n readonly textChanged: ReadonlySet<NodeId>\n readonly structureChanged: boolean\n readonly selectionChanged: boolean\n}\n\n/** One replacement of [from, to) with inserted UTF-16 units, in sequential coordinates. */\nexport interface PositionStep {\n readonly node: NodeId\n readonly from: number\n readonly to: number\n readonly inserted: number\n}\n\n/**\n * Split relocation: offsets > at move to into with offset - at; offset == at\n * follows affinity (before stays, after moves to 0); lower offsets stay.\n */\nexport interface SplitStep {\n readonly node: NodeId\n readonly into: NodeId\n readonly at: number\n}\n\n/**\n * Merge relocation: offsets >= at move to into with base + offset - at;\n * lower offsets stay. Affinity is preserved, not consulted: the source\n * location ceases to exist, so every endpoint must move.\n */\nexport interface RelocateStep {\n readonly node: NodeId\n readonly into: NodeId\n readonly at: number\n readonly base: number\n}\n\n/**\n * Deletion collapse: every offset in node moves to offset 0 of into;\n * affinity is preserved. Emitted per removed run when a surviving run exists;\n * with no text left, positions cannot map and selection clears instead.\n */\nexport interface CollapseStep {\n readonly node: NodeId\n readonly into: NodeId\n}\n\n/** Maps a position through each edit, preserving insertion affinity. */\nexport const mapPosition = (\n position: Position,\n steps: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>,\n): Position =>\n steps.reduce((current, step) => {\n if (current.node !== step.node) return current\n if ('base' in step) {\n if (current.offset < step.at) return current\n return { ...current, node: step.into, offset: step.base + current.offset - step.at }\n }\n if ('at' in step) {\n if (current.offset < step.at) return current\n if (current.offset === step.at && current.affinity === 'before') return current\n return { ...current, node: step.into, offset: current.offset - step.at }\n }\n if ('into' in step) {\n return { ...current, node: step.into, offset: 0 }\n }\n if (current.offset < step.from) return current\n const offset =\n current.offset > step.to\n ? current.offset + step.inserted - (step.to - step.from)\n : step.from + (current.affinity === 'after' ? step.inserted : 0)\n return offset === current.offset ? current : { ...current, offset }\n }, position)\n\n/**\n * Maps a whole selection through steps: both range endpoints, or a node target\n * whose identity a step relocated. Steps that only replace text have no `into`,\n * so a node selection is unaffected by them.\n */\nexport const mapThrough = (\n selection: Selection | null,\n steps: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>,\n): Selection | null => {\n if (selection === null) return null\n if (selection.type === 'Node') {\n const step = steps.find(candidate => 'into' in candidate && candidate.node === selection.node)\n return step === undefined || !('into' in step) ? selection : { ...selection, node: step.into }\n }\n return {\n ...selection,\n anchor: mapPosition(selection.anchor, steps),\n focus: mapPosition(selection.focus, steps),\n }\n}\n\nexport type TransactionResult =\n | {\n readonly ok: true\n readonly state: EditorState\n readonly changeSet: ChangeSet\n readonly positionMap: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>\n /**\n * The transactions that produced `state`, in order, each normalized before the next:\n * folding `apply` over them from the input state yields `state` again. A command can\n * need more than one, and an action has at least one per command.\n */\n readonly transactions: ReadonlyArray<Transaction>\n }\n | {\n readonly ok: false\n readonly error:\n | 'InvalidInput'\n | 'MissingText'\n | 'MissingNode'\n | 'InvalidRange'\n | 'InvalidSelection'\n | 'InvalidParent'\n | 'ForbiddenMark'\n | 'UnexpectedChild'\n | 'UnstableNormalization'\n }\n\nconst decodeTransaction = Schema.decodeUnknownSync(Transaction, { onExcessProperty: 'error' })\nconst sameSelection = (left: Selection | null, right: Selection | null): boolean => {\n if (left === null || right === null) return left === right\n if (left.type === 'Node') return right.type === 'Node' && left.node === right.node\n if (right.type !== 'Range') return false\n return (['anchor', 'focus'] as const).every(\n key =>\n left[key].node === right[key].node &&\n left[key].offset === right[key].offset &&\n left[key].affinity === right[key].affinity,\n )\n}\n\n/** The nested block list of a container, or undefined for any other block. */\nconst nestedOf = (block: Block): ReadonlyArray<Block> | undefined =>\n block.type === 'Node' && block.blocks !== undefined ? block.blocks : undefined\n\n/**\n * A block's address: root-first container indices. `[2]` is the third top-level\n * block; `[2, 0]` is the first block nested inside it (§116). The document's own\n * block list is the container at `[]`.\n */\nconst pathKey = (path: BlockPath): string => path.join('.')\nconst keyToPath = (key: string): BlockPath => (key === '' ? [] : key.split('.').map(Number))\n\ninterface DocumentIndex {\n readonly blockPaths: ReadonlyMap<NodeId, BlockPath>\n readonly runPaths: ReadonlyMap<NodeId, { readonly path: BlockPath; readonly index: number }>\n}\nconst indexes = new WeakMap<Document, DocumentIndex>()\n/** Where each block and run sits, built once per document: documents are immutable. */\nconst indexDocument = (document: Document): DocumentIndex => {\n const cached = indexes.get(document)\n if (cached !== undefined) return cached\n const blockPaths = new Map<NodeId, BlockPath>()\n const runPaths = new Map<NodeId, { readonly path: BlockPath; readonly index: number }>()\n eachBlock(document.children, (block, path) => {\n blockPaths.set(block.id, path)\n for (const [runIndex, run] of block.children.entries()) {\n runPaths.set(run.id, { path, index: runIndex })\n }\n })\n const index = { blockPaths, runPaths }\n indexes.set(document, index)\n return index\n}\n\n/**\n * Pure, atomic text transaction. Rejection returns no partially edited state.\n * `transforms` defaults to the registry's shipped rules; a Kit's transforms\n * arrive here when Kit support lands.\n */\nexport const apply = (\n state: EditorState,\n transaction: Transaction,\n transforms: ReadonlyArray<Transform> = defaultTransforms,\n): TransactionResult => {\n try {\n assertEditorState(state)\n decodeTransaction(transaction)\n } catch {\n return { ok: false, error: 'InvalidInput' }\n }\n const initial = indexDocument(state.document)\n let { blockPaths, runPaths } = initial\n /** The index as this transaction's own copy, once `indexInserted` has written to it. */\n let owned: { blocks: Map<NodeId, BlockPath>; runs: Map<NodeId, RunPlace> } | undefined\n const reindex = () => {\n ;({ blockPaths, runPaths } = indexDocument(document))\n owned = undefined\n }\n // Identities stay reserved for the whole transaction so a reused id can never\n // silently address two nodes across structural edits: the input's, and every one\n // the transaction adds.\n const added = new Set<NodeId>()\n const usedIds = {\n has: (id: NodeId): boolean =>\n initial.runPaths.has(id) || initial.blockPaths.has(id) || added.has(id),\n add: (id: NodeId): void => void added.add(id),\n }\n let document: Document = state.document\n // Working copies: each touched container is copied once per transaction, so N\n // edits in one paragraph cost O(N) rather than N copies of the same array. A\n // container is a block list — the document's, or a node block's nested blocks —\n // and a block's runs are copied separately, keyed by that block's path.\n const workingBlocks = new Map<string, Array<Block>>()\n const workingRuns = new Map<string, Array<Text>>()\n const blockAt = (path: BlockPath): Block | undefined =>\n blocksAt(path.slice(0, -1))[path[path.length - 1]!]\n /** The block list at a container path, reading through any pending copy. */\n function blocksAt(containerPath: BlockPath): ReadonlyArray<Block> {\n const pending = workingBlocks.get(pathKey(containerPath))\n if (pending !== undefined) return pending\n if (containerPath.length === 0) return document.children\n const parent = blockAt(containerPath)\n return parent?.type === 'Node' && parent.blocks !== undefined ? parent.blocks : []\n }\n /** Copies a container, and its ancestors, once: writes never touch the input. */\n const ensureContainer = (containerPath: BlockPath): Array<Block> => {\n const key = pathKey(containerPath)\n const existing = workingBlocks.get(key)\n if (existing !== undefined) return existing\n if (containerPath.length > 0) ensureContainer(containerPath.slice(0, -1))\n const copy = [...blocksAt(containerPath)]\n workingBlocks.set(key, copy)\n return copy\n }\n /** The block's runs as they stand: a pending copy if one exists, else the document's. */\n const runsAt = (path: BlockPath): ReadonlyArray<Text> =>\n workingRuns.get(pathKey(path)) ?? blockAt(path)?.children ?? []\n /** The block's run array, copied on first write and mutated in place after. */\n const runArray = (path: BlockPath): Array<Text> => {\n const key = pathKey(path)\n const existing = workingRuns.get(key)\n if (existing !== undefined) return existing\n ensureContainer(path.slice(0, -1))\n const copy = [...(blockAt(path)?.children ?? [])]\n workingRuns.set(key, copy)\n return copy\n }\n /**\n * Indexes a block just inserted at `at` in a container, and moves each later sibling's\n * subtree one place on, rather than indexing the whole document again: a paste inserts one\n * block at a time, and reindexing after each made it quadratic in the blocks pasted.\n */\n const indexInserted = (containerPath: BlockPath, at: number): void => {\n const index = (owned ??= { blocks: new Map(blockPaths), runs: new Map(runPaths) })\n blockPaths = index.blocks\n runPaths = index.runs\n const record = (block: Block, path: BlockPath): void => {\n index.blocks.set(block.id, path)\n block.children.forEach((run, place) => index.runs.set(run.id, { path, index: place }))\n if (block.type === 'Node' && block.blocks !== undefined) {\n block.blocks.forEach((child, place) => record(child, [...path, place]))\n }\n }\n const blocks = blocksAt(containerPath)\n for (let place = at; place < blocks.length; place++) {\n record(blocks[place]!, [...containerPath, place])\n }\n }\n const writeBlock = (path: BlockPath, block: Block): void => {\n const container = ensureContainer(path.slice(0, -1))\n container[path[path.length - 1]!] = block\n }\n /**\n * The block list a structural operation targets: the document's, or a node\n * block's nested blocks. A parent that cannot hold blocks is `InvalidParent`,\n * one that does not exist is `MissingNode`.\n */\n const containerPathOf = (\n parent: NodeId | undefined,\n ): { readonly path: BlockPath } | { readonly error: 'MissingNode' | 'InvalidParent' } => {\n if (parent === undefined) return { path: [] }\n const path = blockPaths.get(parent)\n if (path === undefined) return { error: 'MissingNode' }\n const block = blockAt(path)\n return block?.type === 'Node' && block.blocks !== undefined\n ? { path }\n : { error: 'InvalidParent' }\n }\n const materialize = (): void => {\n if (workingBlocks.size === 0 && workingRuns.size === 0) return\n // Runs fold into their block, then each container folds into its parent. A\n // container's copy already holds its child's final value, so the order of\n // the second pass does not matter; only touched containers are visited.\n for (const [key, runs] of workingRuns) {\n const path = keyToPath(key)\n const container = workingBlocks.get(pathKey(path.slice(0, -1)))!\n const index = path[path.length - 1]!\n container[index] = { ...container[index]!, children: runs }\n }\n workingRuns.clear()\n for (const [key, blocks] of workingBlocks) {\n const path = keyToPath(key)\n if (path.length === 0) {\n document = { ...document, children: blocks }\n continue\n }\n const parent = workingBlocks.get(pathKey(path.slice(0, -1)))!\n const index = path[path.length - 1]!\n const parentBlock = parent[index]!\n // Only a node block holds nested blocks, and only its path can be a\n // container, so this narrowing always holds.\n if (parentBlock.type === 'Node') parent[index] = { ...parentBlock, blocks }\n }\n workingBlocks.clear()\n }\n let selection = state.selection\n const dirtyNodes = new Set<NodeId>()\n const insertedNodes = new Set<NodeId>()\n const removedNodes = new Set<NodeId>()\n const textChanged = new Set<NodeId>()\n let structureChanged = false\n const positionMap: Array<PositionStep | SplitStep | RelocateStep | CollapseStep> = []\n /** `selectionIsValid` against the working document, read through the index this transaction keeps. */\n const selectionFits = (candidate: Selection | null): boolean => {\n if (candidate === null) return true\n if (candidate.type === 'Node')\n return blockPaths.has(candidate.node) || runPaths.has(candidate.node)\n return [candidate.anchor, candidate.focus].every(position => {\n const location = runPaths.get(position.node)\n const run = location === undefined ? undefined : runsAt(location.path)[location.index]\n // The offset's sign and integrality are the decoded transaction's already.\n return run !== undefined && position.offset <= run.text.length\n })\n }\n for (let operationIndex = 0; operationIndex < transaction.length; operationIndex++) {\n const operation = transaction[operationIndex]!\n if (operation.type === 'SetSelection') {\n // A pending edit could change what a position resolves against.\n materialize()\n if (!selectionFits(operation.selection)) {\n return { ok: false, error: 'InvalidSelection' }\n }\n selection = operation.selection\n continue\n }\n if (operation.type === 'SplitRun') {\n const location = runPaths.get(operation.node)\n if (location === undefined) return { ok: false, error: 'MissingText' }\n const { path, index: textIndex } = location\n const target = blockAt(path)\n if (target === undefined) return { ok: false, error: 'MissingText' }\n const run = runsAt(path)[textIndex]!\n if (operation.offset > run.text.length) return { ok: false, error: 'InvalidRange' }\n if (usedIds.has(operation.textId)) return { ok: false, error: 'InvalidInput' }\n if (operation.offset === 0) {\n // No left remainder: the new run would be an empty duplicate. Splitting\n // at 0 is the caller's no-op, not a silent identity change.\n continue\n }\n const children = runArray(path)\n children[textIndex] = { ...run, text: run.text.slice(0, operation.offset) }\n children.splice(textIndex + 1, 0, {\n ...run,\n id: operation.textId,\n text: run.text.slice(operation.offset),\n })\n usedIds.add(operation.textId)\n materialize()\n reindex()\n const relocate: SplitStep = {\n node: run.id,\n into: operation.textId,\n at: operation.offset,\n }\n positionMap.push(relocate)\n if (selection?.type === 'Range') {\n selection = {\n ...selection,\n anchor: mapPosition(selection.anchor, [relocate]),\n focus: mapPosition(selection.focus, [relocate]),\n }\n }\n dirtyNodes.add(target.id)\n dirtyNodes.add(run.id)\n dirtyNodes.add(operation.textId)\n textChanged.add(run.id)\n textChanged.add(operation.textId)\n insertedNodes.add(operation.textId)\n continue\n }\n if (operation.type === 'SplitNode') {\n materialize()\n const blockPath = blockPaths.get(operation.block)\n if (blockPath === undefined) return { ok: false, error: 'MissingNode' }\n const runLocation = runPaths.get(operation.node)\n if (runLocation === undefined) return { ok: false, error: 'MissingText' }\n const { path: runBlockPath, index: textIndex } = runLocation\n if (pathKey(runBlockPath) !== pathKey(blockPath)) return { ok: false, error: 'InvalidRange' }\n const target = blockAt(blockPath)!\n const run = target.children[textIndex]!\n if (operation.offset > run.text.length) return { ok: false, error: 'InvalidRange' }\n if (\n usedIds.has(operation.blockId) ||\n usedIds.has(operation.textId) ||\n operation.blockId === operation.textId\n ) {\n return { ok: false, error: 'InvalidInput' }\n }\n const leftBlock = {\n ...target,\n children: [\n ...target.children.slice(0, textIndex),\n { ...run, text: run.text.slice(0, operation.offset) },\n ],\n }\n const rightBlock = {\n ...target,\n id: operation.blockId,\n children: [\n { ...run, id: operation.textId, text: run.text.slice(operation.offset) },\n ...target.children.slice(textIndex + 1),\n ],\n }\n // The halves land in the block's own container, so a split inside a\n // container stays inside it.\n const containerPath = blockPath.slice(0, -1)\n const index = blockPath[blockPath.length - 1]!\n const container = ensureContainer(containerPath)\n container[index] = leftBlock\n container.splice(index + 1, 0, rightBlock)\n materialize()\n usedIds.add(operation.blockId)\n usedIds.add(operation.textId)\n reindex()\n const relocate: SplitStep = { node: run.id, into: operation.textId, at: operation.offset }\n positionMap.push(relocate)\n if (selection?.type === 'Range') {\n selection = {\n ...selection,\n anchor: mapPosition(selection.anchor, [relocate]),\n focus: mapPosition(selection.focus, [relocate]),\n }\n }\n dirtyNodes.add(target.id)\n dirtyNodes.add(operation.blockId)\n dirtyNodes.add(run.id)\n dirtyNodes.add(operation.textId)\n for (const moved of target.children.slice(textIndex + 1)) dirtyNodes.add(moved.id)\n textChanged.add(run.id)\n textChanged.add(operation.textId)\n insertedNodes.add(operation.blockId)\n insertedNodes.add(operation.textId)\n structureChanged = true\n continue\n }\n if (operation.type === 'JoinNode') {\n materialize()\n const intoPath = blockPaths.get(operation.into)\n if (intoPath === undefined) return { ok: false, error: 'MissingNode' }\n const removedPath = blockPaths.get(operation.removed)\n if (removedPath === undefined) return { ok: false, error: 'MissingNode' }\n // Siblings only: two blocks in different containers have no boundary\n // between them to remove.\n if (pathKey(intoPath.slice(0, -1)) !== pathKey(removedPath.slice(0, -1))) {\n return { ok: false, error: 'InvalidParent' }\n }\n const containerPath = intoPath.slice(0, -1)\n const intoIndex = intoPath[intoPath.length - 1]!\n const removedIndex = removedPath[removedPath.length - 1]!\n if (removedIndex !== intoIndex + 1) return { ok: false, error: 'InvalidRange' }\n const container = ensureContainer(containerPath)\n const survivor = container[intoIndex]!\n const removedBlocks: Array<Block> = []\n while (operationIndex < transaction.length) {\n const next = transaction[operationIndex]\n if (next?.type !== 'JoinNode' || next.into !== operation.into) break\n const removed = container[intoIndex + removedBlocks.length + 1]\n if (removed?.id !== next.removed) break\n // Opaque content cannot be merged without silently discarding it.\n if (survivor.type === 'Unknown' || removed.type === 'Unknown') {\n return { ok: false, error: 'InvalidRange' }\n }\n if (survivor.type === 'Node' || removed.type === 'Node') {\n if (\n survivor.type !== 'Node' ||\n removed.type !== 'Node' ||\n survivor.kind !== removed.kind ||\n !Equal.equals(survivor.props, removed.props)\n )\n return { ok: false, error: 'InvalidRange' }\n }\n // A container and a run holder merge differently: joining a list with a\n // paragraph would have to drop one side's shape.\n if ((nestedOf(survivor) === undefined) !== (nestedOf(removed) === undefined)) {\n return { ok: false, error: 'InvalidRange' }\n }\n removedBlocks.push(removed)\n operationIndex++\n }\n operationIndex--\n const mergedRuns = [...survivor.children, ...removedBlocks.flatMap(block => block.children)]\n if (survivor.type === 'Node' && survivor.blocks !== undefined) {\n container[intoIndex] = {\n ...survivor,\n children: mergedRuns,\n blocks: [...survivor.blocks, ...removedBlocks.flatMap(block => nestedOf(block) ?? [])],\n }\n } else {\n container[intoIndex] = { ...survivor, children: mergedRuns }\n }\n container.splice(removedIndex, removedBlocks.length)\n materialize()\n reindex()\n for (const removed of removedBlocks) {\n // A Node selection on a retired identity follows the survivor.\n if (selection?.type === 'Node' && selection.node === removed.id) {\n selection = { ...selection, node: operation.into }\n }\n }\n dirtyNodes.add(operation.into)\n for (const removed of removedBlocks) {\n dirtyNodes.add(removed.id)\n removedNodes.add(removed.id)\n for (const moved of removed.children) dirtyNodes.add(moved.id)\n }\n structureChanged = true\n continue\n }\n if (operation.type === 'MoveNode') {\n materialize()\n const fromPath = blockPaths.get(operation.node)\n if (fromPath === undefined) return { ok: false, error: 'MissingNode' }\n const target = containerPathOf(operation.parent)\n if ('error' in target) return { ok: false, error: target.error }\n // A block cannot hold itself: moving one into its own subtree would detach both.\n if (fromPath.every((index, depth) => target.path[depth] === index)) {\n return { ok: false, error: 'InvalidParent' }\n }\n const sourcePath = fromPath.slice(0, -1)\n const fromIndex = fromPath[fromPath.length - 1]!\n // A move within one container lands at an existing index; a move into\n // another can append, so its bound is that container's length.\n const sameContainer = pathKey(sourcePath) === pathKey(target.path)\n const limit = sameContainer ? blocksAt(target.path).length - 1 : blocksAt(target.path).length\n if (operation.to > limit) return { ok: false, error: 'InvalidRange' }\n if (sameContainer && operation.to === fromIndex) continue\n const source = ensureContainer(sourcePath)\n const [moved] = source.splice(fromIndex, 1)\n if (sameContainer) {\n source.splice(operation.to, 0, moved!)\n } else {\n // The removal is folded in and the destination found again before inserting: taking\n // the block out can shift the destination's path, and inserting can shift the\n // source's, so neither copy may be folded against the other's old indices.\n materialize()\n reindex()\n const destination = containerPathOf(operation.parent)\n if ('error' in destination) return { ok: false, error: destination.error }\n ensureContainer(destination.path).splice(operation.to, 0, moved!)\n }\n materialize()\n reindex()\n dirtyNodes.add(operation.node)\n structureChanged = true\n continue\n }\n if (operation.type === 'RetypeBlock') {\n const path = blockPaths.get(operation.node)\n if (path === undefined) return { ok: false, error: 'MissingNode' }\n const target = blockAt(path)\n const to = operation.to\n // Content keeps its shape: runs stay runs, and nested blocks stay nested, so a node\n // holding blocks retypes only to another node. Preserved content is never rewritten.\n const nested = target?.type === 'Node' && target.blocks !== undefined\n if (target === undefined || target.type === 'Unknown' || (nested && to.type !== 'Node')) {\n return { ok: false, error: 'InvalidRange' }\n }\n const already =\n to.type === 'Paragraph'\n ? target.type === 'Paragraph'\n : to.type === 'Heading'\n ? target.type === 'Heading' && target.level === to.level\n : target.type === 'Node' &&\n target.kind === to.kind &&\n Equal.equals(target.props, to.props)\n if (already) continue\n writeBlock(\n path,\n to.type === 'Paragraph'\n ? { type: 'Paragraph', id: target.id, children: target.children }\n : to.type === 'Heading'\n ? { type: 'Heading', id: target.id, level: to.level, children: target.children }\n : {\n type: 'Node',\n kind: to.kind,\n id: target.id,\n props: to.props,\n children: target.children,\n ...(nested ? { blocks: target.blocks } : {}),\n },\n )\n dirtyNodes.add(target.id)\n structureChanged = true\n continue\n }\n if (operation.type === 'SetProps') {\n const path = blockPaths.get(operation.node)\n if (path === undefined) return { ok: false, error: 'MissingNode' }\n const target = blockAt(path)\n // Only an application node has props; a text block's shape is its type.\n if (target?.type !== 'Node') return { ok: false, error: 'InvalidRange' }\n const props = { ...target.props, ...operation.props }\n if (Equal.equals(props, target.props)) continue\n writeBlock(path, { ...target, props })\n dirtyNodes.add(target.id)\n continue\n }\n if (operation.type === 'InsertNode') {\n const target = containerPathOf(operation.parent)\n if ('error' in target) return { ok: false, error: target.error }\n // A pending copy under a place the insert shifts would be folded back at the wrong\n // path. The container and its ancestors do not shift, so a run of inserts into one\n // container, as a paste is, keeps its copy rather than copying the list each time.\n const unshifted = new Set(\n Array.from({ length: target.path.length + 1 }, (_, depth) =>\n pathKey(target.path.slice(0, depth)),\n ),\n )\n if (workingRuns.size > 0 || [...workingBlocks.keys()].some(key => !unshifted.has(key))) {\n materialize()\n }\n if (operation.at > blocksAt(target.path).length) return { ok: false, error: 'InvalidRange' }\n const carried: Array<NodeId> = []\n eachBlock([operation.block], block => {\n carried.push(block.id)\n for (const run of block.children) carried.push(run.id)\n })\n if (new Set(carried).size !== carried.length || carried.some(id => usedIds.has(id))) {\n return { ok: false, error: 'InvalidInput' }\n }\n const container = ensureContainer(target.path)\n container.splice(operation.at, 0, operation.block)\n for (const id of carried) {\n usedIds.add(id)\n dirtyNodes.add(id)\n insertedNodes.add(id)\n }\n indexInserted(target.path, operation.at)\n structureChanged = true\n continue\n }\n if (operation.type === 'DeleteNode') {\n materialize()\n const path = blockPaths.get(operation.node)\n if (path === undefined) return { ok: false, error: 'MissingNode' }\n const containerPath = path.slice(0, -1)\n const index = path[path.length - 1]!\n const target = blockAt(path)!\n const container = ensureContainer(containerPath)\n container.splice(index, 1)\n materialize()\n reindex()\n // The nearest surviving run in document order — the first at or after the\n // removed block's place, else the last before it — or nothing, which\n // clears the selection. Walking the tree is what lets a delete beside a\n // container collapse into the container's own runs.\n const removedPlace = { path, index: 0 }\n let fallback: { readonly block: Block; readonly run: Text } | undefined\n let after: { readonly block: Block; readonly run: Text } | undefined\n eachBlock(document.children, (block, blockPath) => {\n for (const [runIndex, run] of block.children.entries()) {\n const place = { path: blockPath, index: runIndex }\n if (compareRunPlaces(place, removedPlace) >= 0) after ??= { block, run }\n else fallback = { block, run }\n }\n })\n const landing = after ?? fallback\n const collapses: Array<CollapseStep> = []\n const removedRuns: Array<NodeId> = []\n const collect = (block: Block): void => {\n for (const run of block.children) removedRuns.push(run.id)\n if (block.type === 'Node' && block.blocks !== undefined) block.blocks.forEach(collect)\n }\n collect(target)\n if (landing !== undefined) {\n for (const run of removedRuns) collapses.push({ node: run, into: landing.run.id })\n }\n if (selection?.type === 'Range') {\n selection =\n landing === undefined\n ? null\n : {\n ...selection,\n anchor: mapPosition(selection.anchor, collapses),\n focus: mapPosition(selection.focus, collapses),\n }\n } else if (selection?.type === 'Node') {\n const selectedNode = selection.node\n if (selectedNode === operation.node || removedRuns.includes(selectedNode)) {\n selection = landing === undefined ? null : { ...selection, node: landing.block.id }\n }\n }\n for (const step of collapses) positionMap.push(step)\n const removedIds: Array<NodeId> = []\n const collectIds = (block: Block): void => {\n removedIds.push(block.id, ...block.children.map(run => run.id))\n if (block.type === 'Node' && block.blocks !== undefined) block.blocks.forEach(collectIds)\n }\n collectIds(target)\n for (const id of removedIds) {\n dirtyNodes.add(id)\n removedNodes.add(id)\n }\n structureChanged = true\n continue\n }\n const id = operation.type === 'InsertText' ? operation.at.node : operation.node\n const location = runPaths.get(id)\n if (location === undefined) return { ok: false, error: 'MissingText' }\n const { path, index: textIndex } = location\n const block = blockAt(path)\n if (block === undefined) return { ok: false, error: 'MissingText' }\n const text = runsAt(path)[textIndex]!\n if (operation.type === 'AddMark') {\n // A run carries a mark name at most once, so adding is a *set*: append\n // when the name is absent, replace when its props differ, and no-op when\n // the mark is already exactly this one (which keeps state identity).\n const existing = text.marks.find(mark => markName(mark) === markName(operation.mark))\n if (existing !== undefined && sameMark(existing, operation.mark)) continue\n const children = runArray(path)\n children[textIndex] = {\n ...text,\n marks:\n existing === undefined\n ? [...text.marks, operation.mark]\n : text.marks.map(mark =>\n markName(mark) === markName(operation.mark) ? operation.mark : mark,\n ),\n }\n dirtyNodes.add(block.id)\n dirtyNodes.add(id)\n textChanged.add(id)\n continue\n }\n if (operation.type === 'RemoveMark') {\n if (!text.marks.some(mark => markName(mark) === operation.mark)) continue\n const children = runArray(path)\n children[textIndex] = {\n ...text,\n marks: text.marks.filter(mark => markName(mark) !== operation.mark),\n }\n dirtyNodes.add(block.id)\n dirtyNodes.add(id)\n textChanged.add(id)\n continue\n }\n const from = operation.type === 'InsertText' ? operation.at.offset : operation.from\n const to = operation.type === 'InsertText' ? from : operation.to\n const inserted = operation.type === 'InsertText' ? operation.text : ''\n if (from > to || to > text.text.length) return { ok: false, error: 'InvalidRange' }\n if (from === to && inserted.length === 0) continue\n const children = runArray(path)\n children[textIndex] = {\n ...text,\n text: text.text.slice(0, from) + inserted + text.text.slice(to),\n }\n const step = { node: id, from, to, inserted: inserted.length }\n positionMap.push(step)\n if (selection?.type === 'Range') {\n selection = {\n ...selection,\n anchor: mapPosition(selection.anchor, [step]),\n focus: mapPosition(selection.focus, [step]),\n }\n }\n dirtyNodes.add(block.id)\n dirtyNodes.add(id)\n textChanged.add(id)\n }\n // The op loop accumulates; the document is assembled once, here.\n materialize()\n // Normalization runs as transforms (§23): each is deterministic and idempotent\n // on normalized state, so the loop settles. The pass bound is a diagnostic,\n // not a hang: a transform that keeps changing the document is refused rather\n // than spinning.\n let pass = 0\n for (; pass < MAX_NORMALIZATION_PASSES; pass++) {\n let changed = false\n for (const transform of transforms) {\n const report = transform.apply(document, { dirtyNodes, pass })\n if (report.document === document) continue\n changed = true\n document = report.document\n for (const id of report.insertedNodes) insertedNodes.add(id)\n for (const id of report.removedNodes) removedNodes.add(id)\n for (const id of report.dirtyNodes) dirtyNodes.add(id)\n for (const id of report.textChanged) textChanged.add(id)\n for (const step of report.steps) positionMap.push(step)\n if (report.structureChanged) structureChanged = true\n if (report.steps.length > 0) selection = mapThrough(selection, report.steps)\n reindex()\n }\n if (!changed) break\n }\n if (pass === MAX_NORMALIZATION_PASSES) return { ok: false, error: 'UnstableNormalization' }\n return {\n ok: true,\n state:\n document === state.document && sameSelection(selection, state.selection)\n ? state\n : { document, selection },\n changeSet: {\n dirtyNodes,\n insertedNodes,\n removedNodes,\n textChanged,\n structureChanged,\n selectionChanged: !sameSelection(selection, state.selection),\n },\n positionMap,\n transactions: [transaction],\n }\n}\n","/**\n * Indentation in a kind whose lines are indented, as code's are (`node(…, { indents })`):\n * Tab indents, Shift+Tab outdents, and Enter starts the new line as indented as the one it\n * broke. A line is the text between two breaks of one block.\n */\nimport { positionInBlock, type Block, type EditorState, type Position } from './document.js'\nimport { Edit, apply, type Operation, type TransactionResult } from './transaction.js'\n\n/** What one level of indentation is: two spaces. */\nexport const INDENT = ' '\n\nconst textOf = (block: Block): string => block.children.map(run => run.text).join('')\n\n/** A position's offset into its block's whole text, or undefined when it is not the block's. */\nexport const offsetIn = (block: Block, position: Position): number | undefined => {\n let consumed = 0\n for (const run of block.children) {\n if (run.id === position.node) return consumed + position.offset\n consumed += run.text.length\n }\n return undefined\n}\n\nconst lineStart = (text: string, offset: number): number => text.lastIndexOf('\\n', offset - 1) + 1\n\n/** The leading spaces and tabs of the line `offset` is on, up to `offset`. */\nexport const indentationAt = (text: string, offset: number): string =>\n /^[ \\t]*/.exec(text.slice(lineStart(text, offset), offset))?.[0] ?? ''\n\n/**\n * The starts of the lines a range covers, last first, so editing each leaves the offsets of the\n * ones before it as they were. A line the range only reaches the start of is not covered.\n */\nconst linesCovered = (text: string, from: number, to: number): ReadonlyArray<number> => {\n const starts = [lineStart(text, from)]\n for (let at = text.indexOf('\\n', from); at !== -1 && at + 1 < to; at = text.indexOf('\\n', at + 1))\n starts.push(at + 1)\n return starts.reverse()\n}\n\n/** The selection's ends as offsets into the block's text, in order, or undefined. */\nconst span = (\n state: EditorState,\n block: Block,\n): { readonly from: number; readonly to: number } | undefined => {\n const selection = state.selection\n if (selection?.type !== 'Range') return undefined\n const anchor = offsetIn(block, selection.anchor)\n const focus = offsetIn(block, selection.focus)\n if (anchor === undefined || focus === undefined) return undefined\n return { from: Math.min(anchor, focus), to: Math.max(anchor, focus) }\n}\n\n/**\n * Tab: at a caret, a level of indentation where the caret is; over a range, a level at the start\n * of every line it covers, so a block of code moves right together.\n */\nexport const indent = (state: EditorState, block: Block): TransactionResult => {\n const ends = span(state, block)\n if (ends === undefined) return { ok: false, error: 'InvalidSelection' }\n const text = textOf(block)\n const at = (offset: number) => positionInBlock(block, offset)\n if (ends.from === ends.to) {\n const caret = at(ends.from)\n if (caret === undefined) return { ok: false, error: 'InvalidSelection' }\n // The caret goes after the indentation whichever side of the offset it leaned: a caret the\n // browser reports at a line's start leans `before`, and would stay in front of it.\n const after = {\n node: caret.node,\n offset: caret.offset + INDENT.length,\n affinity: 'after' as const,\n }\n return apply(state, [\n Edit.insertText(caret, INDENT),\n Edit.setSelection({ type: 'Range', anchor: after, focus: after }),\n ])\n }\n const operations: Array<Operation> = []\n for (const start of linesCovered(text, ends.from, ends.to)) {\n const position = at(start)\n if (position !== undefined) operations.push(Edit.insertText(position, INDENT))\n }\n return apply(state, operations)\n}\n\n/** Shift+Tab: up to a level of indentation off the start of every line the selection is on. */\nexport const outdent = (state: EditorState, block: Block): TransactionResult => {\n const ends = span(state, block)\n if (ends === undefined) return { ok: false, error: 'InvalidSelection' }\n const text = textOf(block)\n const starts =\n ends.from === ends.to ? [lineStart(text, ends.from)] : linesCovered(text, ends.from, ends.to)\n const operations: Array<Operation> = []\n for (const start of starts) {\n const leading = /^(?: {1,2}|\\t)/.exec(text.slice(start))?.[0].length ?? 0\n const from = positionInBlock(block, start)\n // An indentation split across runs is left alone: code runs carry no marks, so it is one.\n if (leading === 0 || from === undefined || from.offset + leading > runLength(block, from))\n continue\n operations.push(Edit.deleteText(from.node, from.offset, from.offset + leading))\n }\n return apply(state, operations)\n}\n\nconst runLength = (block: Block, position: Position): number =>\n block.children.find(run => run.id === position.node)?.text.length ?? 0\n","/**\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","/**\n * Footnotes: a reference in the text and a definition at the end of the document, tied by a\n * label. The reference is a mark on the run that shows the label, so it moves, splits and undoes\n * with the text; the definition is a block holding blocks, so its note is ordinary editable text.\n * Nothing else ties them: a definition no reference names, or a reference with no definition, is\n * what `footnotesOf` reports, not an invalid document.\n */\nimport { Schema } from 'effect'\nimport {\n blockContent,\n eachBlock,\n markName,\n rangeStart,\n type Block,\n type Document,\n type NodeId,\n type Selection,\n type Text,\n} from './document.js'\nimport { node } from './kit.js'\nimport { mark, markProps } from './marks.js'\n\nconst Label = Schema.Struct({ label: Schema.String })\n\n/** Where a footnote is referred to: the run showing its label carries this mark. */\nexport const FootnoteRef = mark('FootnoteRef', { Props: Label, expand: 'none' })\n\n/** A footnote's note, under the label its references carry. */\nexport const FootnoteDefinition = node('FootnoteDefinition', {\n Props: Label,\n children: blockContent,\n})\n\n/** One footnote: its label, its definition if there is one, and the runs that refer to it. */\nexport interface Footnote {\n readonly label: string\n readonly definition: NodeId | undefined\n /** The runs carrying its reference, in document order. */\n readonly references: ReadonlyArray<NodeId>\n /** The definition's text, one line per block. */\n readonly text: string\n}\n\nconst labelOf = (props: unknown): string | undefined => {\n if (typeof props !== 'object' || props === null || !('label' in props)) return undefined\n return typeof props.label === 'string' ? props.label : undefined\n}\n\n/** The label of the footnote a run refers to, if it carries a reference. */\nexport const referenceLabel = (run: Text): string | undefined => {\n const reference = run.marks.find(each => markName(each) === FootnoteRef.name)\n return reference === undefined ? undefined : labelOf(markProps(reference))\n}\n\nconst textOf = (blocks: ReadonlyArray<Block>): string => {\n const lines: Array<string> = []\n eachBlock(blocks, block => {\n if (block.children.length > 0) lines.push(block.children.map(run => run.text).join(''))\n })\n return lines.join('\\n')\n}\n\n/**\n * Every footnote, in the order its first reference appears; a definition nothing refers to comes\n * after them, in document order.\n */\nexport const footnotesOf = (document: Document): ReadonlyArray<Footnote> => {\n const references = new Map<string, Array<NodeId>>()\n const definitions = new Map<string, { node: NodeId; text: string }>()\n eachBlock(document.children, block => {\n if (block.type === 'Node' && block.kind === FootnoteDefinition.name) {\n const label = labelOf(block.props)\n if (label !== undefined && !definitions.has(label)) {\n definitions.set(label, { node: block.id, text: textOf(block.blocks ?? []) })\n }\n }\n for (const run of block.children) {\n const label = referenceLabel(run)\n if (label === undefined) continue\n const held = references.get(label)\n if (held === undefined) references.set(label, [run.id])\n else held.push(run.id)\n }\n })\n const labels = [...references.keys(), ...[...definitions.keys()].filter(l => !references.has(l))]\n return labels.map(label => ({\n label,\n definition: definitions.get(label)?.node,\n references: references.get(label) ?? [],\n text: definitions.get(label)?.text ?? '',\n }))\n}\n\n/**\n * The label of the footnote whose reference the selection starts in or right beside. A reference\n * is a character or two, and its mark does not extend, so a click on one usually leaves the caret\n * at its edge, in the run next to it; that caret counts as at the reference.\n */\nexport const footnoteAt = (document: Document, selection: Selection | null): string | undefined => {\n if (selection?.type !== 'Range') return undefined\n const start = rangeStart(document, selection)\n if (start === undefined) return undefined\n let found: string | undefined\n eachBlock(document.children, block => {\n const index = block.children.findIndex(each => each.id === start.node)\n if (index < 0) return\n const run = block.children[index]!\n let beside: Text | undefined\n if (start.offset === 0) beside = block.children[index - 1]\n else if (start.offset === run.text.length) beside = block.children[index + 1]\n found = referenceLabel(run) ?? (beside === undefined ? undefined : referenceLabel(beside))\n })\n return found\n}\n\n/** The smallest whole number no footnote uses as its label, as text: the next note's label. */\nexport const nextFootnoteLabel = (document: Document): string => {\n const used = new Set(footnotesOf(document).map(each => each.label))\n let n = 1\n while (used.has(String(n))) n++\n return String(n)\n}\n","/**\n * Editing a table as a grid: rows and columns added and removed beside the caret's cell, and the\n * caret moved from cell to cell, as Tab and Shift+Tab do. A table is the standard vocabulary's\n * `Table` of `TableRow`s of `TableCell`s, each cell holding blocks; a column is the cells at one\n * index across the rows, which may be ragged, so a column that a short row lacks is skipped\n * rather than refused. Each change is one transaction, so it is one undo step.\n */\nimport { withFreshIds } from './clipboard.js'\nimport {\n NodeId,\n blockAtPath,\n eachBlock,\n locateRun,\n rangeStart,\n type Block,\n type Document,\n type EditorState,\n type NodeBlock,\n type Selection,\n type Text,\n} from './document.js'\nimport { Edit, apply, type Operation, type TransactionResult } from './transaction.js'\n\n/** Where a caret stands in a table: the table, its row and the cell's index in that row. */\nexport interface TableAt {\n readonly table: NodeBlock\n readonly rows: ReadonlyArray<NodeBlock>\n readonly row: number\n readonly column: number\n}\n\nconst isKind = (block: Block | undefined, kind: string): block is NodeBlock =>\n block?.type === 'Node' && block.kind === kind\n\n/** The cells of a row, which are its nested blocks. */\nconst cellsOf = (row: NodeBlock): ReadonlyArray<Block> => row.blocks ?? []\n\n/**\n * The table cell the selection starts in, the innermost one when tables nest, or undefined\n * outside a table. A range is read from its start, as the other block commands read it.\n */\nexport const tableAt = (document: Document, selection: Selection | null): TableAt | undefined => {\n if (selection?.type !== 'Range') return undefined\n const start = rangeStart(document, selection)\n const run = start === undefined ? undefined : locateRun(document, start.node)\n if (run === undefined) return undefined\n // The cell is an ancestor of the caret's text block, its row the cell's parent, and the\n // table the row's: so the cell's path is at least three long.\n for (let depth = run.path.length - 1; depth >= 3; depth--) {\n const cell = blockAtPath(document, run.path.slice(0, depth))\n const row = blockAtPath(document, run.path.slice(0, depth - 1))\n const table = blockAtPath(document, run.path.slice(0, depth - 2))\n if (isKind(cell, 'TableCell') && isKind(row, 'TableRow') && isKind(table, 'Table')) {\n return {\n table,\n rows: (table.blocks ?? []).filter(\n (candidate): candidate is NodeBlock => candidate.type === 'Node',\n ),\n row: run.path[depth - 2]!,\n column: run.path[depth - 1]!,\n }\n }\n }\n return undefined\n}\n\n/** An empty cell, under placeholder identities a caller freshens. */\nconst emptyCell = (): Block => ({\n type: 'Node',\n kind: 'TableCell',\n id: NodeId.make('cell'),\n props: {},\n children: [],\n blocks: [\n {\n type: 'Paragraph',\n id: NodeId.make('paragraph'),\n children: [{ type: 'Text', id: NodeId.make('text'), text: '', marks: [] }],\n },\n ],\n})\n\nconst fresh = (block: Block, mint: () => string): Block =>\n withFreshIds({ version: 1, blocks: [block] }, mint).blocks[0]!\n\nconst firstRun = (block: Block | undefined): Text | undefined => {\n if (block === undefined) return undefined\n let found: Text | undefined\n eachBlock([block], inner => {\n found ??= inner.children[0]\n })\n return found\n}\n\n/** The selection at the start of a cell's first text, or the selection as it was. */\nconst caretIn = (cell: Block | undefined, otherwise: Selection | null): Selection | null => {\n const run = firstRun(cell)\n if (run === undefined) return otherwise\n const at = { node: run.id, offset: 0, affinity: 'after' as const }\n return { type: 'Range', anchor: at, focus: at }\n}\n\n/** A table edit, or that the edit would leave the table empty and it should be deleted whole. */\nexport type TableEdit = TransactionResult | { readonly deleteTable: NodeId }\n\n/** The widest row's cell count: what a new row is given so the grid stays as wide. */\nconst widthOf = (rows: ReadonlyArray<NodeBlock>): number =>\n Math.max(1, ...rows.map(row => cellsOf(row).length))\n\n/** A row as wide as the table, under fresh identities, and the operation that puts it there. */\nconst newRow = (at: TableAt, index: number, mint: () => string) => {\n const row = fresh(\n {\n type: 'Node',\n kind: 'TableRow',\n id: NodeId.make('row'),\n props: {},\n children: [],\n blocks: Array.from({ length: widthOf(at.rows) }, emptyCell),\n },\n mint,\n )\n return { row, operation: Edit.insertBlock(row, index, at.table.id) }\n}\n\n/** A row above or below the caret's, as wide as the table; the caret goes to it, same column. */\nexport const insertRow = (\n state: EditorState,\n at: TableAt,\n where: 'before' | 'after',\n mint: () => string,\n): TransactionResult => {\n const { row, operation } = newRow(at, at.row + (where === 'after' ? 1 : 0), mint)\n const cells = row.type === 'Node' ? (row.blocks ?? []) : []\n return apply(state, [\n operation,\n Edit.setSelection(caretIn(cells[Math.min(at.column, cells.length - 1)], state.selection)),\n ])\n}\n\n/**\n * A cell beside the caret's in every row, before or after it; a row too short to have that\n * column gets its cell at its end. The caret goes to the new cell in its own row.\n */\nexport const insertColumn = (\n state: EditorState,\n at: TableAt,\n where: 'before' | 'after',\n mint: () => string,\n): TransactionResult => {\n const index = at.column + (where === 'after' ? 1 : 0)\n let caretCell: Block | undefined\n const operations: Array<Operation> = at.rows.map((row, rowIndex) => {\n const cell = fresh(emptyCell(), mint)\n if (rowIndex === at.row) caretCell = cell\n return Edit.insertBlock(cell, Math.min(index, cellsOf(row).length), row.id)\n })\n return apply(state, [...operations, Edit.setSelection(caretIn(caretCell, state.selection))])\n}\n\n/** The caret's row, gone; the caret goes to the same column of the row after it, or before. */\nexport const deleteRow = (state: EditorState, at: TableAt): TableEdit => {\n if (at.rows.length === 1) return { deleteTable: at.table.id }\n const next = at.rows[at.row + 1] ?? at.rows[at.row - 1]!\n const cells = cellsOf(next)\n return apply(state, [\n Edit.deleteBlock(at.rows[at.row]!.id),\n Edit.setSelection(caretIn(cells[Math.min(at.column, cells.length - 1)], state.selection)),\n ])\n}\n\n/**\n * The caret's column, gone from every row that has it; a row it leaves empty goes too. The\n * caret goes to the cell that takes the column's place in its row, or the one before it.\n */\nexport const deleteColumn = (state: EditorState, at: TableAt): TableEdit => {\n if (at.rows.every(row => cellsOf(row).length <= 1)) return { deleteTable: at.table.id }\n const operations: Array<Operation> = []\n for (const row of at.rows) {\n const cells = cellsOf(row)\n const cell = cells[at.column]\n if (cell === undefined) continue\n operations.push(Edit.deleteBlock(cells.length === 1 ? row.id : cell.id))\n }\n const own = cellsOf(at.rows[at.row]!)\n const landing = own.length === 1 ? undefined : (own[at.column + 1] ?? own[at.column - 1])\n return apply(state, [\n ...operations,\n ...(landing === undefined ? [] : [Edit.setSelection(caretIn(landing, state.selection))]),\n ])\n}\n\n/**\n * The caret to the start of the next cell, across rows, or the previous one: Tab and Shift+Tab.\n * Tab in the last cell adds a row and goes to it; Shift+Tab in the first stays where it is.\n */\nexport const moveToCell = (\n state: EditorState,\n at: TableAt,\n direction: 'next' | 'previous',\n mint: () => string,\n): TransactionResult => {\n const order = at.rows.flatMap((row, rowIndex) =>\n cellsOf(row).map((cell, column) => ({ cell, rowIndex, column })),\n )\n const here = order.findIndex(entry => entry.rowIndex === at.row && entry.column === at.column)\n const target = order[here + (direction === 'next' ? 1 : -1)]\n if (target !== undefined) {\n return apply(state, [Edit.setSelection(caretIn(target.cell, state.selection))])\n }\n if (direction === 'previous') return apply(state, [])\n const { row, operation } = newRow(at, at.rows.length, mint)\n return apply(state, [operation, Edit.setSelection(caretIn(row, state.selection))])\n}\n","import { Equal, Match, Schema } from 'effect'\nimport {\n NodeId,\n blockAtPath,\n compareRunPlaces,\n eachBlock,\n positionInBlock,\n locateBlock,\n rangeStart,\n locateRun,\n pathKey,\n textContent,\n type Block,\n type BlockPath,\n type Document,\n type EditorState,\n type MarkValue,\n type Position,\n type RunMark,\n type Selection,\n type Text as Run,\n} from './document.js'\nimport { withFreshIds, type Slice } from './clipboard.js'\nimport { toText } from './html.js'\nimport {\n markName,\n edgeMarks,\n resolveInsertion,\n propsFailure,\n sameMark,\n shippedRegistry,\n type MarkRegistry,\n} from './marks.js'\nimport { blockKind, standsWithin, type NodeRegistry } from './kit.js'\nimport { indent, indentationAt, offsetIn, outdent } from './indent.js'\nimport { findMatches, type SearchMatch } from './search.js'\nimport {\n FootnoteDefinition,\n FootnoteRef,\n footnotesOf,\n nextFootnoteLabel,\n referenceLabel,\n} from './footnote.js'\nimport {\n deleteColumn,\n deleteRow,\n insertColumn,\n insertRow,\n moveToCell,\n tableAt,\n type TableEdit,\n} from './table.js'\nimport {\n Edit,\n apply,\n type ChangeSet,\n type Operation,\n type TextBlock,\n type TransactionResult,\n} from './transaction.js'\n\n/**\n * Editor intent: what the user is trying to do. Commands resolve against the\n * current document and selection into a Transaction of low-level operations, so\n * durable history keeps its meaning (§19). Identities a command needs come from\n * the caller's `mint`; nothing here reads a clock or a hidden counter.\n */\nexport type Command =\n | {\n readonly type: 'InsertText'\n readonly text: string\n /** Stored marks: a bare name, or a value when the mark carries props. */\n readonly marks?: ReadonlyArray<string | MarkValue>\n }\n | { readonly type: 'DeleteBackward' }\n | { readonly type: 'DeleteForward' }\n | { readonly type: 'SplitBlock' }\n | { readonly type: 'ToggleMark'; readonly mark: string | MarkValue }\n /**\n * Puts exactly this mark on every run the selection covers, replacing a same-named mark\n * whose props differ: how a link gets a new `href`. A caret acts on the extent of the\n * mark around it (`markExtent`), and does nothing outside one.\n */\n | { readonly type: 'SetMark'; readonly mark: string | MarkValue }\n /**\n * Takes the named mark off every run the selection covers; a caret, off its extent. Given a\n * mark value, only off the runs carrying exactly that value: one discussion's highlight,\n * leaving another's inside it.\n */\n | { readonly type: 'ClearMark'; readonly mark: string | MarkValue }\n | { readonly type: 'SetSelection'; readonly selection: Selection | null }\n | { readonly type: 'Paste'; readonly slice: Slice }\n /** Retypes the block the selection starts in: a paragraph, or a heading. */\n | { readonly type: 'RetypeBlock'; readonly to: TextBlock }\n /**\n * Wraps the block the selection starts in, in new containers listed outermost first: a\n * `Quote`, or a `List` holding a `ListItem`. The block keeps its identity and its runs,\n * so the caret stays where it was. Given a vocabulary, a list wrap right after a list of the\n * same kind and props adds the block to it as a new item.\n */\n | { readonly type: 'WrapBlock'; readonly containers: ReadonlyArray<Container> }\n /**\n * Retypes the text block the selection starts in to a node kind that holds text, such as a\n * `CodeBlock`. The block and its runs keep their identities, text, and marks.\n */\n | { readonly type: 'ConvertBlock'; readonly to: Container }\n /**\n * Retypes the container the selection starts in (the node block holding its block, such as\n * a list item) to another node kind, where it stands: its identity and every block it holds\n * are kept, so edits made inside it meanwhile survive. Only from the container's first block,\n * which is where a marker for the container is typed. Given a vocabulary, the new kind must\n * hold blocks, hold each block the container holds, and stand where the container does.\n */\n | { readonly type: 'RetypeContainer'; readonly to: Container }\n /**\n * Lifts the block the selection starts in out of its container, the inverse of a wrap:\n * repeated while the new parent's declaration refuses it, so a list item's paragraph leaves\n * both the item and the list. The block keeps its identity, and the caret with it.\n */\n | { readonly type: 'LiftBlock' }\n /**\n * Moves a block, and everything it holds, before or after another block, in its own container\n * or another one the vocabulary lets it stand in (§149). It addresses blocks rather than the\n * selection, so a handle or a key can move the block it stands for; identities are kept, and\n * the selection with them. A container the move leaves empty is deleted.\n */\n | { readonly type: 'MoveBlock'; readonly node: NodeId; readonly to: Beside }\n /**\n * Sets the named props of a node block, such as a task item's `checked`, keeping the rest.\n * It addresses the block by identity, as `MoveBlock` does, so a checkbox sends it for its\n * own item. Given a vocabulary, props that decode as the kind's must still decode after.\n */\n | { readonly type: 'SetProps'; readonly node: NodeId; readonly props: Schema.JsonObject }\n /**\n * Inserts a block, and everything it holds, before or after another block, under fresh\n * identities from `mint`: an image chosen from a file, a table from a menu, a copy of a block\n * for its handle's Duplicate. The caret goes to the start of its first text, when it has any.\n * Without `to` it goes beside the caret's block: before it when that block is empty, so a\n * slash command typed on a blank line puts its block there and the line stays to type on,\n * and after it otherwise.\n */\n | { readonly type: 'InsertBlock'; readonly block: Block; readonly to?: Beside | undefined }\n /**\n * Deletes a block and everything it holds, with any container that would be left empty by it,\n * as a block handle's Delete does. A caret inside it moves to the nearest text that stays; a\n * document left with no block gets an empty paragraph, so there is somewhere to type.\n */\n | { readonly type: 'DeleteBlock'; readonly node: NodeId }\n /**\n * A row above or below the caret's table cell, as wide as the table's widest row, with the caret\n * moved into it. The table is the standard vocabulary's (`Table`, `TableRow`, `TableCell`).\n */\n | { readonly type: 'InsertRow'; readonly where: 'before' | 'after' }\n /** A cell beside the caret's in every row, before or after it: a column. */\n | { readonly type: 'InsertColumn'; readonly where: 'before' | 'after' }\n /** The caret's row, deleted; the last one deletes the table. */\n | { readonly type: 'DeleteRow' }\n /** The caret's column, deleted from every row that has it; the last one deletes the table. */\n | { readonly type: 'DeleteColumn' }\n /**\n * Tab. In a kind declared `indents` (code), a level of indentation at the caret, or at the\n * start of every line a range covers; in a table cell, the caret to the next cell, adding a row\n * after the last. Refused anywhere else (`InvalidSelection`), so Tab can move focus there.\n */\n | { readonly type: 'Indent' }\n /** Shift+Tab: a level of indentation off each line in code; the previous cell in a table. */\n | { readonly type: 'Outdent' }\n /**\n * Find and replace: the match at index `at` of `query` (in document order, as `findMatches`\n * lists them), or every match when `at` is absent, becomes `replacement`, as one transaction.\n * Case does not count unless `caseSensitive`. The caret ends after the earliest replacement.\n */\n | {\n readonly type: 'Replace'\n readonly query: string\n readonly replacement: string\n readonly caseSensitive?: boolean | undefined\n readonly at?: number | undefined\n }\n /**\n * A footnote at the caret, or at the end of a range: a reference showing the next free label\n * (`nextFootnoteLabel`), and its definition after the last top-level block holding `text`, with\n * the caret at the definition's start, ready to write the note.\n */\n | { readonly type: 'InsertFootnote'; readonly text?: string | undefined }\n /**\n * A footnote's label, `from`, becomes `to`: on its definition, and on every reference, whose\n * text becomes `to` where it showed `from`. Refused (`InvalidInput`) when `to` is blank or\n * another footnote's, or when no footnote is labelled `from`.\n */\n | { readonly type: 'RenameFootnote'; readonly from: string; readonly to: string }\n\n/** Where `MoveBlock` puts a block: before or after a sibling, named by identity. */\nexport const Beside = Schema.Union([\n // Each shape refuses the other's key: `{ before, after }` would name two places.\n Schema.Struct({ before: NodeId, after: Schema.optionalKey(Schema.Never) }),\n Schema.Struct({ after: NodeId, before: Schema.optionalKey(Schema.Never) }),\n])\nexport type Beside = typeof Beside.Type\n\n/** A container a block is wrapped in: a node kind, and the props it starts with. */\nexport const Container = Schema.Struct({\n kind: Schema.NonEmptyString,\n props: Schema.optionalKey(Schema.JsonObject),\n})\nexport type Container = typeof Container.Type\n\n/** Caller-owned identity source. Live edits mint; replay applies transactions. */\nexport interface CommandIds {\n readonly mint: () => string\n}\n\n/** What a command needs beyond state and identity, such as a Kit's mark policy. */\nexport interface RunOptions {\n readonly marks?: MarkRegistry | undefined\n /** The node vocabulary, so an edit a constraint forbids is refused here (§125). */\n readonly nodes?: NodeRegistry | undefined\n}\n\n/**\n * Whether the block at a path is declared to carry no marks, in which case adding one\n * is refused at the command layer rather than reported only by `validate` (§125). A\n * preserved block is left alone: it has no declaration to read, and preserving it\n * matters more than forbidding a mark on it.\n */\nconst forbidsMarks = (\n document: Document,\n path: BlockPath,\n nodes: NodeRegistry | undefined,\n): boolean => {\n if (nodes === undefined) return false\n const block = blockAtPath(document, path)\n if (block === undefined || block.type === 'Unknown') return false\n return kindForbidsMarks(nodes, blockKind(block))\n}\n\nconst kindForbidsMarks = (nodes: NodeRegistry, kind: string): boolean => {\n const declared = nodes.definitionFor(kind)\n return declared?.kind === 'node' && declared.marks === 'none'\n}\n\n/**\n * Whether the block at a path accepts a child of this kind. A declaration without a\n * constraint accepts any block, and a vocabulary that does not declare the parent is\n * not consulted — `validate` reports an undeclared kind, and an edit should not fail\n * for a reason the caller never stated.\n */\nconst acceptsChild = (\n document: Document,\n path: BlockPath,\n kind: string,\n nodes: NodeRegistry | undefined,\n): boolean => {\n const parent = blockAtPath(document, path)\n return parent === undefined || kindAccepts(nodes, blockKind(parent), kind)\n}\n\n/** Whether a kind's declaration lets it hold another as a nested block; undeclared is open. */\nconst kindAccepts = (\n nodes: NodeRegistry | undefined,\n parentKind: string,\n childKind: string,\n): boolean => {\n if (nodes === undefined) return true\n const declared = nodes.definitionFor(parentKind)\n if (declared?.kind !== 'node' || typeof declared.children === 'string') return true\n return declared.children.of.includes(childKind)\n}\n\n/** Whether the vocabulary declares props for a new node that these do not decode as. */\nconst refusesProps = (nodes: NodeRegistry | undefined, container: Container): boolean => {\n const declared = nodes?.definitionFor(container.kind)\n return (\n declared !== undefined &&\n declared.kind !== 'block' &&\n propsFailure(declared.props, container.props ?? {})\n )\n}\n\n/** Whether the vocabulary declares `kind` as a node that holds runs, as `CodeBlock` is. */\nconst declaresText = (nodes: NodeRegistry | undefined, kind: string): boolean => {\n const declared = nodes?.definitionFor(kind)\n return declared?.kind === 'node' && declared.children === textContent\n}\n\n/**\n * Whether a block is an atom, holding neither text nor blocks, as an image is. Without a\n * vocabulary, a node with nothing in it is one.\n */\nexport const isAtom = (nodes: NodeRegistry | undefined, block: Block): boolean => {\n if (block.type !== 'Node') return false\n const declared = nodes?.definitionFor(block.kind)\n return declared === undefined\n ? block.blocks === undefined && block.children.length === 0\n : declared.kind === 'atom'\n}\n\n/** Whether the vocabulary names `itemKind` among the kinds `listKind` holds, as `List` names `ListItem`. */\nconst holdsItem = (nodes: NodeRegistry, listKind: string, itemKind: string): boolean => {\n const declared = nodes.definitionFor(listKind)\n return (\n declared?.kind === 'node' &&\n typeof declared.children !== 'string' &&\n declared.children.of.includes(itemKind)\n )\n}\n\n/**\n * Whether a kind can be a new container. Unlike an existing parent, a kind a wrap creates\n * must be declared as holding nested blocks when there is a vocabulary: wrapping in an\n * undeclared kind, or a text kind such as `CodeBlock`, would make content `validate`\n * refuses.\n */\nconst holdsBlocks = (nodes: NodeRegistry | undefined, kind: string): boolean => {\n if (nodes === undefined) return true\n const declared = nodes.definitionFor(kind)\n return declared?.kind === 'node' && declared.children !== textContent\n}\n\ntype Failure =\n | 'InvalidSelection'\n | 'MissingText'\n | 'InvalidInput'\n | 'InvalidParent'\n | 'ForbiddenMark'\n | 'UnexpectedChild'\nconst failure = (error: Failure): TransactionResult => ({ ok: false, error })\n\ninterface Located {\n readonly path: BlockPath\n readonly runIndex: number\n readonly blockId: NodeId\n readonly id: NodeId\n readonly text: string\n readonly marks: ReadonlyArray<RunMark>\n}\n\n/** Document order over a located run, by the shared place rule. */\nconst locatedOrder = (\n left: { readonly path: BlockPath; readonly runIndex: number },\n right: { readonly path: BlockPath; readonly runIndex: number },\n): number =>\n compareRunPlaces(\n { path: left.path, index: left.runIndex },\n { path: right.path, index: right.runIndex },\n )\n\nconst locate = (document: Document, node: NodeId): Located | undefined => {\n const found = locateRun(document, node)\n if (found === undefined) return undefined\n const block = blockAtPath(document, found.path)\n if (block === undefined) return undefined\n return {\n path: found.path,\n runIndex: found.index,\n blockId: block.id,\n id: found.run.id,\n text: found.run.text,\n marks: found.run.marks,\n }\n}\n\nconst isCollapsed = (selection: Extract<Selection, { readonly type: 'Range' }>): boolean =>\n selection.anchor.node === selection.focus.node &&\n selection.anchor.offset === selection.focus.offset\n\n/** Whether a selection covers text: a range that is not a caret. What a mark or a link applies to. */\nexport const coversText = (selection: Selection | null): boolean =>\n selection?.type === 'Range' && !isCollapsed(selection)\n\n/** A caret is a range whose endpoints coincide; direction is not yet meaningful. */\nconst caretAt = (position: Position): Selection => ({\n type: 'Range',\n anchor: position,\n focus: position,\n})\n\n/** Orders a range's endpoints by document order without losing direction. */\nconst ordered = (\n document: Document,\n selection: Extract<Selection, { readonly type: 'Range' }>,\n): { readonly start: Position; readonly end: Position } | undefined => {\n const anchor = locate(document, selection.anchor.node)\n const focus = locate(document, selection.focus.node)\n if (anchor === undefined || focus === undefined) return undefined\n const byPlace = locatedOrder(anchor, focus)\n const after = byPlace !== 0 ? byPlace > 0 : selection.anchor.offset > selection.focus.offset\n return after\n ? { start: selection.focus, end: selection.anchor }\n : { start: selection.anchor, end: selection.focus }\n}\n\ninterface Span {\n readonly run: Located\n readonly from: number\n readonly to: number\n}\n\n/** Runs intersecting an ordered [start, end), with the covered sub-range. */\nconst covered = (document: Document, start: Position, end: Position): ReadonlyArray<Span> => {\n const startAt = locate(document, start.node)\n const endAt = locate(document, end.node)\n if (startAt === undefined || endAt === undefined) return []\n const spans: Array<Span> = []\n // The walk is document order, so comparing each run's place against the\n // endpoints' places picks out the covered span however deep it sits.\n eachBlock(document.children, (block, path) => {\n for (const [runIndex, run] of block.children.entries()) {\n const place = { path, runIndex }\n if (locatedOrder(place, startAt) < 0 || locatedOrder(place, endAt) > 0) continue\n const from = locatedOrder(place, startAt) === 0 ? start.offset : 0\n const to = locatedOrder(place, endAt) === 0 ? end.offset : run.text.length\n if (from >= to) continue\n spans.push({\n run: {\n path,\n runIndex,\n blockId: block.id,\n id: run.id,\n text: run.text,\n marks: run.marks,\n },\n from,\n to,\n })\n }\n })\n return spans\n}\n\n/** Marks every run in the list carries; empty when there are no runs. */\nconst sharedMarks = (runs: ReadonlyArray<ReadonlyArray<RunMark>>): ReadonlySet<string> => {\n let common: Set<string> | undefined\n for (const marks of runs) {\n const names = new Set(marks.map(markName))\n if (common === undefined) {\n common = names\n continue\n }\n for (const name of common) if (!names.has(name)) common.delete(name)\n }\n return common ?? new Set()\n}\n\n/**\n * The marks every run the selection covers carries: the ones a toggle would\n * remove, which is what an \"active\" toolbar button means. A caret reports its\n * run's marks — an empty run can carry them, which is how a caret holds a format\n * — and a range is not bold when it straddles a bold run and a plain one. A node\n * selection reports what its whole subtree agrees on. A read, not a command:\n * nothing here changes anything.\n */\nexport const marksInRange = (\n document: Document,\n selection: Selection | null,\n): ReadonlySet<string> => {\n if (selection === null) return new Set()\n if (selection.type === 'Node') {\n const found = locateBlock(document, selection.node)\n if (found === undefined) return new Set()\n const runs: Array<ReadonlyArray<RunMark>> = []\n eachBlock([found.block], each => {\n for (const run of each.children) runs.push(run.marks)\n })\n return sharedMarks(runs)\n }\n const bounds = ordered(document, selection)\n if (bounds === undefined) return new Set()\n if (isCollapsed(selection)) {\n const caret = locate(document, selection.anchor.node)\n return caret === undefined ? new Set() : sharedMarks([caret.marks])\n }\n return sharedMarks(covered(document, bounds.start, bounds.end).map(span => span.run.marks))\n}\n\n/** A mark around a caret, and the range of runs it spans. */\nexport interface MarkExtent {\n readonly mark: RunMark\n readonly selection: Extract<Selection, { readonly type: 'Range' }>\n}\n\n/**\n * The named mark on the run a position is in, and the adjacent runs of its block carrying\n * the same mark with the same props: the whole link a caret sits in, which is what a link\n * editor shows and what `SetMark` and `ClearMark` act on at a caret. Undefined when that\n * run does not carry the mark. A read, like `marksInRange`.\n */\nexport const markExtent = (\n document: Document,\n position: Position,\n name: string,\n): MarkExtent | undefined => {\n const found = locateRun(document, position.node)\n const mark = found?.run.marks.find(held => markName(held) === name)\n if (found === undefined || mark === undefined) return undefined\n const runs = blockAtPath(document, found.path)!.children\n const carries = (index: number) => runs[index]?.marks.some(held => sameMark(held, mark)) === true\n let first = found.index\n while (carries(first - 1)) first--\n let last = found.index\n while (carries(last + 1)) last++\n const end = runs[last]!\n return {\n mark,\n selection: {\n type: 'Range',\n anchor: { node: runs[first]!.id, offset: 0, affinity: 'after' },\n focus: { node: end.id, offset: end.text.length, affinity: 'before' },\n },\n }\n}\n\n/**\n * The text style of the block a selection starts in, in the shape `RetypeBlock` takes, so a\n * style picker compares what it would send with what is there. Undefined for a node\n * selection, one that resolves to nothing, or a block a retype does not reach, such as a code\n * block.\n */\nexport const textBlockAt = (\n document: Document,\n selection: Selection | null,\n): TextBlock | undefined => {\n if (selection?.type !== 'Range') return undefined\n const path = startPath(document, selection)\n const block = path === undefined ? undefined : blockAtPath(document, path)\n if (block?.type === 'Paragraph') return { type: 'Paragraph' }\n if (block?.type === 'Heading') return { type: 'Heading', level: block.level }\n return undefined\n}\n\n/**\n * Why block `moving` may not move into the container at `container` (§149), or undefined when\n * it may. Within its own container it always may. Elsewhere, the container must hold its kind,\n * the kind must stand in the container's kind (a `ListItem` only in a `List`), it may not leave\n * a container declared isolating, and it may not go inside itself.\n */\nconst moveFailure = (\n document: Document,\n moving: { readonly path: BlockPath; readonly block: Block },\n container: BlockPath,\n nodes: NodeRegistry | undefined,\n): Failure | undefined => {\n if (moving.path.every((index, depth) => container[depth] === index)) return 'InvalidParent'\n const source = moving.path.slice(0, -1)\n if (pathKey(source) === pathKey(container)) return undefined\n const kind = blockKind(moving.block)\n const parent = container.length === 0 ? undefined : blockAtPath(document, container)\n if (\n !acceptsChild(document, container, kind, nodes) ||\n !standsWithin(nodes?.definitionFor(kind), parent === undefined ? undefined : blockKind(parent))\n ) {\n return 'UnexpectedChild'\n }\n for (let depth = source.length; depth > 0; depth--) {\n const holder = source.slice(0, depth)\n const inside = holder.every((index, at) => container[at] === index)\n if (!inside && isIsolating(document, holder, nodes)) return 'InvalidParent'\n }\n return undefined\n}\n\nconst isIsolating = (document: Document, path: BlockPath, nodes: NodeRegistry | undefined) => {\n const block = blockAtPath(document, path)\n const declared = block === undefined ? undefined : nodes?.definitionFor(blockKind(block))\n return declared?.kind === 'node' && declared.isolating === true\n}\n\n/**\n * The outermost container a block leaving `source` empties, walking up while each held nothing\n * else: a list whose only item's only block moved out goes with it. Never the container it lands\n * in, or one holding that. An isolating one is never reached, since a move may not leave it.\n */\nconst emptiedBy = (\n document: Document,\n source: BlockPath,\n container: BlockPath,\n): NodeId | undefined => {\n let emptied: NodeId | undefined\n for (let path = source; path.length > 0; path = path.slice(0, -1)) {\n const block = blockAtPath(document, path)\n const holdsTarget = path.every((index, depth) => container[depth] === index)\n if (block?.type !== 'Node' || (block.blocks?.length ?? 0) > 1 || holdsTarget) break\n emptied = block.id\n }\n return emptied\n}\n\n/**\n * The blocks `node` may move beside, in document order (§149): the blocks of every container it\n * may move into, which is what a drag offers. Empty when the document does not hold it.\n */\nexport const moveTargets = (\n document: Document,\n node: NodeId,\n nodes?: NodeRegistry,\n): ReadonlyArray<NodeId> => {\n const moving = locateBlock(document, node)\n if (moving === undefined) return []\n const targets: Array<NodeId> = []\n eachBlock(document.children, (block, path) => {\n if (moveFailure(document, moving, path.slice(0, -1), nodes) === undefined)\n targets.push(block.id)\n })\n return targets\n}\n\n/** Where a selection starts: its first run's block, or the block a node selection names. */\nconst startPath = (document: Document, selection: Selection | null): BlockPath | undefined => {\n if (selection === null) return undefined\n if (selection.type === 'Node') return locateBlock(document, selection.node)?.path\n const start = ordered(document, selection)?.start\n return start === undefined ? undefined : locateRun(document, start.node)?.path\n}\n\n/**\n * The blocks a selection starts in, outermost first: a caret in a list item's paragraph gives\n * the list, the item, and the paragraph. What a block handle picks from, and a breadcrumb draws.\n * Empty when the selection is null or resolves to nothing.\n */\nexport const blocksAt = (document: Document, selection: Selection | null): ReadonlyArray<Block> => {\n const path = startPath(document, selection) ?? []\n return path.map((_, depth) => blockAtPath(document, path.slice(0, depth + 1))!)\n}\n\n/** Whether `prefix` is a path to one of the blocks `path` lies inside, or `path` itself. */\nconst startsWith = (path: BlockPath, prefix: BlockPath): boolean =>\n prefix.length <= path.length && prefix.every((index, at) => path[at] === index)\n\n/** Document order of two block paths: a container comes before what it holds. */\nconst pathOrder = (left: BlockPath, right: BlockPath): number => {\n for (let at = 0; at < Math.min(left.length, right.length); at++) {\n if (left[at] !== right[at]) return left[at]! - right[at]!\n }\n return left.length - right.length\n}\n\n/** Whether two blocks can be joined into one: what `JoinNode` accepts. */\nconst joinable = (survivor: Block, removed: Block): boolean => {\n if (survivor.type === 'Unknown' || removed.type === 'Unknown') return false\n if (nestedBlocks(survivor) !== undefined || nestedBlocks(removed) !== undefined) return false\n if (survivor.type !== 'Node' && removed.type !== 'Node') return true\n return (\n survivor.type === 'Node' &&\n removed.type === 'Node' &&\n survivor.kind === removed.kind &&\n Equal.equals(survivor.props, removed.props)\n )\n}\n\nconst nestedBlocks = (block: Block): ReadonlyArray<Block> | undefined =>\n block.type === 'Node' && block.blocks !== undefined ? block.blocks : undefined\n\n/** Whether going from one block to another leaves an isolating container, as a table cell is. */\nconst crossesIsolating = (\n document: Document,\n from: BlockPath,\n to: BlockPath,\n nodes: NodeRegistry | undefined,\n): boolean =>\n [from, to].some((path, side) => {\n const other = side === 0 ? to : from\n for (let depth = 1; depth < path.length; depth++) {\n const container = path.slice(0, depth)\n if (startsWith(other, container)) continue\n const block = blockAtPath(document, container)\n const declared = block?.type === 'Node' ? nodes?.definitionFor(block.kind) : undefined\n if (declared?.kind === 'node' && declared.isolating === true) return true\n }\n return false\n })\n\n/** The innermost first or last block inside the block at `path`: itself when it holds none. */\nconst edgeLeaf = (document: Document, path: BlockPath, last: boolean): BlockPath => {\n let at = path\n for (;;) {\n const held = nestedBlocks(blockAtPath(document, at)!)\n if (held === undefined || held.length === 0) return at\n at = [...at, last ? held.length - 1 : 0]\n }\n}\n\n/** The first block after the one at `path` that holds no blocks, in document order. */\nconst nextLeaf = (document: Document, path: BlockPath): BlockPath | undefined => {\n let found: BlockPath | undefined\n eachBlock(document.children, (block, at) => {\n if (found !== undefined || pathOrder(at, path) <= 0 || startsWith(path, at)) return\n if ((nestedBlocks(block) ?? []).length === 0) found = at\n })\n return found\n}\n\n/** One result followed by another, as one: what `runAction` does for two commands. */\nconst followedBy = (first: TransactionResult, second: TransactionResult): TransactionResult =>\n !first.ok || !second.ok\n ? second.ok\n ? first\n : second\n : {\n ok: true,\n state: second.state,\n changeSet: unionChangeSet(first.changeSet, second.changeSet),\n positionMap: [...first.positionMap, ...second.positionMap],\n transactions: [...first.transactions, ...second.transactions],\n }\n\n/**\n * Deletes a range that leaves its container, as selecting from one kind of block into another\n * (or everything) and pressing Delete does: the text after `start` in its block and before\n * `end` in its block goes, every block wholly between them goes, and the block `end` is in\n * comes up beside the one `start` is in, joining it when the two can be one. A container it\n * leaves empty goes too. A range that leaves a table cell (an isolating container) only loses\n * its text: the cells stay, as a table's structure is not a selection's to remove. The caret\n * ends at `start`.\n */\nconst clearRange = (\n state: EditorState,\n start: Position,\n end: Position,\n options: RunOptions,\n): TransactionResult => {\n const document = state.document\n const startAt = locate(document, start.node)\n const endAt = locate(document, end.node)\n if (startAt === undefined || endAt === undefined) return failure('MissingText')\n const startPath = startAt.path\n const endPath = endAt.path\n const spans = covered(document, start, end)\n if (crossesIsolating(document, startPath, endPath, options.nodes)) {\n return apply(state, [\n ...spans.map(span => Edit.deleteText(span.run.id, span.from, span.to)),\n Edit.setSelection(caretAt(start)),\n ])\n }\n // The ends lose what the range covers of them; everything between them goes whole.\n const ends = spans.filter(\n span =>\n pathKey(span.run.path) === pathKey(startPath) || pathKey(span.run.path) === pathKey(endPath),\n )\n const between: Array<{ readonly id: NodeId; readonly path: BlockPath }> = []\n eachBlock(document.children, (block, path) => {\n if (pathOrder(path, startPath) <= 0 || pathOrder(path, endPath) >= 0) return\n if (startsWith(endPath, path) || startsWith(startPath, path)) return\n if (between.some(outer => startsWith(path, outer.path))) return\n between.push({ id: block.id, path })\n })\n const first = apply(state, [\n ...ends.map(span => Edit.deleteText(span.run.id, span.from, span.to)),\n ...between.map(block => Edit.deleteBlock(block.id)),\n Edit.setSelection(caretAt(start)),\n ])\n if (!first.ok) return first\n // Bring the end block beside the start one, join them if they can be one, and take away\n // the containers the move left empty.\n const startBlock = blockAtPath(document, startPath)!\n const endBlock = blockAtPath(document, endPath)!\n const now = first.state.document\n const survivorAt = locateBlock(now, startBlock.id)\n const removedAt = locateBlock(now, endBlock.id)\n if (survivorAt === undefined || removedAt === undefined) return first\n const operations: Array<Operation> = []\n const parentPath = survivorAt.path.slice(0, -1)\n const parent = parentPath.length === 0 ? undefined : blockAtPath(now, parentPath)\n const index = survivorAt.path[survivorAt.path.length - 1]!\n const siblings = pathKey(removedAt.path.slice(0, -1)) === pathKey(parentPath)\n // It comes up only where its kind may stand: a list holds items, not a paragraph.\n if (\n !siblings &&\n parentPath.length > 0 &&\n !acceptsChild(now, parentPath, blockKind(removedAt.block), options.nodes)\n ) {\n return first\n }\n if (!siblings) operations.push(Edit.moveBlock(endBlock.id, index + 1, parent?.id))\n const adjacent = siblings ? removedAt.path[removedAt.path.length - 1] === index + 1 : true\n if (adjacent && joinable(survivorAt.block, removedAt.block)) {\n operations.push(Edit.joinBlocks(startBlock.id, endBlock.id))\n }\n if (!siblings) {\n // Each container the end block was in, innermost first, goes when nothing else is left in it.\n for (let depth = removedAt.path.length - 1; depth > 0; depth--) {\n const container = blockAtPath(now, removedAt.path.slice(0, depth))\n if (container === undefined || startsWith(survivorAt.path, removedAt.path.slice(0, depth))) {\n break\n }\n // It held the end block, or the container holding it, and is empty once that goes.\n if ((nestedBlocks(container) ?? []).length > 1) break\n operations.push(Edit.deleteBlock(container.id))\n }\n }\n if (operations.length === 0) return first\n return followedBy(first, apply(first.state, [...operations, Edit.setSelection(caretAt(start))]))\n}\n\n/** The last run in a block's subtree, or undefined when it holds none. */\nconst lastRunOf = (block: Block): Run | undefined => {\n if (block.type === 'Node' && block.blocks !== undefined) {\n for (let index = block.blocks.length - 1; index >= 0; index--) {\n const found = lastRunOf(block.blocks[index]!)\n if (found !== undefined) return found\n }\n }\n return block.children[block.children.length - 1]\n}\n\n/** The block list a path lives in: the document's, or a container's nested blocks. */\nconst containerBlocks = (document: Document, containerPath: BlockPath): ReadonlyArray<Block> => {\n if (containerPath.length === 0) return document.children\n const container = blockAtPath(document, containerPath)\n return container?.type === 'Node' && container.blocks !== undefined ? container.blocks : []\n}\n\n/**\n * Deletes an ordered [start, end): one operation per covered run, then the\n * blocks the range spanned are joined, so selecting across a paragraph boundary\n * and deleting removes the boundary too. The first block survives, which is\n * where the caret already is. Returns undefined when the range needs a join this\n * version cannot express — one across containers, which has no boundary to\n * remove — so the caller refuses rather than deleting half of what was selected.\n */\nconst deleteRange = (\n document: Document,\n start: Position,\n end: Position,\n): ReadonlyArray<Operation> | undefined => {\n const startAt = locate(document, start.node)\n const endAt = locate(document, end.node)\n const deletions: Array<Operation> = covered(document, start, end).map(span =>\n Edit.deleteText(span.run.id, span.from, span.to),\n )\n if (startAt === undefined || endAt === undefined) return deletions\n // Within one block there is no boundary to remove.\n if (pathKey(startAt.path) === pathKey(endAt.path)) return deletions\n const containerPath = startAt.path.slice(0, -1)\n // The boundary only exists between siblings; a range that leaves its container\n // needs a merge this version does not define.\n if (pathKey(containerPath) !== pathKey(endAt.path.slice(0, -1))) return undefined\n const blocks = containerBlocks(document, containerPath)\n const from = startAt.path[startAt.path.length - 1]!\n const to = endAt.path[endAt.path.length - 1]!\n const survivor = blocks[from]!\n for (let index = from + 1; index <= to; index++) {\n const block = blocks[index]\n if (block === undefined) continue\n // A block between that cannot be one with the first (an image, a table, a list) is for\n // `clearRange`, which removes it rather than joining it.\n if (!joinable(survivor, block)) return undefined\n deletions.push(Edit.joinBlocks(survivor.id, block.id))\n }\n return deletions\n}\n\nconst segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\n\n/** A caret uses UTF-16 offsets, while a deletion removes a whole grapheme. */\nconst graphemeDeletion = (\n block: Block,\n caret: Position,\n runIndex: number,\n backward: boolean,\n): { operations: ReadonlyArray<Operation>; caret: Position } | undefined => {\n const starts: Array<number> = []\n let length = 0\n for (const run of block.children) {\n starts.push(length)\n length += run.text.length\n }\n const at = starts[runIndex]! + caret.offset\n if (backward ? at === 0 : at === length) return undefined\n const text = block.children.map(run => run.text).join('')\n let from = 0\n let to = 0\n for (const segment of segmenter.segment(text)) {\n const end = segment.index + segment.segment.length\n if (backward ? end >= at : end > at) {\n from = segment.index\n to = end\n break\n }\n }\n const operations: Array<Operation> = []\n let graphemeStart: Position | undefined\n for (const [index, run] of block.children.entries()) {\n const start = starts[index]!\n const localFrom = Math.max(0, from - start)\n const localTo = Math.min(run.text.length, to - start)\n if (localFrom >= localTo) continue\n graphemeStart ??= { node: run.id, offset: localFrom, affinity: 'after' }\n operations.push(Edit.deleteText(run.id, localFrom, localTo))\n }\n if (graphemeStart === undefined) return undefined\n // A backward deletion removes what is to the caret's left, so the caret lands\n // where the grapheme began; a forward one removes to its right, and the caret\n // already sits at the surviving boundary.\n return { operations, caret: backward ? graphemeStart : caret }\n}\n\n/**\n * The operations that lift a block out of its container, or `undefined` when it is at the\n * top level with nothing to leave. One step moves it into the container's parent: before\n * the container when it was first, after it when it was last, and between the two halves\n * of a split container when it was in the middle. A container it leaves empty is deleted.\n * Steps repeat while the vocabulary says the new parent does not hold the block's kind;\n * without a vocabulary, one step is taken. A container the vocabulary declares isolating is\n * never left, so a lift that would start by leaving one lifts nothing.\n *\n * Each step is computed against the document the steps before it produced, applied with no\n * normalization, because a split or a deletion moves the indices the next step reads.\n */\nconst liftOperations = (\n document: Document,\n node: NodeId,\n ids: CommandIds,\n nodes: NodeRegistry | undefined,\n): ReadonlyArray<Operation> | undefined => {\n const operations: Array<Operation> = []\n let current = document\n for (;;) {\n const found = locateBlock(current, node)\n if (found === undefined || found.path.length === 1) break\n const containerPath = found.path.slice(0, -1)\n const container = blockAtPath(current, containerPath)\n if (container?.type !== 'Node' || container.blocks === undefined) break\n const declared = nodes?.definitionFor(container.kind)\n if (declared?.kind === 'node' && declared.isolating === true) break\n const parentPath = containerPath.slice(0, -1)\n const parent = parentPath.length === 0 ? undefined : blockAtPath(current, parentPath)\n const at = containerPath[containerPath.length - 1]!\n const index = found.path[found.path.length - 1]!\n const siblings = container.blocks\n const step: Array<Operation> = []\n if (index === 0) {\n step.push(Edit.moveBlock(node, at, parent?.id))\n if (siblings.length === 1) step.push(Edit.deleteBlock(container.id))\n } else if (index === siblings.length - 1) {\n step.push(Edit.moveBlock(node, at + 1, parent?.id))\n } else {\n // The blocks after it go into a second container of the same kind, so the list or\n // quote continues on the far side of the lifted block.\n const rest = NodeId.make(ids.mint())\n step.push(\n Edit.insertBlock({ ...container, id: rest, children: [], blocks: [] }, at + 1, parent?.id),\n ...siblings\n .slice(index + 1)\n .map((sibling, offset) => Edit.moveBlock(sibling.id, offset, rest)),\n Edit.moveBlock(node, at + 1, parent?.id),\n )\n }\n const stepped = apply({ document: current, selection: null }, step, [])\n // Each step is built from the document it applies to, so a refusal is a bug here.\n if (!stepped.ok) throw new Error(`liftOperations: a lift step was refused (${stepped.error})`)\n operations.push(...step)\n current = stepped.state.document\n if (parent === undefined || kindAccepts(nodes, blockKind(parent), blockKind(found.block))) break\n }\n return operations.length === 0 ? undefined : operations\n}\n\n/** A list item around a block: its container, where that stands, and the list holding it. */\ninterface ItemAround {\n readonly container: Extract<Block, { readonly type: 'Node' }>\n readonly containerPath: BlockPath\n readonly list: Block\n}\n\n/**\n * The item a block sits in, when the vocabulary says its container is one: a kind its own\n * parent declares it holds, as a `List` declares `ListItem`, and not isolating, as a table\n * cell is. Enter treats such a container as the unit it splits.\n */\nconst itemAround = (\n document: Document,\n path: BlockPath,\n nodes: NodeRegistry | undefined,\n): ItemAround | undefined => {\n if (nodes === undefined) return undefined\n const containerPath = path.slice(0, -1)\n const container = blockAtPath(document, containerPath)\n const list = blockAtPath(document, containerPath.slice(0, -1))\n if (container?.type !== 'Node' || list?.type !== 'Node') return undefined\n const declaredItem = nodes.definitionFor(container.kind)\n const isolating = declaredItem?.kind === 'node' && declaredItem.isolating === true\n return holdsItem(nodes, list.kind, container.kind) && !isolating\n ? { container, containerPath, list }\n : undefined\n}\n\n/**\n * Whether Enter in the block at `path`, over to `end`, leaves no heading text after the caret,\n * so the new block is a paragraph: what follows a title is text. Mid-heading, both halves stay\n * the heading they were. Over a range, what follows is what the removal leaves: the heading's\n * own rest when the range ends inside it, or the next block's text, which was never the\n * heading's, when it ends there.\n */\nconst endsHeading = (document: Document, path: BlockPath, end: Position): boolean => {\n const block = blockAtPath(document, path)\n const endAt = locate(document, end.node)\n return (\n block?.type === 'Heading' &&\n endAt !== undefined &&\n (pathKey(endAt.path) !== pathKey(path) ||\n (end.offset >= endAt.text.length &&\n block.children.slice(endAt.runIndex + 1).every(run => run.text.length === 0)))\n )\n}\n\n/**\n * Enter inside a list item. An empty block that is the item's whole content leaves the list,\n * as Backspace does. Otherwise the block splits and the second half, with every block after\n * it in the item, becomes a new item of the same kind and props right after this one.\n */\nconst splitItem = (\n state: EditorState,\n at: Located,\n offset: number,\n { container, containerPath, list }: ItemAround,\n ids: CommandIds,\n nodes: NodeRegistry | undefined,\n): TransactionResult => {\n const blocks = container.blocks ?? []\n const index = at.path[at.path.length - 1]!\n const empty = blockAtPath(state.document, at.path)?.children.every(run => run.text === '')\n if (empty === true && blocks.length === 1) {\n return apply(state, liftOperations(state.document, at.blockId, ids, nodes) ?? [])\n }\n const textId = ids.mint()\n const blockId = ids.mint()\n const itemId = NodeId.make(ids.mint())\n const declared = nodes?.definitionFor(container.kind)\n const props = { ...container.props, ...(declared?.kind === 'node' ? declared.splitProps : {}) }\n // The declaration's props are laid over the item's, so together they must still decode.\n if (declared?.kind === 'node' && propsFailure(declared.props, props))\n return failure('InvalidInput')\n return apply(state, [\n Edit.splitBlock(at.blockId, at.id, offset, blockId, textId),\n ...(endsHeading(state.document, at.path, { node: at.id, offset, affinity: 'after' })\n ? [Edit.retypeBlock(NodeId.make(blockId), { type: 'Paragraph' })]\n : []),\n Edit.insertBlock(\n { ...container, id: itemId, props, children: [], blocks: [] },\n containerPath[containerPath.length - 1]! + 1,\n list.id,\n ),\n Edit.moveBlock(NodeId.make(blockId), 0, itemId),\n ...blocks\n .slice(index + 1)\n .map((later, position) => Edit.moveBlock(later.id, position + 1, itemId)),\n Edit.setSelection(caretAt({ node: NodeId.make(textId), offset: 0, affinity: 'after' })),\n ])\n}\n\n/** The block a block-level command acts on, and where it stands. */\ninterface StartingBlock {\n readonly block: Block\n readonly path: BlockPath\n readonly parentPath: BlockPath\n /** The containing block, or none at the document's top level. */\n readonly parent: Block | undefined\n /** The selection it was found from, which a command that renames runs has to move. */\n readonly selection: Extract<Selection, { readonly type: 'Range' }>\n}\n\n/**\n * A block-level intent acts on the block the selection starts in: the caret's own block,\n * or the first block of a range. Acting on every block a range covers would be a surprise,\n * and a menu or a marker is typed at a caret anyway.\n */\nconst startingBlock = (\n document: Document,\n selection: Extract<Selection, { readonly type: 'Range' }>,\n): StartingBlock | { readonly error: Failure } => {\n const start = isCollapsed(selection) ? selection.anchor : ordered(document, selection)?.start\n if (start === undefined) return { error: 'InvalidSelection' }\n const at = locate(document, start.node)\n const block = at === undefined ? undefined : blockAtPath(document, at.path)\n if (at === undefined || block === undefined) return { error: 'MissingText' }\n const parentPath = at.path.slice(0, -1)\n return {\n block,\n path: at.path,\n parentPath,\n parent: parentPath.length === 0 ? undefined : blockAtPath(document, parentPath),\n selection,\n }\n}\n\n/**\n * Retype, wrap, convert, retype a container, and lift: each reshapes the starting block, or\n * the container holding it, where it stands.\n */\nconst runBlockCommand = (\n state: EditorState,\n command: Extract<\n Command,\n {\n readonly type: 'RetypeBlock' | 'WrapBlock' | 'ConvertBlock' | 'RetypeContainer' | 'LiftBlock'\n }\n >,\n starting: StartingBlock,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n const { block, path, parentPath, parent } = starting\n const index = path[path.length - 1]!\n if (command.type === 'LiftBlock') {\n const lifted = liftOperations(state.document, block.id, ids, options.nodes)\n return lifted === undefined ? failure('InvalidInput') : apply(state, lifted)\n }\n if (command.type === 'RetypeContainer') {\n if (parent?.type !== 'Node' || parent.blocks === undefined || index !== 0) {\n return failure('InvalidInput')\n }\n const { kind } = command.to\n if (refusesProps(options.nodes, command.to)) return failure('InvalidInput')\n const outerPath = parentPath.slice(0, -1)\n const outer = outerPath.length === 0 ? undefined : blockAtPath(state.document, outerPath)\n const declared = options.nodes?.definitionFor(kind)\n const allowed =\n holdsBlocks(options.nodes, kind) &&\n acceptsChild(state.document, outerPath, kind, options.nodes) &&\n standsWithin(declared, outer === undefined ? undefined : blockKind(outer)) &&\n parent.blocks.every(\n child =>\n kindAccepts(options.nodes, kind, blockKind(child)) &&\n standsWithin(options.nodes?.definitionFor(blockKind(child)), kind),\n )\n if (!allowed) return failure('UnexpectedChild')\n return apply(state, [\n Edit.retypeBlock(parent.id, { type: 'Node', kind, props: command.to.props ?? {} }),\n ])\n }\n if (command.type === 'RetypeBlock') {\n // A retype keeps the block where it is, so the parent's constraint decides whether\n // the new kind belongs there.\n if (!acceptsChild(state.document, parentPath, command.to.type, options.nodes)) {\n return failure('UnexpectedChild')\n }\n // Leaving a node kind that holds text — a code block back to a paragraph — keeps the\n // block and its runs, as entering one does. Only a vocabulary says a kind holds text:\n // without one, a node could be an image, whose content a retype would destroy.\n if (\n block.type !== 'Paragraph' &&\n block.type !== 'Heading' &&\n (block.type !== 'Node' || !declaresText(options.nodes, block.kind))\n ) {\n return failure('InvalidInput')\n }\n return apply(state, [Edit.retypeBlock(block.id, command.to)])\n }\n\n if (command.type === 'WrapBlock') {\n const [outer] = command.containers\n if (outer === undefined) return failure('InvalidInput')\n if (command.containers.some(container => refusesProps(options.nodes, container))) {\n return failure('InvalidInput')\n }\n const kinds = [...command.containers.map(container => container.kind), blockKind(block)]\n const parentKind = parent === undefined ? undefined : blockKind(parent)\n // Both sides of every link in the chain: what each container holds, and where each kind,\n // the wrapped block's included, may stand (§149).\n const allowed =\n acceptsChild(state.document, parentPath, outer.kind, options.nodes) &&\n command.containers.every(\n (container, at) =>\n holdsBlocks(options.nodes, container.kind) &&\n kindAccepts(options.nodes, container.kind, kinds[at + 1]!),\n ) &&\n kinds.every((kind, at) =>\n standsWithin(options.nodes?.definitionFor(kind), at === 0 ? parentKind : kinds[at - 1]),\n )\n if (!allowed) return failure('UnexpectedChild')\n // A list wrap right after a list of the same kind and props adds an item to it, as\n // Markdown reads the two; a second list beside the first would print as one.\n const siblings =\n parent === undefined\n ? state.document.children\n : parent.type === 'Node'\n ? (parent.blocks ?? [])\n : []\n const before = siblings[index - 1]\n const item = command.containers[1]\n const joins =\n options.nodes !== undefined &&\n item !== undefined &&\n holdsItem(options.nodes, outer.kind, item.kind) &&\n before?.type === 'Node' &&\n before.kind === outer.kind &&\n Equal.equals(before.props, outer.props ?? {})\n const created = joins ? command.containers.slice(1) : command.containers\n const containerIds = created.map(() => NodeId.make(ids.mint()))\n // Built from the inside out, so each container holds the next and the innermost is\n // empty until the block moves into it.\n const chain = created.reduceRight<Block | undefined>(\n (inner, container, at) => ({\n type: 'Node',\n kind: container.kind,\n id: containerIds[at]!,\n props: container.props ?? {},\n children: [],\n blocks: inner === undefined ? [] : [inner],\n }),\n undefined,\n )!\n return apply(state, [\n joins\n ? Edit.insertBlock(chain, before.blocks?.length ?? 0, before.id)\n : Edit.insertBlock(chain, index, parent?.id),\n Edit.moveBlock(block.id, 0, containerIds[containerIds.length - 1]!),\n ])\n }\n\n // A node kind's content is its Kit's contract, so only a paragraph or heading converts.\n if (block.type !== 'Paragraph' && block.type !== 'Heading') return failure('InvalidInput')\n const kind = command.to.kind\n if (refusesProps(options.nodes, command.to)) return failure('InvalidInput')\n const holdsText = options.nodes === undefined || declaresText(options.nodes, kind)\n if (!holdsText || !acceptsChild(state.document, parentPath, kind, options.nodes)) {\n return failure('UnexpectedChild')\n }\n if (\n options.nodes !== undefined &&\n kindForbidsMarks(options.nodes, kind) &&\n block.children.some(run => run.marks.length > 0)\n ) {\n return failure('ForbiddenMark')\n }\n return apply(state, [\n Edit.retypeBlock(block.id, { type: 'Node', kind, props: command.to.props ?? {} }),\n ])\n}\n\n/**\n * Resolves one intent into a transaction and applies it atomically. Commands\n * describe intent; the returned `positionMap` and `ChangeSet` describe the\n * document effect, and rejection returns no partially edited state.\n */\nexport const run = (\n state: EditorState,\n command: Command,\n ids: CommandIds,\n options: RunOptions = {},\n): TransactionResult => {\n // The vocabulary an edit may add: the caller's Kit, or the shipped marks.\n const declared = options.marks ?? shippedRegistry\n // A range that leaves its container (a selection over several kinds of block, or all of\n // them) is cleared first, and what replaces it then acts on the caret that is left.\n const range = state.selection\n if (\n (command.type === 'InsertText' ||\n command.type === 'DeleteBackward' ||\n command.type === 'DeleteForward' ||\n command.type === 'SplitBlock' ||\n command.type === 'Paste') &&\n range?.type === 'Range' &&\n !isCollapsed(range)\n ) {\n const span = ordered(state.document, range)\n if (span !== undefined && deleteRange(state.document, span.start, span.end) === undefined) {\n const cleared = clearRange(state, span.start, span.end, options)\n if (!cleared.ok || command.type === 'DeleteBackward' || command.type === 'DeleteForward') {\n return cleared\n }\n return followedBy(cleared, run(cleared.state, command, ids, options))\n }\n }\n if (command.type === 'SetSelection') {\n return apply(state, [Edit.setSelection(command.selection)])\n }\n if (command.type === 'SetProps') {\n const target = locateBlock(state.document, command.node)?.block\n if (target?.type !== 'Node') return failure('InvalidInput')\n // Refused only when it makes valid props invalid: props already outside the kind's\n // schema (a key from an older version, say) cannot be deleted, so refusing every change\n // to them would leave the block uneditable.\n const refuses = (props: Schema.JsonObject) =>\n refusesProps(options.nodes, { kind: target.kind, props })\n if (refuses({ ...target.props, ...command.props }) && !refuses(target.props)) {\n return failure('InvalidInput')\n }\n return apply(state, [Edit.setProps(command.node, command.props)])\n }\n if (\n command.type === 'InsertRow' ||\n command.type === 'InsertColumn' ||\n command.type === 'DeleteRow' ||\n command.type === 'DeleteColumn'\n ) {\n const at = tableAt(state.document, state.selection)\n if (at === undefined) return failure('InvalidSelection')\n const edited: TableEdit = Match.value(command).pipe(\n Match.discriminatorsExhaustive('type')({\n InsertRow: ({ where }) => insertRow(state, at, where, ids.mint),\n InsertColumn: ({ where }) => insertColumn(state, at, where, ids.mint),\n DeleteRow: () => deleteRow(state, at),\n DeleteColumn: () => deleteColumn(state, at),\n }),\n )\n // The last row or column takes the table with it, as a handle's Delete would.\n return 'deleteTable' in edited\n ? run(state, { type: 'DeleteBlock', node: edited.deleteTable }, ids, options)\n : edited\n }\n if (command.type === 'Indent' || command.type === 'Outdent') {\n // Code inside a table cell indents: the innermost meaning of Tab wins.\n const code = linesHolder(state, options.nodes)\n if (code !== undefined) {\n return command.type === 'Indent' ? indent(state, code) : outdent(state, code)\n }\n // A list item inside a table cell nests; a table inside a list item moves between cells.\n const item = itemAtCaret(state, options.nodes)\n const at = tableAt(state.document, state.selection)\n const tableDepth =\n at === undefined ? -1 : (locateBlock(state.document, at.table.id)?.path.length ?? -1)\n if (item !== undefined && item.containerPath.length > tableDepth) {\n return command.type === 'Indent'\n ? sinkItem(state, item, ids, options)\n : liftItem(state, item, ids, options)\n }\n if (at === undefined) return failure('InvalidSelection')\n return moveToCell(state, at, command.type === 'Indent' ? 'next' : 'previous', ids.mint)\n }\n if (command.type === 'Replace') {\n const matches = findMatches(state.document, command.query, command)\n const chosen = command.at === undefined ? matches : matches.slice(command.at, command.at + 1)\n return replaceMatches(state, chosen, command.replacement, ids, options)\n }\n if (command.type === 'InsertFootnote')\n return insertFootnote(state, command.text ?? '', ids, options)\n if (command.type === 'RenameFootnote') {\n return renameFootnote(state, command.from, command.to.trim(), ids, options)\n }\n if (command.type === 'InsertBlock') {\n const to = command.to ?? besideCaret(state)\n if (to === undefined) return failure('InvalidSelection')\n const beside = locateBlock(state.document, 'before' in to ? to.before : to.after)\n if (beside === undefined) return failure('InvalidInput')\n const containerPath = beside.path.slice(0, -1)\n const holder =\n containerPath.length === 0 ? undefined : blockAtPath(state.document, containerPath)\n const kind = blockKind(command.block)\n if (\n (holder !== undefined && !acceptsChild(state.document, containerPath, kind, options.nodes)) ||\n !standsWithin(\n options.nodes?.definitionFor(kind),\n holder === undefined ? undefined : blockKind(holder),\n )\n ) {\n return failure('UnexpectedChild')\n }\n const [inserted] = withFreshIds({ version: 1, blocks: [command.block] }, ids.mint).blocks\n const at = beside.path[beside.path.length - 1]! + ('after' in to ? 1 : 0)\n const first = firstRunIn([inserted!])\n return apply(state, [\n Edit.insertBlock(inserted!, at, holder?.id),\n ...(first === undefined\n ? []\n : [Edit.setSelection(caretAt({ node: first.id, offset: 0, affinity: 'after' }))]),\n ])\n }\n if (command.type === 'DeleteBlock') {\n const deleting = locateBlock(state.document, command.node)\n if (deleting === undefined) return failure('InvalidInput')\n // Never a path, so no container counts as holding where the block goes.\n const target = emptiedBy(state.document, deleting.path.slice(0, -1), [-1]) ?? command.node\n const gone = locateBlock(state.document, target)!\n const inside = (path: BlockPath) => gone.path.every((index, depth) => path[depth] === index)\n const runs: Array<{ readonly run: Run; readonly inside: boolean; readonly after: boolean }> = []\n eachBlock(state.document.children, (block, path) => {\n for (const run of block.children) {\n runs.push({ run, inside: inside(path), after: pathOrder(path, gone.path) > 0 })\n }\n })\n const selection = state.selection\n const holds =\n selection !== null &&\n (selection.type === 'Node'\n ? locateBlock(state.document, selection.node) !== undefined &&\n inside(locateBlock(state.document, selection.node)!.path)\n : [selection.anchor, selection.focus].some(end =>\n runs.some(entry => entry.inside && entry.run.id === end.node),\n ))\n // By place, not by the runs the block held: an atom holds none.\n const following = runs.find(entry => entry.after && !entry.inside)\n const preceding = [...runs].reverse().find(entry => !entry.after && !entry.inside)\n const landing =\n following !== undefined\n ? { node: following.run.id, offset: 0, affinity: 'after' as const }\n : preceding !== undefined\n ? {\n node: preceding.run.id,\n offset: preceding.run.text.length,\n affinity: 'after' as const,\n }\n : undefined\n const emptiesDocument = gone.path.length === 1 && state.document.children.length === 1\n if (emptiesDocument) {\n const textId = NodeId.make(ids.mint())\n const paragraph: Block = {\n type: 'Paragraph',\n id: NodeId.make(ids.mint()),\n children: [{ type: 'Text', id: textId, text: '', marks: [] }],\n }\n return apply(state, [\n Edit.insertBlock(paragraph, 1),\n Edit.deleteBlock(target),\n Edit.setSelection(caretAt({ node: textId, offset: 0, affinity: 'after' })),\n ])\n }\n return apply(state, [\n Edit.deleteBlock(target),\n ...(holds ? [Edit.setSelection(landing === undefined ? null : caretAt(landing))] : []),\n ])\n }\n if (command.type === 'MoveBlock') {\n const moving = locateBlock(state.document, command.node)\n const beside = locateBlock(\n state.document,\n 'before' in command.to ? command.to.before : command.to.after,\n )\n if (moving === undefined || beside === undefined) return failure('InvalidInput')\n const container = beside.path.slice(0, -1)\n const refused = moveFailure(state.document, moving, container, options.nodes)\n if (refused !== undefined) return failure(refused)\n const source = moving.path.slice(0, -1)\n const within = pathKey(source) === pathKey(container)\n const from = moving.path[moving.path.length - 1]!\n const place = beside.path[beside.path.length - 1]! + ('after' in command.to ? 1 : 0)\n // The operation's index is after the block leaves, which shifts every later sibling up.\n const to = within && from < place ? place - 1 : place\n const parent = container.length === 0 ? undefined : blockAtPath(state.document, container)?.id\n const emptied = emptiedBy(state.document, source, container)\n // A node selection on a container the move deletes would dangle; the block it held is what\n // it was selecting, so it goes there.\n const gone = emptied === undefined ? undefined : locateBlock(state.document, emptied)\n const selected =\n state.selection?.type === 'Node'\n ? locateBlock(state.document, state.selection.node)\n : undefined\n const inside = (path: BlockPath, holder: BlockPath) =>\n holder.every((index, depth) => path[depth] === index)\n const lost =\n gone !== undefined &&\n selected !== undefined &&\n inside(selected.path, gone.path) &&\n !inside(selected.path, moving.path)\n return apply(state, [\n Edit.moveBlock(command.node, to, parent),\n ...(emptied === undefined ? [] : [Edit.deleteBlock(emptied)]),\n ...(lost ? [Edit.setSelection({ type: 'Node', node: command.node })] : []),\n ])\n }\n const selection = state.selection\n // A selected block is deleted by Delete or Backspace, has a paragraph opened after it by\n // Enter, and is replaced by what is typed over it.\n if (selection?.type === 'Node') {\n const paragraph: Block = {\n type: 'Paragraph',\n id: NodeId.make('paragraph'),\n children: [{ type: 'Text', id: NodeId.make('text'), text: '', marks: [] }],\n }\n const after = { type: 'InsertBlock', block: paragraph, to: { after: selection.node } } as const\n if (command.type === 'DeleteBackward' || command.type === 'DeleteForward') {\n return run(state, { type: 'DeleteBlock', node: selection.node }, ids, options)\n }\n if (command.type === 'SplitBlock') return run(state, after, ids, options)\n if (command.type === 'InsertText') {\n return runAction(\n state,\n [after, { type: 'DeleteBlock', node: selection.node }, command],\n ids,\n options,\n )\n }\n }\n if (selection === null || selection.type === 'Node') return failure('InvalidSelection')\n\n if (command.type === 'InsertText') {\n // Stored marks are explicit: when the command carries them, the inserted\n // text must end up with exactly that set, whatever run it lands in. Without\n // them, the boundary rule decides (typing after bold continues bold).\n // At a block's outer edge, a mark that does not extend there is left behind: the text\n // carries the rest, as stored marks would.\n const edge =\n command.marks === undefined && isCollapsed(selection)\n ? edgeMarks(state.document, selection.anchor, options.marks)\n : undefined\n const stored = command.marks ?? edge\n const target = isCollapsed(selection)\n ? stored === undefined\n ? resolveInsertion(state.document, selection.anchor, options.marks)\n : selection.anchor\n : ordered(state.document, selection)?.start\n if (target === undefined) return failure('InvalidSelection')\n const at = locate(state.document, target.node)\n if (at === undefined) return failure('MissingText')\n const marks: Array<RunMark> = []\n if (stored !== undefined) {\n for (const mark of stored) {\n // Marks kept from the run were already there; only marks a caller names are checked.\n if (edge === undefined && !declared.accepts(mark)) return failure('InvalidInput')\n marks.push(mark)\n }\n // A mark-free kind refuses the format however it arrives, so inserting text\n // that carries marks into a CodeBlock is refused like the toggle that set them.\n if (marks.length > 0 && forbidsMarks(state.document, at.path, options.nodes)) {\n return failure('ForbiddenMark')\n }\n }\n const deletions = isCollapsed(selection)\n ? []\n : deleteRange(state.document, target, ordered(state.document, selection)!.end)\n if (deletions === undefined) return failure('InvalidParent')\n if (command.text.length === 0) {\n return apply(\n state,\n deletions.length === 0 ? [] : [...deletions, Edit.setSelection(caretAt(target))],\n )\n }\n if (stored === undefined) {\n return apply(state, [\n ...deletions,\n Edit.insertText(target, command.text),\n Edit.setSelection(\n caretAt({ ...target, offset: target.offset + command.text.length, affinity: 'after' }),\n ),\n ])\n }\n // Split the inserted span out of its run — at the end first, so the start\n // offset stays valid — then give the span exactly these marks.\n const span = isCollapsed(selection) ? undefined : ordered(state.document, selection)\n // Where the text that survives the range deletion begins in the original\n // run. A range that runs past this run takes its whole tail with it.\n const tailFrom =\n span === undefined\n ? target.offset\n : span.end.node === target.node\n ? span.end.offset\n : at.text.length\n const operations: Array<Operation> = [...deletions, Edit.insertText(target, command.text)]\n const end = target.offset + command.text.length\n if (tailFrom < at.text.length) operations.push(Edit.splitRun(target.node, end, ids.mint()))\n const piece = target.offset > 0 ? NodeId.make(ids.mint()) : target.node\n if (target.offset > 0) operations.push(Edit.splitRun(target.node, target.offset, piece))\n for (const mark of marks) {\n if (!at.marks.some(existing => sameMark(existing, mark))) {\n operations.push(Edit.addMark(piece, mark))\n }\n }\n for (const mark of at.marks) {\n if (!marks.some(kept => markName(kept) === markName(mark))) {\n operations.push(Edit.removeMark(piece, markName(mark)))\n }\n }\n return apply(state, operations)\n }\n\n if (\n command.type === 'RetypeBlock' ||\n command.type === 'WrapBlock' ||\n command.type === 'ConvertBlock' ||\n command.type === 'RetypeContainer' ||\n command.type === 'LiftBlock'\n ) {\n const target = startingBlock(state.document, selection)\n return 'error' in target\n ? failure(target.error)\n : runBlockCommand(state, command, target, ids, options)\n }\n\n if (command.type === 'DeleteBackward' || command.type === 'DeleteForward') {\n if (!isCollapsed(selection)) {\n const span = ordered(state.document, selection)\n if (span === undefined) return failure('InvalidSelection')\n const deletions = deleteRange(state.document, span.start, span.end)\n if (deletions === undefined) return failure('InvalidParent')\n return apply(state, [...deletions, Edit.setSelection(caretAt(span.start))])\n }\n const caret = selection.anchor\n const at = locate(state.document, caret.node)\n if (at === undefined) return failure('MissingText')\n const backward = command.type === 'DeleteBackward'\n const block = blockAtPath(state.document, at.path)\n if (block === undefined) return failure('MissingText')\n const deletion = graphemeDeletion(block, caret, at.runIndex, backward)\n if (deletion !== undefined) {\n return apply(state, [...deletion.operations, Edit.setSelection(caretAt(deletion.caret))])\n }\n // Backspace at the start of a node kind that holds text, such as a code block, turns it\n // back into a paragraph, undoing the fence, rather than joining text across two kinds\n // whose marks and content rules differ. Only a vocabulary says the kind holds text.\n if (backward && block.type === 'Node' && declaresText(options.nodes, block.kind)) {\n return run(state, { type: 'RetypeBlock', to: { type: 'Paragraph' } }, ids, options)\n }\n // A heading does too, undoing the `# ` that made it, before a second press joins it.\n if (backward && block.type === 'Heading') {\n return run(state, { type: 'RetypeBlock', to: { type: 'Paragraph' } }, ids, options)\n }\n // A block edge joins the sibling in the same container, wherever it sits.\n const containerPath = at.path.slice(0, -1)\n const siblings = containerBlocks(state.document, containerPath)\n const index = at.path[at.path.length - 1]!\n const neighborBlock = siblings[backward ? index - 1 : index + 1]\n // An atom cannot take text, so the edge selects it, and a second press deletes it. A\n // block left with nothing in it goes first, as Backspace on an empty line would.\n if (neighborBlock !== undefined && isAtom(options.nodes, neighborBlock)) {\n return apply(state, [\n ...(textOfBlock(block) === '' ? [Edit.deleteBlock(block.id)] : []),\n Edit.setSelection({ type: 'Node', node: neighborBlock.id }),\n ])\n }\n if (neighborBlock === undefined && backward) {\n // Backspace at the start of a container's first block has nothing to join with, so\n // it lifts the block out, undoing what `> ` or `- ` did. Only with a vocabulary: it\n // is what says a list item's paragraph must leave the list too, and a table cell must\n // not be left at all. Otherwise the edge stays a no-op.\n const lifted =\n containerPath.length > 0 && options.nodes !== undefined\n ? liftOperations(state.document, siblings[index]!.id, ids, options.nodes)\n : undefined\n return apply(state, lifted ?? [])\n }\n // Past a sibling it cannot join, or forward past the end of its container, the edge\n // reaches the nearest block on that side that holds no blocks: inside a list or a quote,\n // its last or first line, which joins the line at the caret as clearing the empty range\n // between them would. A table cell or code cannot take the line, so there an emptied line\n // goes and Backspace steps into it, and Delete beside a line with text does nothing.\n if (\n neighborBlock === undefined ||\n !joinable(backward ? neighborBlock : block, backward ? block : neighborBlock)\n ) {\n const leafPath =\n neighborBlock === undefined\n ? nextLeaf(state.document, at.path)\n : edgeLeaf(state.document, [...containerPath, index + (backward ? -1 : 1)], backward)\n const leaf = leafPath === undefined ? undefined : blockAtPath(state.document, leafPath)\n if (leafPath === undefined || leaf === undefined) return apply(state, [])\n const empty = textOfBlock(block) === ''\n if (isAtom(options.nodes, leaf)) {\n return apply(state, [Edit.setSelection({ type: 'Node', node: leaf.id })])\n }\n const first = leaf.children[0]\n const last = leaf.children[leaf.children.length - 1]\n const target = backward ? last : first\n if (target === undefined) return apply(state, [])\n const edge = {\n node: target.id,\n offset: backward ? target.text.length : 0,\n affinity: 'after' as const,\n }\n // An empty line beside a list or a quote goes, rather than taking its line out of it.\n const stepsOnly = empty && neighborBlock !== undefined\n // Across a table cell, clearing the range only steps the caret, as it should.\n if (!stepsOnly && (backward ? joinable(leaf, block) : joinable(block, leaf))) {\n return backward\n ? clearRange(state, edge, caret, options)\n : clearRange(state, caret, edge, options)\n }\n if (neighborBlock === undefined || (!backward && !empty)) return apply(state, [])\n return apply(state, [\n ...(empty ? [Edit.deleteBlock(block.id)] : []),\n Edit.setSelection(caretAt(edge)),\n ])\n }\n const survivor = backward ? neighborBlock : siblings[index]!\n const removed = backward ? siblings[index]! : neighborBlock\n // The caret lands at the junction: the end of what the survivor already had,\n // or the removed block's last run when the survivor holds no runs.\n const lastRun = lastRunOf(survivor) ?? lastRunOf(removed)\n return apply(state, [\n Edit.joinBlocks(survivor.id, removed.id),\n Edit.setSelection(\n caretAt(\n lastRun === undefined\n ? { node: survivor.id, offset: 0, affinity: 'after' }\n : { node: lastRun.id, offset: lastRun.text.length, affinity: 'after' },\n ),\n ),\n ])\n }\n\n if (command.type === 'SplitBlock') {\n const span = isCollapsed(selection) ? undefined : ordered(state.document, selection)\n if (!isCollapsed(selection) && span === undefined) return failure('InvalidSelection')\n const caret = span?.start ?? selection.anchor\n const at = locate(state.document, caret.node)\n if (at === undefined) return failure('MissingText')\n const deletions = span === undefined ? [] : deleteRange(state.document, span.start, span.end)\n if (deletions === undefined) return failure('InvalidParent')\n const holder = blockAtPath(state.document, at.path)\n const definition =\n holder?.type === 'Node' ? options.nodes?.definitionFor(holder.kind) : undefined\n if (holder !== undefined && definition?.kind === 'node' && definition.lineBreaks === true) {\n const last = holder.children[holder.children.length - 1]\n const onEmptyLastLine =\n span === undefined &&\n last?.id === at.id &&\n caret.offset === at.text.length &&\n holder.children\n .map(run => run.text)\n .join('')\n .endsWith('\\n')\n // Enter on an empty last line leaves the block, so one at the end of a document can be\n // left at all; anywhere else it is a line break in the text.\n return onEmptyLastLine\n ? runAction(\n state,\n [\n { type: 'DeleteBackward' },\n {\n type: 'InsertBlock',\n block: {\n type: 'Paragraph',\n id: NodeId.make('paragraph'),\n children: [{ type: 'Text', id: NodeId.make('text'), text: '', marks: [] }],\n },\n to: { after: holder.id },\n },\n ],\n ids,\n options,\n )\n : run(\n state,\n // In code, the new line starts as indented as the one it broke.\n {\n type: 'InsertText',\n text:\n definition.indents === true\n ? `\\n${indentationAt(textOfBlock(holder), offsetIn(holder, caret) ?? 0)}`\n : '\\n',\n },\n ids,\n options,\n )\n }\n const item = itemAround(state.document, at.path, options.nodes)\n if (item !== undefined) {\n // Over a range inside an item, Enter deletes the range and then splits the item, as it\n // would at a caret; the two commands already say how.\n return span === undefined\n ? splitItem(state, at, caret.offset, item, ids, options.nodes)\n : runAction(state, [{ type: 'DeleteBackward' }, { type: 'SplitBlock' }], ids, options)\n }\n const textId = ids.mint()\n const blockId = ids.mint()\n return apply(state, [\n ...deletions,\n Edit.splitBlock(at.blockId, at.id, caret.offset, blockId, textId),\n ...(endsHeading(state.document, at.path, span?.end ?? caret)\n ? [Edit.retypeBlock(NodeId.make(blockId), { type: 'Paragraph' })]\n : []),\n Edit.setSelection(caretAt({ node: NodeId.make(textId), offset: 0, affinity: 'after' })),\n ])\n }\n\n if (command.type === 'ToggleMark' || command.type === 'SetMark' || command.type === 'ClearMark') {\n const mark = command.mark\n const name = markName(mark)\n let span = ordered(state.document, selection)\n if (isCollapsed(selection)) {\n // A toggle at a caret has nothing to cover; setting or clearing one acts on the mark\n // the caret is in, so a link can be edited without selecting it first.\n const extent =\n command.type === 'ToggleMark'\n ? undefined\n : markExtent(state.document, selection.anchor, name)\n if (extent === undefined) return apply(state, [])\n span = ordered(state.document, extent.selection)\n }\n if (span === undefined) return failure('InvalidSelection')\n // A value clears only the runs carrying exactly it, so those are all the runs it covers.\n const spans = covered(state.document, span.start, span.end).filter(\n entry =>\n command.type !== 'ClearMark' ||\n typeof mark === 'string' ||\n entry.run.marks.some(held => sameMark(held, mark)),\n )\n if (spans.length === 0) return apply(state, [])\n // A toggle keys on the name: the mark is present on every covered run, or\n // it is absent everywhere. Props are the mark's own business.\n const adding =\n command.type === 'SetMark' ||\n (command.type === 'ToggleMark' &&\n !spans.every(entry => entry.run.marks.some(held => markName(held) === name)))\n const operations: Array<Operation> = []\n const targets: Array<NodeId> = []\n for (const [index, entry] of spans.entries()) {\n let target = entry.run.id\n let base = 0\n if (index === 0 && entry.from > 0) {\n const textId = ids.mint()\n operations.push(Edit.splitRun(target, entry.from, textId))\n target = NodeId.make(textId)\n base = entry.from\n }\n if (index === spans.length - 1 && entry.to < entry.run.text.length) {\n operations.push(Edit.splitRun(target, entry.to - base, ids.mint()))\n }\n targets.push(target)\n }\n if (adding) {\n // Adding needs the vocabulary to declare the mark and accept its props; removing a\n // preserved one by name is always allowed.\n if (!declared.accepts(mark)) return failure('InvalidInput')\n if (spans.some(entry => forbidsMarks(state.document, entry.run.path, options.nodes))) {\n return failure('ForbiddenMark')\n }\n for (const target of targets) operations.push(Edit.addMark(target, mark))\n } else {\n for (const target of targets) operations.push(Edit.removeMark(target, name))\n }\n return apply(state, operations)\n }\n\n if (command.type === 'Paste') {\n const content = command.slice.blocks\n if (content.length === 0) return apply(state, [])\n const span = isCollapsed(selection) ? undefined : ordered(state.document, selection)\n if (!isCollapsed(selection) && span === undefined) return failure('InvalidSelection')\n const caret = span?.start ?? selection.anchor\n const at = locate(state.document, caret.node)\n if (at === undefined) return failure('MissingText')\n // Into code, or any kind whose text keeps line breaks, what is pasted is its text.\n const into = blockAtPath(state.document, at.path)\n const holds = into?.type === 'Node' ? options.nodes?.definitionFor(into.kind) : undefined\n if (holds?.kind === 'node' && holds.lineBreaks === true) {\n return run(state, { type: 'InsertText', text: toText(content) }, ids, options)\n }\n const index = at.path[at.path.length - 1]!\n const containerPath = at.path.slice(0, -1)\n // The content lands in the caret's own container, so pasting inside a list\n // item stays inside the list.\n const parent =\n containerPath.length === 0 ? undefined : blockAtPath(state.document, containerPath)?.id\n const replacements = span === undefined ? [] : deleteRange(state.document, span.start, span.end)\n if (replacements === undefined) return failure('InvalidParent')\n const operations: Array<Operation> = [...replacements]\n const inserted = withFreshIds(command.slice, ids.mint).blocks\n // The content lands in the caret's container, so that container's constraint decides\n // which kinds it accepts (§125), and each kind's own says whether it may stand there (§149).\n const holder =\n containerPath.length === 0 ? undefined : blockAtPath(state.document, containerPath)\n if (\n inserted.some(\n piece =>\n (containerPath.length > 0 &&\n !acceptsChild(state.document, containerPath, blockKind(piece), options.nodes)) ||\n !standsWithin(\n options.nodes?.definitionFor(blockKind(piece)),\n holder === undefined ? undefined : blockKind(holder),\n ),\n )\n ) {\n return failure('UnexpectedChild')\n }\n const block = blockAtPath(state.document, at.path)\n if (block === undefined) return failure('MissingText')\n // The block splits at the caret and the content lands between the halves. The first\n // piece joins the text before the caret and the last the text after it, when each can be\n // one block with it, so a pasted word or line lands inside the sentence; a half left with\n // nothing in it goes, unless it is the only place after a table or an image to type.\n const end = span?.end ?? caret\n const endBlock = blockAtPath(state.document, locate(state.document, end.node)?.path ?? at.path)\n const beforeEmpty = offsetIn(block, caret) === 0\n const afterEmpty =\n endBlock === undefined || offsetIn(endBlock, end) === textOfBlock(endBlock).length\n const tailText = NodeId.make(ids.mint())\n const tail = NodeId.make(ids.mint())\n operations.push(Edit.splitBlock(at.blockId, at.id, caret.offset, tail, tailText))\n for (const [offset, piece] of inserted.entries()) {\n operations.push(Edit.insertBlock(piece, index + 1 + offset, parent))\n }\n const first = inserted[0]!\n const last = inserted[inserted.length - 1]!\n const lastRun = last.children[last.children.length - 1]\n // Set before the joins, which carry it with the runs they move.\n operations.push(\n Edit.setSelection(\n caretAt(\n lastRun === undefined\n ? { node: tailText, offset: 0, affinity: 'after' }\n : { node: lastRun.id, offset: lastRun.text.length, affinity: 'after' },\n ),\n ),\n )\n const joinsHead = joinable(block, first)\n const joinsTail = joinable(last, block)\n if (joinsHead) operations.push(Edit.joinBlocks(at.blockId, first.id))\n if (joinsTail) {\n operations.push(Edit.joinBlocks(joinsHead && last === first ? at.blockId : last.id, tail))\n }\n if (!joinsHead && beforeEmpty) operations.push(Edit.deleteBlock(at.blockId))\n if (!joinsTail && afterEmpty && lastRun !== undefined) operations.push(Edit.deleteBlock(tail))\n return apply(state, operations)\n }\n\n return apply(state, [])\n}\n\n/** Where an `InsertBlock` without a place goes: beside the caret's block, before it when empty. */\nconst besideCaret = (state: EditorState): Beside | undefined => {\n if (state.selection?.type !== 'Range') return undefined\n const run = locateRun(\n state.document,\n ordered(state.document, state.selection)?.start.node ?? state.selection.anchor.node,\n )\n const block = run === undefined ? undefined : blockAtPath(state.document, run.path)\n if (block === undefined) return undefined\n const empty = block.children.every(child => child.text === '')\n return empty ? { before: block.id } : { after: block.id }\n}\n\nconst textOfBlock = (block: Block): string => block.children.map(run => run.text).join('')\n\n/** The block the selection starts in when its kind indents its lines, as code does. */\nconst linesHolder = (state: EditorState, nodes: NodeRegistry | undefined): Block | undefined => {\n if (state.selection?.type !== 'Range') return undefined\n const start = ordered(state.document, state.selection)?.start\n const run = start === undefined ? undefined : locateRun(state.document, start.node)\n const block = run === undefined ? undefined : blockAtPath(state.document, run.path)\n if (block?.type !== 'Node') return undefined\n const definition = nodes?.definitionFor(block.kind)\n return definition?.kind === 'node' && definition.indents === true ? block : undefined\n}\n\n/**\n * Whether Tab means something where the selection is: in code, or in a table cell. An editor\n * takes Tab only there, so anywhere else it still moves focus out of the editor.\n */\nexport const takesTab = (\n document: Document,\n selection: Selection | null,\n nodes?: NodeRegistry,\n): boolean =>\n linesHolder({ document, selection }, nodes) !== undefined ||\n itemAtCaret({ document, selection }, nodes) !== undefined ||\n tableAt(document, selection) !== undefined\n\n/** The list item the selection starts in, when the vocabulary says its list holds it. */\nconst itemAtCaret = (state: EditorState, nodes: NodeRegistry | undefined) => {\n if (state.selection?.type !== 'Range') return undefined\n const start = ordered(state.document, state.selection)?.start\n const run = start === undefined ? undefined : locateRun(state.document, start.node)\n return run === undefined ? undefined : itemAround(state.document, run.path, nodes)\n}\n\n/** Whether two props hold the same values, for a list that two items may share. */\nconst sameProps = (left: Schema.JsonObject, right: Schema.JsonObject): boolean => {\n const keys = Object.keys(left)\n return (\n keys.length === Object.keys(right).length &&\n keys.every(key => Object.hasOwn(right, key) && Equal.equals(left[key], right[key]))\n )\n}\n\n/**\n * Tab in a list item: the item moves under the item before it, as the last item of the list\n * that item ends with, or of a new one like its own when it ends with none. It keeps its\n * identity, and the caret with it. The first item has nothing to go under, and stays.\n */\nconst sinkItem = (\n state: EditorState,\n item: ItemAround,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n if (item.list.type !== 'Node') return apply(state, [])\n const list = item.list\n const index = item.containerPath[item.containerPath.length - 1]!\n const previous = (list.blocks ?? [])[index - 1]\n if (previous?.type !== 'Node') return apply(state, [])\n const nested = previous.blocks?.at(-1)\n const last = nested?.type === 'Node' ? nested.blocks?.at(-1) : undefined\n if (\n nested?.type === 'Node' &&\n nested.kind === list.kind &&\n sameProps(nested.props, list.props) &&\n last !== undefined\n ) {\n return run(\n state,\n { type: 'MoveBlock', node: item.container.id, to: { after: last.id } },\n ids,\n options,\n )\n }\n const created = NodeId.make(ids.mint())\n return apply(state, [\n Edit.insertBlock(\n { type: 'Node', kind: list.kind, id: created, props: list.props, children: [], blocks: [] },\n (previous.blocks ?? []).length,\n previous.id,\n ),\n Edit.moveBlock(item.container.id, 0, created),\n ])\n}\n\n/**\n * Shift+Tab in a list item: a nested item moves out to follow the item its list is in, and an\n * item at the top level leaves its list, as `LiftBlock` takes it. A list the move empties goes.\n */\nconst liftItem = (\n state: EditorState,\n item: ItemAround,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n const listPath = item.containerPath.slice(0, -1)\n const outerItem = blockAtPath(state.document, listPath.slice(0, -1))\n const outerList = blockAtPath(state.document, listPath.slice(0, -2))\n const nestedInItem =\n outerItem?.type === 'Node' &&\n outerList?.type === 'Node' &&\n options.nodes !== undefined &&\n holdsItem(options.nodes, outerList.kind, outerItem.kind)\n return nestedInItem\n ? run(\n state,\n { type: 'MoveBlock', node: item.container.id, to: { after: outerItem.id } },\n ids,\n options,\n )\n : run(state, { type: 'LiftBlock' }, ids, options)\n}\n\n/**\n * Replaces matches, last first, each read again from its block's offset in the state the one\n * after it left: a replacement later in a block leaves an earlier match's offset alone, though\n * the runs it touched may have merged or split, so positions found before it would not do.\n */\nconst replaceMatches = (\n state: EditorState,\n matches: ReadonlyArray<SearchMatch>,\n replacement: string,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n let done = apply(state, [])\n for (const match of [...matches].reverse()) {\n if (!done.ok) return done\n const block = locateBlock(done.state.document, match.block)?.block\n const from = block === undefined ? undefined : positionInBlock(block, match.at)\n const to = block === undefined ? undefined : positionInBlock(block, match.at + match.length)\n if (from === undefined || to === undefined) return failure('MissingText')\n const step = runAction(\n done.state,\n [\n { type: 'SetSelection', selection: { type: 'Range', anchor: from, focus: to } },\n // Over a range, an insertion replaces it, so an empty replacement deletes the match.\n { type: 'InsertText', text: replacement },\n ],\n ids,\n options,\n )\n if (!step.ok) return step\n done = {\n ok: true,\n state: step.state,\n changeSet: unionChangeSet(done.changeSet, step.changeSet),\n positionMap: [...done.positionMap, ...step.positionMap],\n transactions: [...done.transactions, ...step.transactions],\n }\n }\n return done\n}\n\nconst insertFootnote = (\n state: EditorState,\n text: string,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n const selection = state.selection\n if (selection?.type !== 'Range') return failure('InvalidSelection')\n const start = rangeStart(state.document, selection)\n const last = state.document.children[state.document.children.length - 1]\n if (start === undefined || last === undefined) return failure('InvalidSelection')\n const end = start === selection.anchor ? selection.focus : selection.anchor\n const label = nextFootnoteLabel(state.document)\n // Placeholder identities: InsertBlock mints fresh ones.\n const definition: Block = {\n type: 'Node',\n kind: FootnoteDefinition.name,\n id: NodeId.make('footnote'),\n props: { label },\n children: [],\n blocks: [\n {\n type: 'Paragraph',\n id: NodeId.make('footnote-text'),\n children: [{ type: 'Text', id: NodeId.make('footnote-run'), text, marks: [] }],\n },\n ],\n }\n return runAction(\n state,\n [\n { type: 'SetSelection', selection: { type: 'Range', anchor: end, focus: end } },\n { type: 'InsertText', text: label, marks: [FootnoteRef.of({ label })] },\n { type: 'InsertBlock', block: definition, to: { after: last.id } },\n ],\n ids,\n options,\n )\n}\n\nconst renameFootnote = (\n state: EditorState,\n from: string,\n to: string,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n const notes = footnotesOf(state.document)\n const note = notes.find(each => each.label === from)\n if (note === undefined || to === '' || (to !== from && notes.some(each => each.label === to))) {\n return failure('InvalidInput')\n }\n const relabelled = FootnoteRef.of({ label: to })\n const references: Array<Command> = []\n eachBlock(state.document.children, block => {\n for (const run of block.children) {\n if (referenceLabel(run) !== from) continue\n references.push(\n {\n type: 'SetSelection',\n selection: {\n type: 'Range',\n anchor: { node: run.id, offset: 0, affinity: 'after' },\n focus: { node: run.id, offset: run.text.length, affinity: 'before' },\n },\n },\n {\n type: 'InsertText',\n text: run.text === from ? to : run.text,\n marks: run.marks.map(each => (markName(each) === FootnoteRef.name ? relabelled : each)),\n },\n )\n }\n })\n // The caret goes back where it was, unless it was in a reference the rename rewrote.\n const selection = state.selection\n const inReference =\n selection?.type === 'Range' &&\n (note.references.includes(selection.anchor.node) ||\n note.references.includes(selection.focus.node))\n return runAction(\n state,\n [\n ...(note.definition === undefined\n ? []\n : [{ type: 'SetProps' as const, node: note.definition, props: { label: to } }]),\n ...references,\n ...(inReference || selection === null ? [] : [{ type: 'SetSelection' as const, selection }]),\n ],\n ids,\n options,\n )\n}\n\n/** The first run anywhere in these blocks, nested ones included, in document order. */\nconst firstRunIn = (blocks: ReadonlyArray<Block>): Run | undefined => {\n let found: Run | undefined\n eachBlock(blocks, block => {\n found ??= block.children[0]\n })\n return found\n}\n\n/** An ordered list of commands that commit as one action (§124 §5). */\nexport type Action = ReadonlyArray<Command>\n\n/**\n * A composed action's invalidation summary is the union of its commands': an identity\n * one command retired and a later one restored appears in both sets, and a patch reads\n * that as \"remove it, then render it\", so it never under-invalidates.\n */\nexport const unionChangeSet = (left: ChangeSet, right: ChangeSet): ChangeSet => ({\n dirtyNodes: new Set([...left.dirtyNodes, ...right.dirtyNodes]),\n insertedNodes: new Set([...left.insertedNodes, ...right.insertedNodes]),\n removedNodes: new Set([...left.removedNodes, ...right.removedNodes]),\n textChanged: new Set([...left.textChanged, ...right.textChanged]),\n structureChanged: left.structureChanged || right.structureChanged,\n selectionChanged: left.selectionChanged || right.selectionChanged,\n})\n\n/**\n * Resolves commands in order and commits them as one action: one resulting state, one\n * composed ChangeSet, and one identity stream, so a caller can treat \"remove the query,\n * then apply the choice\" as a single transition. It stops at the first refusal and\n * returns that command's error; state is a value, so nothing partial escapes.\n */\nexport const runAction = (\n state: EditorState,\n commands: Action,\n ids: CommandIds,\n options: RunOptions = {},\n): TransactionResult => {\n const [first, ...rest] = commands\n // An empty action is a no-op, as an empty transaction is.\n if (first === undefined) return apply(state, [])\n const started = run(state, first, ids, options)\n if (!started.ok) return started\n let current = started.state\n let changeSet = started.changeSet\n let positionMap = started.positionMap\n let transactions = started.transactions\n for (const command of rest) {\n const result = run(current, command, ids, options)\n if (!result.ok) return result\n current = result.state\n changeSet = unionChangeSet(changeSet, result.changeSet)\n positionMap = [...positionMap, ...result.positionMap]\n transactions = [...transactions, ...result.transactions]\n }\n return { ok: true, state: current, changeSet, positionMap, transactions }\n}\n","/**\n * Input rules (§124 §4): what someone just typed, read as an intent. A rule is not a\n * Transform (§23): a transform normalizes a document whenever it is applied, while a rule\n * is about the moment a particular thing was typed — `# ` at the start of a block means\n * \"make this a heading\" only at that moment, and never on a document loaded from storage.\n *\n * `applyInputRules` is the composition: the insertion, the deletes that consume what the\n * rule matched, and the rule's commands, as one action, so a transition and an undo step\n * cover typing the marker and the change it made.\n */\nimport type { Action, Command } from './command.js'\n\n/** What a rule makes of the text before the caret, and what to do about it. */\nexport interface InputMatch {\n /** How many characters of that text the rule consumed; the caller deletes them. */\n readonly remove: number\n readonly commands: Action\n /**\n * The marks the text typed next carries, when the rule decides it: `**bold**` ends its bold, so\n * typing on is plain, though the bold run would otherwise continue. Absent, the editor's own\n * rule applies.\n */\n readonly storedMarks?: ReadonlyArray<string> | undefined\n}\n\n/**\n * A rule over the text before the caret. `match` is a pure read: it sees the text and the\n * kinds of the node blocks around the caret's block, innermost first (`['ListItem',\n * 'List']` inside a bulleted item), and nothing else, so a rule cannot depend on a\n * selection, a clock, or the Model.\n */\nexport interface InputRule {\n readonly name: string\n readonly match: (textBefore: string, within: ReadonlyArray<string>) => InputMatch | undefined\n}\n\n/** One edit to read a rule against, named so two strings cannot be handed over swapped. */\nexport interface InputContext {\n /** The caret's block text before the caret, before this insertion. */\n readonly textBefore: string\n /** What was just typed. */\n readonly text: string\n /** The insertion itself, which a matching rule then acts on. */\n readonly insertion: Command\n /** The kinds of the node blocks around the caret's block, innermost first. Default none. */\n readonly within?: ReadonlyArray<string>\n}\n\n/**\n * The commands that insert the text and then let the first matching rule act on it: the\n * insertion, one backward delete per character the rule consumed, and the rule's commands.\n * Consumption is by deleting backwards rather than by a range, because a range would have\n * to be computed against a state the insertion has not produced yet — the deletes resolve\n * as each one runs. A rule that does not match yields the insertion alone.\n *\n * A rule that claims to consume more than it was shown throws: those deletes would run past\n * the block's start and join it to the one before, which no rule means.\n */\nexport const applyInputRules = (rules: ReadonlyArray<InputRule>, input: InputContext): Action =>\n resolveInputRules(rules, input).action\n\n/**\n * `applyInputRules`, with the marks the matching rule says the next typed text carries, which an\n * editor keeps as its stored marks.\n */\nexport const resolveInputRules = (\n rules: ReadonlyArray<InputRule>,\n input: InputContext,\n): { readonly action: Action; readonly storedMarks?: ReadonlyArray<string> | undefined } => {\n const typed = `${input.textBefore}${input.text}`\n for (const rule of rules) {\n const matched = rule.match(typed, input.within ?? [])\n if (matched === undefined) continue\n if (!Number.isInteger(matched.remove) || matched.remove < 0 || matched.remove > typed.length) {\n throw new RangeError(\n `Input rule \"${rule.name}\" removes ${matched.remove} characters of the ${typed.length} it was shown`,\n )\n }\n const consumed: ReadonlyArray<Command> = Array.from(\n { length: matched.remove },\n (): Command => ({ type: 'DeleteBackward' }),\n )\n return {\n action: [input.insertion, ...consumed, ...matched.commands],\n storedMarks: matched.storedMarks,\n }\n }\n return { action: [input.insertion] }\n}\n","import { Schema } from 'effect'\nimport type { Command } from './command.js'\nimport { EditorState } from './document.js'\n\n/**\n * Local undo history over editor snapshots. Snapshots are `EditorState` values\n * (document plus selection), so undo restores what the user saw, including the\n * caret. History is interaction state: it belongs in the application Model\n * beside the selection, never in published content, and collaborative undo is a\n * different operation (§§65–66).\n */\nexport const History = Schema.Struct({\n /** States to return to, oldest first. */\n past: Schema.Array(EditorState),\n /** States undone from, nearest first. */\n future: Schema.Array(EditorState),\n /** The group the last commit joined, if any. */\n group: Schema.optional(Schema.String),\n})\nexport type History = typeof History.Type\n\nexport const emptyHistory: History = Object.freeze({ past: [], future: [] })\n\nexport interface CommitOptions {\n /**\n * Joins the previous step when it used the same group. Consecutive typing\n * shares one undo step; omit the group and every commit stands alone.\n */\n readonly group?: string | undefined\n /** Most steps to keep; the oldest is dropped beyond this. Default 200. */\n readonly capacity?: number\n}\n\n/**\n * Typing continues one undo step; every other command is its own step. Callers\n * pass this to `commit`, so grouping policy lives with the editor vocabulary\n * rather than being reinvented per adapter.\n */\nexport const groupFor = (command: Command): string | undefined =>\n command.type === 'InsertText' ||\n command.type === 'DeleteBackward' ||\n command.type === 'DeleteForward'\n ? 'typing'\n : undefined\n\nconst bounded = (past: ReadonlyArray<EditorState>, capacity: number): ReadonlyArray<EditorState> =>\n past.length > capacity ? past.slice(past.length - capacity) : past\n\n/**\n * Records a committed transition. `previous` is the state before the command\n * and `next` the state after it; only `previous` is stored, because the caller\n * already holds `next`.\n */\nexport const commit = (\n history: History,\n previous: EditorState,\n options: CommitOptions = {},\n): History => {\n const joins = options.group !== undefined && history.group === options.group\n const past = joins ? history.past : bounded([...history.past, previous], options.capacity ?? 200)\n return options.group === undefined\n ? { past, future: [] }\n : { past, future: [], group: options.group }\n}\n\nexport interface Restore {\n readonly history: History\n readonly state: EditorState\n}\n\n/** Steps back one group. Returns undefined when there is nothing to undo. */\nexport const undo = (history: History, current: EditorState): Restore | undefined => {\n const previous = history.past[history.past.length - 1]\n if (previous === undefined) return undefined\n return {\n history: { past: history.past.slice(0, -1), future: [current, ...history.future] },\n state: previous,\n }\n}\n\n/** Steps forward again. Returns undefined when there is nothing to redo. */\nexport const redo = (history: History, current: EditorState): Restore | undefined => {\n const next = history.future[0]\n if (next === undefined) return undefined\n return {\n history: {\n past: [...history.past, current],\n future: history.future.slice(1),\n group: history.group,\n },\n state: next,\n }\n}\n\nexport const canUndo = (history: History): boolean => history.past.length > 0\nexport const canRedo = (history: History): boolean => history.future.length > 0\n\n/** Structural summary for tooling and tests. */\nexport const inspectHistory = (history: History) => ({\n past: history.past.length,\n future: history.future.length,\n group: history.group ?? null,\n})\n","/**\n * Decorations (§64): the ephemeral third kind beside Marks and Annotations. A\n * decoration is presentation derived from current state — a search match, a lint\n * warning, a remote cursor, a syntax token — rendered by an interpreter and then\n * discarded. It is never serialized, never part of undo, and never authored content,\n * which is why this module holds contracts rather than document data.\n *\n * The projection here is shared on purpose: a read-only renderer, the editable adapter,\n * and any other interpreter all need the same answer to \"which decorations cover this\n * run, and where\", so they compute it once, in the core, rather than each cutting ranges\n * their own way.\n */\nimport { eachBlock, type Document, type NodeId, type Position } from './document.js'\n\n/**\n * One decoration over a document range. `kind` is a fixed word the presentation is\n * chosen by (`search`, `syntax`, `cursor`, …); `data` is the renderer's own payload,\n * which the core never reads.\n */\nexport interface Decoration<Data = unknown> {\n readonly from: Position\n readonly to: Position\n readonly kind: string\n readonly data?: Data\n}\n\n/** A set of decorations is a value, computed for one render and then discarded. */\nexport type DecorationSet<Data = unknown> = ReadonlyArray<Decoration<Data>>\n\n/** A decoration's sub-range inside one run, in that run's own offsets. */\nexport interface DecorationSpan<Data = unknown> {\n readonly from: number\n readonly to: number\n readonly decoration: Decoration<Data>\n}\n\n/**\n * The decorations covering each run, as offsets into it, in document order. A decoration\n * that crosses runs is cut at each run's edge, so a renderer never has to reason about\n * document order; a decoration whose endpoints do not resolve is skipped rather than\n * guessed at, the way every other read treats a position it cannot resolve, and a\n * direction is honoured rather than required to run forwards.\n *\n * The runs are indexed once, so a decoration costs the runs it covers: a hundred search\n * matches over a long document is one walk, not a hundred.\n */\nexport const decorationsIn = <Data>(\n document: Document,\n set: DecorationSet<Data>,\n): ReadonlyMap<NodeId, ReadonlyArray<DecorationSpan<Data>>> => {\n const spans = new Map<NodeId, Array<DecorationSpan<Data>>>()\n if (set.length === 0) return spans\n // Document order is depth-first, which is what `compareRunPlaces` orders by too.\n const runs: Array<{ readonly id: NodeId; readonly length: number }> = []\n const indexByRun = new Map<NodeId, number>()\n eachBlock(document.children, block => {\n for (const run of block.children) {\n indexByRun.set(run.id, runs.length)\n runs.push({ id: run.id, length: run.text.length })\n }\n })\n for (const decoration of set) {\n const anchor = indexByRun.get(decoration.from.node)\n const focus = indexByRun.get(decoration.to.node)\n if (anchor === undefined || focus === undefined) continue\n const forward = anchor <= focus\n const first = forward ? anchor : focus\n const last = forward ? focus : anchor\n const firstOffset = forward ? decoration.from.offset : decoration.to.offset\n const lastOffset = forward ? decoration.to.offset : decoration.from.offset\n for (let index = first; index <= last; index += 1) {\n const run = runs[index]!\n const from = Math.max(0, index === first ? firstOffset : 0)\n const to = Math.min(run.length, index === last ? lastOffset : run.length)\n if (from >= to) continue\n const covered = spans.get(run.id)\n const span = { from, to, decoration }\n if (covered === undefined) spans.set(run.id, [span])\n else covered.push(span)\n }\n }\n // A renderer walks a run's text forwards, so its spans are in that order.\n for (const covered of spans.values()) covered.sort((left, right) => left.from - right.from)\n return spans\n}\n\n/** A stretch of one run's text, and the decorations covering all of it. */\nexport interface RunPiece<Data = unknown> {\n readonly text: string\n readonly decorations: ReadonlyArray<Decoration<Data>>\n}\n\n/**\n * A run's text cut at every edge of the spans over it, each piece with the decorations\n * that cover it — what every interpreter draws, so each draws the same pieces. An empty run,\n * or one no span touches, is one undecorated piece: an interpreter still has to render\n * somewhere for a caret to sit, and nothing can be drawn over no text.\n */\nexport const runPieces = <Data>(\n text: string,\n spans: ReadonlyArray<DecorationSpan<Data>>,\n): ReadonlyArray<RunPiece<Data>> => {\n if (spans.length === 0 || text.length === 0) return [{ text, decorations: [] }]\n const edges = new Set<number>([0, text.length])\n for (const span of spans) {\n edges.add(Math.max(0, Math.min(text.length, span.from)))\n edges.add(Math.max(0, Math.min(text.length, span.to)))\n }\n const cuts = [...edges].sort((left, right) => left - right)\n const pieces: Array<RunPiece<Data>> = []\n for (let index = 0; index < cuts.length - 1; index += 1) {\n const from = cuts[index]!\n const to = cuts[index + 1]!\n pieces.push({\n text: text.slice(from, to),\n decorations: spans\n .filter(span => span.from <= from && to <= span.to)\n .map(span => span.decoration),\n })\n }\n return pieces\n}\n","/**\n * Code highlighting, as decorations (§124 §7, §130): the document holds a `CodeBlock`'s\n * language and its plain text, and what a highlighter finds in that text is presentation,\n * derived and discarded like a search match. The contract lives here because it is\n * format-agnostic — a tokenizer is a function from text to ranges — while grammars, which\n * are not, live in `foldkit-richtext-code` and its Shiki adapter.\n */\nimport { eachBlock, positionInBlock, type Document } from './document.js'\nimport type { Decoration, DecorationSet } from './decoration.js'\n\n/**\n * One token in a code block's text, as offsets into that text. `kind` becomes the\n * decoration's kind, so it is what a stylesheet reaches the token by — a grammar names its\n * kinds `syntax-string`, `syntax-number`, and so on (§129).\n */\nexport interface CodeToken {\n readonly from: number\n readonly to: number\n readonly kind: string\n}\n\n/** A pure read of one code block's text. A tokenizer that needs to load first is Shiki's case. */\nexport type CodeTokenizer = (text: string) => ReadonlyArray<CodeToken>\n\n/**\n * Every token the given tokenizers find in the document's `CodeBlock`s, as decorations. A\n * block is tokenized by the tokenizer registered for its `language` prop; one with no\n * language, or one nothing is registered for, yields nothing. The registry is a `Map`\n * because the language is read from the document, and a plain object would answer a\n * language named `constructor` from its prototype.\n *\n * A token outside its block's text, one that covers nothing, or one at a fractional offset\n * throws with the language that produced it: it is a tokenizer's bug, and a decoration guessed from it would\n * highlight the wrong text.\n */\nexport const codeDecorations = (\n document: Document,\n tokenizers: ReadonlyMap<string, CodeTokenizer>,\n): DecorationSet => {\n const found: Array<Decoration> = []\n eachBlock(document.children, block => {\n if (block.type !== 'Node' || block.kind !== 'CodeBlock') return\n const language = block.props.language\n if (typeof language !== 'string') return\n const tokenizer = tokenizers.get(language)\n if (tokenizer === undefined) return\n const text = block.children.map(run => run.text).join('')\n for (const token of tokenizer(text)) {\n const covers =\n Number.isInteger(token.from) && Number.isInteger(token.to) && token.from < token.to\n const from = covers ? positionInBlock(block, token.from) : undefined\n const to = from === undefined ? undefined : positionInBlock(block, token.to)\n if (from === undefined || to === undefined) {\n throw new RangeError(\n `The ${language} tokenizer produced ${token.kind} at [${token.from}, ${token.to}) in a block of ${text.length} characters`,\n )\n }\n found.push({ from, to, kind: token.kind })\n }\n })\n return found\n}\n","/**\n * The URL policy every importer shares (§70, §124 §10). A link's `href` and an image's `src`\n * arrive from pasted HTML or Markdown, which is untrusted, and the standard rendering writes\n * them into attributes, so each passes here before it can become a prop, and again before\n * the standard rendering writes it.\n */\n\n/** Schemes a link or a source may carry; anything else — `javascript:`, `data:` — is refused. */\nconst SAFE_SCHEMES = new Set(['http', 'https', 'mailto', 'tel'])\n\n/**\n * A URL safe to carry into props, or `undefined` when it is not. Control characters are\n * removed first, because `java\\tscript:` and a leading NUL are how a scheme check is\n * usually walked past; then a URL that names a scheme outside the allowlist is refused,\n * and one with no scheme — a relative path, a fragment, a protocol-relative URL — is\n * kept. The value is never interpreted, only copied, so what a policy leaves through is\n * still the application's to trust.\n */\nexport const safeUrl = (value: string | null): string | undefined => {\n if (value === null) return undefined\n const cleaned = value.replace(/[\\u0000-\\u001F\\u007F]/g, '').trim()\n if (cleaned.length === 0) return undefined\n const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(cleaned)?.[1]?.toLowerCase()\n return scheme === undefined || SAFE_SCHEMES.has(scheme) ? cleaned : undefined\n}\n","/**\n * The standard semantic vocabulary (§124 §2, §125): the node kinds and marks a\n * document uses to mean what Markdown and HTML also mean, so an interpreter is a\n * mapping from this vocabulary rather than a private one. Declarations only — no\n * renderers, no executable code (§34) — and an application spreads them into its Kit\n * and adds its own:\n *\n * ```ts\n * RichText.kit({\n * nodes: [...RichText.standardNodes, Callout],\n * marks: [...RichText.standardMarks, Highlight],\n * })\n * ```\n *\n * `Paragraph` and `Heading` are built-in text blocks, `Code` is the inline-code mark,\n * and the rest are ordinary declarations. `HardBreak` is deliberately absent: it is\n * inline content, and the model has no inline atoms yet (§116, deferred).\n */\nimport { Schema } from 'effect'\nimport { markExtent } from './command.js'\nimport { blockContent, rangeStart, textContent, type Document, type Selection } from './document.js'\nimport { atom, block, blocksOf, node, type NodeDefinition } from './kit.js'\nimport { Bold, Code, Italic, mark, markProps, type MarkDef } from './marks.js'\nimport { rendering, type Rendering } from './rendering.js'\nimport { safeUrl } from './url.js'\n\n/**\n * A struck-through span. It expands `after`, so typing at its edge continues it, as\n * bold and italic do.\n */\nexport const Strikethrough = mark('Strikethrough', { expand: 'after' })\n\n/**\n * A hyperlink. Its `href` is a prop rather than a mark name, which is what lets the\n * serializer render a real `<a href>` (§121); it expands `none`, because text typed\n * after a link is new text, not a continuation of the link.\n */\nexport const Link = mark('Link', {\n Props: Schema.Struct({ href: Schema.String }),\n expand: 'none',\n})\n\n/** The link a selection starts in: its `href`, and the range of runs it spans. */\nexport interface LinkAt {\n /** The stored `href`, or `''` when the stored one is not a string. */\n readonly href: string\n readonly selection: Extract<Selection, { readonly type: 'Range' }>\n}\n\n/**\n * The link a selection starts in, which is what a link editor opens on: at a caret, the\n * link around it; over a range, the link its start is in. Undefined outside a link, and for\n * a node selection, which covers blocks rather than text.\n */\nexport const linkAt = (document: Document, selection: Selection | null): LinkAt | undefined => {\n if (selection?.type !== 'Range') return undefined\n const start = rangeStart(document, selection)\n const extent = start === undefined ? undefined : markExtent(document, start, Link.name)\n if (extent === undefined) return undefined\n const href = markProps(extent.mark)?.href\n return { href: typeof href === 'string' ? href : '', selection: extent.selection }\n}\n\n/** Every mark the standard vocabulary names, in menu order. */\nexport const standardMarks: ReadonlyArray<MarkDef> = [Bold, Italic, Code, Strikethrough, Link]\n\n/**\n * The standard node kinds. Constraints are what make a kind more than a name: a\n * `List` accepts only `ListItem`s and a `Table` only `TableRow`s, so `validate`\n * reports a document that says otherwise (§125); a `CodeBlock` carries text with no\n * formatting, and its `language` is a prop, not a mark.\n */\nexport const standardNodes: ReadonlyArray<NodeDefinition> = [\n block('Paragraph'),\n block('Heading'),\n node('Quote', { children: blockContent }),\n node('List', {\n // An ordered list, and where its numbering starts; both are Markdown's.\n Props: Schema.Struct({\n ordered: Schema.optional(Schema.Boolean),\n start: Schema.optional(Schema.Number),\n }),\n children: blocksOf('ListItem', 'TaskItem'),\n }),\n node('ListItem', { children: blockContent, within: ['List'] }),\n node('TaskItem', {\n Props: Schema.Struct({ checked: Schema.Boolean }),\n children: blockContent,\n // A task split off a done one is a new task, not a done one.\n splitProps: { checked: false },\n within: ['List'],\n }),\n node('CodeBlock', {\n Props: Schema.Struct({ language: Schema.optional(Schema.String) }),\n children: textContent,\n marks: 'none',\n lineBreaks: true,\n indents: true,\n }),\n atom('ThematicBreak'),\n atom('Image', {\n // What a figure needs beside its source: a caption under it, the width it is shown at in\n // CSS pixels, and which way it sits. The standard rendering draws the `img` alone; a\n // rendering that draws a figure reads the rest (`examples/richtext-playground`).\n Props: Schema.Struct({\n src: Schema.String,\n alt: Schema.optional(Schema.String),\n caption: Schema.optional(Schema.String),\n width: Schema.optional(Schema.Number.check(Schema.isGreaterThan(0))),\n align: Schema.optional(Schema.Literals(['start', 'center', 'end'])),\n }),\n }),\n node('Table', { children: blocksOf('TableRow') }),\n node('TableRow', {\n // GFM's first row is the header; saying so explicitly is what lets HTML and Markdown\n // agree about it instead of each assuming.\n Props: Schema.Struct({ header: Schema.optional(Schema.Boolean) }),\n children: blocksOf('TableCell'),\n within: ['Table'],\n }),\n // A cell's content stays in the cell: Backspace at its start lifts nothing out of it.\n node('TableCell', { children: blockContent, isolating: true, within: ['TableRow'] }),\n]\n\n/**\n * A URL attribute, or none when the value fails the URL policy. Import already applies the\n * policy, but a document also arrives decoded, synchronized, or edited through `SetMark`,\n * and this is where a `javascript:` href would become live.\n */\nconst urlAttribute = (name: string, value: unknown): Readonly<Record<string, string>> => {\n const safe = typeof value === 'string' ? safeUrl(value) : undefined\n return safe === undefined ? {} : { [name]: safe }\n}\n\n/**\n * How the standard vocabulary renders (§121): the element each kind is, with the props\n * that belong in attributes read from the block, so a `Link` is an `<a href>`, an `Image`\n * carries its source, and a `List` is an `<ol>` or a `<ul>`. The shipped marks already\n * nest in `strong`/`em`/`code`; this adds the two that do not. An application composes it\n * with `renderingOver` and names its own kinds beside it:\n *\n * ```ts\n * renderingOver(RichText.standardRendering, { nodes: { Callout: { tag: 'aside' } } })\n * ```\n */\nexport const standardRendering: Rendering = rendering({\n marks: {\n Strikethrough: { tag: 's', attributes: {} },\n Link: mark => ({ tag: 'a', attributes: urlAttribute('href', markProps(mark)?.href) }),\n },\n nodes: {\n Quote: { tag: 'blockquote', attributes: {} },\n List: block => {\n const ordered = block.props.ordered === true\n const start = block.props.start\n return {\n tag: ordered ? 'ol' : 'ul',\n attributes: ordered && typeof start === 'number' ? { start: String(start) } : {},\n }\n },\n ListItem: { tag: 'li', attributes: {} },\n TaskItem: block => ({\n tag: 'li',\n attributes: { 'data-task': block.props.checked === true ? 'checked' : 'unchecked' },\n }),\n CodeBlock: block => ({\n tag: 'pre',\n attributes: { 'data-language': String(block.props.language ?? '') },\n }),\n ThematicBreak: { tag: 'hr', attributes: {} },\n Image: block => ({\n tag: 'img',\n attributes: {\n ...urlAttribute('src', block.props.src),\n alt: String(block.props.alt ?? ''),\n },\n }),\n Table: { tag: 'table', attributes: {}, inner: 'tbody' },\n // A row says it is the header; its cells do not have to be told apart by their parent.\n TableRow: block =>\n block.props.header === true\n ? { tag: 'tr', attributes: { 'data-header': '' } }\n : { tag: 'tr', attributes: {} },\n TableCell: { tag: 'td', attributes: {} },\n },\n})\n","import { Schema } from 'effect'\nimport {\n Block,\n NodeBlock,\n NodeId,\n Document,\n blockContent,\n textContent,\n type ContentMode,\n} from './document.js'\n\n/**\n * Migrations move semantic data forward when a deployment changes its\n * vocabulary (§73): a preserved node that is now implemented, a prop renamed, a\n * block kind replaced. They operate on blocks, never on DOM, and they run at a\n * boundary the application chooses — loading, publishing, or an explicit\n * upgrade — never automatically on every read.\n *\n * Two rules keep a migration safe to run anywhere:\n *\n * - **Identity survives.** A migration returns the same `id`, so positions,\n * references, and selections keep addressing the same node.\n * - **Declining is allowed.** Returning `undefined` keeps the block as it is,\n * which is what a migration does when the data is not its shape after all.\n */\nexport interface Migration {\n readonly name: string\n /** The type, kind, or preserved `originalType` this migration reads. */\n readonly from: string\n /** The kind it produces, for a report; the returned block is the truth. */\n readonly to?: string | undefined\n readonly migrate: (block: Block) => Block | undefined\n}\n\nexport interface MigrationApplied {\n readonly name: string\n readonly node: NodeId\n}\n\nexport interface MigrationReport {\n readonly document: Document\n /** Every block a migration rewrote, in the order it happened. */\n readonly applied: ReadonlyArray<MigrationApplied>\n /** Migrations that found no block of their `from` in this document. */\n readonly unused: ReadonlyArray<string>\n}\n\nconst matches = (block: Block, from: string): boolean =>\n block.type === 'Unknown'\n ? block.originalType === from\n : block.type === 'Node'\n ? block.kind === from\n : block.type === from\n\nconst decodeMigratedDocument = Schema.decodeUnknownSync(Document, { onExcessProperty: 'error' })\n\n/** Declares a migration, checking at construction that it is shaped like one. */\nexport const migration = (\n name: string,\n from: string,\n migrate: (block: Block) => Block | undefined,\n to?: string,\n): Migration => {\n if (name.length === 0) throw new Error('Migration.make: a migration needs a name')\n if (from.length === 0) throw new Error(`Migration \"${name}\": from must not be empty`)\n return { name, from, migrate, to }\n}\n\n/**\n * Runs one migration over a block list, recursing into containers so a nested\n * block is migrated where it sits. A later migration sees what an earlier one\n * produced, because the caller runs them in list order.\n */\nconst migrateBlocks = (\n blocks: ReadonlyArray<Block>,\n migration: Migration,\n applied: Array<MigrationApplied>,\n): { readonly blocks: ReadonlyArray<Block>; readonly changed: boolean } => {\n let changed = false\n const next = blocks.map(block => {\n let current = block\n if (current.type === 'Node' && current.blocks !== undefined) {\n const nested = migrateBlocks(current.blocks, migration, applied)\n if (nested.changed) {\n changed = true\n current = { ...current, blocks: nested.blocks }\n }\n }\n if (!matches(current, migration.from)) return current\n const migrated = migration.migrate(current)\n if (migrated === undefined) return current\n // A migration that changes a block's identity is a bug: it would silently\n // break every reference to that node.\n if (migrated.id !== current.id) {\n throw new Error(`Migration \"${migration.name}\" changed a block's identity`)\n }\n // What a migration returns becomes persisted content, so it must still\n // decode as a block: a migration cannot write non-JSON props or an\n // unknown shape into the document.\n try {\n Schema.decodeUnknownSync(Block, { onExcessProperty: 'error' })(migrated)\n } catch {\n throw new Error(`Migration \"${migration.name}\" produced an invalid block`)\n }\n applied.push({ name: migration.name, node: current.id })\n changed = true\n return migrated\n })\n return { blocks: changed ? next : blocks, changed }\n}\n\n/**\n * Runs each migration over every block it reads, in list order, descending into\n * containers. A migration that changes a block's identity is a bug and throws\n * rather than silently breaking every reference to that node.\n */\nexport const migrate = (\n document: Document,\n migrations: ReadonlyArray<Migration>,\n): MigrationReport => {\n const applied: Array<MigrationApplied> = []\n const unused: Array<string> = []\n let next = document\n for (const migration of migrations) {\n const result = migrateBlocks(next.children, migration, applied)\n if (!result.changed) {\n unused.push(migration.name)\n continue\n }\n next = { ...next, children: result.blocks }\n try {\n decodeMigratedDocument(next)\n } catch {\n throw new Error(`Migration \"${migration.name}\" produced an invalid document`)\n }\n }\n return { document: next, applied, unused }\n}\n\n/**\n * A migration from a preserved unknown block into a declared node kind: the\n * props are decoded by the target's own schema, and a block whose data does not\n * decode is left alone rather than half-converted. The target's content mode\n * decides whether the promoted node holds runs or (empty) nested blocks, so\n * promoting into a container kind produces a valid block rather than one the\n * Kit will call a mismatch.\n */\nexport const promoteUnknown = (\n name: string,\n from: string,\n to: string,\n Props: Schema.Codec<any, any, never>,\n children: ContentMode = textContent,\n): Migration =>\n migration(\n name,\n from,\n block => {\n if (block.type !== 'Unknown') return undefined\n const decoded = decodeProps(Props, block.props)\n if (decoded === undefined) return undefined\n const promoted: NodeBlock = {\n type: 'Node',\n kind: to,\n id: block.id,\n props: decoded,\n children: [],\n }\n return children === blockContent ? { ...promoted, blocks: [] } : promoted\n },\n to,\n )\n\nconst decodeProps = (\n Props: Schema.Codec<any, any, never>,\n props: Readonly<Record<string, unknown>>,\n): NodeBlock['props'] | undefined => {\n try {\n const decoded: unknown = Schema.decodeUnknownSync(Props)(props)\n // Persisted props stay JSON: a schema that produces something else is\n // declined rather than written into the document.\n return Schema.decodeUnknownSync(Schema.JsonObject)(decoded)\n } catch {\n return undefined\n }\n}\n\n/** A node block's props as the codec stores them: plain JSON, nothing more. */\nexport const nodeProps = (block: NodeBlock): Readonly<Record<string, unknown>> => block.props\n","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","/**\n * The document's outline: its headings in document order, which a table of contents draws, and\n * the section a selection is in. Both are reads; nothing here changes the document.\n */\nimport { eachBlock, rangeStart, type Document, type NodeId, type Selection } from './document.js'\n\n/** One heading: its identity, its level, and its text. */\nexport interface OutlineEntry {\n readonly node: NodeId\n readonly level: number\n readonly text: string\n}\n\n/** Every heading with text, in document order, inside containers too. */\nexport const outlineOf = (document: Document): ReadonlyArray<OutlineEntry> => {\n const entries: Array<OutlineEntry> = []\n eachBlock(document.children, block => {\n if (block.type !== 'Heading') return\n const text = block.children.map(run => run.text).join('')\n if (text.trim() !== '') entries.push({ node: block.id, level: block.level, text })\n })\n return entries\n}\n\n/**\n * The heading of the section the selection starts in: the last heading with text at or before\n * its block. Undefined with no selection, or before the first heading.\n */\nexport const sectionAt = (document: Document, selection: Selection | null): NodeId | undefined => {\n if (selection?.type !== 'Range') return undefined\n const start = rangeStart(document, selection)\n if (start === undefined) return undefined\n let last: NodeId | undefined\n let found: NodeId | undefined\n eachBlock(document.children, block => {\n if (block.type === 'Heading' && block.children.some(run => run.text.trim() !== '')) {\n last = block.id\n }\n if (block.children.some(run => run.id === start.node)) {\n found = last\n }\n })\n return found\n}\n","/**\n * Media beside the standard `Image`: a video and a sound played with the browser's own controls,\n * and a file to download. Opt-in vocabulary like footnotes: add `mediaNodes` to a kit and draw\n * them with `mediaRendering` under the rendering. Each is an atom holding where its media is\n * (`src`); where that is, a `data:` URL read from a file or a URL an upload returned, is the\n * application's to decide.\n */\nimport { Schema } from 'effect'\nimport { NodeId, type Block } from './document.js'\nimport { atom } from './kit.js'\nimport { rendering, type Rendering } from './rendering.js'\nimport { safeUrl } from './url.js'\n\nconst Width = Schema.optional(Schema.Number.check(Schema.isGreaterThan(0)))\n\n/** A video, played with the browser's controls, at `width` CSS pixels when it says. */\nexport const Video = atom('Video', {\n Props: Schema.Struct({ src: Schema.String, title: Schema.optional(Schema.String), width: Width }),\n})\n\n/** A sound, played with the browser's controls. */\nexport const Audio = atom('Audio', {\n Props: Schema.Struct({ src: Schema.String, title: Schema.optional(Schema.String) }),\n})\n\n/** A file to download, under its name, with its size and type when they are known. */\nexport const Attachment = atom('Attachment', {\n Props: Schema.Struct({\n src: Schema.String,\n name: Schema.String,\n size: Schema.optional(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0))),\n type: Schema.optional(Schema.String),\n }),\n})\n\nexport const mediaNodes = [Video, Audio, Attachment]\n\n/** Types a page could run as script or markup if one were ever opened rather than saved. */\nconst ACTIVE = /^(text\\/html|application\\/xhtml\\+xml|image\\/svg\\+xml|text\\/xml|application\\/xml)\\b/i\n\n/**\n * Where a media element may load from: what the URL policy allows, or a `data:` URL whose type\n * `accepts` admits. The policy refuses `data:` in general, since a link to one could carry a\n * page; a video's own bytes cannot.\n */\nconst mediaUrl = (value: unknown, accepts: (type: string) => boolean): string | undefined => {\n if (typeof value !== 'string') return undefined\n const data = /^data:([^;,]*)[;,]/i.exec(value.trim())\n if (data === null) return safeUrl(value)\n return accepts(data[1] ?? '') ? value.trim() : undefined\n}\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value : '')\n\n/** A size as a reader says it: `820 B`, `12 KB`, `3.4 MB`. */\nexport const fileSize = (bytes: number): string => {\n if (bytes < 1024) return `${bytes} B`\n if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`\n}\n\n/**\n * How media draws: a `video` or `audio` with `controls`, which loads only its metadata until it\n * is played, and an attachment as a download link showing its name and size. A source the policy\n * refuses leaves the element without one, so it draws nothing playable.\n */\nexport const mediaRendering: Rendering = rendering({\n nodes: {\n Video: block => {\n const src = mediaUrl(block.props.src, type => type.toLowerCase().startsWith('video/'))\n const width = block.props.width\n return {\n tag: 'video',\n attributes: {\n ...(src === undefined ? {} : { src }),\n controls: '',\n preload: 'metadata',\n title: text(block.props.title),\n ...(typeof width === 'number' ? { width: String(width) } : {}),\n },\n }\n },\n Audio: block => {\n const src = mediaUrl(block.props.src, type => type.toLowerCase().startsWith('audio/'))\n return {\n tag: 'audio',\n attributes: {\n ...(src === undefined ? {} : { src }),\n controls: '',\n preload: 'metadata',\n title: text(block.props.title),\n },\n }\n },\n Attachment: block => {\n const href = mediaUrl(block.props.src, type => !ACTIVE.test(type))\n const name = text(block.props.name)\n const size = block.props.size\n return {\n tag: 'a',\n attributes: {\n ...(href === undefined ? {} : { href }),\n download: name,\n 'data-attachment': '',\n },\n adornments: [\n { tag: 'span', attributes: { 'data-attachment-name': '' }, text: name },\n ...(typeof size === 'number'\n ? [{ tag: 'span', attributes: { 'data-attachment-size': '' }, text: fileSize(size) }]\n : []),\n ],\n }\n },\n },\n})\n\n/** A file a reader added, as its type says: where it is, and what it is called. */\nexport interface MediaFile {\n readonly src: string\n readonly name: string\n readonly type: string\n readonly size: number\n}\n\n/**\n * The block for a file a reader added: an `Image`, `Video` or `Audio` when its type is one, and\n * an `Attachment` otherwise. Its identity is a placeholder, which `InsertBlock` replaces.\n */\nexport const mediaBlock = (file: MediaFile): Block => {\n const family = file.type.toLowerCase().split('/')[0]\n const title = file.name.replace(/\\.[^.]+$/, '')\n const node = (kind: string, props: Readonly<Record<string, string | number>>): Block => ({\n type: 'Node',\n kind,\n id: NodeId.make('media'),\n props,\n children: [],\n })\n if (family === 'image') return node('Image', { src: file.src, alt: title })\n if (family === 'video') return node('Video', { src: file.src, title })\n if (family === 'audio') return node('Audio', { src: file.src, title })\n return node('Attachment', {\n src: file.src,\n name: file.name,\n size: file.size,\n ...(file.type === '' ? {} : { type: file.type }),\n })\n}\n"],"mappings":";;;;AAGA,MAAa,SAAS,OAAO,eAAe,KAAK,OAAO,MAAM,yBAAyB,CA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,CAAC,IAClF,CAAC,CACP;EACF;CACF;AACF,EACF,CAAC;;;;;AAcD,MAAa,cAAc,SAA2B;CACpD,MAAM,SAAS,KAAK,KAAK,YAAY,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;CAClD,MAAM,QAAQ,KAAK,KAAK,QAAQ,YAAY,EAAE;CAC9C,MAAM,QAAQ,MAAc,WAA6D;EACvF,MAAM;EACN;EACA,IAAI,OAAO,KAAK,OAAO;EACvB;EACA,UAAU,CAAC;CACb;CACA,IAAI,WAAW,SAAS,OAAO,KAAK,SAAS;EAAE,KAAK,KAAK;EAAK,KAAK;CAAM,CAAC;CAC1E,IAAI,WAAW,SAAS,OAAO,KAAK,SAAS;EAAE,KAAK,KAAK;EAAK;CAAM,CAAC;CACrE,IAAI,WAAW,SAAS,OAAO,KAAK,SAAS;EAAE,KAAK,KAAK;EAAK;CAAM,CAAC;CACrE,OAAO,KAAK,cAAc;EACxB,KAAK,KAAK;EACV,MAAM,KAAK;EACX,MAAM,KAAK;EACX,GAAI,KAAK,SAAS,KAAK,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK;CAChD,CAAC;AACH"}
1
+ {"version":3,"file":"index.mjs","names":["pathKey","resolve","pathKey","textOf","holdsBlocks","pathKey","locateRun"],"sources":["../src/document.ts","../src/marks.ts","../src/rendering.ts","../src/html.ts","../src/clipboard.ts","../src/kit.ts","../src/transform.ts","../src/transaction.ts","../src/indent.ts","../src/search.ts","../src/footnote.ts","../src/table.ts","../src/command.ts","../src/input.ts","../src/history.ts","../src/decoration.ts","../src/code.ts","../src/url.ts","../src/standard.ts","../src/migration.ts","../src/replicated.ts","../src/outline.ts","../src/media.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Caller-assigned identity, unique across blocks and text runs in a document. */\nexport const NodeId = Schema.NonEmptyString.pipe(Schema.brand('foldkit-richtext/NodeId'))\nexport type NodeId = typeof NodeId.Type\n\n/** The mark names this vocabulary defines; a document may hold others verbatim. */\nexport const Mark = Schema.Literals(['Bold', 'Italic', 'Code'])\nexport type Mark = typeof Mark.Type\n\n/** A schema this version can hand to `decodeUnknownSync` at a Kit boundary. */\nexport type PropsSchema = Schema.Codec<any, any, never>\n\n/**\n * A mark with props: which mark, plus the JSON data it carries. Props are JSON\n * here for the same reason a node's are: the document codec cannot know an\n * application's schemas, so a Kit validates them at that boundary (§12).\n */\nexport const MarkValue = Schema.Struct({\n name: Schema.NonEmptyString,\n props: Schema.optionalKey(Schema.JsonObject),\n})\nexport type MarkValue = typeof MarkValue.Type\n\n/**\n * A mark as a text run stores it: a bare name for a mark with no props, or a\n * value when it has them. Loading preserves the form it found, so a names-only\n * document round-trips byte-equal, and because a run carries a name at most once\n * it never holds both forms of one mark.\n */\nexport const RunMark = Schema.Union([Schema.NonEmptyString, MarkValue])\nexport type RunMark = typeof RunMark.Type\n\n/** A mark's name: a bare string is a mark with no props, an object carries them. */\nexport const markName = (mark: RunMark): string => (typeof mark === 'string' ? mark : mark.name)\n\n/**\n * The content a block holds: runs, or nested blocks (§13). A document does not\n * declare which a block kind accepts — its Kit does — so these are the words a\n * declaration and a migration both use.\n */\nexport const textContent = 'text' as const\nexport const blockContent = 'blocks' as const\nexport type ContentMode = typeof textContent | typeof blockContent\n\n/**\n * The wire shape of a value: the same structure with identities unbranded. A\n * branded `NodeId` encodes as a plain string, so an annotated schema whose type\n * mentions one cannot claim its encoded form is the type itself; this names the\n * wire side, which the recursive block schema needs to break its type cycle.\n */\ntype Wire<T> = T extends NodeId\n ? string\n : T extends ReadonlyArray<infer E>\n ? ReadonlyArray<Wire<E>>\n : T extends object\n ? { readonly [K in keyof T]: Wire<T[K]> }\n : T\n\nexport const Text = Schema.Struct({\n type: Schema.Literal('Text'),\n id: NodeId,\n text: Schema.String,\n // A mark name this version does not define loads verbatim; `Edit.addMark`\n // still accepts only what the caller's vocabulary declares. A run carries a\n // name at most once; see `findUnknownMarks` for the publishing gate.\n marks: Schema.Array(RunMark).check(\n Schema.makeFilter(\n marks => new Set(marks.map(markName)).size === marks.length || 'Invalid marks',\n ),\n ),\n})\nexport type Text = typeof Text.Type\n\nexport const Paragraph = Schema.Struct({\n type: Schema.Literal('Paragraph'),\n id: NodeId,\n children: Schema.Array(Text),\n})\nexport type Paragraph = typeof Paragraph.Type\n\nexport const Heading = Schema.Struct({\n type: Schema.Literal('Heading'),\n id: NodeId,\n level: Schema.Literals([1, 2, 3, 4, 5, 6]),\n children: Schema.Array(Text),\n})\nexport type Heading = typeof Heading.Type\n\n/**\n * A block whose `type` this version does not implement, retained verbatim for\n * recovery and migration: the original type, its remaining JSON fields, and no\n * text runs (its subtree lives in `props`, opaque). Unknown blocks are\n * read-only content: address them structurally, never edit their text.\n */\nexport const UnknownBlock = Schema.Struct({\n type: Schema.Literal('Unknown'),\n id: NodeId,\n originalType: Schema.NonEmptyString,\n props: Schema.JsonObject,\n children: Schema.Array(Text).check(\n Schema.makeFilter(runs => runs.length === 0 || 'Unknown blocks keep no text runs'),\n ),\n})\nexport type UnknownBlock = typeof UnknownBlock.Type\n\n/**\n * A block whose kind the application declares: a Callout, an Image, an embed.\n * `props` is JSON at the codec level because the document codec cannot know an\n * application's schemas; a Kit's node definition validates it at that boundary,\n * and runtime declarations stay outside the codec (§12). `children` are text\n * runs, so positions, operations, and selection work on it unchanged.\n *\n * `blocks` holds nested blocks, and its presence is what says the kind accepts\n * them (§116): a List holds ListItems, a Quote holds paragraphs. A kind with\n * nested blocks has no direct runs, which is why `children` stays `Text[]` on\n * every block kind — a container simply leaves it empty, as `UnknownBlock` does.\n *\n * The shape is written by hand because `Block` and this type are mutually\n * recursive, and TypeScript cannot infer through that cycle: the schema's\n * nested field names the interface, and the interface names the union.\n */\nexport interface NodeBlock {\n readonly type: 'Node'\n readonly kind: string\n readonly id: NodeId\n readonly props: Schema.JsonObject\n readonly children: ReadonlyArray<Text>\n readonly blocks?: ReadonlyArray<Block>\n}\n\nexport const NodeBlock = Schema.Struct({\n type: Schema.Literal('Node'),\n kind: Schema.NonEmptyString,\n id: NodeId,\n props: Schema.JsonObject,\n children: Schema.Array(Text),\n blocks: Schema.optionalKey(\n Schema.suspend((): Schema.Codec<ReadonlyArray<Block>, Wire<ReadonlyArray<Block>>> =>\n Schema.Array(Block),\n ),\n ),\n}).check(\n Schema.makeFilter(\n block =>\n block.blocks === undefined ||\n block.children.length === 0 ||\n 'A block with nested blocks keeps no direct runs',\n ),\n)\n\nexport type Block = Paragraph | Heading | NodeBlock | UnknownBlock\nexport const Block = Schema.Union([Paragraph, Heading, NodeBlock, UnknownBlock])\n\n/** Every identity a block subtree owns, block and run alike, in document order. */\nconst subtreeIds = (block: Block): ReadonlyArray<NodeId> => [\n block.id,\n ...block.children.map(run => run.id),\n ...(block.type === 'Node' && block.blocks !== undefined ? block.blocks.flatMap(subtreeIds) : []),\n]\n\n/** Version 1's initial block vocabulary, with document-wide identity validation. */\nexport const Document = Schema.Struct({\n version: Schema.Literal(1),\n children: Schema.Array(Block),\n}).check(\n Schema.makeFilter(document => {\n const ids = new Set<NodeId>()\n for (const block of document.children) {\n for (const id of subtreeIds(block)) {\n if (ids.has(id)) return 'Duplicate node identity'\n ids.add(id)\n }\n }\n return true\n }),\n)\nexport type Document = typeof Document.Type\n\nconst isKnownBlockType = (type: unknown): boolean =>\n type === 'Paragraph' || type === 'Heading' || type === 'Node'\n\n/**\n * Converts a block whose type this version does not implement into an `Unknown`\n * node, and does the same inside a known node block's nested blocks. Everything\n * except `type` and `id` becomes opaque JSON props; the raw subtree is preserved\n * there verbatim.\n */\nconst preserveBlock = (input: unknown): unknown => {\n if (typeof input !== 'object' || input === null) return input\n const block = input as Record<string, unknown>\n if (!isKnownBlockType(block.type) && block.type !== 'Unknown') {\n const { type, id, ...props } = block\n return { type: 'Unknown', id, originalType: type, props, children: [] }\n }\n return Array.isArray(block.blocks) ? { ...block, blocks: block.blocks.map(preserveBlock) } : block\n}\n\n/**\n * Converts blocks whose type this version does not implement into `Unknown`\n * nodes before structural decoding, so persisted content survives a deploy\n * that lost a node implementation. Nested blocks are walked for the same reason.\n */\nconst preserveUnknownBlocks = (input: unknown): unknown => {\n if (typeof input !== 'object' || input === null) return input\n const document = input as { children?: unknown }\n if (!Array.isArray(document.children)) return input\n return { ...document, children: document.children.map(preserveBlock) }\n}\n\n/** Strict boundary for persisted content. Throws a Schema error on invalid input. */\nconst decodeStructure = Schema.decodeUnknownSync(Document, { onExcessProperty: 'error' })\n\nconst PositiveCount = Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0))\n\n/** Bounds for decoded documents: blocks, text runs, and total UTF-16 text units. */\nexport const DocumentLimits = Schema.Struct({\n maxBlocks: PositiveCount,\n maxTextRuns: PositiveCount,\n maxTextLength: PositiveCount,\n})\nexport type DocumentLimits = typeof DocumentLimits.Type\n\n/** Generous DoS guardrails, not application quotas; tighten per document with a spread. */\nexport const DefaultDocumentLimits: DocumentLimits = DocumentLimits.make({\n maxBlocks: 10_000,\n maxTextRuns: 50_000,\n maxTextLength: 5_000_000,\n})\n\n/** Every block a subtree holds, nested ones included. */\nconst countBlocks = (blocks: ReadonlyArray<Block>): number => {\n let count = 0\n eachBlock(blocks, () => {\n count += 1\n })\n return count\n}\n\n/**\n * Strict boundary for persisted content. Decodes structure first, then enforces\n * `limits`. Throws a Schema error on invalid input, or an Error naming the\n * first exceeded bound.\n */\nexport const decodeDocument = (\n input: unknown,\n limits: DocumentLimits = DefaultDocumentLimits,\n): Document => {\n const document = decodeStructure(preserveUnknownBlocks(input))\n const summary = inspect(document)\n const blocks = countBlocks(document.children)\n const runs = summary.nodeCount - blocks\n if (blocks > limits.maxBlocks)\n throw new Error(`Document exceeds maxBlocks: ${blocks} > ${limits.maxBlocks}`)\n if (runs > limits.maxTextRuns)\n throw new Error(`Document exceeds maxTextRuns: ${runs} > ${limits.maxTextRuns}`)\n if (summary.textLength > limits.maxTextLength)\n throw new Error(\n `Document exceeds maxTextLength: ${summary.textLength} > ${limits.maxTextLength}`,\n )\n return document\n}\n\n/**\n * A block's address: root-first container indices. `[2]` is the third top-level\n * block, `[2, 0]` is the first block nested inside it (§116). A block's depth is\n * its path's length.\n */\nexport type BlockPath = ReadonlyArray<number>\n\n/** A stable key for a block path, so paths can key maps and compare cheaply. */\nexport const pathKey = (path: BlockPath): string => path.join('.')\n\n/** Walks every block subtree in document order, visiting each with its path. */\nexport const eachBlock = (\n blocks: ReadonlyArray<Block>,\n visit: (block: Block, path: BlockPath) => void,\n prefix: BlockPath = [],\n): void => {\n for (const [index, block] of blocks.entries()) {\n const path = [...prefix, index]\n visit(block, path)\n if (block.type === 'Node' && block.blocks !== undefined) eachBlock(block.blocks, visit, path)\n }\n}\n\n/** A run's place in document order: its block's path, then its index in that block. */\nexport interface RunPlace {\n readonly path: BlockPath\n readonly index: number\n}\n\n/** A run with the identity it was found by. */\nexport interface LocatedRun extends RunPlace {\n readonly run: Text\n}\n\n/** Document order over run places: path first, then the run's index. */\nexport const compareRunPlaces = (left: RunPlace, right: RunPlace): number => {\n const shared = Math.min(left.path.length, right.path.length)\n for (let index = 0; index < shared; index++) {\n if (left.path[index] !== right.path[index]) return left.path[index]! - right.path[index]!\n }\n if (left.path.length !== right.path.length) return left.path.length - right.path.length\n return left.index - right.index\n}\n\n/** A position's place in document order: its run's place, then its offset in that run. */\nexport interface PositionPlace extends RunPlace {\n readonly offset: number\n}\n\n/** Document order over position places: the run first, then the offset within it. */\nexport const comparePositionPlaces = (left: PositionPlace, right: PositionPlace): number =>\n compareRunPlaces(left, right) || left.offset - right.offset\n\n/** The block a path addresses, or undefined when the path does not resolve. */\nexport const blockAtPath = (document: Document, path: BlockPath): Block | undefined => {\n let blocks: ReadonlyArray<Block> = document.children\n let found: Block | undefined\n for (const index of path) {\n found = blocks[index]\n if (found === undefined) return undefined\n blocks = found.type === 'Node' && found.blocks !== undefined ? found.blocks : []\n }\n return found\n}\n\n/** The block with this identity, wherever it sits. */\nexport const locateBlock = (\n document: Document,\n node: NodeId,\n): { readonly path: BlockPath; readonly block: Block } | undefined => {\n let found: { readonly path: BlockPath; readonly block: Block } | undefined\n eachBlock(document.children, (block, path) => {\n if (found === undefined && block.id === node) found = { path, block }\n })\n return found\n}\n\n/**\n * The blocks either side of a block in its own container, which a handle's up and down move it\n * past; both absent when the document does not hold it.\n */\nexport const siblingsOf = (\n document: Document,\n node: NodeId,\n): { readonly previous?: Block | undefined; readonly next?: Block | undefined } => {\n const found = locateBlock(document, node)\n if (found === undefined) return {}\n const index = found.path[found.path.length - 1]!\n const container = found.path.slice(0, -1)\n const parent = container.length === 0 ? undefined : blockAtPath(document, container)\n const blocks = parent?.type === 'Node' ? (parent.blocks ?? []) : document.children\n return { previous: blocks[index - 1], next: blocks[index + 1] }\n}\n\n/** The run with this identity, wherever it sits. */\nexport const locateRun = (document: Document, node: NodeId): LocatedRun | undefined => {\n let found: LocatedRun | undefined\n eachBlock(document.children, (block, path) => {\n if (found !== undefined) return\n const index = block.children.findIndex(run => run.id === node)\n if (index >= 0) found = { path, index, run: block.children[index]! }\n })\n return found\n}\n\n/**\n * Whether a reader would see nothing: no blocks, or a lone paragraph or heading whose runs\n * hold no text. What an editor shows its placeholder for; a lone empty list or code block is\n * content a writer made, so it is not blank.\n */\nexport const isBlank = (document: Document): boolean => {\n const first = document.children[0]\n if (first === undefined) return true\n return (\n document.children.length === 1 &&\n (first.type === 'Paragraph' || first.type === 'Heading') &&\n first.children.every(run => run.text.length === 0)\n )\n}\n\n/**\n * The text of the block a position addresses, up to that position, in run order.\n * A menu reads this: what a query is typed into is the block's text between its\n * start and the caret, and a query never spans blocks. Affinity is not consulted — a\n * prefix ends between characters whatever side the caret leans to — an offset past a\n * run's end clamps to it, a negative one reads as none of it, and a position that\n * resolves to nothing gives an empty string.\n */\nexport const textBefore = (document: Document, position: Position): string => {\n const found = locateRun(document, position.node)\n if (found === undefined) return ''\n const block = blockAtPath(document, found.path)\n if (block === undefined) return ''\n const lead = block.children\n .slice(0, found.index)\n .map(earlier => earlier.text)\n .join('')\n return lead + found.run.text.slice(0, Math.max(0, position.offset))\n}\n\n/**\n * Whichever end of a range comes first in the document, whatever direction it was made in,\n * or `undefined` when either end does not resolve. What replaces a range starts here, so a\n * read of the text before an edit reads from this end rather than the anchor.\n */\nexport const rangeStart = (\n document: Document,\n range: Extract<Selection, { readonly type: 'Range' }>,\n): Position | undefined => {\n const anchor = locateRun(document, range.anchor.node)\n const focus = locateRun(document, range.focus.node)\n if (anchor === undefined || focus === undefined) return undefined\n return comparePositionPlaces(\n { ...anchor, offset: range.anchor.offset },\n { ...focus, offset: range.focus.offset },\n ) <= 0\n ? range.anchor\n : range.focus\n}\n\n/**\n * The position a block's text offset addresses, or `undefined` when it is negative or past\n * the end. The inverse of `textBefore` for one block: a rule, a search match, or any producer\n * working in a block's own text needs it to say where what it found is.\n */\nexport const positionInBlock = (block: Block, offset: number): Position | undefined => {\n if (offset < 0) return undefined\n let consumed = 0\n for (const run of block.children) {\n const next = consumed + run.text.length\n if (offset <= next) {\n return {\n node: run.id,\n offset: offset - consumed,\n affinity: offset === next ? 'after' : 'before',\n }\n }\n consumed = next\n }\n return undefined\n}\n\n/**\n * The range covering the `length` characters before `position` in its block, or\n * `undefined` when the position does not resolve, `length` is not positive, or fewer\n * characters precede it. The inverse of `textBefore`: an input rule or a menu deletes\n * what it matched with this range, so removing the match and acting on it commit as one\n * action (§124 §5). Endpoints land at run boundaries with `after` affinity, which is\n * where a caret that typed that character would sit.\n */\nexport const textRangeBefore = (\n document: Document,\n position: Position,\n length: number,\n): Selection | undefined => {\n if (length <= 0) return undefined\n const found = locateRun(document, position.node)\n if (found === undefined) return undefined\n const block = blockAtPath(document, found.path)\n if (block === undefined) return undefined\n const lead = block.children\n .slice(0, found.index)\n .reduce((total, run) => total + run.text.length, 0)\n // Clamped to the run as `textBefore` clamps, so an overlong offset never reads into the next run.\n const end = lead + Math.min(found.run.text.length, Math.max(0, position.offset))\n const start = end - length\n if (start < 0) return undefined\n const anchor = positionInBlock(block, start)\n const focus = positionInBlock(block, end)\n return anchor === undefined || focus === undefined ? undefined : { type: 'Range', anchor, focus }\n}\n\n/** Every node a block subtree owns, block and run alike, keyed by identity. */\nconst indexNodes = (blocks: ReadonlyArray<Block>, nodes: Map<NodeId, Block | Text>): void => {\n eachBlock(blocks, block => {\n nodes.set(block.id, block)\n for (const run of block.children) nodes.set(run.id, run)\n })\n}\n\nconst isKnownMarkName = Schema.is(Mark)\n\n/** A mark this vocabulary does not define, kept verbatim on its text run. */\nexport interface UnknownMark {\n readonly node: NodeId\n /** The mark's name; its props, if any, stay on the run. */\n readonly mark: string\n}\n\n/** Lists unknown marks per text run; empty means the document publishes cleanly. */\nexport const findUnknownMarks = (document: Document): ReadonlyArray<UnknownMark> => {\n const unknown: Array<UnknownMark> = []\n eachBlock(document.children, block => {\n for (const text of block.children) {\n for (const mark of text.marks) {\n const name = markName(mark)\n if (!isKnownMarkName(name)) unknown.push({ node: text.id, mark: name })\n }\n }\n })\n return unknown\n}\n\n/** A block this vocabulary does not implement, retained for migration. */\nexport interface UnknownNode {\n readonly node: NodeId\n readonly originalType: string\n}\n\n/** Lists preserved unknown blocks; empty means the document publishes cleanly. */\nexport const findUnknownNodes = (document: Document): ReadonlyArray<UnknownNode> => {\n const unknown: Array<UnknownNode> = []\n eachBlock(document.children, block => {\n if (block.type === 'Unknown') {\n unknown.push({ node: block.id, originalType: block.originalType })\n }\n })\n return unknown\n}\n\n/** UTF-16 offset in one text run, with insertion affinity at that offset. */\nexport const Position = Schema.Struct({\n node: NodeId,\n offset: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),\n affinity: Schema.Literals(['before', 'after']),\n})\nexport type Position = typeof Position.Type\n\n/** A reusable identity resolved against an explicit document, without owning its content. */\nexport interface NodeReference {\n readonly id: NodeId\n /** Returns the current node, or undefined if this document does not contain it. */\n readonly read: (document: Document) => Block | Text | undefined\n /** Describes a text position; application of an edit checks the target and bounds. */\n readonly at: (offset: number, affinity: Position['affinity']) => Position\n}\n\nexport const Node = {\n /** Declares an immutable reference. Does not insert a node or reserve its ID. */\n make: (id: string): NodeReference => {\n const nodeId = NodeId.make(id)\n return Object.freeze({\n id: nodeId,\n read: (document: Document): Block | Text | undefined => {\n const nodes = new Map<NodeId, Block | Text>()\n indexNodes(document.children, nodes)\n return nodes.get(nodeId)\n },\n at: (offset: number, affinity: Position['affinity']): Position =>\n Position.make({ node: nodeId, offset, affinity }),\n })\n },\n}\n\nexport const Selection = Schema.Union([\n Schema.Struct({ type: Schema.Literal('Range'), anchor: Position, focus: Position }),\n Schema.Struct({ type: Schema.Literal('Node'), node: NodeId }),\n])\nexport type Selection = typeof Selection.Type\n\n/** Every node of a document by identity, with where each block and run sits. */\nexport interface NodeIndex {\n readonly nodes: ReadonlyMap<NodeId, Block | Text>\n /** Each run's block. */\n readonly blockOf: ReadonlyMap<NodeId, Block>\n /** Each block's parent block, `null` at the top level. */\n readonly parentOf: ReadonlyMap<NodeId, NodeId | null>\n}\nconst nodeIndexes = new WeakMap<Document, NodeIndex>()\n/** The document's `NodeIndex`, built once per document: documents are immutable. */\nexport const nodeIndex = (document: Document): NodeIndex => {\n const cached = nodeIndexes.get(document)\n if (cached !== undefined) return cached\n const nodes = new Map<NodeId, Block | Text>()\n const blockOf = new Map<NodeId, Block>()\n const parentOf = new Map<NodeId, NodeId | null>()\n const visit = (blocks: ReadonlyArray<Block>, parent: NodeId | null): void => {\n for (const block of blocks) {\n nodes.set(block.id, block)\n parentOf.set(block.id, parent)\n for (const run of block.children) {\n nodes.set(run.id, run)\n blockOf.set(run.id, block)\n }\n if (block.type === 'Node' && block.blocks !== undefined) visit(block.blocks, block.id)\n }\n }\n visit(document.children, null)\n const index = { nodes, blockOf, parentOf }\n nodeIndexes.set(document, index)\n return index\n}\n\n/** Validates references without sorting range endpoints or changing direction. */\nexport const selectionIsValid = (document: Document, selection: Selection | null): boolean => {\n if (selection === null) return true\n const { nodes } = nodeIndex(document)\n if (selection.type === 'Node') return nodes.has(selection.node)\n return [selection.anchor, selection.focus].every(position => {\n const node = nodes.get(position.node)\n return (\n node?.type === 'Text' &&\n Number.isInteger(position.offset) &&\n position.offset >= 0 &&\n position.offset <= node.text.length\n )\n })\n}\n\nexport const EditorState = Schema.Struct({\n document: Document,\n selection: Schema.NullOr(Selection),\n}).check(\n Schema.makeFilter(\n state => selectionIsValid(state.document, state.selection) || 'Unresolved selection',\n ),\n)\nexport type EditorState = typeof EditorState.Type\n\nconst decodeBlock = Schema.decodeUnknownSync(Block, { onExcessProperty: 'error' })\nconst decodeSelection = Schema.decodeUnknownSync(Schema.NullOr(Selection), {\n onExcessProperty: 'error',\n})\n/**\n * Blocks and documents that have passed validation. They are immutable, and an edit copies\n * only the blocks on the path to what it touches, so a keystroke re-validates that path\n * rather than the document or a whole container.\n */\nconst validBlocks = new WeakSet<Block>()\nconst validDocuments = new WeakSet<Document>()\n\n/**\n * Throws unless `block` decodes as a `Block`, caching every block that passes, nested ones\n * included. A block's validity does not depend on where it sits (the codec has no placement\n * or depth rules; identity is checked document-wide by the caller), so a node block is valid\n * exactly when its own fields are and each nested block is: those are checked separately, the\n * fields by decoding the block with its nested blocks emptied.\n */\nconst assertBlock = (block: unknown): void => {\n if (typeof block !== 'object' || block === null) return void decodeBlock(block)\n if (validBlocks.has(block as Block)) return\n const nested = Object.getOwnPropertyDescriptor(block, 'blocks')\n if ((block as { type?: unknown }).type === 'Node' && Array.isArray(nested?.value)) {\n // Every other own key, enumerable or not, symbol or not, stays, so the decoder sees\n // what it would see in `block` itself; a spread would drop some of them.\n decodeBlock(\n Object.create(Object.getPrototypeOf(block), {\n ...Object.getOwnPropertyDescriptors(block),\n blocks: { ...nested, value: [] },\n }),\n )\n for (const child of nested.value) assertBlock(child)\n } else decodeBlock(block)\n validBlocks.add(block as Block)\n}\n\nconst hasOnlyKeys = (value: object, keys: ReadonlyArray<string>): boolean =>\n Object.keys(value).every(key => keys.includes(key))\n\n/**\n * Whether `input` decodes as an `EditorState`, with no excess properties, as\n * `Schema.decodeUnknownSync(EditorState, { onExcessProperty: 'error' })` decides, but\n * remembering each block and document that passed. Throws on invalid input.\n */\nexport const assertEditorState = (input: unknown): void => {\n if (typeof input !== 'object' || input === null || !hasOnlyKeys(input, ['document', 'selection']))\n throw new Error('Invalid editor state')\n const { document, selection } = input as { document?: unknown; selection?: unknown }\n if (typeof document !== 'object' || document === null) throw new Error('Invalid document')\n if (!validDocuments.has(document as Document)) {\n const { version, children } = document as { version?: unknown; children?: unknown }\n if (\n version !== 1 ||\n !Array.isArray(children) ||\n !hasOnlyKeys(document, ['version', 'children'])\n )\n throw new Error('Invalid document')\n for (const block of children) assertBlock(block)\n const ids = new Set<NodeId>()\n for (const block of children as ReadonlyArray<Block>) {\n for (const id of subtreeIds(block)) {\n if (ids.has(id)) throw new Error('Duplicate node identity')\n ids.add(id)\n }\n }\n validDocuments.add(document as Document)\n }\n decodeSelection(selection)\n if (!selectionIsValid(document as Document, selection as Selection | null))\n throw new Error('Unresolved selection')\n}\n\n/**\n * Counts semantic nodes and UTF-16 text units, and reports nesting depth. Depth\n * counts levels of content: an empty document is 0, blocks are 1, runs inside a\n * block are 2, and a block nested inside a block adds a level (§116).\n */\nexport const inspect = (document: Document) => {\n let nodeCount = 0\n let textLength = 0\n let depth = 0\n eachBlock(document.children, (block, path) => {\n nodeCount += 1 + block.children.length\n for (const text of block.children) textLength += text.text.length\n depth = Math.max(depth, path.length + (block.children.length > 0 ? 1 : 0))\n })\n return { nodeCount, textLength, depth }\n}\n\nconst words = new Intl.Segmenter(undefined, { granularity: 'word' })\nconst graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\n\n/**\n * What a reader would count: words and user-perceived characters, as `Intl.Segmenter` splits\n * them in the default locale, so a word in a script without spaces still counts. Runs are\n * joined within a block, so a word that changes mark midway is one word, and blocks never\n * join, so the last word of one block and the first of the next are two.\n */\nexport const count = (document: Document): { words: number; characters: number } => {\n let wordCount = 0\n let characterCount = 0\n eachBlock(document.children, block => {\n const text = block.children.map(run => run.text).join('')\n for (const segment of words.segment(text)) if (segment.isWordLike) wordCount += 1\n for (const _ of graphemes.segment(text)) characterCount += 1\n })\n return { words: wordCount, characters: characterCount }\n}\n","import { Equal, Schema } from 'effect'\nimport {\n eachBlock,\n markName,\n type Document,\n type MarkValue,\n type Position,\n type PropsSchema,\n type RunMark,\n} from './document.js'\n\nexport { markName }\n\n/** Which edges a mark continues across when typing at a run boundary. */\nexport type MarkExpansion = 'before' | 'after' | 'both' | 'none'\n\nconst decodeJsonProps = Schema.decodeUnknownSync(Schema.JsonObject)\n\n/**\n * A mark definition: its name, where it continues across a boundary, and the\n * schema its props must satisfy when it has any. A Kit declares the vocabulary\n * an editor accepts, so an application can say that its own mark behaves like a\n * link (nothing expands, an `href` prop) or like bold (it continues).\n */\nexport interface MarkDef<Props extends PropsSchema | undefined = PropsSchema | undefined> {\n readonly name: string\n readonly expand: MarkExpansion\n /** Validates a mark value's props at the Kit boundary, not in the codec. */\n readonly Props: Props\n /** Encodes decoded props into the JSON value stored on a text run. */\n readonly of: Props extends Schema.Codec<infer A, any, any>\n ? (props: A) => MarkValue\n : () => MarkValue\n}\n\n/**\n * Declares a mark. Expansion defaults to `both`: the conservative choice for a\n * name no policy knows. A definition with `Props` gets an `of` that builds the\n * value; a definition without props builds a value that carries only its name.\n */\nexport const mark = <Props extends PropsSchema | undefined = undefined>(\n name: string,\n options: { readonly Props?: Props; readonly expand?: MarkExpansion } = {},\n): MarkDef<Props> => {\n if (name.length === 0) throw new Error('RichText.mark: a mark needs a name')\n const encodeProps =\n options.Props === undefined\n ? undefined\n : Schema.encodeUnknownSync(options.Props, { onExcessProperty: 'error' })\n return {\n name,\n expand: options.expand ?? 'both',\n Props: options.Props as Props,\n of: ((props?: unknown): MarkValue => {\n if (encodeProps === undefined) return { name }\n // The stored value is the schema's *encoded* form: a transforming codec\n // (`NumberFromString`) must persist `'42'`, which is what Kit validation\n // decodes. Decoding the result against JSON keeps the boundary honest.\n return { name, props: decodeJsonProps(encodeProps(props)) }\n }) as MarkDef<Props>['of'],\n }\n}\n\nexport const Bold: MarkDef = mark('Bold', { expand: 'after' })\nexport const Italic: MarkDef = mark('Italic', { expand: 'after' })\nexport const Code: MarkDef = mark('Code', { expand: 'none' })\n\n/** The marks this vocabulary defines, and the policy a document without a Kit gets. */\nexport const shippedMarks: ReadonlyArray<MarkDef> = [Bold, Italic, Code]\n\n/**\n * Whether props fail to decode against a node's or a mark's declared schema. The\n * diagnostic is deliberately stable: a schema's own message can name internals\n * an API boundary should not leak, so only the verdict travels.\n */\nexport const propsFailure = (props: PropsSchema | undefined, value: unknown): boolean => {\n if (props === undefined) return false\n try {\n // Strict, like the persisted-content boundary: a field the schema does not\n // declare is a failure, not something silently kept beside the props.\n Schema.decodeUnknownSync(props, { onExcessProperty: 'error' })(value)\n return false\n } catch {\n return true\n }\n}\n\n/**\n * The expansion policy of a set of definitions, and which names it declares. A\n * mark the registry does not declare expands both ways: preservation never\n * retargets it away. Declared names are what an edit may add.\n */\nexport interface MarkRegistry {\n readonly expansionOf: (name: string) => MarkExpansion\n readonly declares: (name: string) => boolean\n /** Whether an edit may add this mark: its name is declared and its props decode. */\n readonly accepts: (mark: RunMark) => boolean\n}\n\nexport const markRegistry = (definitions: ReadonlyArray<MarkDef>): MarkRegistry => {\n const byName = new Map(definitions.map(definition => [definition.name, definition]))\n return {\n expansionOf: name => byName.get(name)?.expand ?? 'both',\n declares: name => byName.has(name),\n accepts: mark => {\n const definition = byName.get(markName(mark))\n return definition !== undefined && !propsFailure(definition.Props, markProps(mark))\n },\n }\n}\n\n/** The policy of the shipped vocabulary. */\nexport const shippedRegistry: MarkRegistry = markRegistry(shippedMarks)\n\n/** A mark's props, or undefined when it carries none. */\nexport const markProps = (mark: RunMark): MarkValue['props'] | undefined =>\n typeof mark === 'string' ? undefined : mark.props\n\n/**\n * Whether two marks are the same mark with the same props. This is the\n * equivalence normalization merges on, so props compare structurally and key\n * order does not matter.\n */\nexport const sameMark = (left: RunMark, right: RunMark): boolean =>\n markName(left) === markName(right) && Equal.equals(markProps(left), markProps(right))\n\n/** Order-insensitive mark-set equality; a run carries a name at most once. */\nexport const sameMarkSet = (left: ReadonlyArray<RunMark>, right: ReadonlyArray<RunMark>): boolean =>\n left.length === right.length && left.every(mark => right.some(other => sameMark(mark, other)))\n\n/**\n * Retargets a boundary insertion to the neighboring run when the current run\n * carries marks that forbid the edge and the neighbor carries exactly the\n * marks that remain. Interior positions, missing neighbors, and mismatched\n * neighbors return the input reference unchanged; unknown node ids are left\n * for `apply` to diagnose. Never invents runs: mixed-mark edges stay put.\n */\nexport const resolveInsertion = (\n document: Document,\n position: Position,\n registry: MarkRegistry = shippedRegistry,\n): Position => {\n let resolved = position\n // Nested blocks too: a list item's or a table cell's runs follow the same rule.\n eachBlock(document.children, block => {\n const index = block.children.findIndex(run => run.id === position.node)\n const run = block.children[index]\n if (run === undefined) return\n const leavingLeft = position.affinity === 'before' && position.offset === 0\n const leavingRight = position.affinity === 'after' && position.offset === run.text.length\n if (!leavingLeft && !leavingRight) return\n const neighbor = leavingLeft ? block.children[index - 1] : block.children[index + 1]\n if (neighbor === undefined) return\n const desired = extending(run.marks, leavingLeft ? 'before' : 'after', registry)\n if (!sameMarkSet(desired, neighbor.marks)) return\n resolved = {\n node: neighbor.id,\n offset: leavingLeft ? neighbor.text.length : 0,\n affinity: position.affinity,\n }\n })\n return resolved\n}\n\n/** The marks of a run that extend past its edge in this direction. */\nconst extending = (\n marks: ReadonlyArray<RunMark>,\n direction: 'before' | 'after',\n registry: MarkRegistry,\n): ReadonlyArray<RunMark> =>\n marks.filter(mark => {\n const expand = registry.expansionOf(markName(mark))\n return expand === 'both' || expand === direction\n })\n\n/**\n * The marks text typed at the outer edge of a block should carry, when they differ from its run's:\n * a mark that does not extend past that edge (a link, a footnote reference) stops there. There is\n * no neighbouring run to type into instead, as `resolveInsertion` finds inside a block, so the\n * text needs a run of its own. Undefined anywhere else, and where every mark extends.\n */\nexport const edgeMarks = (\n document: Document,\n position: Position,\n registry: MarkRegistry = shippedRegistry,\n): ReadonlyArray<RunMark> | undefined => {\n let found: ReadonlyArray<RunMark> | undefined\n eachBlock(document.children, block => {\n const index = block.children.findIndex(run => run.id === position.node)\n const run = block.children[index]\n if (run === undefined || run.text.length === 0) return\n const atEnd = index === block.children.length - 1 && position.offset === run.text.length\n const atStart = index === 0 && position.offset === 0\n if (!atEnd && !atStart) return\n const desired = extending(run.marks, atEnd ? 'after' : 'before', registry)\n if (desired.length !== run.marks.length) found = desired\n })\n return found\n}\n","import type { NodeBlock, RunMark, Text } from './document.js'\nimport { markName } from './marks.js'\n\n/**\n * How an element is rendered: a tag and its attributes. Data, not a view (§121),\n * so the DOM-free serializer writes it and the DOM interpreters build it without\n * the core learning about Foldkit or the DOM.\n */\nexport interface ElementRendering {\n readonly tag: string\n /** Values are escaped when written; a name that would end the markup is refused. */\n readonly attributes: Readonly<Record<string, string>>\n /**\n * An element the nested blocks go inside, where HTML's parser would insert one anyway: a\n * `table`'s rows go in a `tbody`. Without it, markup sent from a server parses to a tree\n * the renderer did not write, and Foldkit refuses to serialize it.\n */\n readonly inner?: string | undefined\n /**\n * Elements drawn inside the block before its content that are not content: a task's\n * checkbox, an image's picture and caption, a callout's icon. They hold no position, are\n * never edited as text, and an HTML import skips them, so a block's text stays its runs'.\n */\n readonly adornments?: ReadonlyArray<Adornment> | undefined\n}\n\n/**\n * One element of a block's adornments. `toggles` names a boolean prop of the block that a click\n * on the element flips, through the editor's own Message (a task's `checked`, a toggle's\n * `open`), so the document stays the one place that state lives. `action` names something a\n * click on it asks the application for that is not an edit, a code block's Copy or its language\n * menu: the editor reports it, with the block, and changes nothing.\n */\nexport interface Adornment {\n readonly tag: string\n readonly attributes: Readonly<Record<string, string>>\n readonly text?: string | undefined\n readonly toggles?: string | undefined\n readonly action?: string | undefined\n}\n\n/** The attribute that marks an element as an adornment, which every interpreter skips as content. */\nexport const ADORNMENT_ATTRIBUTE = 'data-adornment'\n/** The attribute naming the prop an adornment's click flips. */\nexport const TOGGLES_ATTRIBUTE = 'data-toggles'\n/** The attribute naming what an adornment's click asks the application for. */\nexport const ACTION_ATTRIBUTE = 'data-action'\n\n/** An adornment's attributes as every interpreter writes them: its own, then the markers. */\nexport const adornmentAttributes = (\n adornment: Adornment,\n): ReadonlyArray<readonly [string, string]> => [\n ...Object.entries(adornment.attributes).filter(\n ([name]) =>\n name !== ADORNMENT_ATTRIBUTE && name !== TOGGLES_ATTRIBUTE && name !== ACTION_ATTRIBUTE,\n ),\n [ADORNMENT_ATTRIBUTE, ''],\n ...(adornment.toggles === undefined ? [] : [[TOGGLES_ATTRIBUTE, adornment.toggles] as const]),\n ...(adornment.action === undefined ? [] : [[ACTION_ATTRIBUTE, adornment.action] as const]),\n]\n\n/** Whether two renderings draw the same element: tag, attributes, holder and adornments. */\nexport const sameElementRendering = (left: ElementRendering, right: ElementRendering): boolean =>\n left.tag === right.tag &&\n left.inner === right.inner &&\n sameRecord(left.attributes, right.attributes) &&\n (left.adornments ?? []).length === (right.adornments ?? []).length &&\n (left.adornments ?? []).every((adornment, at) => {\n const other = right.adornments![at]!\n return (\n adornment.tag === other.tag &&\n adornment.text === other.text &&\n adornment.toggles === other.toggles &&\n adornment.action === other.action &&\n sameRecord(adornment.attributes, other.attributes)\n )\n })\n\nconst sameRecord = (\n left: Readonly<Record<string, string>>,\n right: Readonly<Record<string, string>>,\n): boolean => {\n const names = Object.keys(left)\n return (\n names.length === Object.keys(right).length &&\n names.every(name => Object.hasOwn(right, name) && left[name] === right[name])\n )\n}\n\n/**\n * A rendering entry: fixed data, or computed from the value being rendered, which\n * is how a mark's attributes reach its props. `undefined` means the entry does not\n * apply, so the name falls back the way an entry-less name does.\n */\nexport type RenderingEntry<Value> =\n | ElementRendering\n | ((value: Value) => ElementRendering | undefined)\n\n/**\n * A vocabulary of renderings built *over* a Kit, never inside it (§34, §121). A\n * name with no entry renders the shipped way: its mark nests in `strong`, `em`, or\n * `code`, an application node keeps its default element, and any other name rides\n * on `data-marks` — which is what keeps the slice format and an HTML round trip\n * lossless rather than lossy.\n */\nexport interface Rendering {\n readonly marks: Readonly<Record<string, RenderingEntry<RunMark>>>\n readonly nodes: Readonly<Record<string, RenderingEntry<NodeBlock>>>\n}\n\n/** The nesting the shipped marks get, innermost first. */\nconst BUILT_IN_MARK_TAGS: ReadonlyArray<readonly [string, string]> = [\n ['Bold', 'strong'],\n ['Italic', 'em'],\n ['Code', 'code'],\n]\n\n/**\n * Own-property lookup: a mark or node name is document content, so a plain or\n * hand-built `Rendering` must not let `__proto__` resolve to a prototype.\n */\nconst entryFor = <Value>(\n entries: Readonly<Record<string, RenderingEntry<Value>>>,\n name: string,\n): RenderingEntry<Value> | undefined => (Object.hasOwn(entries, name) ? entries[name] : undefined)\n\nconst resolve = <Value>(\n entry: RenderingEntry<Value>,\n value: Value,\n): ElementRendering | undefined => (typeof entry === 'function' ? entry(value) : entry)\n\n/** A name's own entry map, with no prototype for a content-chosen name to reach. */\nconst entryMap = <Value>(\n entries: Readonly<Record<string, RenderingEntry<Value>>> | undefined,\n): Readonly<Record<string, RenderingEntry<Value>>> => {\n const map: Record<string, RenderingEntry<Value>> = Object.create(null)\n for (const [name, entry] of Object.entries(entries ?? {})) map[name] = entry\n return Object.freeze(map)\n}\n\nexport const rendering = (\n definition: {\n readonly marks?: Readonly<Record<string, RenderingEntry<RunMark>>>\n readonly nodes?: Readonly<Record<string, RenderingEntry<NodeBlock>>>\n } = {},\n): Rendering =>\n Object.freeze({ marks: entryMap(definition.marks), nodes: entryMap(definition.nodes) })\n\n/** The behaviour without a renderer: shipped tags for shipped marks, names otherwise. */\nexport const noRendering: Rendering = rendering()\n\n/**\n * A registry built over another: an entry named here wins, and every name the base\n * renders keeps its entry, so an application extends a vocabulary like the standard one\n * without restating it.\n */\nexport const renderingOver = (\n base: Rendering,\n definition: {\n readonly marks?: Readonly<Record<string, RenderingEntry<RunMark>>>\n readonly nodes?: Readonly<Record<string, RenderingEntry<NodeBlock>>>\n } = {},\n): Rendering =>\n rendering({\n marks: { ...base.marks, ...definition.marks },\n nodes: { ...base.nodes, ...definition.nodes },\n })\n\n/** What a run's marks nest in, and which names nest nowhere. */\nexport interface RunRendering {\n /** Elements to wrap the run's text in, innermost first. */\n readonly nest: ReadonlyArray<ElementRendering>\n /** Names with neither an entry nor a shipped tag, sorted so output is stable. */\n readonly unrendered: ReadonlyArray<string>\n}\n\nconst byName = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0)\n\n/**\n * Resolves a run's marks to elements. Order is the vocabulary's, then names\n * alphabetically, never the order marks happen to be stored in — the same set of\n * marks must serialize the same way however it was assembled. An entry for a\n * shipped name replaces that name's tag but keeps its place in the nesting.\n */\nexport const runRendering = (definition: Rendering, run: Text): RunRendering => {\n const nest: Array<ElementRendering> = []\n const unrendered: Array<string> = []\n for (const [name, tag] of BUILT_IN_MARK_TAGS) {\n const mark = run.marks.find(candidate => markName(candidate) === name)\n if (mark === undefined) continue\n const entry = entryFor(definition.marks, name)\n nest.push(\n entry === undefined\n ? { tag, attributes: {} }\n : (resolve(entry, mark) ?? { tag, attributes: {} }),\n )\n }\n const others = run.marks\n .filter(mark => !BUILT_IN_MARK_TAGS.some(([name]) => name === markName(mark)))\n .sort((left, right) => byName(markName(left), markName(right)))\n for (const mark of others) {\n const name = markName(mark)\n const entry = entryFor(definition.marks, name)\n const element = entry === undefined ? undefined : resolve(entry, mark)\n if (element === undefined) unrendered.push(name)\n else nest.push(element)\n }\n return { nest, unrendered }\n}\n\n/** The element a node kind renders as, or undefined when no entry applies. */\nexport const nodeRendering = (\n definition: Rendering,\n block: NodeBlock,\n): ElementRendering | undefined => {\n const entry = entryFor(definition.nodes, block.kind)\n return entry === undefined ? undefined : resolve(entry, block)\n}\n","import type { Block, Document, Text } from './document.js'\nimport {\n adornmentAttributes,\n noRendering,\n nodeRendering,\n runRendering,\n type ElementRendering,\n type Rendering,\n} from './rendering.js'\n\n/**\n * HTML is an interchange format, not the document model (§70). This serializer\n * exists so a copy can offer HTML to other applications and a preview can be\n * read by anything; nothing here is ever parsed back into authority. Unknown\n * marks survive as `data-marks` on a span and unknown blocks as a placeholder\n * carrying their original type, so a round trip through HTML cannot silently\n * invent formatting the document never had.\n *\n * A renderer (§121) decides which element a declared mark or node kind produces,\n * which is how a Link's `href` becomes a real attribute. Without one, this\n * fallback still carries mark *names*, and a mark's props travel in the slice\n * format, which is the lossless path.\n */\nexport type BlockList = ReadonlyArray<Block>\n\nconst escapeText = (text: string): string =>\n text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n\nconst escapeAttribute = (value: string): string =>\n escapeText(value).replace(/\"/g, '&quot;').replace(/'/g, '&#39;')\n\nconst TAG = /^[A-Za-z][-A-Za-z0-9]*$/\nconst ATTRIBUTE = /^[A-Za-z_:][-A-Za-z0-9_:.]*$/\n\n/**\n * HTML void elements: they have no closing tag, so a rendering that names one — a\n * standard `Image` is an `img`, a `ThematicBreak` an `hr` — writes one tag and no\n * children rather than `<img></img>`.\n */\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n])\n\n/**\n * Writes an element. An attribute *value* is content and is escaped; a tag or\n * attribute *name* is refused rather than written when malformed, because a name\n * cannot be escaped — one holding a quote, a space, or `>` would end the attribute\n * and inject markup. A well-formed but unwise name (an event handler built from a\n * mark's props, say) is the application's own decision to make.\n */\nconst renderElement = (element: ElementRendering, inner: string): string => {\n if (!TAG.test(element.tag)) throw new Error(`RichText.toHtml: invalid tag \"${element.tag}\"`)\n const attributes = Object.entries(element.attributes)\n .map(([name, value]) => {\n if (!ATTRIBUTE.test(name))\n throw new Error(`RichText.toHtml: invalid attribute name \"${name}\"`)\n return ` ${name}=\"${escapeAttribute(value)}\"`\n })\n .join('')\n if (VOID_ELEMENTS.has(element.tag.toLowerCase())) return `<${element.tag}${attributes}>`\n return `<${element.tag}${attributes}>${inner}</${element.tag}>`\n}\n\nconst renderRun = (run: Text, renderer: Rendering): string => {\n const { nest, unrendered } = runRendering(renderer, run)\n let html = escapeText(run.text)\n for (const element of nest) html = renderElement(element, html)\n return unrendered.length === 0\n ? html\n : `<span data-marks=\"${escapeAttribute(unrendered.join(' '))}\">${html}</span>`\n}\n\nconst blockTag = (block: Block): string => {\n if (block.type === 'Heading') return `h${block.level}`\n return block.type === 'Node' ? 'div' : 'p'\n}\n\nconst renderBlock = (block: Block, renderer: Rendering): string => {\n if (block.type === 'Unknown')\n return `<div data-unknown=\"${escapeAttribute(block.originalType)}\"></div>`\n const runs = block.children.map(run => renderRun(run, renderer)).join('')\n // A node that accepts nested blocks renders them inside it, so a list keeps\n // its items.\n const nested =\n block.type === 'Node' && block.blocks !== undefined ? toHtml(block.blocks, renderer) : ''\n // An application node carries its kind so a stylesheet can reach it; a renderer\n // entry replaces this default element entirely.\n const element = (block.type === 'Node' ? nodeRendering(renderer, block) : undefined) ?? {\n tag: blockTag(block),\n attributes: block.type === 'Node' ? { 'data-node': block.kind } : {},\n }\n const adornment = (element.adornments ?? [])\n .map(piece =>\n renderElement(\n { tag: piece.tag, attributes: Object.fromEntries(adornmentAttributes(piece)) },\n escapeText(piece.text ?? ''),\n ),\n )\n .join('')\n return renderElement(\n element,\n element.inner === undefined\n ? `${adornment}${runs}${nested}`\n : `${adornment}${runs}${renderElement({ tag: element.inner, attributes: {} }, nested)}`,\n )\n}\n\n/** Serializes blocks as HTML, with text and attributes escaped. */\nexport const toHtml = (blocks: BlockList, renderer: Rendering = noRendering): string =>\n blocks.map(block => renderBlock(block, renderer)).join('')\n\n/**\n * Plain text of blocks, one line per text block; unknown blocks keep a\n * placeholder and a container contributes its children's lines.\n */\nexport const toText = (blocks: BlockList): string => {\n const lines: Array<string> = []\n const walk = (current: BlockList): void => {\n for (const block of current) {\n if (block.type === 'Unknown') {\n lines.push(`[${block.originalType}]`)\n continue\n }\n if (block.type === 'Node' && block.blocks !== undefined) {\n walk(block.blocks)\n continue\n }\n lines.push(block.children.map(run => run.text).join(''))\n }\n }\n walk(blocks)\n return lines.join('\\n')\n}\n\n/** Convenience for a whole document, whose blocks are its children. */\nexport const documentToHtml = (document: Document, renderer?: Rendering): string =>\n toHtml(document.children, renderer)\nexport const documentToText = (document: Document): string => toText(document.children)\n","import { Schema } from 'effect'\nimport { toText } from './html.js'\nimport {\n Block,\n NodeId,\n blockAtPath,\n compareRunPlaces,\n comparePositionPlaces,\n eachBlock,\n locateBlock,\n locateRun,\n pathKey,\n type BlockPath,\n type Document,\n type RunPlace,\n type Selection,\n type Text,\n} from './document.js'\n\n/**\n * Clipboard content is semantic, not HTML (§69). A slice is a versioned,\n * identity-carrying fragment of a document: it round-trips through an\n * application's own format, and a paste mints fresh identities so nothing\n * collides with the document it lands in. HTML and plain text are interchange\n * fallbacks the adapter adds; they are not the slice.\n */\nexport const Slice = Schema.Struct({\n version: Schema.Literal(1),\n blocks: Schema.Array(Block),\n}).check(\n Schema.makeFilter(slice => {\n const ids = new Set<NodeId>()\n let duplicate = false\n eachBlock(slice.blocks, block => {\n for (const id of [block.id, ...block.children.map(run => run.id)]) {\n if (ids.has(id)) duplicate = true\n ids.add(id)\n }\n })\n return !duplicate || 'Duplicate slice identity'\n }),\n)\nexport type Slice = typeof Slice.Type\n\nexport const emptySlice: Slice = Object.freeze({ version: 1, blocks: [] })\n\nconst decodeSlice = Schema.decodeUnknownSync(Slice, { onExcessProperty: 'error' })\nconst encodeSlice = Schema.encodeSync(Slice)\n\nconst trim = (run: Text, from: number, to: number): Text => ({\n ...run,\n text: run.text.slice(from, to),\n})\n\n/** A covered span: the two endpoints, ordered, each with its offset in its run. */\ninterface CoveredSpan {\n readonly start: RunPlace & { readonly offset: number }\n readonly end: RunPlace & { readonly offset: number }\n}\n\n/** Whether a block's subtree contains an endpoint, or sits between the two. */\nconst inRange = (blockPath: BlockPath, span: CoveredSpan): boolean => {\n const contains = (place: RunPlace): boolean =>\n blockPath.length <= place.path.length &&\n blockPath.every((index, depth) => place.path[depth] === index)\n if (contains(span.start) || contains(span.end)) return true\n const first = { path: blockPath, index: 0 }\n return compareRunPlaces(first, span.start) > 0 && compareRunPlaces(first, span.end) < 0\n}\n\n/** The runs of one block that the span covers, trimmed to it. */\nconst coveredRuns = (\n block: Block,\n blockPath: BlockPath,\n span: CoveredSpan,\n): ReadonlyArray<Text> => {\n const atStart = pathKey(blockPath) === pathKey(span.start.path)\n const atEnd = pathKey(blockPath) === pathKey(span.end.path)\n if (!atStart && !atEnd) return block.children\n const from = atStart ? span.start.index : 0\n const to = atEnd ? span.end.index : block.children.length - 1\n const children: Array<Text> = []\n for (const [index, run] of block.children.entries()) {\n if (index < from || index > to) continue\n const trimFrom = index === from && atStart ? span.start.offset : 0\n const trimTo = index === to && atEnd ? span.end.offset : run.text.length\n if (trimFrom >= trimTo) continue\n children.push(trim(run, trimFrom, trimTo))\n }\n return children\n}\n\n/**\n * The covered part of a block list: the blocks the span reaches, each trimmed to\n * it. A container is kept with the children the span reaches, so copying across\n * two list items carries the list rather than two loose paragraphs.\n */\nconst coveredBlocks = (\n blocks: ReadonlyArray<Block>,\n prefix: BlockPath,\n span: CoveredSpan,\n): ReadonlyArray<Block> => {\n const covered: Array<Block> = []\n for (const [index, block] of blocks.entries()) {\n const path = [...prefix, index]\n if (!inRange(path, span)) continue\n if (block.type === 'Unknown') {\n covered.push(block)\n continue\n }\n const children = coveredRuns(block, path, span)\n if (block.type === 'Node' && block.blocks !== undefined) {\n const nested = coveredBlocks(block.blocks, path, span)\n if (children.length === 0 && nested.length === 0) continue\n covered.push({ ...block, children, blocks: nested })\n continue\n }\n if (children.length === 0) continue\n covered.push({ ...block, children })\n }\n return covered\n}\n\n/**\n * The semantic content a copy would take: a whole block for a node selection,\n * and for a range only the covered part of what it reaches, with runs trimmed to\n * the selection. Blocks the range never enters are left out, so a partial copy\n * never drags a paragraph along.\n */\nexport const sliceOf = (document: Document, selection: Selection | null): Slice | undefined => {\n if (selection === null) return undefined\n if (selection.type === 'Node') {\n const located = locateBlock(document, selection.node)\n return located === undefined ? undefined : { version: 1, blocks: [located.block] }\n }\n const anchor = locateRun(document, selection.anchor.node)\n const focus = locateRun(document, selection.focus.node)\n if (anchor === undefined || focus === undefined) return undefined\n const anchorPlace = { ...anchor, offset: selection.anchor.offset }\n const focusPlace = { ...focus, offset: selection.focus.offset }\n const span: CoveredSpan =\n comparePositionPlaces(anchorPlace, focusPlace) <= 0\n ? { start: anchorPlace, end: focusPlace }\n : { start: focusPlace, end: anchorPlace }\n // A span inside one block copies that block, as it does at the top level; a\n // span across blocks keeps the containers that hold them, so copying across\n // two list items carries the list.\n if (pathKey(span.start.path) === pathKey(span.end.path)) {\n const block = blockAtPath(document, span.start.path)\n if (block === undefined || block.type === 'Unknown') return { version: 1, blocks: [] }\n const children = coveredRuns(block, span.start.path, span)\n return { version: 1, blocks: children.length === 0 ? [] : [{ ...block, children }] }\n }\n return { version: 1, blocks: coveredBlocks(document.children, [], span) }\n}\n\n/**\n * Plain text of a slice, one line per text block. A slice and a block list have\n * the same shape, so the serializer's walk serves both.\n */\nexport const plainTextOf = (slice: Slice): string => toText(slice.blocks)\n\n/**\n * A slice from pasted plain text: one paragraph per line. Identities come from\n * the caller, like every other identity a live edit mints.\n */\nexport const sliceFromText = (text: string, mint: () => string): Slice => ({\n version: 1,\n blocks: text.split(/\\r\\n|\\r|\\n/).map(line => ({\n type: 'Paragraph' as const,\n id: NodeId.make(mint()),\n children: [\n {\n type: 'Text' as const,\n id: NodeId.make(mint()),\n text: line,\n marks: [],\n },\n ],\n })),\n})\n\n/** The same content under fresh identities, so a paste can never collide. */\nexport const withFreshIds = (slice: Slice, mint: () => string): Slice => {\n // Pre-order: a block's identity, then its runs, then its nested blocks.\n const freshBlock = (block: Block): Block => {\n const id = NodeId.make(mint())\n const children = block.children.map(run => ({ ...run, id: NodeId.make(mint()) }))\n if (block.type === 'Node' && block.blocks !== undefined) {\n return { ...block, id, children, blocks: block.blocks.map(freshBlock) }\n }\n return { ...block, id, children }\n }\n return { version: 1, blocks: slice.blocks.map(freshBlock) }\n}\n\n/** Encodes a slice for the clipboard. */\nexport const serializeSlice = (slice: Slice): string => JSON.stringify(encodeSlice(slice))\n\n/** Decodes a slice, or undefined when the payload is not one this version wrote. */\nexport const deserializeSlice = (input: unknown): Slice | undefined => {\n try {\n return decodeSlice(typeof input === 'string' ? JSON.parse(input) : input)\n } catch {\n return undefined\n }\n}\n","import type { Schema } from 'effect'\nimport {\n blockAtPath,\n blockContent,\n eachBlock,\n textContent,\n type Block,\n type ContentMode,\n type Document,\n type NodeBlock,\n type NodeId,\n type PropsSchema,\n} from './document.js'\nimport { markName, markProps, propsFailure, type MarkDef } from './marks.js'\n\n/** Whether a kind's runs may carry formatting marks; `all` unless declared otherwise. */\nexport type MarksPolicy = 'all' | 'none'\n\n/**\n * Block content that accepts only the named kinds, so a `List` can declare that its\n * children are `ListItem`s and `validate` can report one that is not (§13, §125).\n */\nexport interface BlockConstraint {\n readonly mode: typeof blockContent\n readonly of: ReadonlyArray<string>\n}\n\n/** Declares that a node holds nested blocks, only of the named kinds. */\nexport const blocksOf = (...kinds: ReadonlyArray<string>): BlockConstraint =>\n Object.freeze({ mode: blockContent, of: [...kinds] })\n\n/** A kind's declared content: a mode, or block content restricted to named kinds. */\nexport type ChildrenDeclaration = ContentMode | BlockConstraint\n\n/**\n * The node shapes this version can declare: a `block` is one of the built-in\n * text blocks, an `atom` is an addressable node holding nothing (with optional\n * props), and an application `node` holds runs or nested blocks plus props its own\n * schema validates (§13).\n */\nexport type NodeDefinition =\n | { readonly name: string; readonly kind: 'block'; readonly children: 'text' }\n | {\n readonly name: string\n readonly kind: 'atom'\n readonly children: 'none'\n /** An atom's props decode at this boundary too, so an `Image` carries a source. */\n readonly props?: PropsSchema | undefined\n }\n | {\n readonly name: string\n readonly kind: 'node'\n /** `textContent` holds runs; `blockContent` or `blocksOf(…)` holds nested blocks. */\n readonly children: ChildrenDeclaration\n /** `none` forbids marks on this kind's runs, as a `CodeBlock` needs. */\n readonly marks: MarksPolicy\n /** Validates a `Node` block's `props` at this boundary, not in the codec. */\n readonly props?: PropsSchema | undefined\n /**\n * A boundary a lift never crosses: a table cell's content stays in the cell, where a\n * quote's or a list item's would be lifted out.\n */\n readonly isolating?: boolean | undefined\n /** Props a copy split off this node starts with, over the original's (§135). */\n readonly splitProps?: NodeBlock['props'] | undefined\n /**\n * The kinds this one may stand in (§149); absent, any that holds it. A kind that names\n * them never stands at the top level, as a `ListItem` stands only in a `List`.\n */\n readonly within?: ReadonlyArray<string> | undefined\n /** Its text keeps line breaks: Enter inserts one rather than splitting, as in code. */\n readonly lineBreaks?: boolean | undefined\n /** Tab indents its lines, and a new line starts as indented as the last, as in code. */\n readonly indents?: boolean | undefined\n }\n\n/**\n * A declared application node, with the caller's name, prop schema, and content\n * mode kept in the type: the erasure to `any` happens only where heterogeneous\n * definitions are collected, not at the authoring call.\n */\nexport interface NodeDefinitionOf<\n Name extends string,\n Props extends PropsSchema | undefined,\n Children extends ChildrenDeclaration = typeof textContent,\n> {\n readonly name: Name\n readonly kind: 'node'\n readonly children: Children\n readonly marks: MarksPolicy\n readonly props: Props\n readonly isolating: boolean\n readonly splitProps: NodeBlock['props'] | undefined\n readonly within: ReadonlyArray<string> | undefined\n readonly lineBreaks: boolean\n readonly indents: boolean\n}\n\n/** Declares a block node kind: a top-level node containing text runs. */\nexport const block = (name: string): NodeDefinition => ({\n name,\n kind: 'block',\n children: 'text',\n})\n\n/**\n * Declares an atom: an addressable node with no text content. Its optional props\n * decode at the same boundary as a `node`'s, so an `Image` is an atom carrying a\n * source rather than a run holder.\n */\nexport const atom = (\n name: string,\n options: { readonly Props?: PropsSchema | undefined } = {},\n): NodeDefinition => ({ name, kind: 'atom', children: 'none', props: options.Props })\n\n/**\n * Declares an application node kind: a `Node` block whose props this schema\n * validates and whose content the `children` declaration states — a mode, or block\n * content restricted to the kinds `blocksOf` names. `marks: 'none'` forbids marks on\n * its runs. The document codec keeps those props as JSON; the Kit is where an\n * application's types meet them.\n */\nexport const node = <\n const Name extends string,\n Props extends PropsSchema | undefined = undefined,\n Children extends ChildrenDeclaration = typeof textContent,\n>(\n name: Name,\n options: {\n readonly Props?: Props\n readonly children?: Children\n readonly marks?: MarksPolicy\n /** A boundary a lift never crosses, as a table cell is. */\n readonly isolating?: boolean\n /**\n * Props a copy split off this node starts with, laid over the original's: Enter in a\n * checked task item starts an unchecked one.\n */\n readonly splitProps?: Props extends PropsSchema\n ? Partial<Schema.Schema.Type<Props>>\n : NodeBlock['props']\n /** The kinds this one may stand in; it then never stands at the top level (§149). */\n readonly within?: ReadonlyArray<string>\n /**\n * Its text keeps line breaks, as code does: Enter inserts a newline instead of splitting\n * the block, and Enter on an empty last line leaves it for a paragraph after. A callout's\n * text can keep them too, for a note of several lines.\n */\n readonly lineBreaks?: boolean\n /**\n * Its lines are indented, as code's are: Tab and Shift+Tab indent and outdent them, and a\n * line broken with Enter starts as indented as the one before.\n */\n readonly indents?: boolean\n } = {},\n): NodeDefinitionOf<Name, Props, Children> => ({\n name,\n kind: 'node',\n children: (options.children ?? textContent) as Children,\n marks: options.marks ?? 'all',\n props: options.Props as Props,\n isolating: options.isolating ?? false,\n splitProps: options.splitProps,\n within: options.within,\n lineBreaks: options.lineBreaks ?? false,\n indents: options.indents ?? false,\n})\n\n/**\n * The vocabulary one editor accepts: which node kinds and marks are available.\n * A Kit is a definition, never document state, and it never holds renderers or\n * executable code. Transforms and metadata arrive later.\n */\nexport interface Kit {\n readonly nodes: ReadonlyArray<NodeDefinition>\n /** Mark definitions, not just names: a Kit carries each mark's boundary policy. */\n readonly marks: ReadonlyArray<MarkDef>\n}\n\nexport const kit = (definition: {\n readonly nodes: ReadonlyArray<NodeDefinition>\n readonly marks: ReadonlyArray<MarkDef>\n}): Kit => Object.freeze({ nodes: [...definition.nodes], marks: [...definition.marks] })\n\nexport interface Diagnostic {\n readonly code:\n | 'UnknownNode'\n | 'UnsupportedNode'\n | 'UnknownMark'\n | 'InvalidProps'\n | 'MismatchedDefinition'\n | 'UnexpectedChild'\n | 'MisplacedNode'\n | 'ForbiddenMark'\n readonly message: string\n readonly node?: NodeId\n readonly detail?: string\n}\n\n/** Whether a block is held as a built-in block or as an application node. */\nconst heldShape = (block: Block): 'block' | 'node' => (block.type === 'Node' ? 'node' : 'block')\n\n/**\n * The content a block actually holds. An empty application node is `either`: the\n * document cannot say whether it is an atom or a run holder that happens to have\n * no runs, so a declaration of either kind agrees with it.\n */\nconst heldContent = (block: Block): 'text' | 'blocks' | 'either' => {\n if (block.type !== 'Node') return 'text'\n if (block.blocks !== undefined) return 'blocks'\n return block.children.length > 0 ? 'text' : 'either'\n}\n\n/** The content mode a declaration names, or `'none'` for an atom. */\nconst declaredContent = (definition: NodeDefinition): ContentMode | 'none' =>\n definition.kind === 'atom'\n ? 'none'\n : typeof definition.children === 'string'\n ? definition.children\n : blockContent\n\n/**\n * Whether a declared definition agrees with the block it is declared for, and\n * why not. A `block` declaration expects a built-in block and a `node` or `atom`\n * one expects an application node; then the declared content mode must match what\n * the block holds, which is what makes an atom's no-children rule real.\n */\nconst definitionMismatch = (definition: NodeDefinition, block: Block): string | undefined => {\n const expected = definition.kind === 'block' ? 'block' : 'node'\n const held = heldShape(block)\n if (held !== expected) {\n return `\"${definition.name}\" is declared as ${definition.kind}, but the document holds it as ${held}`\n }\n const declared = declaredContent(definition)\n const content = heldContent(block)\n const agrees = content === 'either' ? declared !== 'blocks' : declared === content\n return agrees\n ? undefined\n : `\"${definition.name}\" is declared to hold ${declared}, but the document holds ${content}`\n}\n\n/**\n * A block's semantic kind: an application node's declared kind, a preserved node's\n * original type, or a built-in block's own type. This is what a `blocksOf`\n * constraint names, and what a `NodeRegistry` is looked up by.\n */\nexport const blockKind = (block: Block): string =>\n block.type === 'Node' ? block.kind : block.type === 'Unknown' ? block.originalType : block.type\n\n/**\n * The children a constrained kind does not accept. A declaration without a\n * constraint accepts any block, and a block that holds runs has no children to\n * check; `definitionMismatch` is what reports the mode itself.\n */\nconst childKindDiagnostics = (\n definition: NodeDefinition,\n block: Block,\n): ReadonlyArray<Diagnostic> => {\n if (definition.kind !== 'node' || typeof definition.children === 'string') return []\n if (block.type !== 'Node' || block.blocks === undefined) return []\n const allowed = definition.children.of\n const permitted = new Set(allowed)\n return block.blocks\n .filter(child => !permitted.has(blockKind(child)))\n .map(child => ({\n code: 'UnexpectedChild' as const,\n node: child.id,\n detail: blockKind(child),\n message: `\"${block.kind}\" accepts only ${allowed.join(', ')}`,\n }))\n}\n\n/**\n * Whether a kind may stand in a parent of `parentKind`, or at the top level when that is\n * undefined: anywhere, unless its declaration names where (§149).\n */\nexport const standsWithin = (\n declared: NodeDefinition | undefined,\n parentKind: string | undefined,\n): boolean =>\n declared?.kind !== 'node' ||\n declared.within === undefined ||\n (parentKind !== undefined && declared.within.includes(parentKind))\n\n/** Structural summary of a Kit, for tooling and tests. */\nexport const inspectKit = (definition: Kit) => ({\n blocks: definition.nodes.filter(node => node.kind === 'block').length,\n atoms: definition.nodes.filter(node => node.kind === 'atom').length,\n nodes: definition.nodes.filter(node => node.kind === 'node').length,\n marks: definition.marks.length,\n})\n\n/**\n * The node vocabulary an edit may target, the way `MarkRegistry` is the mark\n * vocabulary a mark edit consults. `run` reads a kind's declaration from it to refuse\n * an edit a constraint forbids (§117, §125); `apply` still takes none, so a durable\n * transaction never depends on a vocabulary that may have moved.\n */\nexport interface NodeRegistry {\n /** The declaration for a block kind, or undefined when this vocabulary has none. */\n readonly definitionFor: (kind: string) => NodeDefinition | undefined\n}\n\n/** Builds the registry an edit consults. A later declaration for a name wins, as a Map does. */\nexport const nodeRegistry = (definitions: ReadonlyArray<NodeDefinition>): NodeRegistry => {\n const byName = new Map(definitions.map(definition => [definition.name, definition]))\n return Object.freeze({ definitionFor: (kind: string) => byName.get(kind) })\n}\n\n/**\n * Checks a document against a Kit's vocabulary without changing it, walking\n * nested blocks so a container's children are checked too. Reports preserved\n * unknown blocks, known blocks the Kit does not declare, declarations that\n * disagree with how the document holds a block, application nodes whose props\n * their schema refuses, and marks outside the Kit or whose props their definition\n * refuses. Content diagnostics never strip or repair the document; callers decide\n * whether to block publishing or surface a placeholder.\n */\nexport const validate = (document: Document, definition: Kit): ReadonlyArray<Diagnostic> => {\n const byName = new Map(definition.nodes.map(node => [node.name, node]))\n const declaredMarks = new Map(definition.marks.map(mark => [mark.name, mark]))\n const diagnostics: Array<Diagnostic> = []\n eachBlock(document.children, (block, path) => {\n if (block.type === 'Unknown') {\n diagnostics.push({\n code: 'UnknownNode',\n node: block.id,\n detail: block.originalType,\n message: `Unimplemented node type \"${block.originalType}\"`,\n })\n return\n }\n const kind = blockKind(block)\n const declared = byName.get(kind)\n if (declared === undefined) {\n diagnostics.push({\n code: 'UnsupportedNode',\n node: block.id,\n detail: kind,\n message: `The Kit does not declare ${block.type === 'Node' ? 'node ' : ''}\"${kind}\"`,\n })\n } else {\n const mismatch = definitionMismatch(declared, block)\n if (mismatch !== undefined) {\n diagnostics.push({\n code: 'MismatchedDefinition',\n node: block.id,\n detail: kind,\n message: mismatch,\n })\n } else {\n if (\n block.type === 'Node' &&\n declared.kind !== 'block' &&\n propsFailure(declared.props, block.props)\n ) {\n diagnostics.push({\n code: 'InvalidProps',\n node: block.id,\n detail: kind,\n message: `\"${kind}\" props do not match its declared schema`,\n })\n }\n diagnostics.push(...childKindDiagnostics(declared, block))\n const parent = path.length > 1 ? blockAtPath(document, path.slice(0, -1)) : undefined\n const parentKind = parent === undefined ? undefined : blockKind(parent)\n if (!standsWithin(declared, parentKind)) {\n diagnostics.push({\n code: 'MisplacedNode',\n node: block.id,\n detail: kind,\n message: `\"${kind}\" cannot stand ${parentKind === undefined ? 'at the top level' : `in \"${parentKind}\"`}`,\n })\n }\n }\n }\n // A kind declared mark-free has no formatting to carry, so any mark it does is\n // reported as well as checked against the vocabulary that declared it.\n const forbidsMarks = declared?.kind === 'node' && declared.marks === 'none'\n for (const run of block.children) {\n for (const mark of run.marks) {\n const name = markName(mark)\n if (forbidsMarks) {\n diagnostics.push({\n code: 'ForbiddenMark',\n node: run.id,\n detail: name,\n message: `\"${kind}\" accepts no marks`,\n })\n }\n const declaredMark = declaredMarks.get(name)\n if (declaredMark === undefined) {\n diagnostics.push({\n code: 'UnknownMark',\n node: run.id,\n detail: name,\n message: `The Kit does not declare mark \"${name}\"`,\n })\n } else if (propsFailure(declaredMark.Props, markProps(mark))) {\n diagnostics.push({\n code: 'InvalidProps',\n node: run.id,\n detail: name,\n message: `\"${name}\" props do not match its declared schema`,\n })\n }\n }\n }\n })\n return diagnostics\n}\n","import { NodeId, type Block, type Document, type Text } from './document.js'\nimport { sameMarkSet } from './marks.js'\nimport type { CollapseStep, PositionStep, RelocateStep, SplitStep } from './transaction.js'\n\n/**\n * Transforms normalize or derive semantic structure after edits (§23). A\n * transform is a pure function of the document plus what the transaction\n * touched: it returns a whole new document and the position steps and identity\n * bookkeeping that go with it, so `apply` can fold it into the same ChangeSet\n * and position map it was already building.\n *\n * Two rules make a registry safe to run in a loop (§24): a transform must be\n * deterministic, and it must be idempotent on normalized state — so running it\n * again after it has run changes nothing, which is how the loop knows it has\n * settled.\n */\nexport interface TransformContext {\n /** Blocks the transaction touched, plus whatever earlier transforms touched. */\n readonly dirtyNodes: ReadonlySet<NodeId>\n /** Runs already spent, so a transform can bail out rather than spin. */\n readonly pass: number\n}\n\nexport interface TransformReport {\n readonly document: Document\n /** The same step vocabulary a transaction uses, so `apply` can fold either. */\n readonly steps: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>\n readonly insertedNodes: ReadonlySet<NodeId>\n readonly removedNodes: ReadonlySet<NodeId>\n readonly dirtyNodes: ReadonlySet<NodeId>\n /** Runs whose text a transform rewrote, such as a merge's accumulator. */\n readonly textChanged: ReadonlySet<NodeId>\n /** Whether the block list changed shape, not just the runs inside a block. */\n readonly structureChanged: boolean\n}\n\nexport interface Transform {\n readonly name: string\n readonly apply: (document: Document, context: TransformContext) => TransformReport\n}\n\n/** A transform that found nothing to do. */\nexport const unchanged = (document: Document): TransformReport => ({\n document,\n steps: [],\n insertedNodes: new Set(),\n removedNodes: new Set(),\n dirtyNodes: new Set(),\n textChanged: new Set(),\n structureChanged: false,\n})\n\nconst mergeRunInto = (accumulator: Text, run: Text): Text => ({\n ...accumulator,\n text: accumulator.text + run.text,\n})\n\n/**\n * Merges adjacent runs whose mark sets match, within the blocks the transaction\n * touched, at any depth. Merging strictly reduces the run count, so one pass reaches\n * a stable state and a second pass finds nothing: the rule is idempotent, and only\n * equal mark sets merge, so an unknown mark never drops.\n */\nexport const mergeAdjacentRuns: Transform = {\n name: 'mergeAdjacentRuns',\n apply: (document, context) => {\n const steps: Array<RelocateStep> = []\n const removedNodes = new Set<NodeId>()\n const dirtyNodes = new Set<NodeId>()\n const textChanged = new Set<NodeId>()\n const mergeRuns = (block: Block): Block => {\n const first = block.children[0]\n if (!context.dirtyNodes.has(block.id) || first === undefined) return block\n let accumulator = first\n let changed = false\n const kept: Array<Text> = [accumulator]\n for (const run of block.children.slice(1)) {\n if (sameMarkSet(accumulator.marks, run.marks)) {\n steps.push({\n node: run.id,\n into: accumulator.id,\n at: 0,\n base: accumulator.text.length,\n })\n accumulator = mergeRunInto(accumulator, run)\n kept[kept.length - 1] = accumulator\n removedNodes.add(run.id)\n dirtyNodes.add(accumulator.id)\n textChanged.add(accumulator.id)\n changed = true\n } else {\n accumulator = run\n kept.push(run)\n }\n }\n return changed ? { ...block, children: kept } : block\n }\n // Returns the same array when nothing inside changed, so untouched containers keep\n // their identity and `apply` can tell that this transform found nothing.\n const mergeWithin = (blocks: ReadonlyArray<Block>): ReadonlyArray<Block> => {\n let changed = false\n const next = blocks.map(block => {\n let merged = mergeRuns(block)\n if (merged.type === 'Node' && merged.blocks !== undefined) {\n const nested = mergeWithin(merged.blocks)\n if (nested !== merged.blocks) merged = { ...merged, blocks: nested }\n }\n if (merged !== block) changed = true\n return merged\n })\n return changed ? next : blocks\n }\n const children = mergeWithin(document.children)\n return {\n document: children === document.children ? document : { ...document, children },\n steps,\n insertedNodes: new Set(),\n removedNodes,\n dirtyNodes,\n textChanged,\n structureChanged: false,\n }\n },\n}\n\n/** The transforms every transaction runs, in order, unless a caller says otherwise. */\nexport const defaultTransforms: ReadonlyArray<Transform> = [mergeAdjacentRuns]\n","import { Equal, Schema } from 'effect'\nimport { markName, sameMark } from './marks.js'\nimport {\n assertEditorState,\n Block,\n eachBlock,\n EditorState,\n NodeId,\n Position,\n RunMark,\n Selection,\n compareRunPlaces,\n type BlockPath,\n type Document,\n type NodeReference,\n type RunPlace,\n type Text,\n} from './document.js'\nimport { defaultTransforms, type Transform } from './transform.js'\n\n/** How many normalization passes a transaction may spend before it gives up. */\nexport const MAX_NORMALIZATION_PASSES = 10\n\nconst Offset = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\nconst InsertTextOperation = Schema.Struct({\n type: Schema.Literal('InsertText'),\n at: Position,\n text: Schema.String,\n})\nconst DeleteTextOperation = Schema.Struct({\n type: Schema.Literal('DeleteText'),\n node: NodeId,\n from: Offset,\n to: Offset,\n})\nconst AddMarkOperation = Schema.Struct({\n type: Schema.Literal('AddMark'),\n node: NodeId,\n mark: RunMark,\n})\nconst RemoveMarkOperation = Schema.Struct({\n type: Schema.Literal('RemoveMark'),\n node: NodeId,\n mark: Schema.String,\n})\nconst SetSelectionOperation = Schema.Struct({\n type: Schema.Literal('SetSelection'),\n selection: Schema.NullOr(Selection),\n})\nconst SplitNodeOperation = Schema.Struct({\n type: Schema.Literal('SplitNode'),\n block: NodeId,\n node: NodeId,\n offset: Offset,\n blockId: NodeId,\n textId: NodeId,\n})\nconst JoinNodeOperation = Schema.Struct({\n type: Schema.Literal('JoinNode'),\n into: NodeId,\n removed: NodeId,\n})\nconst MoveNodeOperation = Schema.Struct({\n type: Schema.Literal('MoveNode'),\n node: NodeId,\n to: Offset,\n /** The block list to move into: a node block's, or the document's when absent. */\n parent: Schema.optionalKey(NodeId),\n})\n/**\n * What a text block retypes to: a paragraph, or a heading at a level. Its runs are\n * its own and survive the change; only the block's type does not.\n */\nexport const TextBlock = 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])\nexport type TextBlock = typeof TextBlock.Type\n\n/**\n * What a block becomes, under its own identity and with its own content: a block that holds\n * text becomes a paragraph, a heading, or an application node kind that holds text, such as a\n * code block, keeping its runs; a node that holds blocks becomes another node kind, keeping\n * its nested blocks, as a list item becomes a task.\n */\nexport const RetypeTarget = 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 }),\n])\nexport type RetypeTarget = typeof RetypeTarget.Type\n\nconst RetypeBlockOperation = Schema.Struct({\n type: Schema.Literal('RetypeBlock'),\n node: NodeId,\n to: RetypeTarget,\n})\nconst SetPropsOperation = Schema.Struct({\n type: Schema.Literal('SetProps'),\n node: NodeId,\n props: Schema.JsonObject,\n})\nconst InsertNodeOperation = Schema.Struct({\n type: Schema.Literal('InsertNode'),\n block: Block,\n at: Offset,\n /** The block list to insert into: a node block's, or the document's when absent. */\n parent: Schema.optionalKey(NodeId),\n})\nconst DeleteNodeOperation = Schema.Struct({\n type: Schema.Literal('DeleteNode'),\n node: NodeId,\n})\nconst SplitRunOperation = Schema.Struct({\n type: Schema.Literal('SplitRun'),\n node: NodeId,\n offset: Offset,\n textId: NodeId,\n})\n\nexport const Operation = Schema.Union([\n InsertTextOperation,\n DeleteTextOperation,\n AddMarkOperation,\n RemoveMarkOperation,\n SetSelectionOperation,\n SplitNodeOperation,\n JoinNodeOperation,\n MoveNodeOperation,\n RetypeBlockOperation,\n SetPropsOperation,\n InsertNodeOperation,\n DeleteNodeOperation,\n SplitRunOperation,\n])\nexport type Operation = typeof Operation.Type\nexport const Transaction = Schema.Array(Operation)\nexport type Transaction = typeof Transaction.Type\n\n/** A text-run target: a validated id or a reusable node reference. */\nexport type TextTarget = NodeId | NodeReference\n\nconst targetId = (target: TextTarget): NodeId => (typeof target === 'string' ? target : target.id)\n\n/** Accepts a raw string or validated id; empty strings throw via `NodeId`. */\nconst freshId = (id: string | NodeId): NodeId => (typeof id === 'string' ? NodeId.make(id) : id)\n\n/**\n * Typesafe constructors for transaction operations. Each builder accepts a\n * `NodeId` or a `Node.make` reference and validates shape immediately\n * (misuse throws), while document-dependent checks — node kind, existence,\n * bounds, selection resolution — remain `apply` diagnostics. Compose with\n * `Node.at` for positions: `Edit.insertText(Text.at(5, 'after'), '!')`.\n */\nexport const Edit = {\n insertText: (at: Position, text: string): Extract<Operation, { readonly type: 'InsertText' }> =>\n InsertTextOperation.make({ type: 'InsertText', at, text }),\n\n deleteText: (\n node: TextTarget,\n from: number,\n to: number,\n ): Extract<Operation, { readonly type: 'DeleteText' }> => {\n if (from > to) throw new Error(`Edit.deleteText: from (${from}) must not exceed to (${to})`)\n return DeleteTextOperation.make({ type: 'DeleteText', node: targetId(node), from, to })\n },\n\n addMark: (node: TextTarget, mark: RunMark): Extract<Operation, { readonly type: 'AddMark' }> =>\n AddMarkOperation.make({ type: 'AddMark', node: targetId(node), mark }),\n\n removeMark: (\n node: TextTarget,\n mark: string,\n ): Extract<Operation, { readonly type: 'RemoveMark' }> =>\n RemoveMarkOperation.make({ type: 'RemoveMark', node: targetId(node), mark }),\n\n setSelection: (\n selection: Selection | null,\n ): Extract<Operation, { readonly type: 'SetSelection' }> =>\n SetSelectionOperation.make({ type: 'SetSelection', selection }),\n\n splitBlock: (\n block: TextTarget,\n node: TextTarget,\n offset: number,\n newBlock: string | NodeId,\n newRun: string | NodeId,\n ): Extract<Operation, { readonly type: 'SplitNode' }> =>\n SplitNodeOperation.make({\n type: 'SplitNode',\n block: targetId(block),\n node: targetId(node),\n offset,\n blockId: freshId(newBlock),\n textId: freshId(newRun),\n }),\n\n joinBlocks: (\n survivor: TextTarget,\n removed: TextTarget,\n ): Extract<Operation, { readonly type: 'JoinNode' }> =>\n JoinNodeOperation.make({\n type: 'JoinNode',\n into: targetId(survivor),\n removed: targetId(removed),\n }),\n\n moveBlock: (\n node: TextTarget,\n to: number,\n parent?: TextTarget,\n ): Extract<Operation, { readonly type: 'MoveNode' }> =>\n MoveNodeOperation.make({\n type: 'MoveNode',\n node: targetId(node),\n to,\n ...(parent === undefined ? {} : { parent: targetId(parent) }),\n }),\n\n retypeBlock: (\n node: TextTarget,\n to: RetypeTarget,\n ): Extract<Operation, { readonly type: 'RetypeBlock' }> =>\n RetypeBlockOperation.make({ type: 'RetypeBlock', node: targetId(node), to }),\n\n /** Sets the named props of a node block; props it does not name keep their values. */\n setProps: (\n node: TextTarget,\n props: Schema.JsonObject,\n ): Extract<Operation, { readonly type: 'SetProps' }> =>\n SetPropsOperation.make({ type: 'SetProps', node: targetId(node), props }),\n\n insertBlock: (\n block: Block,\n at: number,\n parent?: TextTarget,\n ): Extract<Operation, { readonly type: 'InsertNode' }> =>\n InsertNodeOperation.make({\n type: 'InsertNode',\n block,\n at,\n ...(parent === undefined ? {} : { parent: targetId(parent) }),\n }),\n\n deleteBlock: (node: TextTarget): Extract<Operation, { readonly type: 'DeleteNode' }> =>\n DeleteNodeOperation.make({ type: 'DeleteNode', node: targetId(node) }),\n\n splitRun: (\n node: TextTarget,\n offset: number,\n newRun: string | NodeId,\n ): Extract<Operation, { readonly type: 'SplitRun' }> =>\n SplitRunOperation.make({\n type: 'SplitRun',\n node: targetId(node),\n offset,\n textId: freshId(newRun),\n }),\n}\n\nexport interface ChangeSet {\n readonly dirtyNodes: ReadonlySet<NodeId>\n readonly insertedNodes: ReadonlySet<NodeId>\n readonly removedNodes: ReadonlySet<NodeId>\n readonly textChanged: ReadonlySet<NodeId>\n readonly structureChanged: boolean\n readonly selectionChanged: boolean\n}\n\n/** One replacement of [from, to) with inserted UTF-16 units, in sequential coordinates. */\nexport interface PositionStep {\n readonly node: NodeId\n readonly from: number\n readonly to: number\n readonly inserted: number\n}\n\n/**\n * Split relocation: offsets > at move to into with offset - at; offset == at\n * follows affinity (before stays, after moves to 0); lower offsets stay.\n */\nexport interface SplitStep {\n readonly node: NodeId\n readonly into: NodeId\n readonly at: number\n}\n\n/**\n * Merge relocation: offsets >= at move to into with base + offset - at;\n * lower offsets stay. Affinity is preserved, not consulted: the source\n * location ceases to exist, so every endpoint must move.\n */\nexport interface RelocateStep {\n readonly node: NodeId\n readonly into: NodeId\n readonly at: number\n readonly base: number\n}\n\n/**\n * Deletion collapse: every offset in node moves to offset 0 of into;\n * affinity is preserved. Emitted per removed run when a surviving run exists;\n * with no text left, positions cannot map and selection clears instead.\n */\nexport interface CollapseStep {\n readonly node: NodeId\n readonly into: NodeId\n}\n\n/** Maps a position through each edit, preserving insertion affinity. */\nexport const mapPosition = (\n position: Position,\n steps: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>,\n): Position =>\n steps.reduce((current, step) => {\n if (current.node !== step.node) return current\n if ('base' in step) {\n if (current.offset < step.at) return current\n return { ...current, node: step.into, offset: step.base + current.offset - step.at }\n }\n if ('at' in step) {\n if (current.offset < step.at) return current\n if (current.offset === step.at && current.affinity === 'before') return current\n return { ...current, node: step.into, offset: current.offset - step.at }\n }\n if ('into' in step) {\n return { ...current, node: step.into, offset: 0 }\n }\n if (current.offset < step.from) return current\n const offset =\n current.offset > step.to\n ? current.offset + step.inserted - (step.to - step.from)\n : step.from + (current.affinity === 'after' ? step.inserted : 0)\n return offset === current.offset ? current : { ...current, offset }\n }, position)\n\n/**\n * Maps a whole selection through steps: both range endpoints, or a node target\n * whose identity a step relocated. Steps that only replace text have no `into`,\n * so a node selection is unaffected by them.\n */\nexport const mapThrough = (\n selection: Selection | null,\n steps: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>,\n): Selection | null => {\n if (selection === null) return null\n if (selection.type === 'Node') {\n const step = steps.find(candidate => 'into' in candidate && candidate.node === selection.node)\n return step === undefined || !('into' in step) ? selection : { ...selection, node: step.into }\n }\n return {\n ...selection,\n anchor: mapPosition(selection.anchor, steps),\n focus: mapPosition(selection.focus, steps),\n }\n}\n\nexport type TransactionResult =\n | {\n readonly ok: true\n readonly state: EditorState\n readonly changeSet: ChangeSet\n readonly positionMap: ReadonlyArray<PositionStep | SplitStep | RelocateStep | CollapseStep>\n /**\n * The transactions that produced `state`, in order, each normalized before the next:\n * folding `apply` over them from the input state yields `state` again. A command can\n * need more than one, and an action has at least one per command.\n */\n readonly transactions: ReadonlyArray<Transaction>\n }\n | {\n readonly ok: false\n readonly error:\n | 'InvalidInput'\n | 'MissingText'\n | 'MissingNode'\n | 'InvalidRange'\n | 'InvalidSelection'\n | 'InvalidParent'\n | 'ForbiddenMark'\n | 'UnexpectedChild'\n | 'UnstableNormalization'\n }\n\nconst decodeTransaction = Schema.decodeUnknownSync(Transaction, { onExcessProperty: 'error' })\nconst sameSelection = (left: Selection | null, right: Selection | null): boolean => {\n if (left === null || right === null) return left === right\n if (left.type === 'Node') return right.type === 'Node' && left.node === right.node\n if (right.type !== 'Range') return false\n return (['anchor', 'focus'] as const).every(\n key =>\n left[key].node === right[key].node &&\n left[key].offset === right[key].offset &&\n left[key].affinity === right[key].affinity,\n )\n}\n\n/** The nested block list of a container, or undefined for any other block. */\nconst nestedOf = (block: Block): ReadonlyArray<Block> | undefined =>\n block.type === 'Node' && block.blocks !== undefined ? block.blocks : undefined\n\n/**\n * A block's address: root-first container indices. `[2]` is the third top-level\n * block; `[2, 0]` is the first block nested inside it (§116). The document's own\n * block list is the container at `[]`.\n */\nconst pathKey = (path: BlockPath): string => path.join('.')\nconst keyToPath = (key: string): BlockPath => (key === '' ? [] : key.split('.').map(Number))\n\ninterface DocumentIndex {\n readonly blockPaths: ReadonlyMap<NodeId, BlockPath>\n readonly runPaths: ReadonlyMap<NodeId, { readonly path: BlockPath; readonly index: number }>\n}\nconst indexes = new WeakMap<Document, DocumentIndex>()\n/** Where each block and run sits, built once per document: documents are immutable. */\nconst indexDocument = (document: Document): DocumentIndex => {\n const cached = indexes.get(document)\n if (cached !== undefined) return cached\n const blockPaths = new Map<NodeId, BlockPath>()\n const runPaths = new Map<NodeId, { readonly path: BlockPath; readonly index: number }>()\n eachBlock(document.children, (block, path) => {\n blockPaths.set(block.id, path)\n for (const [runIndex, run] of block.children.entries()) {\n runPaths.set(run.id, { path, index: runIndex })\n }\n })\n const index = { blockPaths, runPaths }\n indexes.set(document, index)\n return index\n}\n\n/**\n * Pure, atomic text transaction. Rejection returns no partially edited state.\n * `transforms` defaults to the registry's shipped rules; a Kit's transforms\n * arrive here when Kit support lands.\n */\nexport const apply = (\n state: EditorState,\n transaction: Transaction,\n transforms: ReadonlyArray<Transform> = defaultTransforms,\n): TransactionResult => {\n try {\n assertEditorState(state)\n decodeTransaction(transaction)\n } catch {\n return { ok: false, error: 'InvalidInput' }\n }\n const initial = indexDocument(state.document)\n let { blockPaths, runPaths } = initial\n /** The index as this transaction's own copy, once `indexInserted` has written to it. */\n let owned: { blocks: Map<NodeId, BlockPath>; runs: Map<NodeId, RunPlace> } | undefined\n const reindex = () => {\n ;({ blockPaths, runPaths } = indexDocument(document))\n owned = undefined\n }\n // Identities stay reserved for the whole transaction so a reused id can never\n // silently address two nodes across structural edits: the input's, and every one\n // the transaction adds.\n const added = new Set<NodeId>()\n const usedIds = {\n has: (id: NodeId): boolean =>\n initial.runPaths.has(id) || initial.blockPaths.has(id) || added.has(id),\n add: (id: NodeId): void => void added.add(id),\n }\n let document: Document = state.document\n // Working copies: each touched container is copied once per transaction, so N\n // edits in one paragraph cost O(N) rather than N copies of the same array. A\n // container is a block list — the document's, or a node block's nested blocks —\n // and a block's runs are copied separately, keyed by that block's path.\n const workingBlocks = new Map<string, Array<Block>>()\n const workingRuns = new Map<string, Array<Text>>()\n const blockAt = (path: BlockPath): Block | undefined =>\n blocksAt(path.slice(0, -1))[path[path.length - 1]!]\n /** The block list at a container path, reading through any pending copy. */\n function blocksAt(containerPath: BlockPath): ReadonlyArray<Block> {\n const pending = workingBlocks.get(pathKey(containerPath))\n if (pending !== undefined) return pending\n if (containerPath.length === 0) return document.children\n const parent = blockAt(containerPath)\n return parent?.type === 'Node' && parent.blocks !== undefined ? parent.blocks : []\n }\n /** Copies a container, and its ancestors, once: writes never touch the input. */\n const ensureContainer = (containerPath: BlockPath): Array<Block> => {\n const key = pathKey(containerPath)\n const existing = workingBlocks.get(key)\n if (existing !== undefined) return existing\n if (containerPath.length > 0) ensureContainer(containerPath.slice(0, -1))\n const copy = [...blocksAt(containerPath)]\n workingBlocks.set(key, copy)\n return copy\n }\n /** The block's runs as they stand: a pending copy if one exists, else the document's. */\n const runsAt = (path: BlockPath): ReadonlyArray<Text> =>\n workingRuns.get(pathKey(path)) ?? blockAt(path)?.children ?? []\n /** The block's run array, copied on first write and mutated in place after. */\n const runArray = (path: BlockPath): Array<Text> => {\n const key = pathKey(path)\n const existing = workingRuns.get(key)\n if (existing !== undefined) return existing\n ensureContainer(path.slice(0, -1))\n const copy = [...(blockAt(path)?.children ?? [])]\n workingRuns.set(key, copy)\n return copy\n }\n /**\n * Indexes a block just inserted at `at` in a container, and moves each later sibling's\n * subtree one place on, rather than indexing the whole document again: a paste inserts one\n * block at a time, and reindexing after each made it quadratic in the blocks pasted.\n */\n const indexInserted = (containerPath: BlockPath, at: number): void => {\n const index = (owned ??= { blocks: new Map(blockPaths), runs: new Map(runPaths) })\n blockPaths = index.blocks\n runPaths = index.runs\n const record = (block: Block, path: BlockPath): void => {\n index.blocks.set(block.id, path)\n block.children.forEach((run, place) => index.runs.set(run.id, { path, index: place }))\n if (block.type === 'Node' && block.blocks !== undefined) {\n block.blocks.forEach((child, place) => record(child, [...path, place]))\n }\n }\n const blocks = blocksAt(containerPath)\n for (let place = at; place < blocks.length; place++) {\n record(blocks[place]!, [...containerPath, place])\n }\n }\n const writeBlock = (path: BlockPath, block: Block): void => {\n const container = ensureContainer(path.slice(0, -1))\n container[path[path.length - 1]!] = block\n }\n /**\n * The block list a structural operation targets: the document's, or a node\n * block's nested blocks. A parent that cannot hold blocks is `InvalidParent`,\n * one that does not exist is `MissingNode`.\n */\n const containerPathOf = (\n parent: NodeId | undefined,\n ): { readonly path: BlockPath } | { readonly error: 'MissingNode' | 'InvalidParent' } => {\n if (parent === undefined) return { path: [] }\n const path = blockPaths.get(parent)\n if (path === undefined) return { error: 'MissingNode' }\n const block = blockAt(path)\n return block?.type === 'Node' && block.blocks !== undefined\n ? { path }\n : { error: 'InvalidParent' }\n }\n const materialize = (): void => {\n if (workingBlocks.size === 0 && workingRuns.size === 0) return\n // Runs fold into their block, then each container folds into its parent. A\n // container's copy already holds its child's final value, so the order of\n // the second pass does not matter; only touched containers are visited.\n for (const [key, runs] of workingRuns) {\n const path = keyToPath(key)\n const container = workingBlocks.get(pathKey(path.slice(0, -1)))!\n const index = path[path.length - 1]!\n container[index] = { ...container[index]!, children: runs }\n }\n workingRuns.clear()\n for (const [key, blocks] of workingBlocks) {\n const path = keyToPath(key)\n if (path.length === 0) {\n document = { ...document, children: blocks }\n continue\n }\n const parent = workingBlocks.get(pathKey(path.slice(0, -1)))!\n const index = path[path.length - 1]!\n const parentBlock = parent[index]!\n // Only a node block holds nested blocks, and only its path can be a\n // container, so this narrowing always holds.\n if (parentBlock.type === 'Node') parent[index] = { ...parentBlock, blocks }\n }\n workingBlocks.clear()\n }\n let selection = state.selection\n const dirtyNodes = new Set<NodeId>()\n const insertedNodes = new Set<NodeId>()\n const removedNodes = new Set<NodeId>()\n const textChanged = new Set<NodeId>()\n let structureChanged = false\n const positionMap: Array<PositionStep | SplitStep | RelocateStep | CollapseStep> = []\n /** `selectionIsValid` against the working document, read through the index this transaction keeps. */\n const selectionFits = (candidate: Selection | null): boolean => {\n if (candidate === null) return true\n if (candidate.type === 'Node')\n return blockPaths.has(candidate.node) || runPaths.has(candidate.node)\n return [candidate.anchor, candidate.focus].every(position => {\n const location = runPaths.get(position.node)\n const run = location === undefined ? undefined : runsAt(location.path)[location.index]\n // The offset's sign and integrality are the decoded transaction's already.\n return run !== undefined && position.offset <= run.text.length\n })\n }\n for (let operationIndex = 0; operationIndex < transaction.length; operationIndex++) {\n const operation = transaction[operationIndex]!\n if (operation.type === 'SetSelection') {\n // A pending edit could change what a position resolves against.\n materialize()\n if (!selectionFits(operation.selection)) {\n return { ok: false, error: 'InvalidSelection' }\n }\n selection = operation.selection\n continue\n }\n if (operation.type === 'SplitRun') {\n const location = runPaths.get(operation.node)\n if (location === undefined) return { ok: false, error: 'MissingText' }\n const { path, index: textIndex } = location\n const target = blockAt(path)\n if (target === undefined) return { ok: false, error: 'MissingText' }\n const run = runsAt(path)[textIndex]!\n if (operation.offset > run.text.length) return { ok: false, error: 'InvalidRange' }\n if (usedIds.has(operation.textId)) return { ok: false, error: 'InvalidInput' }\n if (operation.offset === 0) {\n // No left remainder: the new run would be an empty duplicate. Splitting\n // at 0 is the caller's no-op, not a silent identity change.\n continue\n }\n const children = runArray(path)\n children[textIndex] = { ...run, text: run.text.slice(0, operation.offset) }\n children.splice(textIndex + 1, 0, {\n ...run,\n id: operation.textId,\n text: run.text.slice(operation.offset),\n })\n usedIds.add(operation.textId)\n materialize()\n reindex()\n const relocate: SplitStep = {\n node: run.id,\n into: operation.textId,\n at: operation.offset,\n }\n positionMap.push(relocate)\n if (selection?.type === 'Range') {\n selection = {\n ...selection,\n anchor: mapPosition(selection.anchor, [relocate]),\n focus: mapPosition(selection.focus, [relocate]),\n }\n }\n dirtyNodes.add(target.id)\n dirtyNodes.add(run.id)\n dirtyNodes.add(operation.textId)\n textChanged.add(run.id)\n textChanged.add(operation.textId)\n insertedNodes.add(operation.textId)\n continue\n }\n if (operation.type === 'SplitNode') {\n materialize()\n const blockPath = blockPaths.get(operation.block)\n if (blockPath === undefined) return { ok: false, error: 'MissingNode' }\n const runLocation = runPaths.get(operation.node)\n if (runLocation === undefined) return { ok: false, error: 'MissingText' }\n const { path: runBlockPath, index: textIndex } = runLocation\n if (pathKey(runBlockPath) !== pathKey(blockPath)) return { ok: false, error: 'InvalidRange' }\n const target = blockAt(blockPath)!\n const run = target.children[textIndex]!\n if (operation.offset > run.text.length) return { ok: false, error: 'InvalidRange' }\n if (\n usedIds.has(operation.blockId) ||\n usedIds.has(operation.textId) ||\n operation.blockId === operation.textId\n ) {\n return { ok: false, error: 'InvalidInput' }\n }\n const leftBlock = {\n ...target,\n children: [\n ...target.children.slice(0, textIndex),\n { ...run, text: run.text.slice(0, operation.offset) },\n ],\n }\n const rightBlock = {\n ...target,\n id: operation.blockId,\n children: [\n { ...run, id: operation.textId, text: run.text.slice(operation.offset) },\n ...target.children.slice(textIndex + 1),\n ],\n }\n // The halves land in the block's own container, so a split inside a\n // container stays inside it.\n const containerPath = blockPath.slice(0, -1)\n const index = blockPath[blockPath.length - 1]!\n const container = ensureContainer(containerPath)\n container[index] = leftBlock\n container.splice(index + 1, 0, rightBlock)\n materialize()\n usedIds.add(operation.blockId)\n usedIds.add(operation.textId)\n reindex()\n const relocate: SplitStep = { node: run.id, into: operation.textId, at: operation.offset }\n positionMap.push(relocate)\n if (selection?.type === 'Range') {\n selection = {\n ...selection,\n anchor: mapPosition(selection.anchor, [relocate]),\n focus: mapPosition(selection.focus, [relocate]),\n }\n }\n dirtyNodes.add(target.id)\n dirtyNodes.add(operation.blockId)\n dirtyNodes.add(run.id)\n dirtyNodes.add(operation.textId)\n for (const moved of target.children.slice(textIndex + 1)) dirtyNodes.add(moved.id)\n textChanged.add(run.id)\n textChanged.add(operation.textId)\n insertedNodes.add(operation.blockId)\n insertedNodes.add(operation.textId)\n structureChanged = true\n continue\n }\n if (operation.type === 'JoinNode') {\n materialize()\n const intoPath = blockPaths.get(operation.into)\n if (intoPath === undefined) return { ok: false, error: 'MissingNode' }\n const removedPath = blockPaths.get(operation.removed)\n if (removedPath === undefined) return { ok: false, error: 'MissingNode' }\n // Siblings only: two blocks in different containers have no boundary\n // between them to remove.\n if (pathKey(intoPath.slice(0, -1)) !== pathKey(removedPath.slice(0, -1))) {\n return { ok: false, error: 'InvalidParent' }\n }\n const containerPath = intoPath.slice(0, -1)\n const intoIndex = intoPath[intoPath.length - 1]!\n const removedIndex = removedPath[removedPath.length - 1]!\n if (removedIndex !== intoIndex + 1) return { ok: false, error: 'InvalidRange' }\n const container = ensureContainer(containerPath)\n const survivor = container[intoIndex]!\n const removedBlocks: Array<Block> = []\n while (operationIndex < transaction.length) {\n const next = transaction[operationIndex]\n if (next?.type !== 'JoinNode' || next.into !== operation.into) break\n const removed = container[intoIndex + removedBlocks.length + 1]\n if (removed?.id !== next.removed) break\n // Opaque content cannot be merged without silently discarding it.\n if (survivor.type === 'Unknown' || removed.type === 'Unknown') {\n return { ok: false, error: 'InvalidRange' }\n }\n if (survivor.type === 'Node' || removed.type === 'Node') {\n if (\n survivor.type !== 'Node' ||\n removed.type !== 'Node' ||\n survivor.kind !== removed.kind ||\n !Equal.equals(survivor.props, removed.props)\n )\n return { ok: false, error: 'InvalidRange' }\n }\n // A container and a run holder merge differently: joining a list with a\n // paragraph would have to drop one side's shape.\n if ((nestedOf(survivor) === undefined) !== (nestedOf(removed) === undefined)) {\n return { ok: false, error: 'InvalidRange' }\n }\n removedBlocks.push(removed)\n operationIndex++\n }\n operationIndex--\n const mergedRuns = [...survivor.children, ...removedBlocks.flatMap(block => block.children)]\n if (survivor.type === 'Node' && survivor.blocks !== undefined) {\n container[intoIndex] = {\n ...survivor,\n children: mergedRuns,\n blocks: [...survivor.blocks, ...removedBlocks.flatMap(block => nestedOf(block) ?? [])],\n }\n } else {\n container[intoIndex] = { ...survivor, children: mergedRuns }\n }\n container.splice(removedIndex, removedBlocks.length)\n materialize()\n reindex()\n for (const removed of removedBlocks) {\n // A Node selection on a retired identity follows the survivor.\n if (selection?.type === 'Node' && selection.node === removed.id) {\n selection = { ...selection, node: operation.into }\n }\n }\n dirtyNodes.add(operation.into)\n for (const removed of removedBlocks) {\n dirtyNodes.add(removed.id)\n removedNodes.add(removed.id)\n for (const moved of removed.children) dirtyNodes.add(moved.id)\n }\n structureChanged = true\n continue\n }\n if (operation.type === 'MoveNode') {\n materialize()\n const fromPath = blockPaths.get(operation.node)\n if (fromPath === undefined) return { ok: false, error: 'MissingNode' }\n const target = containerPathOf(operation.parent)\n if ('error' in target) return { ok: false, error: target.error }\n // A block cannot hold itself: moving one into its own subtree would detach both.\n if (fromPath.every((index, depth) => target.path[depth] === index)) {\n return { ok: false, error: 'InvalidParent' }\n }\n const sourcePath = fromPath.slice(0, -1)\n const fromIndex = fromPath[fromPath.length - 1]!\n // A move within one container lands at an existing index; a move into\n // another can append, so its bound is that container's length.\n const sameContainer = pathKey(sourcePath) === pathKey(target.path)\n const limit = sameContainer ? blocksAt(target.path).length - 1 : blocksAt(target.path).length\n if (operation.to > limit) return { ok: false, error: 'InvalidRange' }\n if (sameContainer && operation.to === fromIndex) continue\n const source = ensureContainer(sourcePath)\n const [moved] = source.splice(fromIndex, 1)\n if (sameContainer) {\n source.splice(operation.to, 0, moved!)\n } else {\n // The removal is folded in and the destination found again before inserting: taking\n // the block out can shift the destination's path, and inserting can shift the\n // source's, so neither copy may be folded against the other's old indices.\n materialize()\n reindex()\n const destination = containerPathOf(operation.parent)\n if ('error' in destination) return { ok: false, error: destination.error }\n ensureContainer(destination.path).splice(operation.to, 0, moved!)\n }\n materialize()\n reindex()\n dirtyNodes.add(operation.node)\n structureChanged = true\n continue\n }\n if (operation.type === 'RetypeBlock') {\n const path = blockPaths.get(operation.node)\n if (path === undefined) return { ok: false, error: 'MissingNode' }\n const target = blockAt(path)\n const to = operation.to\n // Content keeps its shape: runs stay runs, and nested blocks stay nested, so a node\n // holding blocks retypes only to another node. Preserved content is never rewritten.\n const nested = target?.type === 'Node' && target.blocks !== undefined\n if (target === undefined || target.type === 'Unknown' || (nested && to.type !== 'Node')) {\n return { ok: false, error: 'InvalidRange' }\n }\n const already =\n to.type === 'Paragraph'\n ? target.type === 'Paragraph'\n : to.type === 'Heading'\n ? target.type === 'Heading' && target.level === to.level\n : target.type === 'Node' &&\n target.kind === to.kind &&\n Equal.equals(target.props, to.props)\n if (already) continue\n writeBlock(\n path,\n to.type === 'Paragraph'\n ? { type: 'Paragraph', id: target.id, children: target.children }\n : to.type === 'Heading'\n ? { type: 'Heading', id: target.id, level: to.level, children: target.children }\n : {\n type: 'Node',\n kind: to.kind,\n id: target.id,\n props: to.props,\n children: target.children,\n ...(nested ? { blocks: target.blocks } : {}),\n },\n )\n dirtyNodes.add(target.id)\n structureChanged = true\n continue\n }\n if (operation.type === 'SetProps') {\n const path = blockPaths.get(operation.node)\n if (path === undefined) return { ok: false, error: 'MissingNode' }\n const target = blockAt(path)\n // Only an application node has props; a text block's shape is its type.\n if (target?.type !== 'Node') return { ok: false, error: 'InvalidRange' }\n const props = { ...target.props, ...operation.props }\n if (Equal.equals(props, target.props)) continue\n writeBlock(path, { ...target, props })\n dirtyNodes.add(target.id)\n continue\n }\n if (operation.type === 'InsertNode') {\n const target = containerPathOf(operation.parent)\n if ('error' in target) return { ok: false, error: target.error }\n // A pending copy under a place the insert shifts would be folded back at the wrong\n // path. The container and its ancestors do not shift, so a run of inserts into one\n // container, as a paste is, keeps its copy rather than copying the list each time.\n const unshifted = new Set(\n Array.from({ length: target.path.length + 1 }, (_, depth) =>\n pathKey(target.path.slice(0, depth)),\n ),\n )\n if (workingRuns.size > 0 || [...workingBlocks.keys()].some(key => !unshifted.has(key))) {\n materialize()\n }\n if (operation.at > blocksAt(target.path).length) return { ok: false, error: 'InvalidRange' }\n const carried: Array<NodeId> = []\n eachBlock([operation.block], block => {\n carried.push(block.id)\n for (const run of block.children) carried.push(run.id)\n })\n if (new Set(carried).size !== carried.length || carried.some(id => usedIds.has(id))) {\n return { ok: false, error: 'InvalidInput' }\n }\n const container = ensureContainer(target.path)\n container.splice(operation.at, 0, operation.block)\n for (const id of carried) {\n usedIds.add(id)\n dirtyNodes.add(id)\n insertedNodes.add(id)\n }\n indexInserted(target.path, operation.at)\n structureChanged = true\n continue\n }\n if (operation.type === 'DeleteNode') {\n materialize()\n const path = blockPaths.get(operation.node)\n if (path === undefined) return { ok: false, error: 'MissingNode' }\n const containerPath = path.slice(0, -1)\n const index = path[path.length - 1]!\n const target = blockAt(path)!\n const container = ensureContainer(containerPath)\n container.splice(index, 1)\n materialize()\n reindex()\n // The nearest surviving run in document order — the first at or after the\n // removed block's place, else the last before it — or nothing, which\n // clears the selection. Walking the tree is what lets a delete beside a\n // container collapse into the container's own runs.\n const removedPlace = { path, index: 0 }\n let fallback: { readonly block: Block; readonly run: Text } | undefined\n let after: { readonly block: Block; readonly run: Text } | undefined\n eachBlock(document.children, (block, blockPath) => {\n for (const [runIndex, run] of block.children.entries()) {\n const place = { path: blockPath, index: runIndex }\n if (compareRunPlaces(place, removedPlace) >= 0) after ??= { block, run }\n else fallback = { block, run }\n }\n })\n const landing = after ?? fallback\n const collapses: Array<CollapseStep> = []\n const removedRuns: Array<NodeId> = []\n const collect = (block: Block): void => {\n for (const run of block.children) removedRuns.push(run.id)\n if (block.type === 'Node' && block.blocks !== undefined) block.blocks.forEach(collect)\n }\n collect(target)\n if (landing !== undefined) {\n for (const run of removedRuns) collapses.push({ node: run, into: landing.run.id })\n }\n if (selection?.type === 'Range') {\n selection =\n landing === undefined\n ? null\n : {\n ...selection,\n anchor: mapPosition(selection.anchor, collapses),\n focus: mapPosition(selection.focus, collapses),\n }\n } else if (selection?.type === 'Node') {\n const selectedNode = selection.node\n if (selectedNode === operation.node || removedRuns.includes(selectedNode)) {\n selection = landing === undefined ? null : { ...selection, node: landing.block.id }\n }\n }\n for (const step of collapses) positionMap.push(step)\n const removedIds: Array<NodeId> = []\n const collectIds = (block: Block): void => {\n removedIds.push(block.id, ...block.children.map(run => run.id))\n if (block.type === 'Node' && block.blocks !== undefined) block.blocks.forEach(collectIds)\n }\n collectIds(target)\n for (const id of removedIds) {\n dirtyNodes.add(id)\n removedNodes.add(id)\n }\n structureChanged = true\n continue\n }\n const id = operation.type === 'InsertText' ? operation.at.node : operation.node\n const location = runPaths.get(id)\n if (location === undefined) return { ok: false, error: 'MissingText' }\n const { path, index: textIndex } = location\n const block = blockAt(path)\n if (block === undefined) return { ok: false, error: 'MissingText' }\n const text = runsAt(path)[textIndex]!\n if (operation.type === 'AddMark') {\n // A run carries a mark name at most once, so adding is a *set*: append\n // when the name is absent, replace when its props differ, and no-op when\n // the mark is already exactly this one (which keeps state identity).\n const existing = text.marks.find(mark => markName(mark) === markName(operation.mark))\n if (existing !== undefined && sameMark(existing, operation.mark)) continue\n const children = runArray(path)\n children[textIndex] = {\n ...text,\n marks:\n existing === undefined\n ? [...text.marks, operation.mark]\n : text.marks.map(mark =>\n markName(mark) === markName(operation.mark) ? operation.mark : mark,\n ),\n }\n dirtyNodes.add(block.id)\n dirtyNodes.add(id)\n textChanged.add(id)\n continue\n }\n if (operation.type === 'RemoveMark') {\n if (!text.marks.some(mark => markName(mark) === operation.mark)) continue\n const children = runArray(path)\n children[textIndex] = {\n ...text,\n marks: text.marks.filter(mark => markName(mark) !== operation.mark),\n }\n dirtyNodes.add(block.id)\n dirtyNodes.add(id)\n textChanged.add(id)\n continue\n }\n const from = operation.type === 'InsertText' ? operation.at.offset : operation.from\n const to = operation.type === 'InsertText' ? from : operation.to\n const inserted = operation.type === 'InsertText' ? operation.text : ''\n if (from > to || to > text.text.length) return { ok: false, error: 'InvalidRange' }\n if (from === to && inserted.length === 0) continue\n const children = runArray(path)\n children[textIndex] = {\n ...text,\n text: text.text.slice(0, from) + inserted + text.text.slice(to),\n }\n const step = { node: id, from, to, inserted: inserted.length }\n positionMap.push(step)\n if (selection?.type === 'Range') {\n selection = {\n ...selection,\n anchor: mapPosition(selection.anchor, [step]),\n focus: mapPosition(selection.focus, [step]),\n }\n }\n dirtyNodes.add(block.id)\n dirtyNodes.add(id)\n textChanged.add(id)\n }\n // The op loop accumulates; the document is assembled once, here.\n materialize()\n // Normalization runs as transforms (§23): each is deterministic and idempotent\n // on normalized state, so the loop settles. The pass bound is a diagnostic,\n // not a hang: a transform that keeps changing the document is refused rather\n // than spinning.\n let pass = 0\n for (; pass < MAX_NORMALIZATION_PASSES; pass++) {\n let changed = false\n for (const transform of transforms) {\n const report = transform.apply(document, { dirtyNodes, pass })\n if (report.document === document) continue\n changed = true\n document = report.document\n for (const id of report.insertedNodes) insertedNodes.add(id)\n for (const id of report.removedNodes) removedNodes.add(id)\n for (const id of report.dirtyNodes) dirtyNodes.add(id)\n for (const id of report.textChanged) textChanged.add(id)\n for (const step of report.steps) positionMap.push(step)\n if (report.structureChanged) structureChanged = true\n if (report.steps.length > 0) selection = mapThrough(selection, report.steps)\n reindex()\n }\n if (!changed) break\n }\n if (pass === MAX_NORMALIZATION_PASSES) return { ok: false, error: 'UnstableNormalization' }\n return {\n ok: true,\n state:\n document === state.document && sameSelection(selection, state.selection)\n ? state\n : { document, selection },\n changeSet: {\n dirtyNodes,\n insertedNodes,\n removedNodes,\n textChanged,\n structureChanged,\n selectionChanged: !sameSelection(selection, state.selection),\n },\n positionMap,\n transactions: [transaction],\n }\n}\n","/**\n * Indentation in a kind whose lines are indented, as code's are (`node(…, { indents })`):\n * Tab indents, Shift+Tab outdents, and Enter starts the new line as indented as the one it\n * broke. A line is the text between two breaks of one block.\n */\nimport { positionInBlock, type Block, type EditorState, type Position } from './document.js'\nimport { Edit, apply, type Operation, type TransactionResult } from './transaction.js'\n\n/** What one level of indentation is: two spaces. */\nexport const INDENT = ' '\n\nconst textOf = (block: Block): string => block.children.map(run => run.text).join('')\n\n/** A position's offset into its block's whole text, or undefined when it is not the block's. */\nexport const offsetIn = (block: Block, position: Position): number | undefined => {\n let consumed = 0\n for (const run of block.children) {\n if (run.id === position.node) return consumed + position.offset\n consumed += run.text.length\n }\n return undefined\n}\n\nconst lineStart = (text: string, offset: number): number => text.lastIndexOf('\\n', offset - 1) + 1\n\n/** The leading spaces and tabs of the line `offset` is on, up to `offset`. */\nexport const indentationAt = (text: string, offset: number): string =>\n /^[ \\t]*/.exec(text.slice(lineStart(text, offset), offset))?.[0] ?? ''\n\n/**\n * The starts of the lines a range covers, last first, so editing each leaves the offsets of the\n * ones before it as they were. A line the range only reaches the start of is not covered.\n */\nconst linesCovered = (text: string, from: number, to: number): ReadonlyArray<number> => {\n const starts = [lineStart(text, from)]\n for (let at = text.indexOf('\\n', from); at !== -1 && at + 1 < to; at = text.indexOf('\\n', at + 1))\n starts.push(at + 1)\n return starts.reverse()\n}\n\n/** The selection's ends as offsets into the block's text, in order, or undefined. */\nconst span = (\n state: EditorState,\n block: Block,\n): { readonly from: number; readonly to: number } | undefined => {\n const selection = state.selection\n if (selection?.type !== 'Range') return undefined\n const anchor = offsetIn(block, selection.anchor)\n const focus = offsetIn(block, selection.focus)\n if (anchor === undefined || focus === undefined) return undefined\n return { from: Math.min(anchor, focus), to: Math.max(anchor, focus) }\n}\n\n/**\n * Tab: at a caret, a level of indentation where the caret is; over a range, a level at the start\n * of every line it covers, so a block of code moves right together.\n */\nexport const indent = (state: EditorState, block: Block): TransactionResult => {\n const ends = span(state, block)\n if (ends === undefined) return { ok: false, error: 'InvalidSelection' }\n const text = textOf(block)\n const at = (offset: number) => positionInBlock(block, offset)\n if (ends.from === ends.to) {\n const caret = at(ends.from)\n if (caret === undefined) return { ok: false, error: 'InvalidSelection' }\n // The caret goes after the indentation whichever side of the offset it leaned: a caret the\n // browser reports at a line's start leans `before`, and would stay in front of it.\n const after = {\n node: caret.node,\n offset: caret.offset + INDENT.length,\n affinity: 'after' as const,\n }\n return apply(state, [\n Edit.insertText(caret, INDENT),\n Edit.setSelection({ type: 'Range', anchor: after, focus: after }),\n ])\n }\n const operations: Array<Operation> = []\n for (const start of linesCovered(text, ends.from, ends.to)) {\n const position = at(start)\n if (position !== undefined) operations.push(Edit.insertText(position, INDENT))\n }\n return apply(state, operations)\n}\n\n/** Shift+Tab: up to a level of indentation off the start of every line the selection is on. */\nexport const outdent = (state: EditorState, block: Block): TransactionResult => {\n const ends = span(state, block)\n if (ends === undefined) return { ok: false, error: 'InvalidSelection' }\n const text = textOf(block)\n const starts =\n ends.from === ends.to ? [lineStart(text, ends.from)] : linesCovered(text, ends.from, ends.to)\n const operations: Array<Operation> = []\n for (const start of starts) {\n const leading = /^(?: {1,2}|\\t)/.exec(text.slice(start))?.[0].length ?? 0\n const from = positionInBlock(block, start)\n // An indentation split across runs is left alone: code runs carry no marks, so it is one.\n if (leading === 0 || from === undefined || from.offset + leading > runLength(block, from))\n continue\n operations.push(Edit.deleteText(from.node, from.offset, from.offset + leading))\n }\n return apply(state, operations)\n}\n\nconst runLength = (block: Block, position: Position): number =>\n block.children.find(run => run.id === position.node)?.text.length ?? 0\n","/**\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","/**\n * Footnotes: a reference in the text and a definition at the end of the document, tied by a\n * label. The reference is a mark on the run that shows the label, so it moves, splits and undoes\n * with the text; the definition is a block holding blocks, so its note is ordinary editable text.\n * Nothing else ties them: a definition no reference names, or a reference with no definition, is\n * what `footnotesOf` reports, not an invalid document.\n */\nimport { Schema } from 'effect'\nimport {\n blockContent,\n eachBlock,\n markName,\n rangeStart,\n type Block,\n type Document,\n type NodeId,\n type Selection,\n type Text,\n} from './document.js'\nimport { node } from './kit.js'\nimport { mark, markProps } from './marks.js'\n\nconst Label = Schema.Struct({ label: Schema.String })\n\n/** Where a footnote is referred to: the run showing its label carries this mark. */\nexport const FootnoteRef = mark('FootnoteRef', { Props: Label, expand: 'none' })\n\n/** A footnote's note, under the label its references carry. */\nexport const FootnoteDefinition = node('FootnoteDefinition', {\n Props: Label,\n children: blockContent,\n})\n\n/** One footnote: its label, its definition if there is one, and the runs that refer to it. */\nexport interface Footnote {\n readonly label: string\n readonly definition: NodeId | undefined\n /** The runs carrying its reference, in document order. */\n readonly references: ReadonlyArray<NodeId>\n /** The definition's text, one line per block. */\n readonly text: string\n}\n\nconst labelOf = (props: unknown): string | undefined => {\n if (typeof props !== 'object' || props === null || !('label' in props)) return undefined\n return typeof props.label === 'string' ? props.label : undefined\n}\n\n/** The label of the footnote a run refers to, if it carries a reference. */\nexport const referenceLabel = (run: Text): string | undefined => {\n const reference = run.marks.find(each => markName(each) === FootnoteRef.name)\n return reference === undefined ? undefined : labelOf(markProps(reference))\n}\n\nconst textOf = (blocks: ReadonlyArray<Block>): string => {\n const lines: Array<string> = []\n eachBlock(blocks, block => {\n if (block.children.length > 0) lines.push(block.children.map(run => run.text).join(''))\n })\n return lines.join('\\n')\n}\n\n/**\n * Every footnote, in the order its first reference appears; a definition nothing refers to comes\n * after them, in document order.\n */\nexport const footnotesOf = (document: Document): ReadonlyArray<Footnote> => {\n const references = new Map<string, Array<NodeId>>()\n const definitions = new Map<string, { node: NodeId; text: string }>()\n eachBlock(document.children, block => {\n if (block.type === 'Node' && block.kind === FootnoteDefinition.name) {\n const label = labelOf(block.props)\n if (label !== undefined && !definitions.has(label)) {\n definitions.set(label, { node: block.id, text: textOf(block.blocks ?? []) })\n }\n }\n for (const run of block.children) {\n const label = referenceLabel(run)\n if (label === undefined) continue\n const held = references.get(label)\n if (held === undefined) references.set(label, [run.id])\n else held.push(run.id)\n }\n })\n const labels = [...references.keys(), ...[...definitions.keys()].filter(l => !references.has(l))]\n return labels.map(label => ({\n label,\n definition: definitions.get(label)?.node,\n references: references.get(label) ?? [],\n text: definitions.get(label)?.text ?? '',\n }))\n}\n\n/**\n * The label of the footnote whose reference the selection starts in or right beside. A reference\n * is a character or two, and its mark does not extend, so a click on one usually leaves the caret\n * at its edge, in the run next to it; that caret counts as at the reference.\n */\nexport const footnoteAt = (document: Document, selection: Selection | null): string | undefined => {\n if (selection?.type !== 'Range') return undefined\n const start = rangeStart(document, selection)\n if (start === undefined) return undefined\n let found: string | undefined\n eachBlock(document.children, block => {\n const index = block.children.findIndex(each => each.id === start.node)\n if (index < 0) return\n const run = block.children[index]!\n let beside: Text | undefined\n if (start.offset === 0) beside = block.children[index - 1]\n else if (start.offset === run.text.length) beside = block.children[index + 1]\n found = referenceLabel(run) ?? (beside === undefined ? undefined : referenceLabel(beside))\n })\n return found\n}\n\n/** The smallest whole number no footnote uses as its label, as text: the next note's label. */\nexport const nextFootnoteLabel = (document: Document): string => {\n const used = new Set(footnotesOf(document).map(each => each.label))\n let n = 1\n while (used.has(String(n))) n++\n return String(n)\n}\n","/**\n * Editing a table as a grid: rows and columns added and removed beside the caret's cell, and the\n * caret moved from cell to cell, as Tab and Shift+Tab do. A table is the standard vocabulary's\n * `Table` of `TableRow`s of `TableCell`s, each cell holding blocks; a column is the cells at one\n * index across the rows, which may be ragged, so a column that a short row lacks is skipped\n * rather than refused. Each change is one transaction, so it is one undo step.\n */\nimport { withFreshIds } from './clipboard.js'\nimport {\n NodeId,\n blockAtPath,\n eachBlock,\n locateRun,\n rangeStart,\n type Block,\n type Document,\n type EditorState,\n type NodeBlock,\n type Selection,\n type Text,\n} from './document.js'\nimport { Edit, apply, type Operation, type TransactionResult } from './transaction.js'\n\n/** Where a caret stands in a table: the table, its row and the cell's index in that row. */\nexport interface TableAt {\n readonly table: NodeBlock\n readonly rows: ReadonlyArray<NodeBlock>\n readonly row: number\n readonly column: number\n}\n\nconst isKind = (block: Block | undefined, kind: string): block is NodeBlock =>\n block?.type === 'Node' && block.kind === kind\n\n/** The cells of a row, which are its nested blocks. */\nconst cellsOf = (row: NodeBlock): ReadonlyArray<Block> => row.blocks ?? []\n\n/**\n * The table cell the selection starts in, the innermost one when tables nest, or undefined\n * outside a table. A range is read from its start, as the other block commands read it.\n */\nexport const tableAt = (document: Document, selection: Selection | null): TableAt | undefined => {\n if (selection?.type !== 'Range') return undefined\n const start = rangeStart(document, selection)\n const run = start === undefined ? undefined : locateRun(document, start.node)\n if (run === undefined) return undefined\n // The cell is an ancestor of the caret's text block, its row the cell's parent, and the\n // table the row's: so the cell's path is at least three long.\n for (let depth = run.path.length - 1; depth >= 3; depth--) {\n const cell = blockAtPath(document, run.path.slice(0, depth))\n const row = blockAtPath(document, run.path.slice(0, depth - 1))\n const table = blockAtPath(document, run.path.slice(0, depth - 2))\n if (isKind(cell, 'TableCell') && isKind(row, 'TableRow') && isKind(table, 'Table')) {\n return {\n table,\n rows: (table.blocks ?? []).filter(\n (candidate): candidate is NodeBlock => candidate.type === 'Node',\n ),\n row: run.path[depth - 2]!,\n column: run.path[depth - 1]!,\n }\n }\n }\n return undefined\n}\n\n/** An empty cell, under placeholder identities a caller freshens. */\nconst emptyCell = (): Block => ({\n type: 'Node',\n kind: 'TableCell',\n id: NodeId.make('cell'),\n props: {},\n children: [],\n blocks: [\n {\n type: 'Paragraph',\n id: NodeId.make('paragraph'),\n children: [{ type: 'Text', id: NodeId.make('text'), text: '', marks: [] }],\n },\n ],\n})\n\nconst fresh = (block: Block, mint: () => string): Block =>\n withFreshIds({ version: 1, blocks: [block] }, mint).blocks[0]!\n\nconst firstRun = (block: Block | undefined): Text | undefined => {\n if (block === undefined) return undefined\n let found: Text | undefined\n eachBlock([block], inner => {\n found ??= inner.children[0]\n })\n return found\n}\n\n/** The selection at the start of a cell's first text, or the selection as it was. */\nconst caretIn = (cell: Block | undefined, otherwise: Selection | null): Selection | null => {\n const run = firstRun(cell)\n if (run === undefined) return otherwise\n const at = { node: run.id, offset: 0, affinity: 'after' as const }\n return { type: 'Range', anchor: at, focus: at }\n}\n\n/** A table edit, or that the edit would leave the table empty and it should be deleted whole. */\nexport type TableEdit = TransactionResult | { readonly deleteTable: NodeId }\n\n/** The widest row's cell count: what a new row is given so the grid stays as wide. */\nconst widthOf = (rows: ReadonlyArray<NodeBlock>): number =>\n Math.max(1, ...rows.map(row => cellsOf(row).length))\n\n/** A row as wide as the table, under fresh identities, and the operation that puts it there. */\nconst newRow = (at: TableAt, index: number, mint: () => string) => {\n const row = fresh(\n {\n type: 'Node',\n kind: 'TableRow',\n id: NodeId.make('row'),\n props: {},\n children: [],\n blocks: Array.from({ length: widthOf(at.rows) }, emptyCell),\n },\n mint,\n )\n return { row, operation: Edit.insertBlock(row, index, at.table.id) }\n}\n\n/** A row above or below the caret's, as wide as the table; the caret goes to it, same column. */\nexport const insertRow = (\n state: EditorState,\n at: TableAt,\n where: 'before' | 'after',\n mint: () => string,\n): TransactionResult => {\n const { row, operation } = newRow(at, at.row + (where === 'after' ? 1 : 0), mint)\n const cells = row.type === 'Node' ? (row.blocks ?? []) : []\n return apply(state, [\n operation,\n Edit.setSelection(caretIn(cells[Math.min(at.column, cells.length - 1)], state.selection)),\n ])\n}\n\n/**\n * A cell beside the caret's in every row, before or after it; a row too short to have that\n * column gets its cell at its end. The caret goes to the new cell in its own row.\n */\nexport const insertColumn = (\n state: EditorState,\n at: TableAt,\n where: 'before' | 'after',\n mint: () => string,\n): TransactionResult => {\n const index = at.column + (where === 'after' ? 1 : 0)\n let caretCell: Block | undefined\n const operations: Array<Operation> = at.rows.map((row, rowIndex) => {\n const cell = fresh(emptyCell(), mint)\n if (rowIndex === at.row) caretCell = cell\n return Edit.insertBlock(cell, Math.min(index, cellsOf(row).length), row.id)\n })\n return apply(state, [...operations, Edit.setSelection(caretIn(caretCell, state.selection))])\n}\n\n/** The caret's row, gone; the caret goes to the same column of the row after it, or before. */\nexport const deleteRow = (state: EditorState, at: TableAt): TableEdit => {\n if (at.rows.length === 1) return { deleteTable: at.table.id }\n const next = at.rows[at.row + 1] ?? at.rows[at.row - 1]!\n const cells = cellsOf(next)\n return apply(state, [\n Edit.deleteBlock(at.rows[at.row]!.id),\n Edit.setSelection(caretIn(cells[Math.min(at.column, cells.length - 1)], state.selection)),\n ])\n}\n\n/**\n * The caret's column, gone from every row that has it; a row it leaves empty goes too. The\n * caret goes to the cell that takes the column's place in its row, or the one before it.\n */\nexport const deleteColumn = (state: EditorState, at: TableAt): TableEdit => {\n if (at.rows.every(row => cellsOf(row).length <= 1)) return { deleteTable: at.table.id }\n const operations: Array<Operation> = []\n for (const row of at.rows) {\n const cells = cellsOf(row)\n const cell = cells[at.column]\n if (cell === undefined) continue\n operations.push(Edit.deleteBlock(cells.length === 1 ? row.id : cell.id))\n }\n const own = cellsOf(at.rows[at.row]!)\n const landing = own.length === 1 ? undefined : (own[at.column + 1] ?? own[at.column - 1])\n return apply(state, [\n ...operations,\n ...(landing === undefined ? [] : [Edit.setSelection(caretIn(landing, state.selection))]),\n ])\n}\n\n/**\n * The caret to the start of the next cell, across rows, or the previous one: Tab and Shift+Tab.\n * Tab in the last cell adds a row and goes to it; Shift+Tab in the first stays where it is.\n */\nexport const moveToCell = (\n state: EditorState,\n at: TableAt,\n direction: 'next' | 'previous',\n mint: () => string,\n): TransactionResult => {\n const order = at.rows.flatMap((row, rowIndex) =>\n cellsOf(row).map((cell, column) => ({ cell, rowIndex, column })),\n )\n const here = order.findIndex(entry => entry.rowIndex === at.row && entry.column === at.column)\n const target = order[here + (direction === 'next' ? 1 : -1)]\n if (target !== undefined) {\n return apply(state, [Edit.setSelection(caretIn(target.cell, state.selection))])\n }\n if (direction === 'previous') return apply(state, [])\n const { row, operation } = newRow(at, at.rows.length, mint)\n return apply(state, [operation, Edit.setSelection(caretIn(row, state.selection))])\n}\n","import { Equal, Match, Schema } from 'effect'\nimport {\n NodeId,\n blockAtPath,\n compareRunPlaces,\n eachBlock,\n positionInBlock,\n locateBlock,\n rangeStart,\n locateRun,\n pathKey,\n textContent,\n type Block,\n type BlockPath,\n type Document,\n type EditorState,\n type MarkValue,\n type Position,\n type RunMark,\n type Selection,\n type Text as Run,\n} from './document.js'\nimport { withFreshIds, type Slice } from './clipboard.js'\nimport { toText } from './html.js'\nimport {\n markName,\n edgeMarks,\n resolveInsertion,\n propsFailure,\n sameMark,\n shippedRegistry,\n type MarkRegistry,\n} from './marks.js'\nimport { blockKind, standsWithin, type NodeRegistry } from './kit.js'\nimport { indent, indentationAt, offsetIn, outdent } from './indent.js'\nimport { findMatches, type SearchMatch } from './search.js'\nimport {\n FootnoteDefinition,\n FootnoteRef,\n footnotesOf,\n nextFootnoteLabel,\n referenceLabel,\n} from './footnote.js'\nimport {\n deleteColumn,\n deleteRow,\n insertColumn,\n insertRow,\n moveToCell,\n tableAt,\n type TableEdit,\n} from './table.js'\nimport {\n Edit,\n apply,\n type ChangeSet,\n type Operation,\n type TextBlock,\n type TransactionResult,\n} from './transaction.js'\n\n/**\n * Editor intent: what the user is trying to do. Commands resolve against the\n * current document and selection into a Transaction of low-level operations, so\n * durable history keeps its meaning (§19). Identities a command needs come from\n * the caller's `mint`; nothing here reads a clock or a hidden counter.\n */\nexport type Command =\n | {\n readonly type: 'InsertText'\n readonly text: string\n /** Stored marks: a bare name, or a value when the mark carries props. */\n readonly marks?: ReadonlyArray<string | MarkValue>\n }\n | { readonly type: 'DeleteBackward' }\n | { readonly type: 'DeleteForward' }\n | { readonly type: 'SplitBlock' }\n | { readonly type: 'ToggleMark'; readonly mark: string | MarkValue }\n /**\n * Puts exactly this mark on every run the selection covers, replacing a same-named mark\n * whose props differ: how a link gets a new `href`. A caret acts on the extent of the\n * mark around it (`markExtent`), and does nothing outside one.\n */\n | { readonly type: 'SetMark'; readonly mark: string | MarkValue }\n /**\n * Takes the named mark off every run the selection covers; a caret, off its extent. Given a\n * mark value, only off the runs carrying exactly that value: one discussion's highlight,\n * leaving another's inside it.\n */\n | { readonly type: 'ClearMark'; readonly mark: string | MarkValue }\n | { readonly type: 'SetSelection'; readonly selection: Selection | null }\n | { readonly type: 'Paste'; readonly slice: Slice }\n /** Retypes the block the selection starts in: a paragraph, or a heading. */\n | { readonly type: 'RetypeBlock'; readonly to: TextBlock }\n /**\n * Wraps the block the selection starts in, in new containers listed outermost first: a\n * `Quote`, or a `List` holding a `ListItem`. The block keeps its identity and its runs,\n * so the caret stays where it was. Given a vocabulary, a list wrap right after a list of the\n * same kind and props adds the block to it as a new item.\n */\n | { readonly type: 'WrapBlock'; readonly containers: ReadonlyArray<Container> }\n /**\n * Retypes the text block the selection starts in to a node kind that holds text, such as a\n * `CodeBlock`. The block and its runs keep their identities, text, and marks.\n */\n | { readonly type: 'ConvertBlock'; readonly to: Container }\n /**\n * Retypes the container the selection starts in (the node block holding its block, such as\n * a list item) to another node kind, where it stands: its identity and every block it holds\n * are kept, so edits made inside it meanwhile survive. Only from the container's first block,\n * which is where a marker for the container is typed. Given a vocabulary, the new kind must\n * hold blocks, hold each block the container holds, and stand where the container does.\n */\n | { readonly type: 'RetypeContainer'; readonly to: Container }\n /**\n * Lifts the block the selection starts in out of its container, the inverse of a wrap:\n * repeated while the new parent's declaration refuses it, so a list item's paragraph leaves\n * both the item and the list. The block keeps its identity, and the caret with it.\n */\n | { readonly type: 'LiftBlock' }\n /**\n * Moves a block, and everything it holds, before or after another block, in its own container\n * or another one the vocabulary lets it stand in (§149). It addresses blocks rather than the\n * selection, so a handle or a key can move the block it stands for; identities are kept, and\n * the selection with them. A container the move leaves empty is deleted.\n */\n | { readonly type: 'MoveBlock'; readonly node: NodeId; readonly to: Beside }\n /**\n * Sets the named props of a node block, such as a task item's `checked`, keeping the rest.\n * It addresses the block by identity, as `MoveBlock` does, so a checkbox sends it for its\n * own item. Given a vocabulary, props that decode as the kind's must still decode after.\n */\n | { readonly type: 'SetProps'; readonly node: NodeId; readonly props: Schema.JsonObject }\n /**\n * Inserts a block, and everything it holds, before or after another block, under fresh\n * identities from `mint`: an image chosen from a file, a table from a menu, a copy of a block\n * for its handle's Duplicate. The caret goes to the start of its first text, when it has any.\n * Without `to` it goes beside the caret's block: before it when that block is empty, so a\n * slash command typed on a blank line puts its block there and the line stays to type on,\n * and after it otherwise.\n */\n | { readonly type: 'InsertBlock'; readonly block: Block; readonly to?: Beside | undefined }\n /**\n * Deletes a block and everything it holds, with any container that would be left empty by it,\n * as a block handle's Delete does. A caret inside it moves to the nearest text that stays; a\n * document left with no block gets an empty paragraph, so there is somewhere to type.\n */\n | { readonly type: 'DeleteBlock'; readonly node: NodeId }\n /**\n * A row above or below the caret's table cell, as wide as the table's widest row, with the caret\n * moved into it. The table is the standard vocabulary's (`Table`, `TableRow`, `TableCell`).\n */\n | { readonly type: 'InsertRow'; readonly where: 'before' | 'after' }\n /** A cell beside the caret's in every row, before or after it: a column. */\n | { readonly type: 'InsertColumn'; readonly where: 'before' | 'after' }\n /** The caret's row, deleted; the last one deletes the table. */\n | { readonly type: 'DeleteRow' }\n /** The caret's column, deleted from every row that has it; the last one deletes the table. */\n | { readonly type: 'DeleteColumn' }\n /**\n * Tab. In a kind declared `indents` (code), a level of indentation at the caret, or at the\n * start of every line a range covers; in a table cell, the caret to the next cell, adding a row\n * after the last. Refused anywhere else (`InvalidSelection`), so Tab can move focus there.\n */\n | { readonly type: 'Indent' }\n /** Shift+Tab: a level of indentation off each line in code; the previous cell in a table. */\n | { readonly type: 'Outdent' }\n /**\n * Find and replace: the match at index `at` of `query` (in document order, as `findMatches`\n * lists them), or every match when `at` is absent, becomes `replacement`, as one transaction.\n * Case does not count unless `caseSensitive`. The caret ends after the earliest replacement.\n */\n | {\n readonly type: 'Replace'\n readonly query: string\n readonly replacement: string\n readonly caseSensitive?: boolean | undefined\n readonly at?: number | undefined\n }\n /**\n * A footnote at the caret, or at the end of a range: a reference showing the next free label\n * (`nextFootnoteLabel`), and its definition after the last top-level block holding `text`, with\n * the caret at the definition's start, ready to write the note.\n */\n | { readonly type: 'InsertFootnote'; readonly text?: string | undefined }\n /**\n * A footnote's label, `from`, becomes `to`: on its definition, and on every reference, whose\n * text becomes `to` where it showed `from`. Refused (`InvalidInput`) when `to` is blank or\n * another footnote's, or when no footnote is labelled `from`.\n */\n | { readonly type: 'RenameFootnote'; readonly from: string; readonly to: string }\n\n/** Where `MoveBlock` puts a block: before or after a sibling, named by identity. */\nexport const Beside = Schema.Union([\n // Each shape refuses the other's key: `{ before, after }` would name two places.\n Schema.Struct({ before: NodeId, after: Schema.optionalKey(Schema.Never) }),\n Schema.Struct({ after: NodeId, before: Schema.optionalKey(Schema.Never) }),\n])\nexport type Beside = typeof Beside.Type\n\n/** A container a block is wrapped in: a node kind, and the props it starts with. */\nexport const Container = Schema.Struct({\n kind: Schema.NonEmptyString,\n props: Schema.optionalKey(Schema.JsonObject),\n})\nexport type Container = typeof Container.Type\n\n/** Caller-owned identity source. Live edits mint; replay applies transactions. */\nexport interface CommandIds {\n readonly mint: () => string\n}\n\n/** What a command needs beyond state and identity, such as a Kit's mark policy. */\nexport interface RunOptions {\n readonly marks?: MarkRegistry | undefined\n /** The node vocabulary, so an edit a constraint forbids is refused here (§125). */\n readonly nodes?: NodeRegistry | undefined\n}\n\n/**\n * Whether the block at a path is declared to carry no marks, in which case adding one\n * is refused at the command layer rather than reported only by `validate` (§125). A\n * preserved block is left alone: it has no declaration to read, and preserving it\n * matters more than forbidding a mark on it.\n */\nconst forbidsMarks = (\n document: Document,\n path: BlockPath,\n nodes: NodeRegistry | undefined,\n): boolean => {\n if (nodes === undefined) return false\n const block = blockAtPath(document, path)\n if (block === undefined || block.type === 'Unknown') return false\n return kindForbidsMarks(nodes, blockKind(block))\n}\n\nconst kindForbidsMarks = (nodes: NodeRegistry, kind: string): boolean => {\n const declared = nodes.definitionFor(kind)\n return declared?.kind === 'node' && declared.marks === 'none'\n}\n\n/**\n * Whether the block at a path accepts a child of this kind. A declaration without a\n * constraint accepts any block, and a vocabulary that does not declare the parent is\n * not consulted — `validate` reports an undeclared kind, and an edit should not fail\n * for a reason the caller never stated.\n */\nconst acceptsChild = (\n document: Document,\n path: BlockPath,\n kind: string,\n nodes: NodeRegistry | undefined,\n): boolean => {\n const parent = blockAtPath(document, path)\n return parent === undefined || kindAccepts(nodes, blockKind(parent), kind)\n}\n\n/** Whether a kind's declaration lets it hold another as a nested block; undeclared is open. */\nconst kindAccepts = (\n nodes: NodeRegistry | undefined,\n parentKind: string,\n childKind: string,\n): boolean => {\n if (nodes === undefined) return true\n const declared = nodes.definitionFor(parentKind)\n if (declared?.kind !== 'node' || typeof declared.children === 'string') return true\n return declared.children.of.includes(childKind)\n}\n\n/** Whether the vocabulary declares props for a new node that these do not decode as. */\nconst refusesProps = (nodes: NodeRegistry | undefined, container: Container): boolean => {\n const declared = nodes?.definitionFor(container.kind)\n return (\n declared !== undefined &&\n declared.kind !== 'block' &&\n propsFailure(declared.props, container.props ?? {})\n )\n}\n\n/** Whether the vocabulary declares `kind` as a node that holds runs, as `CodeBlock` is. */\nconst declaresText = (nodes: NodeRegistry | undefined, kind: string): boolean => {\n const declared = nodes?.definitionFor(kind)\n return declared?.kind === 'node' && declared.children === textContent\n}\n\n/**\n * Whether a block is an atom, holding neither text nor blocks, as an image is. Without a\n * vocabulary, a node with nothing in it is one.\n */\nexport const isAtom = (nodes: NodeRegistry | undefined, block: Block): boolean => {\n if (block.type !== 'Node') return false\n const declared = nodes?.definitionFor(block.kind)\n return declared === undefined\n ? block.blocks === undefined && block.children.length === 0\n : declared.kind === 'atom'\n}\n\n/** Whether the vocabulary names `itemKind` among the kinds `listKind` holds, as `List` names `ListItem`. */\nconst holdsItem = (nodes: NodeRegistry, listKind: string, itemKind: string): boolean => {\n const declared = nodes.definitionFor(listKind)\n return (\n declared?.kind === 'node' &&\n typeof declared.children !== 'string' &&\n declared.children.of.includes(itemKind)\n )\n}\n\n/**\n * Whether a kind can be a new container. Unlike an existing parent, a kind a wrap creates\n * must be declared as holding nested blocks when there is a vocabulary: wrapping in an\n * undeclared kind, or a text kind such as `CodeBlock`, would make content `validate`\n * refuses.\n */\nconst holdsBlocks = (nodes: NodeRegistry | undefined, kind: string): boolean => {\n if (nodes === undefined) return true\n const declared = nodes.definitionFor(kind)\n return declared?.kind === 'node' && declared.children !== textContent\n}\n\ntype Failure =\n | 'InvalidSelection'\n | 'MissingText'\n | 'InvalidInput'\n | 'InvalidParent'\n | 'ForbiddenMark'\n | 'UnexpectedChild'\nconst failure = (error: Failure): TransactionResult => ({ ok: false, error })\n\ninterface Located {\n readonly path: BlockPath\n readonly runIndex: number\n readonly blockId: NodeId\n readonly id: NodeId\n readonly text: string\n readonly marks: ReadonlyArray<RunMark>\n}\n\n/** Document order over a located run, by the shared place rule. */\nconst locatedOrder = (\n left: { readonly path: BlockPath; readonly runIndex: number },\n right: { readonly path: BlockPath; readonly runIndex: number },\n): number =>\n compareRunPlaces(\n { path: left.path, index: left.runIndex },\n { path: right.path, index: right.runIndex },\n )\n\nconst locate = (document: Document, node: NodeId): Located | undefined => {\n const found = locateRun(document, node)\n if (found === undefined) return undefined\n const block = blockAtPath(document, found.path)\n if (block === undefined) return undefined\n return {\n path: found.path,\n runIndex: found.index,\n blockId: block.id,\n id: found.run.id,\n text: found.run.text,\n marks: found.run.marks,\n }\n}\n\nconst isCollapsed = (selection: Extract<Selection, { readonly type: 'Range' }>): boolean =>\n selection.anchor.node === selection.focus.node &&\n selection.anchor.offset === selection.focus.offset\n\n/** Whether a selection covers text: a range that is not a caret. What a mark or a link applies to. */\nexport const coversText = (selection: Selection | null): boolean =>\n selection?.type === 'Range' && !isCollapsed(selection)\n\n/** A caret is a range whose endpoints coincide; direction is not yet meaningful. */\nconst caretAt = (position: Position): Selection => ({\n type: 'Range',\n anchor: position,\n focus: position,\n})\n\n/** Orders a range's endpoints by document order without losing direction. */\nconst ordered = (\n document: Document,\n selection: Extract<Selection, { readonly type: 'Range' }>,\n): { readonly start: Position; readonly end: Position } | undefined => {\n const anchor = locate(document, selection.anchor.node)\n const focus = locate(document, selection.focus.node)\n if (anchor === undefined || focus === undefined) return undefined\n const byPlace = locatedOrder(anchor, focus)\n const after = byPlace !== 0 ? byPlace > 0 : selection.anchor.offset > selection.focus.offset\n return after\n ? { start: selection.focus, end: selection.anchor }\n : { start: selection.anchor, end: selection.focus }\n}\n\ninterface Span {\n readonly run: Located\n readonly from: number\n readonly to: number\n}\n\n/** Runs intersecting an ordered [start, end), with the covered sub-range. */\nconst covered = (document: Document, start: Position, end: Position): ReadonlyArray<Span> => {\n const startAt = locate(document, start.node)\n const endAt = locate(document, end.node)\n if (startAt === undefined || endAt === undefined) return []\n const spans: Array<Span> = []\n // The walk is document order, so comparing each run's place against the\n // endpoints' places picks out the covered span however deep it sits.\n eachBlock(document.children, (block, path) => {\n for (const [runIndex, run] of block.children.entries()) {\n const place = { path, runIndex }\n if (locatedOrder(place, startAt) < 0 || locatedOrder(place, endAt) > 0) continue\n const from = locatedOrder(place, startAt) === 0 ? start.offset : 0\n const to = locatedOrder(place, endAt) === 0 ? end.offset : run.text.length\n if (from >= to) continue\n spans.push({\n run: {\n path,\n runIndex,\n blockId: block.id,\n id: run.id,\n text: run.text,\n marks: run.marks,\n },\n from,\n to,\n })\n }\n })\n return spans\n}\n\n/** Marks every run in the list carries; empty when there are no runs. */\nconst sharedMarks = (runs: ReadonlyArray<ReadonlyArray<RunMark>>): ReadonlySet<string> => {\n let common: Set<string> | undefined\n for (const marks of runs) {\n const names = new Set(marks.map(markName))\n if (common === undefined) {\n common = names\n continue\n }\n for (const name of common) if (!names.has(name)) common.delete(name)\n }\n return common ?? new Set()\n}\n\n/**\n * The marks every run the selection covers carries: the ones a toggle would\n * remove, which is what an \"active\" toolbar button means. A caret reports its\n * run's marks — an empty run can carry them, which is how a caret holds a format\n * — and a range is not bold when it straddles a bold run and a plain one. A node\n * selection reports what its whole subtree agrees on. A read, not a command:\n * nothing here changes anything.\n */\nexport const marksInRange = (\n document: Document,\n selection: Selection | null,\n): ReadonlySet<string> => {\n if (selection === null) return new Set()\n if (selection.type === 'Node') {\n const found = locateBlock(document, selection.node)\n if (found === undefined) return new Set()\n const runs: Array<ReadonlyArray<RunMark>> = []\n eachBlock([found.block], each => {\n for (const run of each.children) runs.push(run.marks)\n })\n return sharedMarks(runs)\n }\n const bounds = ordered(document, selection)\n if (bounds === undefined) return new Set()\n if (isCollapsed(selection)) {\n const caret = locate(document, selection.anchor.node)\n return caret === undefined ? new Set() : sharedMarks([caret.marks])\n }\n return sharedMarks(covered(document, bounds.start, bounds.end).map(span => span.run.marks))\n}\n\n/** A mark around a caret, and the range of runs it spans. */\nexport interface MarkExtent {\n readonly mark: RunMark\n readonly selection: Extract<Selection, { readonly type: 'Range' }>\n}\n\n/**\n * The named mark on the run a position is in, and the adjacent runs of its block carrying\n * the same mark with the same props: the whole link a caret sits in, which is what a link\n * editor shows and what `SetMark` and `ClearMark` act on at a caret. Undefined when that\n * run does not carry the mark. A read, like `marksInRange`.\n */\nexport const markExtent = (\n document: Document,\n position: Position,\n name: string,\n): MarkExtent | undefined => {\n const found = locateRun(document, position.node)\n const mark = found?.run.marks.find(held => markName(held) === name)\n if (found === undefined || mark === undefined) return undefined\n const runs = blockAtPath(document, found.path)!.children\n const carries = (index: number) => runs[index]?.marks.some(held => sameMark(held, mark)) === true\n let first = found.index\n while (carries(first - 1)) first--\n let last = found.index\n while (carries(last + 1)) last++\n const end = runs[last]!\n return {\n mark,\n selection: {\n type: 'Range',\n anchor: { node: runs[first]!.id, offset: 0, affinity: 'after' },\n focus: { node: end.id, offset: end.text.length, affinity: 'before' },\n },\n }\n}\n\n/**\n * The text style of the block a selection starts in, in the shape `RetypeBlock` takes, so a\n * style picker compares what it would send with what is there. Undefined for a node\n * selection, one that resolves to nothing, or a block a retype does not reach, such as a code\n * block.\n */\nexport const textBlockAt = (\n document: Document,\n selection: Selection | null,\n): TextBlock | undefined => {\n if (selection?.type !== 'Range') return undefined\n const path = startPath(document, selection)\n const block = path === undefined ? undefined : blockAtPath(document, path)\n if (block?.type === 'Paragraph') return { type: 'Paragraph' }\n if (block?.type === 'Heading') return { type: 'Heading', level: block.level }\n return undefined\n}\n\n/**\n * Why block `moving` may not move into the container at `container` (§149), or undefined when\n * it may. Within its own container it always may. Elsewhere, the container must hold its kind,\n * the kind must stand in the container's kind (a `ListItem` only in a `List`), it may not leave\n * a container declared isolating, and it may not go inside itself.\n */\nconst moveFailure = (\n document: Document,\n moving: { readonly path: BlockPath; readonly block: Block },\n container: BlockPath,\n nodes: NodeRegistry | undefined,\n): Failure | undefined => {\n if (moving.path.every((index, depth) => container[depth] === index)) return 'InvalidParent'\n const source = moving.path.slice(0, -1)\n if (pathKey(source) === pathKey(container)) return undefined\n const kind = blockKind(moving.block)\n const parent = container.length === 0 ? undefined : blockAtPath(document, container)\n if (\n !acceptsChild(document, container, kind, nodes) ||\n !standsWithin(nodes?.definitionFor(kind), parent === undefined ? undefined : blockKind(parent))\n ) {\n return 'UnexpectedChild'\n }\n for (let depth = source.length; depth > 0; depth--) {\n const holder = source.slice(0, depth)\n const inside = holder.every((index, at) => container[at] === index)\n if (!inside && isIsolating(document, holder, nodes)) return 'InvalidParent'\n }\n return undefined\n}\n\nconst isIsolating = (document: Document, path: BlockPath, nodes: NodeRegistry | undefined) => {\n const block = blockAtPath(document, path)\n const declared = block === undefined ? undefined : nodes?.definitionFor(blockKind(block))\n return declared?.kind === 'node' && declared.isolating === true\n}\n\n/**\n * The outermost container a block leaving `source` empties, walking up while each held nothing\n * else: a list whose only item's only block moved out goes with it. Never the container it lands\n * in, or one holding that. An isolating one is never reached, since a move may not leave it.\n */\nconst emptiedBy = (\n document: Document,\n source: BlockPath,\n container: BlockPath,\n): NodeId | undefined => {\n let emptied: NodeId | undefined\n for (let path = source; path.length > 0; path = path.slice(0, -1)) {\n const block = blockAtPath(document, path)\n const holdsTarget = path.every((index, depth) => container[depth] === index)\n if (block?.type !== 'Node' || (block.blocks?.length ?? 0) > 1 || holdsTarget) break\n emptied = block.id\n }\n return emptied\n}\n\n/**\n * The blocks `node` may move beside, in document order (§149): the blocks of every container it\n * may move into, which is what a drag offers. Empty when the document does not hold it.\n */\nexport const moveTargets = (\n document: Document,\n node: NodeId,\n nodes?: NodeRegistry,\n): ReadonlyArray<NodeId> => {\n const moving = locateBlock(document, node)\n if (moving === undefined) return []\n const targets: Array<NodeId> = []\n eachBlock(document.children, (block, path) => {\n if (moveFailure(document, moving, path.slice(0, -1), nodes) === undefined)\n targets.push(block.id)\n })\n return targets\n}\n\n/** Where a selection starts: its first run's block, or the block a node selection names. */\nconst startPath = (document: Document, selection: Selection | null): BlockPath | undefined => {\n if (selection === null) return undefined\n if (selection.type === 'Node') return locateBlock(document, selection.node)?.path\n const start = ordered(document, selection)?.start\n return start === undefined ? undefined : locateRun(document, start.node)?.path\n}\n\n/**\n * The blocks a selection starts in, outermost first: a caret in a list item's paragraph gives\n * the list, the item, and the paragraph. What a block handle picks from, and a breadcrumb draws.\n * Empty when the selection is null or resolves to nothing.\n */\nexport const blocksAt = (document: Document, selection: Selection | null): ReadonlyArray<Block> => {\n const path = startPath(document, selection) ?? []\n return path.map((_, depth) => blockAtPath(document, path.slice(0, depth + 1))!)\n}\n\n/** Whether `prefix` is a path to one of the blocks `path` lies inside, or `path` itself. */\nconst startsWith = (path: BlockPath, prefix: BlockPath): boolean =>\n prefix.length <= path.length && prefix.every((index, at) => path[at] === index)\n\n/** Document order of two block paths: a container comes before what it holds. */\nconst pathOrder = (left: BlockPath, right: BlockPath): number => {\n for (let at = 0; at < Math.min(left.length, right.length); at++) {\n if (left[at] !== right[at]) return left[at]! - right[at]!\n }\n return left.length - right.length\n}\n\n/** Whether two blocks can be joined into one: what `JoinNode` accepts. */\nconst joinable = (survivor: Block, removed: Block): boolean => {\n if (survivor.type === 'Unknown' || removed.type === 'Unknown') return false\n if (nestedBlocks(survivor) !== undefined || nestedBlocks(removed) !== undefined) return false\n if (survivor.type !== 'Node' && removed.type !== 'Node') return true\n return (\n survivor.type === 'Node' &&\n removed.type === 'Node' &&\n survivor.kind === removed.kind &&\n Equal.equals(survivor.props, removed.props)\n )\n}\n\nconst nestedBlocks = (block: Block): ReadonlyArray<Block> | undefined =>\n block.type === 'Node' && block.blocks !== undefined ? block.blocks : undefined\n\n/** Whether going from one block to another leaves an isolating container, as a table cell is. */\nconst crossesIsolating = (\n document: Document,\n from: BlockPath,\n to: BlockPath,\n nodes: NodeRegistry | undefined,\n): boolean =>\n [from, to].some((path, side) => {\n const other = side === 0 ? to : from\n for (let depth = 1; depth < path.length; depth++) {\n const container = path.slice(0, depth)\n if (startsWith(other, container)) continue\n const block = blockAtPath(document, container)\n const declared = block?.type === 'Node' ? nodes?.definitionFor(block.kind) : undefined\n if (declared?.kind === 'node' && declared.isolating === true) return true\n }\n return false\n })\n\n/** The innermost first or last block inside the block at `path`: itself when it holds none. */\nconst edgeLeaf = (document: Document, path: BlockPath, last: boolean): BlockPath => {\n let at = path\n for (;;) {\n const held = nestedBlocks(blockAtPath(document, at)!)\n if (held === undefined || held.length === 0) return at\n at = [...at, last ? held.length - 1 : 0]\n }\n}\n\n/** The first block after the one at `path` that holds no blocks, in document order. */\nconst nextLeaf = (document: Document, path: BlockPath): BlockPath | undefined => {\n let found: BlockPath | undefined\n eachBlock(document.children, (block, at) => {\n if (found !== undefined || pathOrder(at, path) <= 0 || startsWith(path, at)) return\n if ((nestedBlocks(block) ?? []).length === 0) found = at\n })\n return found\n}\n\n/** One result followed by another, as one: what `runAction` does for two commands. */\nconst followedBy = (first: TransactionResult, second: TransactionResult): TransactionResult =>\n !first.ok || !second.ok\n ? second.ok\n ? first\n : second\n : {\n ok: true,\n state: second.state,\n changeSet: unionChangeSet(first.changeSet, second.changeSet),\n positionMap: [...first.positionMap, ...second.positionMap],\n transactions: [...first.transactions, ...second.transactions],\n }\n\n/**\n * Deletes a range that leaves its container, as selecting from one kind of block into another\n * (or everything) and pressing Delete does: the text after `start` in its block and before\n * `end` in its block goes, every block wholly between them goes, and the block `end` is in\n * comes up beside the one `start` is in, joining it when the two can be one. A container it\n * leaves empty goes too. A range that leaves a table cell (an isolating container) only loses\n * its text: the cells stay, as a table's structure is not a selection's to remove. The caret\n * ends at `start`.\n */\nconst clearRange = (\n state: EditorState,\n start: Position,\n end: Position,\n options: RunOptions,\n): TransactionResult => {\n const document = state.document\n const startAt = locate(document, start.node)\n const endAt = locate(document, end.node)\n if (startAt === undefined || endAt === undefined) return failure('MissingText')\n const startPath = startAt.path\n const endPath = endAt.path\n const spans = covered(document, start, end)\n if (crossesIsolating(document, startPath, endPath, options.nodes)) {\n return apply(state, [\n ...spans.map(span => Edit.deleteText(span.run.id, span.from, span.to)),\n Edit.setSelection(caretAt(start)),\n ])\n }\n // The ends lose what the range covers of them; everything between them goes whole.\n const ends = spans.filter(\n span =>\n pathKey(span.run.path) === pathKey(startPath) || pathKey(span.run.path) === pathKey(endPath),\n )\n const between: Array<{ readonly id: NodeId; readonly path: BlockPath }> = []\n eachBlock(document.children, (block, path) => {\n if (pathOrder(path, startPath) <= 0 || pathOrder(path, endPath) >= 0) return\n if (startsWith(endPath, path) || startsWith(startPath, path)) return\n if (between.some(outer => startsWith(path, outer.path))) return\n between.push({ id: block.id, path })\n })\n const first = apply(state, [\n ...ends.map(span => Edit.deleteText(span.run.id, span.from, span.to)),\n ...between.map(block => Edit.deleteBlock(block.id)),\n Edit.setSelection(caretAt(start)),\n ])\n if (!first.ok) return first\n // Bring the end block beside the start one, join them if they can be one, and take away\n // the containers the move left empty.\n const startBlock = blockAtPath(document, startPath)!\n const endBlock = blockAtPath(document, endPath)!\n const now = first.state.document\n const survivorAt = locateBlock(now, startBlock.id)\n const removedAt = locateBlock(now, endBlock.id)\n if (survivorAt === undefined || removedAt === undefined) return first\n const operations: Array<Operation> = []\n const parentPath = survivorAt.path.slice(0, -1)\n const parent = parentPath.length === 0 ? undefined : blockAtPath(now, parentPath)\n const index = survivorAt.path[survivorAt.path.length - 1]!\n const siblings = pathKey(removedAt.path.slice(0, -1)) === pathKey(parentPath)\n // It comes up only where its kind may stand: a list holds items, not a paragraph.\n if (\n !siblings &&\n parentPath.length > 0 &&\n !acceptsChild(now, parentPath, blockKind(removedAt.block), options.nodes)\n ) {\n return first\n }\n if (!siblings) operations.push(Edit.moveBlock(endBlock.id, index + 1, parent?.id))\n const adjacent = siblings ? removedAt.path[removedAt.path.length - 1] === index + 1 : true\n if (adjacent && joinable(survivorAt.block, removedAt.block)) {\n operations.push(Edit.joinBlocks(startBlock.id, endBlock.id))\n }\n if (!siblings) {\n // Each container the end block was in, innermost first, goes when nothing else is left in it.\n for (let depth = removedAt.path.length - 1; depth > 0; depth--) {\n const container = blockAtPath(now, removedAt.path.slice(0, depth))\n if (container === undefined || startsWith(survivorAt.path, removedAt.path.slice(0, depth))) {\n break\n }\n // It held the end block, or the container holding it, and is empty once that goes.\n if ((nestedBlocks(container) ?? []).length > 1) break\n operations.push(Edit.deleteBlock(container.id))\n }\n }\n if (operations.length === 0) return first\n return followedBy(first, apply(first.state, [...operations, Edit.setSelection(caretAt(start))]))\n}\n\n/** The last run in a block's subtree, or undefined when it holds none. */\nconst lastRunOf = (block: Block): Run | undefined => {\n if (block.type === 'Node' && block.blocks !== undefined) {\n for (let index = block.blocks.length - 1; index >= 0; index--) {\n const found = lastRunOf(block.blocks[index]!)\n if (found !== undefined) return found\n }\n }\n return block.children[block.children.length - 1]\n}\n\n/** The block list a path lives in: the document's, or a container's nested blocks. */\nconst containerBlocks = (document: Document, containerPath: BlockPath): ReadonlyArray<Block> => {\n if (containerPath.length === 0) return document.children\n const container = blockAtPath(document, containerPath)\n return container?.type === 'Node' && container.blocks !== undefined ? container.blocks : []\n}\n\n/**\n * Deletes an ordered [start, end): one operation per covered run, then the\n * blocks the range spanned are joined, so selecting across a paragraph boundary\n * and deleting removes the boundary too. The first block survives, which is\n * where the caret already is. Returns undefined when the range needs a join this\n * version cannot express — one across containers, which has no boundary to\n * remove — so the caller refuses rather than deleting half of what was selected.\n */\nconst deleteRange = (\n document: Document,\n start: Position,\n end: Position,\n): ReadonlyArray<Operation> | undefined => {\n const startAt = locate(document, start.node)\n const endAt = locate(document, end.node)\n const deletions: Array<Operation> = covered(document, start, end).map(span =>\n Edit.deleteText(span.run.id, span.from, span.to),\n )\n if (startAt === undefined || endAt === undefined) return deletions\n // Within one block there is no boundary to remove.\n if (pathKey(startAt.path) === pathKey(endAt.path)) return deletions\n const containerPath = startAt.path.slice(0, -1)\n // The boundary only exists between siblings; a range that leaves its container\n // needs a merge this version does not define.\n if (pathKey(containerPath) !== pathKey(endAt.path.slice(0, -1))) return undefined\n const blocks = containerBlocks(document, containerPath)\n const from = startAt.path[startAt.path.length - 1]!\n const to = endAt.path[endAt.path.length - 1]!\n const survivor = blocks[from]!\n for (let index = from + 1; index <= to; index++) {\n const block = blocks[index]\n if (block === undefined) continue\n // A block between that cannot be one with the first (an image, a table, a list) is for\n // `clearRange`, which removes it rather than joining it.\n if (!joinable(survivor, block)) return undefined\n deletions.push(Edit.joinBlocks(survivor.id, block.id))\n }\n return deletions\n}\n\nconst segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\n\n/** A caret uses UTF-16 offsets, while a deletion removes a whole grapheme. */\nconst graphemeDeletion = (\n block: Block,\n caret: Position,\n runIndex: number,\n backward: boolean,\n): { operations: ReadonlyArray<Operation>; caret: Position } | undefined => {\n const starts: Array<number> = []\n let length = 0\n for (const run of block.children) {\n starts.push(length)\n length += run.text.length\n }\n const at = starts[runIndex]! + caret.offset\n if (backward ? at === 0 : at === length) return undefined\n const text = block.children.map(run => run.text).join('')\n let from = 0\n let to = 0\n for (const segment of segmenter.segment(text)) {\n const end = segment.index + segment.segment.length\n if (backward ? end >= at : end > at) {\n from = segment.index\n to = end\n break\n }\n }\n const operations: Array<Operation> = []\n let graphemeStart: Position | undefined\n for (const [index, run] of block.children.entries()) {\n const start = starts[index]!\n const localFrom = Math.max(0, from - start)\n const localTo = Math.min(run.text.length, to - start)\n if (localFrom >= localTo) continue\n graphemeStart ??= { node: run.id, offset: localFrom, affinity: 'after' }\n operations.push(Edit.deleteText(run.id, localFrom, localTo))\n }\n if (graphemeStart === undefined) return undefined\n // A backward deletion removes what is to the caret's left, so the caret lands\n // where the grapheme began; a forward one removes to its right, and the caret\n // already sits at the surviving boundary.\n return { operations, caret: backward ? graphemeStart : caret }\n}\n\n/**\n * The operations that lift a block out of its container, or `undefined` when it is at the\n * top level with nothing to leave. One step moves it into the container's parent: before\n * the container when it was first, after it when it was last, and between the two halves\n * of a split container when it was in the middle. A container it leaves empty is deleted.\n * Steps repeat while the vocabulary says the new parent does not hold the block's kind;\n * without a vocabulary, one step is taken. A container the vocabulary declares isolating is\n * never left, so a lift that would start by leaving one lifts nothing.\n *\n * Each step is computed against the document the steps before it produced, applied with no\n * normalization, because a split or a deletion moves the indices the next step reads.\n */\nconst liftOperations = (\n document: Document,\n node: NodeId,\n ids: CommandIds,\n nodes: NodeRegistry | undefined,\n): ReadonlyArray<Operation> | undefined => {\n const operations: Array<Operation> = []\n let current = document\n for (;;) {\n const found = locateBlock(current, node)\n if (found === undefined || found.path.length === 1) break\n const containerPath = found.path.slice(0, -1)\n const container = blockAtPath(current, containerPath)\n if (container?.type !== 'Node' || container.blocks === undefined) break\n const declared = nodes?.definitionFor(container.kind)\n if (declared?.kind === 'node' && declared.isolating === true) break\n const parentPath = containerPath.slice(0, -1)\n const parent = parentPath.length === 0 ? undefined : blockAtPath(current, parentPath)\n const at = containerPath[containerPath.length - 1]!\n const index = found.path[found.path.length - 1]!\n const siblings = container.blocks\n const step: Array<Operation> = []\n if (index === 0) {\n step.push(Edit.moveBlock(node, at, parent?.id))\n if (siblings.length === 1) step.push(Edit.deleteBlock(container.id))\n } else if (index === siblings.length - 1) {\n step.push(Edit.moveBlock(node, at + 1, parent?.id))\n } else {\n // The blocks after it go into a second container of the same kind, so the list or\n // quote continues on the far side of the lifted block.\n const rest = NodeId.make(ids.mint())\n step.push(\n Edit.insertBlock({ ...container, id: rest, children: [], blocks: [] }, at + 1, parent?.id),\n ...siblings\n .slice(index + 1)\n .map((sibling, offset) => Edit.moveBlock(sibling.id, offset, rest)),\n Edit.moveBlock(node, at + 1, parent?.id),\n )\n }\n const stepped = apply({ document: current, selection: null }, step, [])\n // Each step is built from the document it applies to, so a refusal is a bug here.\n if (!stepped.ok) throw new Error(`liftOperations: a lift step was refused (${stepped.error})`)\n operations.push(...step)\n current = stepped.state.document\n if (parent === undefined || kindAccepts(nodes, blockKind(parent), blockKind(found.block))) break\n }\n return operations.length === 0 ? undefined : operations\n}\n\n/** A list item around a block: its container, where that stands, and the list holding it. */\ninterface ItemAround {\n readonly container: Extract<Block, { readonly type: 'Node' }>\n readonly containerPath: BlockPath\n readonly list: Block\n}\n\n/**\n * The item a block sits in, when the vocabulary says its container is one: a kind its own\n * parent declares it holds, as a `List` declares `ListItem`, and not isolating, as a table\n * cell is. Enter treats such a container as the unit it splits.\n */\nconst itemAround = (\n document: Document,\n path: BlockPath,\n nodes: NodeRegistry | undefined,\n): ItemAround | undefined => {\n if (nodes === undefined) return undefined\n const containerPath = path.slice(0, -1)\n const container = blockAtPath(document, containerPath)\n const list = blockAtPath(document, containerPath.slice(0, -1))\n if (container?.type !== 'Node' || list?.type !== 'Node') return undefined\n const declaredItem = nodes.definitionFor(container.kind)\n const isolating = declaredItem?.kind === 'node' && declaredItem.isolating === true\n return holdsItem(nodes, list.kind, container.kind) && !isolating\n ? { container, containerPath, list }\n : undefined\n}\n\n/**\n * Whether Enter in the block at `path`, over to `end`, leaves no heading text after the caret,\n * so the new block is a paragraph: what follows a title is text. Mid-heading, both halves stay\n * the heading they were. Over a range, what follows is what the removal leaves: the heading's\n * own rest when the range ends inside it, or the next block's text, which was never the\n * heading's, when it ends there.\n */\nconst endsHeading = (document: Document, path: BlockPath, end: Position): boolean => {\n const block = blockAtPath(document, path)\n const endAt = locate(document, end.node)\n return (\n block?.type === 'Heading' &&\n endAt !== undefined &&\n (pathKey(endAt.path) !== pathKey(path) ||\n (end.offset >= endAt.text.length &&\n block.children.slice(endAt.runIndex + 1).every(run => run.text.length === 0)))\n )\n}\n\n/**\n * Enter inside a list item. An empty block that is the item's whole content leaves the list,\n * as Backspace does. Otherwise the block splits and the second half, with every block after\n * it in the item, becomes a new item of the same kind and props right after this one.\n */\nconst splitItem = (\n state: EditorState,\n at: Located,\n offset: number,\n { container, containerPath, list }: ItemAround,\n ids: CommandIds,\n nodes: NodeRegistry | undefined,\n): TransactionResult => {\n const blocks = container.blocks ?? []\n const index = at.path[at.path.length - 1]!\n const empty = blockAtPath(state.document, at.path)?.children.every(run => run.text === '')\n if (empty === true && blocks.length === 1) {\n return apply(state, liftOperations(state.document, at.blockId, ids, nodes) ?? [])\n }\n const textId = ids.mint()\n const blockId = ids.mint()\n const itemId = NodeId.make(ids.mint())\n const declared = nodes?.definitionFor(container.kind)\n const props = { ...container.props, ...(declared?.kind === 'node' ? declared.splitProps : {}) }\n // The declaration's props are laid over the item's, so together they must still decode.\n if (declared?.kind === 'node' && propsFailure(declared.props, props))\n return failure('InvalidInput')\n return apply(state, [\n Edit.splitBlock(at.blockId, at.id, offset, blockId, textId),\n ...(endsHeading(state.document, at.path, { node: at.id, offset, affinity: 'after' })\n ? [Edit.retypeBlock(NodeId.make(blockId), { type: 'Paragraph' })]\n : []),\n Edit.insertBlock(\n { ...container, id: itemId, props, children: [], blocks: [] },\n containerPath[containerPath.length - 1]! + 1,\n list.id,\n ),\n Edit.moveBlock(NodeId.make(blockId), 0, itemId),\n ...blocks\n .slice(index + 1)\n .map((later, position) => Edit.moveBlock(later.id, position + 1, itemId)),\n Edit.setSelection(caretAt({ node: NodeId.make(textId), offset: 0, affinity: 'after' })),\n ])\n}\n\n/** The block a block-level command acts on, and where it stands. */\ninterface StartingBlock {\n readonly block: Block\n readonly path: BlockPath\n readonly parentPath: BlockPath\n /** The containing block, or none at the document's top level. */\n readonly parent: Block | undefined\n /** The selection it was found from, which a command that renames runs has to move. */\n readonly selection: Extract<Selection, { readonly type: 'Range' }>\n}\n\n/**\n * A block-level intent acts on the block the selection starts in: the caret's own block,\n * or the first block of a range. Acting on every block a range covers would be a surprise,\n * and a menu or a marker is typed at a caret anyway.\n */\nconst startingBlock = (\n document: Document,\n selection: Extract<Selection, { readonly type: 'Range' }>,\n): StartingBlock | { readonly error: Failure } => {\n const start = isCollapsed(selection) ? selection.anchor : ordered(document, selection)?.start\n if (start === undefined) return { error: 'InvalidSelection' }\n const at = locate(document, start.node)\n const block = at === undefined ? undefined : blockAtPath(document, at.path)\n if (at === undefined || block === undefined) return { error: 'MissingText' }\n const parentPath = at.path.slice(0, -1)\n return {\n block,\n path: at.path,\n parentPath,\n parent: parentPath.length === 0 ? undefined : blockAtPath(document, parentPath),\n selection,\n }\n}\n\n/**\n * Retype, wrap, convert, retype a container, and lift: each reshapes the starting block, or\n * the container holding it, where it stands.\n */\nconst runBlockCommand = (\n state: EditorState,\n command: Extract<\n Command,\n {\n readonly type: 'RetypeBlock' | 'WrapBlock' | 'ConvertBlock' | 'RetypeContainer' | 'LiftBlock'\n }\n >,\n starting: StartingBlock,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n const { block, path, parentPath, parent } = starting\n const index = path[path.length - 1]!\n if (command.type === 'LiftBlock') {\n const lifted = liftOperations(state.document, block.id, ids, options.nodes)\n return lifted === undefined ? failure('InvalidInput') : apply(state, lifted)\n }\n if (command.type === 'RetypeContainer') {\n if (parent?.type !== 'Node' || parent.blocks === undefined || index !== 0) {\n return failure('InvalidInput')\n }\n const { kind } = command.to\n if (refusesProps(options.nodes, command.to)) return failure('InvalidInput')\n const outerPath = parentPath.slice(0, -1)\n const outer = outerPath.length === 0 ? undefined : blockAtPath(state.document, outerPath)\n const declared = options.nodes?.definitionFor(kind)\n const allowed =\n holdsBlocks(options.nodes, kind) &&\n acceptsChild(state.document, outerPath, kind, options.nodes) &&\n standsWithin(declared, outer === undefined ? undefined : blockKind(outer)) &&\n parent.blocks.every(\n child =>\n kindAccepts(options.nodes, kind, blockKind(child)) &&\n standsWithin(options.nodes?.definitionFor(blockKind(child)), kind),\n )\n if (!allowed) return failure('UnexpectedChild')\n return apply(state, [\n Edit.retypeBlock(parent.id, { type: 'Node', kind, props: command.to.props ?? {} }),\n ])\n }\n if (command.type === 'RetypeBlock') {\n // A retype keeps the block where it is, so the parent's constraint decides whether\n // the new kind belongs there.\n if (!acceptsChild(state.document, parentPath, command.to.type, options.nodes)) {\n return failure('UnexpectedChild')\n }\n // Leaving a node kind that holds text — a code block back to a paragraph — keeps the\n // block and its runs, as entering one does. Only a vocabulary says a kind holds text:\n // without one, a node could be an image, whose content a retype would destroy.\n if (\n block.type !== 'Paragraph' &&\n block.type !== 'Heading' &&\n (block.type !== 'Node' || !declaresText(options.nodes, block.kind))\n ) {\n return failure('InvalidInput')\n }\n return apply(state, [Edit.retypeBlock(block.id, command.to)])\n }\n\n if (command.type === 'WrapBlock') {\n const [outer] = command.containers\n if (outer === undefined) return failure('InvalidInput')\n if (command.containers.some(container => refusesProps(options.nodes, container))) {\n return failure('InvalidInput')\n }\n const kinds = [...command.containers.map(container => container.kind), blockKind(block)]\n const parentKind = parent === undefined ? undefined : blockKind(parent)\n // Both sides of every link in the chain: what each container holds, and where each kind,\n // the wrapped block's included, may stand (§149).\n const allowed =\n acceptsChild(state.document, parentPath, outer.kind, options.nodes) &&\n command.containers.every(\n (container, at) =>\n holdsBlocks(options.nodes, container.kind) &&\n kindAccepts(options.nodes, container.kind, kinds[at + 1]!),\n ) &&\n kinds.every((kind, at) =>\n standsWithin(options.nodes?.definitionFor(kind), at === 0 ? parentKind : kinds[at - 1]),\n )\n if (!allowed) return failure('UnexpectedChild')\n // A list wrap right after a list of the same kind and props adds an item to it, as\n // Markdown reads the two; a second list beside the first would print as one.\n const siblings =\n parent === undefined\n ? state.document.children\n : parent.type === 'Node'\n ? (parent.blocks ?? [])\n : []\n const before = siblings[index - 1]\n const item = command.containers[1]\n const joins =\n options.nodes !== undefined &&\n item !== undefined &&\n holdsItem(options.nodes, outer.kind, item.kind) &&\n before?.type === 'Node' &&\n before.kind === outer.kind &&\n Equal.equals(before.props, outer.props ?? {})\n const created = joins ? command.containers.slice(1) : command.containers\n const containerIds = created.map(() => NodeId.make(ids.mint()))\n // Built from the inside out, so each container holds the next and the innermost is\n // empty until the block moves into it.\n const chain = created.reduceRight<Block | undefined>(\n (inner, container, at) => ({\n type: 'Node',\n kind: container.kind,\n id: containerIds[at]!,\n props: container.props ?? {},\n children: [],\n blocks: inner === undefined ? [] : [inner],\n }),\n undefined,\n )!\n return apply(state, [\n joins\n ? Edit.insertBlock(chain, before.blocks?.length ?? 0, before.id)\n : Edit.insertBlock(chain, index, parent?.id),\n Edit.moveBlock(block.id, 0, containerIds[containerIds.length - 1]!),\n ])\n }\n\n // A node kind's content is its Kit's contract, so only a paragraph or heading converts.\n if (block.type !== 'Paragraph' && block.type !== 'Heading') return failure('InvalidInput')\n const kind = command.to.kind\n if (refusesProps(options.nodes, command.to)) return failure('InvalidInput')\n const holdsText = options.nodes === undefined || declaresText(options.nodes, kind)\n if (!holdsText || !acceptsChild(state.document, parentPath, kind, options.nodes)) {\n return failure('UnexpectedChild')\n }\n if (\n options.nodes !== undefined &&\n kindForbidsMarks(options.nodes, kind) &&\n block.children.some(run => run.marks.length > 0)\n ) {\n return failure('ForbiddenMark')\n }\n return apply(state, [\n Edit.retypeBlock(block.id, { type: 'Node', kind, props: command.to.props ?? {} }),\n ])\n}\n\n/**\n * Resolves one intent into a transaction and applies it atomically. Commands\n * describe intent; the returned `positionMap` and `ChangeSet` describe the\n * document effect, and rejection returns no partially edited state.\n */\nexport const run = (\n state: EditorState,\n command: Command,\n ids: CommandIds,\n options: RunOptions = {},\n): TransactionResult => {\n // The vocabulary an edit may add: the caller's Kit, or the shipped marks.\n const declared = options.marks ?? shippedRegistry\n // A range that leaves its container (a selection over several kinds of block, or all of\n // them) is cleared first, and what replaces it then acts on the caret that is left.\n const range = state.selection\n if (\n (command.type === 'InsertText' ||\n command.type === 'DeleteBackward' ||\n command.type === 'DeleteForward' ||\n command.type === 'SplitBlock' ||\n command.type === 'Paste') &&\n range?.type === 'Range' &&\n !isCollapsed(range)\n ) {\n const span = ordered(state.document, range)\n if (span !== undefined && deleteRange(state.document, span.start, span.end) === undefined) {\n const cleared = clearRange(state, span.start, span.end, options)\n if (!cleared.ok || command.type === 'DeleteBackward' || command.type === 'DeleteForward') {\n return cleared\n }\n return followedBy(cleared, run(cleared.state, command, ids, options))\n }\n }\n if (command.type === 'SetSelection') {\n return apply(state, [Edit.setSelection(command.selection)])\n }\n if (command.type === 'SetProps') {\n const target = locateBlock(state.document, command.node)?.block\n if (target?.type !== 'Node') return failure('InvalidInput')\n // Refused only when it makes valid props invalid: props already outside the kind's\n // schema (a key from an older version, say) cannot be deleted, so refusing every change\n // to them would leave the block uneditable.\n const refuses = (props: Schema.JsonObject) =>\n refusesProps(options.nodes, { kind: target.kind, props })\n if (refuses({ ...target.props, ...command.props }) && !refuses(target.props)) {\n return failure('InvalidInput')\n }\n return apply(state, [Edit.setProps(command.node, command.props)])\n }\n if (\n command.type === 'InsertRow' ||\n command.type === 'InsertColumn' ||\n command.type === 'DeleteRow' ||\n command.type === 'DeleteColumn'\n ) {\n const at = tableAt(state.document, state.selection)\n if (at === undefined) return failure('InvalidSelection')\n const edited: TableEdit = Match.value(command).pipe(\n Match.discriminatorsExhaustive('type')({\n InsertRow: ({ where }) => insertRow(state, at, where, ids.mint),\n InsertColumn: ({ where }) => insertColumn(state, at, where, ids.mint),\n DeleteRow: () => deleteRow(state, at),\n DeleteColumn: () => deleteColumn(state, at),\n }),\n )\n // The last row or column takes the table with it, as a handle's Delete would.\n return 'deleteTable' in edited\n ? run(state, { type: 'DeleteBlock', node: edited.deleteTable }, ids, options)\n : edited\n }\n if (command.type === 'Indent' || command.type === 'Outdent') {\n // Code inside a table cell indents: the innermost meaning of Tab wins.\n const code = linesHolder(state, options.nodes)\n if (code !== undefined) {\n return command.type === 'Indent' ? indent(state, code) : outdent(state, code)\n }\n // A list item inside a table cell nests; a table inside a list item moves between cells.\n const item = itemAtCaret(state, options.nodes)\n const at = tableAt(state.document, state.selection)\n const tableDepth =\n at === undefined ? -1 : (locateBlock(state.document, at.table.id)?.path.length ?? -1)\n if (item !== undefined && item.containerPath.length > tableDepth) {\n return command.type === 'Indent'\n ? sinkItem(state, item, ids, options)\n : liftItem(state, item, ids, options)\n }\n if (at === undefined) return failure('InvalidSelection')\n return moveToCell(state, at, command.type === 'Indent' ? 'next' : 'previous', ids.mint)\n }\n if (command.type === 'Replace') {\n const matches = findMatches(state.document, command.query, command)\n const chosen = command.at === undefined ? matches : matches.slice(command.at, command.at + 1)\n return replaceMatches(state, chosen, command.replacement, ids, options)\n }\n if (command.type === 'InsertFootnote')\n return insertFootnote(state, command.text ?? '', ids, options)\n if (command.type === 'RenameFootnote') {\n return renameFootnote(state, command.from, command.to.trim(), ids, options)\n }\n if (command.type === 'InsertBlock') {\n const to = command.to ?? besideCaret(state)\n if (to === undefined) return failure('InvalidSelection')\n const beside = locateBlock(state.document, 'before' in to ? to.before : to.after)\n if (beside === undefined) return failure('InvalidInput')\n const containerPath = beside.path.slice(0, -1)\n const holder =\n containerPath.length === 0 ? undefined : blockAtPath(state.document, containerPath)\n const kind = blockKind(command.block)\n if (\n (holder !== undefined && !acceptsChild(state.document, containerPath, kind, options.nodes)) ||\n !standsWithin(\n options.nodes?.definitionFor(kind),\n holder === undefined ? undefined : blockKind(holder),\n )\n ) {\n return failure('UnexpectedChild')\n }\n const [inserted] = withFreshIds({ version: 1, blocks: [command.block] }, ids.mint).blocks\n const at = beside.path[beside.path.length - 1]! + ('after' in to ? 1 : 0)\n const first = firstRunIn([inserted!])\n return apply(state, [\n Edit.insertBlock(inserted!, at, holder?.id),\n ...(first === undefined\n ? []\n : [Edit.setSelection(caretAt({ node: first.id, offset: 0, affinity: 'after' }))]),\n ])\n }\n if (command.type === 'DeleteBlock') {\n const deleting = locateBlock(state.document, command.node)\n if (deleting === undefined) return failure('InvalidInput')\n // Never a path, so no container counts as holding where the block goes.\n const target = emptiedBy(state.document, deleting.path.slice(0, -1), [-1]) ?? command.node\n const gone = locateBlock(state.document, target)!\n const inside = (path: BlockPath) => gone.path.every((index, depth) => path[depth] === index)\n const runs: Array<{ readonly run: Run; readonly inside: boolean; readonly after: boolean }> = []\n eachBlock(state.document.children, (block, path) => {\n for (const run of block.children) {\n runs.push({ run, inside: inside(path), after: pathOrder(path, gone.path) > 0 })\n }\n })\n const selection = state.selection\n const holds =\n selection !== null &&\n (selection.type === 'Node'\n ? locateBlock(state.document, selection.node) !== undefined &&\n inside(locateBlock(state.document, selection.node)!.path)\n : [selection.anchor, selection.focus].some(end =>\n runs.some(entry => entry.inside && entry.run.id === end.node),\n ))\n // By place, not by the runs the block held: an atom holds none.\n const following = runs.find(entry => entry.after && !entry.inside)\n const preceding = [...runs].reverse().find(entry => !entry.after && !entry.inside)\n const landing =\n following !== undefined\n ? { node: following.run.id, offset: 0, affinity: 'after' as const }\n : preceding !== undefined\n ? {\n node: preceding.run.id,\n offset: preceding.run.text.length,\n affinity: 'after' as const,\n }\n : undefined\n const emptiesDocument = gone.path.length === 1 && state.document.children.length === 1\n if (emptiesDocument) {\n const textId = NodeId.make(ids.mint())\n const paragraph: Block = {\n type: 'Paragraph',\n id: NodeId.make(ids.mint()),\n children: [{ type: 'Text', id: textId, text: '', marks: [] }],\n }\n return apply(state, [\n Edit.insertBlock(paragraph, 1),\n Edit.deleteBlock(target),\n Edit.setSelection(caretAt({ node: textId, offset: 0, affinity: 'after' })),\n ])\n }\n return apply(state, [\n Edit.deleteBlock(target),\n ...(holds ? [Edit.setSelection(landing === undefined ? null : caretAt(landing))] : []),\n ])\n }\n if (command.type === 'MoveBlock') {\n const moving = locateBlock(state.document, command.node)\n const beside = locateBlock(\n state.document,\n 'before' in command.to ? command.to.before : command.to.after,\n )\n if (moving === undefined || beside === undefined) return failure('InvalidInput')\n const container = beside.path.slice(0, -1)\n const refused = moveFailure(state.document, moving, container, options.nodes)\n if (refused !== undefined) return failure(refused)\n const source = moving.path.slice(0, -1)\n const within = pathKey(source) === pathKey(container)\n const from = moving.path[moving.path.length - 1]!\n const place = beside.path[beside.path.length - 1]! + ('after' in command.to ? 1 : 0)\n // The operation's index is after the block leaves, which shifts every later sibling up.\n const to = within && from < place ? place - 1 : place\n const parent = container.length === 0 ? undefined : blockAtPath(state.document, container)?.id\n const emptied = emptiedBy(state.document, source, container)\n // A node selection on a container the move deletes would dangle; the block it held is what\n // it was selecting, so it goes there.\n const gone = emptied === undefined ? undefined : locateBlock(state.document, emptied)\n const selected =\n state.selection?.type === 'Node'\n ? locateBlock(state.document, state.selection.node)\n : undefined\n const inside = (path: BlockPath, holder: BlockPath) =>\n holder.every((index, depth) => path[depth] === index)\n const lost =\n gone !== undefined &&\n selected !== undefined &&\n inside(selected.path, gone.path) &&\n !inside(selected.path, moving.path)\n return apply(state, [\n Edit.moveBlock(command.node, to, parent),\n ...(emptied === undefined ? [] : [Edit.deleteBlock(emptied)]),\n ...(lost ? [Edit.setSelection({ type: 'Node', node: command.node })] : []),\n ])\n }\n const selection = state.selection\n // A selected block is deleted by Delete or Backspace, has a paragraph opened after it by\n // Enter, and is replaced by what is typed over it.\n if (selection?.type === 'Node') {\n const paragraph: Block = {\n type: 'Paragraph',\n id: NodeId.make('paragraph'),\n children: [{ type: 'Text', id: NodeId.make('text'), text: '', marks: [] }],\n }\n const after = { type: 'InsertBlock', block: paragraph, to: { after: selection.node } } as const\n if (command.type === 'DeleteBackward' || command.type === 'DeleteForward') {\n return run(state, { type: 'DeleteBlock', node: selection.node }, ids, options)\n }\n if (command.type === 'SplitBlock') return run(state, after, ids, options)\n if (command.type === 'InsertText') {\n return runAction(\n state,\n [after, { type: 'DeleteBlock', node: selection.node }, command],\n ids,\n options,\n )\n }\n }\n if (selection === null || selection.type === 'Node') return failure('InvalidSelection')\n\n if (command.type === 'InsertText') {\n // Stored marks are explicit: when the command carries them, the inserted\n // text must end up with exactly that set, whatever run it lands in. Without\n // them, the boundary rule decides (typing after bold continues bold).\n // At a block's outer edge, a mark that does not extend there is left behind: the text\n // carries the rest, as stored marks would.\n const edge =\n command.marks === undefined && isCollapsed(selection)\n ? edgeMarks(state.document, selection.anchor, options.marks)\n : undefined\n const stored = command.marks ?? edge\n const target = isCollapsed(selection)\n ? stored === undefined\n ? resolveInsertion(state.document, selection.anchor, options.marks)\n : selection.anchor\n : ordered(state.document, selection)?.start\n if (target === undefined) return failure('InvalidSelection')\n const at = locate(state.document, target.node)\n if (at === undefined) return failure('MissingText')\n const marks: Array<RunMark> = []\n if (stored !== undefined) {\n for (const mark of stored) {\n // Marks kept from the run were already there; only marks a caller names are checked.\n if (edge === undefined && !declared.accepts(mark)) return failure('InvalidInput')\n marks.push(mark)\n }\n // A mark-free kind refuses the format however it arrives, so inserting text\n // that carries marks into a CodeBlock is refused like the toggle that set them.\n if (marks.length > 0 && forbidsMarks(state.document, at.path, options.nodes)) {\n return failure('ForbiddenMark')\n }\n }\n const deletions = isCollapsed(selection)\n ? []\n : deleteRange(state.document, target, ordered(state.document, selection)!.end)\n if (deletions === undefined) return failure('InvalidParent')\n if (command.text.length === 0) {\n return apply(\n state,\n deletions.length === 0 ? [] : [...deletions, Edit.setSelection(caretAt(target))],\n )\n }\n if (stored === undefined) {\n return apply(state, [\n ...deletions,\n Edit.insertText(target, command.text),\n Edit.setSelection(\n caretAt({ ...target, offset: target.offset + command.text.length, affinity: 'after' }),\n ),\n ])\n }\n // Split the inserted span out of its run — at the end first, so the start\n // offset stays valid — then give the span exactly these marks.\n const span = isCollapsed(selection) ? undefined : ordered(state.document, selection)\n // Where the text that survives the range deletion begins in the original\n // run. A range that runs past this run takes its whole tail with it.\n const tailFrom =\n span === undefined\n ? target.offset\n : span.end.node === target.node\n ? span.end.offset\n : at.text.length\n const operations: Array<Operation> = [...deletions, Edit.insertText(target, command.text)]\n const end = target.offset + command.text.length\n if (tailFrom < at.text.length) operations.push(Edit.splitRun(target.node, end, ids.mint()))\n const piece = target.offset > 0 ? NodeId.make(ids.mint()) : target.node\n if (target.offset > 0) operations.push(Edit.splitRun(target.node, target.offset, piece))\n for (const mark of marks) {\n if (!at.marks.some(existing => sameMark(existing, mark))) {\n operations.push(Edit.addMark(piece, mark))\n }\n }\n for (const mark of at.marks) {\n if (!marks.some(kept => markName(kept) === markName(mark))) {\n operations.push(Edit.removeMark(piece, markName(mark)))\n }\n }\n return apply(state, operations)\n }\n\n if (\n command.type === 'RetypeBlock' ||\n command.type === 'WrapBlock' ||\n command.type === 'ConvertBlock' ||\n command.type === 'RetypeContainer' ||\n command.type === 'LiftBlock'\n ) {\n const target = startingBlock(state.document, selection)\n return 'error' in target\n ? failure(target.error)\n : runBlockCommand(state, command, target, ids, options)\n }\n\n if (command.type === 'DeleteBackward' || command.type === 'DeleteForward') {\n if (!isCollapsed(selection)) {\n const span = ordered(state.document, selection)\n if (span === undefined) return failure('InvalidSelection')\n const deletions = deleteRange(state.document, span.start, span.end)\n if (deletions === undefined) return failure('InvalidParent')\n return apply(state, [...deletions, Edit.setSelection(caretAt(span.start))])\n }\n const caret = selection.anchor\n const at = locate(state.document, caret.node)\n if (at === undefined) return failure('MissingText')\n const backward = command.type === 'DeleteBackward'\n const block = blockAtPath(state.document, at.path)\n if (block === undefined) return failure('MissingText')\n const deletion = graphemeDeletion(block, caret, at.runIndex, backward)\n if (deletion !== undefined) {\n return apply(state, [...deletion.operations, Edit.setSelection(caretAt(deletion.caret))])\n }\n // Backspace at the start of a node kind that holds text, such as a code block, turns it\n // back into a paragraph, undoing the fence, rather than joining text across two kinds\n // whose marks and content rules differ. Only a vocabulary says the kind holds text.\n if (backward && block.type === 'Node' && declaresText(options.nodes, block.kind)) {\n return run(state, { type: 'RetypeBlock', to: { type: 'Paragraph' } }, ids, options)\n }\n // A heading does too, undoing the `# ` that made it, before a second press joins it.\n if (backward && block.type === 'Heading') {\n return run(state, { type: 'RetypeBlock', to: { type: 'Paragraph' } }, ids, options)\n }\n // A block edge joins the sibling in the same container, wherever it sits.\n const containerPath = at.path.slice(0, -1)\n const siblings = containerBlocks(state.document, containerPath)\n const index = at.path[at.path.length - 1]!\n const neighborBlock = siblings[backward ? index - 1 : index + 1]\n // An atom cannot take text, so the edge selects it, and a second press deletes it. A\n // block left with nothing in it goes first, as Backspace on an empty line would.\n if (neighborBlock !== undefined && isAtom(options.nodes, neighborBlock)) {\n return apply(state, [\n ...(textOfBlock(block) === '' ? [Edit.deleteBlock(block.id)] : []),\n Edit.setSelection({ type: 'Node', node: neighborBlock.id }),\n ])\n }\n if (neighborBlock === undefined && backward) {\n // Backspace at the start of a container's first block has nothing to join with, so\n // it lifts the block out, undoing what `> ` or `- ` did. Only with a vocabulary: it\n // is what says a list item's paragraph must leave the list too, and a table cell must\n // not be left at all. Otherwise the edge stays a no-op.\n const lifted =\n containerPath.length > 0 && options.nodes !== undefined\n ? liftOperations(state.document, siblings[index]!.id, ids, options.nodes)\n : undefined\n return apply(state, lifted ?? [])\n }\n // Past a sibling it cannot join, or forward past the end of its container, the edge\n // reaches the nearest block on that side that holds no blocks: inside a list or a quote,\n // its last or first line, which joins the line at the caret as clearing the empty range\n // between them would. A table cell or code cannot take the line, so there an emptied line\n // goes and Backspace steps into it, and Delete beside a line with text does nothing.\n if (\n neighborBlock === undefined ||\n !joinable(backward ? neighborBlock : block, backward ? block : neighborBlock)\n ) {\n const leafPath =\n neighborBlock === undefined\n ? nextLeaf(state.document, at.path)\n : edgeLeaf(state.document, [...containerPath, index + (backward ? -1 : 1)], backward)\n const leaf = leafPath === undefined ? undefined : blockAtPath(state.document, leafPath)\n if (leafPath === undefined || leaf === undefined) return apply(state, [])\n const empty = textOfBlock(block) === ''\n if (isAtom(options.nodes, leaf)) {\n return apply(state, [Edit.setSelection({ type: 'Node', node: leaf.id })])\n }\n const first = leaf.children[0]\n const last = leaf.children[leaf.children.length - 1]\n const target = backward ? last : first\n if (target === undefined) return apply(state, [])\n const edge = {\n node: target.id,\n offset: backward ? target.text.length : 0,\n affinity: 'after' as const,\n }\n // An empty line beside a list or a quote goes, rather than taking its line out of it.\n const stepsOnly = empty && neighborBlock !== undefined\n // Across a table cell, clearing the range only steps the caret, as it should.\n if (!stepsOnly && (backward ? joinable(leaf, block) : joinable(block, leaf))) {\n return backward\n ? clearRange(state, edge, caret, options)\n : clearRange(state, caret, edge, options)\n }\n if (neighborBlock === undefined || (!backward && !empty)) return apply(state, [])\n return apply(state, [\n ...(empty ? [Edit.deleteBlock(block.id)] : []),\n Edit.setSelection(caretAt(edge)),\n ])\n }\n const survivor = backward ? neighborBlock : siblings[index]!\n const removed = backward ? siblings[index]! : neighborBlock\n // The caret lands at the junction: the end of what the survivor already had,\n // or the removed block's last run when the survivor holds no runs.\n const lastRun = lastRunOf(survivor) ?? lastRunOf(removed)\n return apply(state, [\n Edit.joinBlocks(survivor.id, removed.id),\n Edit.setSelection(\n caretAt(\n lastRun === undefined\n ? { node: survivor.id, offset: 0, affinity: 'after' }\n : { node: lastRun.id, offset: lastRun.text.length, affinity: 'after' },\n ),\n ),\n ])\n }\n\n if (command.type === 'SplitBlock') {\n const span = isCollapsed(selection) ? undefined : ordered(state.document, selection)\n if (!isCollapsed(selection) && span === undefined) return failure('InvalidSelection')\n const caret = span?.start ?? selection.anchor\n const at = locate(state.document, caret.node)\n if (at === undefined) return failure('MissingText')\n const deletions = span === undefined ? [] : deleteRange(state.document, span.start, span.end)\n if (deletions === undefined) return failure('InvalidParent')\n const holder = blockAtPath(state.document, at.path)\n const definition =\n holder?.type === 'Node' ? options.nodes?.definitionFor(holder.kind) : undefined\n if (holder !== undefined && definition?.kind === 'node' && definition.lineBreaks === true) {\n const last = holder.children[holder.children.length - 1]\n const onEmptyLastLine =\n span === undefined &&\n last?.id === at.id &&\n caret.offset === at.text.length &&\n holder.children\n .map(run => run.text)\n .join('')\n .endsWith('\\n')\n // Enter on an empty last line leaves the block, so one at the end of a document can be\n // left at all; anywhere else it is a line break in the text.\n return onEmptyLastLine\n ? runAction(\n state,\n [\n { type: 'DeleteBackward' },\n {\n type: 'InsertBlock',\n block: {\n type: 'Paragraph',\n id: NodeId.make('paragraph'),\n children: [{ type: 'Text', id: NodeId.make('text'), text: '', marks: [] }],\n },\n to: { after: holder.id },\n },\n ],\n ids,\n options,\n )\n : run(\n state,\n // In code, the new line starts as indented as the one it broke.\n {\n type: 'InsertText',\n text:\n definition.indents === true\n ? `\\n${indentationAt(textOfBlock(holder), offsetIn(holder, caret) ?? 0)}`\n : '\\n',\n },\n ids,\n options,\n )\n }\n const item = itemAround(state.document, at.path, options.nodes)\n if (item !== undefined) {\n // Over a range inside an item, Enter deletes the range and then splits the item, as it\n // would at a caret; the two commands already say how.\n return span === undefined\n ? splitItem(state, at, caret.offset, item, ids, options.nodes)\n : runAction(state, [{ type: 'DeleteBackward' }, { type: 'SplitBlock' }], ids, options)\n }\n const textId = ids.mint()\n const blockId = ids.mint()\n return apply(state, [\n ...deletions,\n Edit.splitBlock(at.blockId, at.id, caret.offset, blockId, textId),\n ...(endsHeading(state.document, at.path, span?.end ?? caret)\n ? [Edit.retypeBlock(NodeId.make(blockId), { type: 'Paragraph' })]\n : []),\n Edit.setSelection(caretAt({ node: NodeId.make(textId), offset: 0, affinity: 'after' })),\n ])\n }\n\n if (command.type === 'ToggleMark' || command.type === 'SetMark' || command.type === 'ClearMark') {\n const mark = command.mark\n const name = markName(mark)\n let span = ordered(state.document, selection)\n if (isCollapsed(selection)) {\n // A toggle at a caret has nothing to cover; setting or clearing one acts on the mark\n // the caret is in, so a link can be edited without selecting it first.\n const extent =\n command.type === 'ToggleMark'\n ? undefined\n : markExtent(state.document, selection.anchor, name)\n if (extent === undefined) return apply(state, [])\n span = ordered(state.document, extent.selection)\n }\n if (span === undefined) return failure('InvalidSelection')\n // A value clears only the runs carrying exactly it, so those are all the runs it covers.\n const spans = covered(state.document, span.start, span.end).filter(\n entry =>\n command.type !== 'ClearMark' ||\n typeof mark === 'string' ||\n entry.run.marks.some(held => sameMark(held, mark)),\n )\n if (spans.length === 0) return apply(state, [])\n // A toggle keys on the name: the mark is present on every covered run, or\n // it is absent everywhere. Props are the mark's own business.\n const adding =\n command.type === 'SetMark' ||\n (command.type === 'ToggleMark' &&\n !spans.every(entry => entry.run.marks.some(held => markName(held) === name)))\n const operations: Array<Operation> = []\n const targets: Array<NodeId> = []\n for (const [index, entry] of spans.entries()) {\n let target = entry.run.id\n let base = 0\n if (index === 0 && entry.from > 0) {\n const textId = ids.mint()\n operations.push(Edit.splitRun(target, entry.from, textId))\n target = NodeId.make(textId)\n base = entry.from\n }\n if (index === spans.length - 1 && entry.to < entry.run.text.length) {\n operations.push(Edit.splitRun(target, entry.to - base, ids.mint()))\n }\n targets.push(target)\n }\n if (adding) {\n // Adding needs the vocabulary to declare the mark and accept its props; removing a\n // preserved one by name is always allowed.\n if (!declared.accepts(mark)) return failure('InvalidInput')\n if (spans.some(entry => forbidsMarks(state.document, entry.run.path, options.nodes))) {\n return failure('ForbiddenMark')\n }\n for (const target of targets) operations.push(Edit.addMark(target, mark))\n } else {\n for (const target of targets) operations.push(Edit.removeMark(target, name))\n }\n return apply(state, operations)\n }\n\n if (command.type === 'Paste') {\n const content = command.slice.blocks\n if (content.length === 0) return apply(state, [])\n const span = isCollapsed(selection) ? undefined : ordered(state.document, selection)\n if (!isCollapsed(selection) && span === undefined) return failure('InvalidSelection')\n const caret = span?.start ?? selection.anchor\n const at = locate(state.document, caret.node)\n if (at === undefined) return failure('MissingText')\n // Into code, or any kind whose text keeps line breaks, what is pasted is its text.\n const into = blockAtPath(state.document, at.path)\n const holds = into?.type === 'Node' ? options.nodes?.definitionFor(into.kind) : undefined\n if (holds?.kind === 'node' && holds.lineBreaks === true) {\n return run(state, { type: 'InsertText', text: toText(content) }, ids, options)\n }\n const index = at.path[at.path.length - 1]!\n const containerPath = at.path.slice(0, -1)\n // The content lands in the caret's own container, so pasting inside a list\n // item stays inside the list.\n const parent =\n containerPath.length === 0 ? undefined : blockAtPath(state.document, containerPath)?.id\n const replacements = span === undefined ? [] : deleteRange(state.document, span.start, span.end)\n if (replacements === undefined) return failure('InvalidParent')\n const operations: Array<Operation> = [...replacements]\n const inserted = withFreshIds(command.slice, ids.mint).blocks\n // The content lands in the caret's container, so that container's constraint decides\n // which kinds it accepts (§125), and each kind's own says whether it may stand there (§149).\n const holder =\n containerPath.length === 0 ? undefined : blockAtPath(state.document, containerPath)\n if (\n inserted.some(\n piece =>\n (containerPath.length > 0 &&\n !acceptsChild(state.document, containerPath, blockKind(piece), options.nodes)) ||\n !standsWithin(\n options.nodes?.definitionFor(blockKind(piece)),\n holder === undefined ? undefined : blockKind(holder),\n ),\n )\n ) {\n return failure('UnexpectedChild')\n }\n const block = blockAtPath(state.document, at.path)\n if (block === undefined) return failure('MissingText')\n // The block splits at the caret and the content lands between the halves. The first\n // piece joins the text before the caret and the last the text after it, when each can be\n // one block with it, so a pasted word or line lands inside the sentence; a half left with\n // nothing in it goes, unless it is the only place after a table or an image to type.\n const end = span?.end ?? caret\n const endBlock = blockAtPath(state.document, locate(state.document, end.node)?.path ?? at.path)\n const beforeEmpty = offsetIn(block, caret) === 0\n const afterEmpty =\n endBlock === undefined || offsetIn(endBlock, end) === textOfBlock(endBlock).length\n const tailText = NodeId.make(ids.mint())\n const tail = NodeId.make(ids.mint())\n operations.push(Edit.splitBlock(at.blockId, at.id, caret.offset, tail, tailText))\n for (const [offset, piece] of inserted.entries()) {\n operations.push(Edit.insertBlock(piece, index + 1 + offset, parent))\n }\n const first = inserted[0]!\n const last = inserted[inserted.length - 1]!\n const lastRun = last.children[last.children.length - 1]\n // Set before the joins, which carry it with the runs they move.\n operations.push(\n Edit.setSelection(\n caretAt(\n lastRun === undefined\n ? { node: tailText, offset: 0, affinity: 'after' }\n : { node: lastRun.id, offset: lastRun.text.length, affinity: 'after' },\n ),\n ),\n )\n const joinsHead = joinable(block, first)\n const joinsTail = joinable(last, block)\n if (joinsHead) operations.push(Edit.joinBlocks(at.blockId, first.id))\n if (joinsTail) {\n operations.push(Edit.joinBlocks(joinsHead && last === first ? at.blockId : last.id, tail))\n }\n if (!joinsHead && beforeEmpty) operations.push(Edit.deleteBlock(at.blockId))\n if (!joinsTail && afterEmpty && lastRun !== undefined) operations.push(Edit.deleteBlock(tail))\n return apply(state, operations)\n }\n\n return apply(state, [])\n}\n\n/** Where an `InsertBlock` without a place goes: beside the caret's block, before it when empty. */\nconst besideCaret = (state: EditorState): Beside | undefined => {\n if (state.selection?.type !== 'Range') return undefined\n const run = locateRun(\n state.document,\n ordered(state.document, state.selection)?.start.node ?? state.selection.anchor.node,\n )\n const block = run === undefined ? undefined : blockAtPath(state.document, run.path)\n if (block === undefined) return undefined\n const empty = block.children.every(child => child.text === '')\n return empty ? { before: block.id } : { after: block.id }\n}\n\nconst textOfBlock = (block: Block): string => block.children.map(run => run.text).join('')\n\n/** The block the selection starts in when its kind indents its lines, as code does. */\nconst linesHolder = (state: EditorState, nodes: NodeRegistry | undefined): Block | undefined => {\n if (state.selection?.type !== 'Range') return undefined\n const start = ordered(state.document, state.selection)?.start\n const run = start === undefined ? undefined : locateRun(state.document, start.node)\n const block = run === undefined ? undefined : blockAtPath(state.document, run.path)\n if (block?.type !== 'Node') return undefined\n const definition = nodes?.definitionFor(block.kind)\n return definition?.kind === 'node' && definition.indents === true ? block : undefined\n}\n\n/**\n * Whether Tab means something where the selection is: in code, or in a table cell. An editor\n * takes Tab only there, so anywhere else it still moves focus out of the editor.\n */\nexport const takesTab = (\n document: Document,\n selection: Selection | null,\n nodes?: NodeRegistry,\n): boolean =>\n linesHolder({ document, selection }, nodes) !== undefined ||\n itemAtCaret({ document, selection }, nodes) !== undefined ||\n tableAt(document, selection) !== undefined\n\n/** The list item the selection starts in, when the vocabulary says its list holds it. */\nconst itemAtCaret = (state: EditorState, nodes: NodeRegistry | undefined) => {\n if (state.selection?.type !== 'Range') return undefined\n const start = ordered(state.document, state.selection)?.start\n const run = start === undefined ? undefined : locateRun(state.document, start.node)\n return run === undefined ? undefined : itemAround(state.document, run.path, nodes)\n}\n\n/** Whether two props hold the same values, for a list that two items may share. */\nconst sameProps = (left: Schema.JsonObject, right: Schema.JsonObject): boolean => {\n const keys = Object.keys(left)\n return (\n keys.length === Object.keys(right).length &&\n keys.every(key => Object.hasOwn(right, key) && Equal.equals(left[key], right[key]))\n )\n}\n\n/**\n * Tab in a list item: the item moves under the item before it, as the last item of the list\n * that item ends with, or of a new one like its own when it ends with none. It keeps its\n * identity, and the caret with it. The first item has nothing to go under, and stays.\n */\nconst sinkItem = (\n state: EditorState,\n item: ItemAround,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n if (item.list.type !== 'Node') return apply(state, [])\n const list = item.list\n const index = item.containerPath[item.containerPath.length - 1]!\n const previous = (list.blocks ?? [])[index - 1]\n if (previous?.type !== 'Node') return apply(state, [])\n const nested = previous.blocks?.at(-1)\n const last = nested?.type === 'Node' ? nested.blocks?.at(-1) : undefined\n if (\n nested?.type === 'Node' &&\n nested.kind === list.kind &&\n sameProps(nested.props, list.props) &&\n last !== undefined\n ) {\n return run(\n state,\n { type: 'MoveBlock', node: item.container.id, to: { after: last.id } },\n ids,\n options,\n )\n }\n const created = NodeId.make(ids.mint())\n return apply(state, [\n Edit.insertBlock(\n { type: 'Node', kind: list.kind, id: created, props: list.props, children: [], blocks: [] },\n (previous.blocks ?? []).length,\n previous.id,\n ),\n Edit.moveBlock(item.container.id, 0, created),\n ])\n}\n\n/**\n * Shift+Tab in a list item: a nested item moves out to follow the item its list is in, and an\n * item at the top level leaves its list, as `LiftBlock` takes it. A list the move empties goes.\n */\nconst liftItem = (\n state: EditorState,\n item: ItemAround,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n const listPath = item.containerPath.slice(0, -1)\n const outerItem = blockAtPath(state.document, listPath.slice(0, -1))\n const outerList = blockAtPath(state.document, listPath.slice(0, -2))\n const nestedInItem =\n outerItem?.type === 'Node' &&\n outerList?.type === 'Node' &&\n options.nodes !== undefined &&\n holdsItem(options.nodes, outerList.kind, outerItem.kind)\n return nestedInItem\n ? run(\n state,\n { type: 'MoveBlock', node: item.container.id, to: { after: outerItem.id } },\n ids,\n options,\n )\n : run(state, { type: 'LiftBlock' }, ids, options)\n}\n\n/**\n * Replaces matches, last first, each read again from its block's offset in the state the one\n * after it left: a replacement later in a block leaves an earlier match's offset alone, though\n * the runs it touched may have merged or split, so positions found before it would not do.\n */\nconst replaceMatches = (\n state: EditorState,\n matches: ReadonlyArray<SearchMatch>,\n replacement: string,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n let done = apply(state, [])\n for (const match of [...matches].reverse()) {\n if (!done.ok) return done\n const block = locateBlock(done.state.document, match.block)?.block\n const from = block === undefined ? undefined : positionInBlock(block, match.at)\n const to = block === undefined ? undefined : positionInBlock(block, match.at + match.length)\n if (from === undefined || to === undefined) return failure('MissingText')\n const step = runAction(\n done.state,\n [\n { type: 'SetSelection', selection: { type: 'Range', anchor: from, focus: to } },\n // Over a range, an insertion replaces it, so an empty replacement deletes the match.\n { type: 'InsertText', text: replacement },\n ],\n ids,\n options,\n )\n if (!step.ok) return step\n done = {\n ok: true,\n state: step.state,\n changeSet: unionChangeSet(done.changeSet, step.changeSet),\n positionMap: [...done.positionMap, ...step.positionMap],\n transactions: [...done.transactions, ...step.transactions],\n }\n }\n return done\n}\n\nconst insertFootnote = (\n state: EditorState,\n text: string,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n const selection = state.selection\n if (selection?.type !== 'Range') return failure('InvalidSelection')\n const start = rangeStart(state.document, selection)\n const last = state.document.children[state.document.children.length - 1]\n if (start === undefined || last === undefined) return failure('InvalidSelection')\n const end = start === selection.anchor ? selection.focus : selection.anchor\n const label = nextFootnoteLabel(state.document)\n // Placeholder identities: InsertBlock mints fresh ones.\n const definition: Block = {\n type: 'Node',\n kind: FootnoteDefinition.name,\n id: NodeId.make('footnote'),\n props: { label },\n children: [],\n blocks: [\n {\n type: 'Paragraph',\n id: NodeId.make('footnote-text'),\n children: [{ type: 'Text', id: NodeId.make('footnote-run'), text, marks: [] }],\n },\n ],\n }\n return runAction(\n state,\n [\n { type: 'SetSelection', selection: { type: 'Range', anchor: end, focus: end } },\n { type: 'InsertText', text: label, marks: [FootnoteRef.of({ label })] },\n { type: 'InsertBlock', block: definition, to: { after: last.id } },\n ],\n ids,\n options,\n )\n}\n\nconst renameFootnote = (\n state: EditorState,\n from: string,\n to: string,\n ids: CommandIds,\n options: RunOptions,\n): TransactionResult => {\n const notes = footnotesOf(state.document)\n const note = notes.find(each => each.label === from)\n if (note === undefined || to === '' || (to !== from && notes.some(each => each.label === to))) {\n return failure('InvalidInput')\n }\n const relabelled = FootnoteRef.of({ label: to })\n const references: Array<Command> = []\n eachBlock(state.document.children, block => {\n for (const run of block.children) {\n if (referenceLabel(run) !== from) continue\n references.push(\n {\n type: 'SetSelection',\n selection: {\n type: 'Range',\n anchor: { node: run.id, offset: 0, affinity: 'after' },\n focus: { node: run.id, offset: run.text.length, affinity: 'before' },\n },\n },\n {\n type: 'InsertText',\n text: run.text === from ? to : run.text,\n marks: run.marks.map(each => (markName(each) === FootnoteRef.name ? relabelled : each)),\n },\n )\n }\n })\n // The caret goes back where it was, unless it was in a reference the rename rewrote.\n const selection = state.selection\n const inReference =\n selection?.type === 'Range' &&\n (note.references.includes(selection.anchor.node) ||\n note.references.includes(selection.focus.node))\n return runAction(\n state,\n [\n ...(note.definition === undefined\n ? []\n : [{ type: 'SetProps' as const, node: note.definition, props: { label: to } }]),\n ...references,\n ...(inReference || selection === null ? [] : [{ type: 'SetSelection' as const, selection }]),\n ],\n ids,\n options,\n )\n}\n\n/** The first run anywhere in these blocks, nested ones included, in document order. */\nconst firstRunIn = (blocks: ReadonlyArray<Block>): Run | undefined => {\n let found: Run | undefined\n eachBlock(blocks, block => {\n found ??= block.children[0]\n })\n return found\n}\n\n/** An ordered list of commands that commit as one action (§124 §5). */\nexport type Action = ReadonlyArray<Command>\n\n/**\n * A composed action's invalidation summary is the union of its commands': an identity\n * one command retired and a later one restored appears in both sets, and a patch reads\n * that as \"remove it, then render it\", so it never under-invalidates.\n */\nexport const unionChangeSet = (left: ChangeSet, right: ChangeSet): ChangeSet => ({\n dirtyNodes: new Set([...left.dirtyNodes, ...right.dirtyNodes]),\n insertedNodes: new Set([...left.insertedNodes, ...right.insertedNodes]),\n removedNodes: new Set([...left.removedNodes, ...right.removedNodes]),\n textChanged: new Set([...left.textChanged, ...right.textChanged]),\n structureChanged: left.structureChanged || right.structureChanged,\n selectionChanged: left.selectionChanged || right.selectionChanged,\n})\n\n/**\n * Resolves commands in order and commits them as one action: one resulting state, one\n * composed ChangeSet, and one identity stream, so a caller can treat \"remove the query,\n * then apply the choice\" as a single transition. It stops at the first refusal and\n * returns that command's error; state is a value, so nothing partial escapes.\n */\nexport const runAction = (\n state: EditorState,\n commands: Action,\n ids: CommandIds,\n options: RunOptions = {},\n): TransactionResult => {\n const [first, ...rest] = commands\n // An empty action is a no-op, as an empty transaction is.\n if (first === undefined) return apply(state, [])\n const started = run(state, first, ids, options)\n if (!started.ok) return started\n let current = started.state\n let changeSet = started.changeSet\n let positionMap = started.positionMap\n let transactions = started.transactions\n for (const command of rest) {\n const result = run(current, command, ids, options)\n if (!result.ok) return result\n current = result.state\n changeSet = unionChangeSet(changeSet, result.changeSet)\n positionMap = [...positionMap, ...result.positionMap]\n transactions = [...transactions, ...result.transactions]\n }\n return { ok: true, state: current, changeSet, positionMap, transactions }\n}\n","/**\n * Input rules (§124 §4): what someone just typed, read as an intent. A rule is not a\n * Transform (§23): a transform normalizes a document whenever it is applied, while a rule\n * is about the moment a particular thing was typed — `# ` at the start of a block means\n * \"make this a heading\" only at that moment, and never on a document loaded from storage.\n *\n * `applyInputRules` is the composition: the insertion, the deletes that consume what the\n * rule matched, and the rule's commands, as one action, so a transition and an undo step\n * cover typing the marker and the change it made.\n */\nimport type { Action, Command } from './command.js'\n\n/** What a rule makes of the text before the caret, and what to do about it. */\nexport interface InputMatch {\n /** How many characters of that text the rule consumed; the caller deletes them. */\n readonly remove: number\n readonly commands: Action\n /**\n * The marks the text typed next carries, when the rule decides it: `**bold**` ends its bold, so\n * typing on is plain, though the bold run would otherwise continue. Absent, the editor's own\n * rule applies.\n */\n readonly storedMarks?: ReadonlyArray<string> | undefined\n}\n\n/**\n * A rule over the text before the caret. `match` is a pure read: it sees the text and the\n * kinds of the node blocks around the caret's block, innermost first (`['ListItem',\n * 'List']` inside a bulleted item), and nothing else, so a rule cannot depend on a\n * selection, a clock, or the Model.\n */\nexport interface InputRule {\n readonly name: string\n readonly match: (textBefore: string, within: ReadonlyArray<string>) => InputMatch | undefined\n}\n\n/** One edit to read a rule against, named so two strings cannot be handed over swapped. */\nexport interface InputContext {\n /** The caret's block text before the caret, before this insertion. */\n readonly textBefore: string\n /** What was just typed. */\n readonly text: string\n /** The insertion itself, which a matching rule then acts on. */\n readonly insertion: Command\n /** The kinds of the node blocks around the caret's block, innermost first. Default none. */\n readonly within?: ReadonlyArray<string>\n}\n\n/**\n * The commands that insert the text and then let the first matching rule act on it: the\n * insertion, one backward delete per character the rule consumed, and the rule's commands.\n * Consumption is by deleting backwards rather than by a range, because a range would have\n * to be computed against a state the insertion has not produced yet — the deletes resolve\n * as each one runs. A rule that does not match yields the insertion alone.\n *\n * A rule that claims to consume more than it was shown throws: those deletes would run past\n * the block's start and join it to the one before, which no rule means.\n */\nexport const applyInputRules = (rules: ReadonlyArray<InputRule>, input: InputContext): Action =>\n resolveInputRules(rules, input).action\n\n/**\n * `applyInputRules`, with the marks the matching rule says the next typed text carries, which an\n * editor keeps as its stored marks.\n */\nexport const resolveInputRules = (\n rules: ReadonlyArray<InputRule>,\n input: InputContext,\n): { readonly action: Action; readonly storedMarks?: ReadonlyArray<string> | undefined } => {\n const typed = `${input.textBefore}${input.text}`\n for (const rule of rules) {\n const matched = rule.match(typed, input.within ?? [])\n if (matched === undefined) continue\n if (!Number.isInteger(matched.remove) || matched.remove < 0 || matched.remove > typed.length) {\n throw new RangeError(\n `Input rule \"${rule.name}\" removes ${matched.remove} characters of the ${typed.length} it was shown`,\n )\n }\n const consumed: ReadonlyArray<Command> = Array.from(\n { length: matched.remove },\n (): Command => ({ type: 'DeleteBackward' }),\n )\n return {\n action: [input.insertion, ...consumed, ...matched.commands],\n storedMarks: matched.storedMarks,\n }\n }\n return { action: [input.insertion] }\n}\n","import { Schema } from 'effect'\nimport type { Command } from './command.js'\nimport { EditorState } from './document.js'\n\n/**\n * Local undo history over editor snapshots. Snapshots are `EditorState` values\n * (document plus selection), so undo restores what the user saw, including the\n * caret. History is interaction state: it belongs in the application Model\n * beside the selection, never in published content, and collaborative undo is a\n * different operation (§§65–66).\n */\nexport const History = Schema.Struct({\n /** States to return to, oldest first. */\n past: Schema.Array(EditorState),\n /** States undone from, nearest first. */\n future: Schema.Array(EditorState),\n /** The group the last commit joined, if any. */\n group: Schema.optional(Schema.String),\n})\nexport type History = typeof History.Type\n\nexport const emptyHistory: History = Object.freeze({ past: [], future: [] })\n\nexport interface CommitOptions {\n /**\n * Joins the previous step when it used the same group. Consecutive typing\n * shares one undo step; omit the group and every commit stands alone.\n */\n readonly group?: string | undefined\n /** Most steps to keep; the oldest is dropped beyond this. Default 200. */\n readonly capacity?: number\n}\n\n/**\n * Typing continues one undo step; every other command is its own step. Callers\n * pass this to `commit`, so grouping policy lives with the editor vocabulary\n * rather than being reinvented per adapter.\n */\nexport const groupFor = (command: Command): string | undefined =>\n command.type === 'InsertText' ||\n command.type === 'DeleteBackward' ||\n command.type === 'DeleteForward'\n ? 'typing'\n : undefined\n\nconst bounded = (past: ReadonlyArray<EditorState>, capacity: number): ReadonlyArray<EditorState> =>\n past.length > capacity ? past.slice(past.length - capacity) : past\n\n/**\n * Records a committed transition. `previous` is the state before the command\n * and `next` the state after it; only `previous` is stored, because the caller\n * already holds `next`.\n */\nexport const commit = (\n history: History,\n previous: EditorState,\n options: CommitOptions = {},\n): History => {\n const joins = options.group !== undefined && history.group === options.group\n const past = joins ? history.past : bounded([...history.past, previous], options.capacity ?? 200)\n return options.group === undefined\n ? { past, future: [] }\n : { past, future: [], group: options.group }\n}\n\nexport interface Restore {\n readonly history: History\n readonly state: EditorState\n}\n\n/** Steps back one group. Returns undefined when there is nothing to undo. */\nexport const undo = (history: History, current: EditorState): Restore | undefined => {\n const previous = history.past[history.past.length - 1]\n if (previous === undefined) return undefined\n return {\n history: { past: history.past.slice(0, -1), future: [current, ...history.future] },\n state: previous,\n }\n}\n\n/** Steps forward again. Returns undefined when there is nothing to redo. */\nexport const redo = (history: History, current: EditorState): Restore | undefined => {\n const next = history.future[0]\n if (next === undefined) return undefined\n return {\n history: {\n past: [...history.past, current],\n future: history.future.slice(1),\n group: history.group,\n },\n state: next,\n }\n}\n\nexport const canUndo = (history: History): boolean => history.past.length > 0\nexport const canRedo = (history: History): boolean => history.future.length > 0\n\n/** Structural summary for tooling and tests. */\nexport const inspectHistory = (history: History) => ({\n past: history.past.length,\n future: history.future.length,\n group: history.group ?? null,\n})\n","/**\n * Decorations (§64): the ephemeral third kind beside Marks and Annotations. A\n * decoration is presentation derived from current state — a search match, a lint\n * warning, a remote cursor, a syntax token — rendered by an interpreter and then\n * discarded. It is never serialized, never part of undo, and never authored content,\n * which is why this module holds contracts rather than document data.\n *\n * The projection here is shared on purpose: a read-only renderer, the editable adapter,\n * and any other interpreter all need the same answer to \"which decorations cover this\n * run, and where\", so they compute it once, in the core, rather than each cutting ranges\n * their own way.\n */\nimport { eachBlock, type Document, type NodeId, type Position } from './document.js'\n\n/**\n * One decoration over a document range. `kind` is a fixed word the presentation is\n * chosen by (`search`, `syntax`, `cursor`, …); `data` is the renderer's own payload,\n * which the core never reads.\n */\nexport interface Decoration<Data = unknown> {\n readonly from: Position\n readonly to: Position\n readonly kind: string\n readonly data?: Data\n}\n\n/** A set of decorations is a value, computed for one render and then discarded. */\nexport type DecorationSet<Data = unknown> = ReadonlyArray<Decoration<Data>>\n\n/** A decoration's sub-range inside one run, in that run's own offsets. */\nexport interface DecorationSpan<Data = unknown> {\n readonly from: number\n readonly to: number\n readonly decoration: Decoration<Data>\n}\n\n/**\n * The decorations covering each run, as offsets into it, in document order. A decoration\n * that crosses runs is cut at each run's edge, so a renderer never has to reason about\n * document order; a decoration whose endpoints do not resolve is skipped rather than\n * guessed at, the way every other read treats a position it cannot resolve, and a\n * direction is honoured rather than required to run forwards.\n *\n * The runs are indexed once, so a decoration costs the runs it covers: a hundred search\n * matches over a long document is one walk, not a hundred.\n */\nexport const decorationsIn = <Data>(\n document: Document,\n set: DecorationSet<Data>,\n): ReadonlyMap<NodeId, ReadonlyArray<DecorationSpan<Data>>> => {\n const spans = new Map<NodeId, Array<DecorationSpan<Data>>>()\n if (set.length === 0) return spans\n // Document order is depth-first, which is what `compareRunPlaces` orders by too.\n const runs: Array<{ readonly id: NodeId; readonly length: number }> = []\n const indexByRun = new Map<NodeId, number>()\n eachBlock(document.children, block => {\n for (const run of block.children) {\n indexByRun.set(run.id, runs.length)\n runs.push({ id: run.id, length: run.text.length })\n }\n })\n for (const decoration of set) {\n const anchor = indexByRun.get(decoration.from.node)\n const focus = indexByRun.get(decoration.to.node)\n if (anchor === undefined || focus === undefined) continue\n const forward = anchor <= focus\n const first = forward ? anchor : focus\n const last = forward ? focus : anchor\n const firstOffset = forward ? decoration.from.offset : decoration.to.offset\n const lastOffset = forward ? decoration.to.offset : decoration.from.offset\n for (let index = first; index <= last; index += 1) {\n const run = runs[index]!\n const from = Math.max(0, index === first ? firstOffset : 0)\n const to = Math.min(run.length, index === last ? lastOffset : run.length)\n if (from >= to) continue\n const covered = spans.get(run.id)\n const span = { from, to, decoration }\n if (covered === undefined) spans.set(run.id, [span])\n else covered.push(span)\n }\n }\n // A renderer walks a run's text forwards, so its spans are in that order.\n for (const covered of spans.values()) covered.sort((left, right) => left.from - right.from)\n return spans\n}\n\n/** A stretch of one run's text, and the decorations covering all of it. */\nexport interface RunPiece<Data = unknown> {\n readonly text: string\n readonly decorations: ReadonlyArray<Decoration<Data>>\n}\n\n/**\n * A run's text cut at every edge of the spans over it, each piece with the decorations\n * that cover it — what every interpreter draws, so each draws the same pieces. An empty run,\n * or one no span touches, is one undecorated piece: an interpreter still has to render\n * somewhere for a caret to sit, and nothing can be drawn over no text.\n */\nexport const runPieces = <Data>(\n text: string,\n spans: ReadonlyArray<DecorationSpan<Data>>,\n): ReadonlyArray<RunPiece<Data>> => {\n if (spans.length === 0 || text.length === 0) return [{ text, decorations: [] }]\n const edges = new Set<number>([0, text.length])\n for (const span of spans) {\n edges.add(Math.max(0, Math.min(text.length, span.from)))\n edges.add(Math.max(0, Math.min(text.length, span.to)))\n }\n const cuts = [...edges].sort((left, right) => left - right)\n const pieces: Array<RunPiece<Data>> = []\n for (let index = 0; index < cuts.length - 1; index += 1) {\n const from = cuts[index]!\n const to = cuts[index + 1]!\n pieces.push({\n text: text.slice(from, to),\n decorations: spans\n .filter(span => span.from <= from && to <= span.to)\n .map(span => span.decoration),\n })\n }\n return pieces\n}\n","/**\n * Code highlighting, as decorations (§124 §7, §130): the document holds a `CodeBlock`'s\n * language and its plain text, and what a highlighter finds in that text is presentation,\n * derived and discarded like a search match. The contract lives here because it is\n * format-agnostic — a tokenizer is a function from text to ranges — while grammars, which\n * are not, live in `foldkit-richtext-code` and its Shiki adapter.\n */\nimport { eachBlock, positionInBlock, type Document } from './document.js'\nimport type { Decoration, DecorationSet } from './decoration.js'\n\n/**\n * One token in a code block's text, as offsets into that text. `kind` becomes the\n * decoration's kind, so it is what a stylesheet reaches the token by — a grammar names its\n * kinds `syntax-string`, `syntax-number`, and so on (§129).\n */\nexport interface CodeToken {\n readonly from: number\n readonly to: number\n readonly kind: string\n}\n\n/** A pure read of one code block's text. A tokenizer that needs to load first is Shiki's case. */\nexport type CodeTokenizer = (text: string) => ReadonlyArray<CodeToken>\n\n/**\n * Every token the given tokenizers find in the document's `CodeBlock`s, as decorations. A\n * block is tokenized by the tokenizer registered for its `language` prop; one with no\n * language, or one nothing is registered for, yields nothing. The registry is a `Map`\n * because the language is read from the document, and a plain object would answer a\n * language named `constructor` from its prototype.\n *\n * A token outside its block's text, one that covers nothing, or one at a fractional offset\n * throws with the language that produced it: it is a tokenizer's bug, and a decoration guessed from it would\n * highlight the wrong text.\n */\nexport const codeDecorations = (\n document: Document,\n tokenizers: ReadonlyMap<string, CodeTokenizer>,\n): DecorationSet => {\n const found: Array<Decoration> = []\n eachBlock(document.children, block => {\n if (block.type !== 'Node' || block.kind !== 'CodeBlock') return\n const language = block.props.language\n if (typeof language !== 'string') return\n const tokenizer = tokenizers.get(language)\n if (tokenizer === undefined) return\n const text = block.children.map(run => run.text).join('')\n for (const token of tokenizer(text)) {\n const covers =\n Number.isInteger(token.from) && Number.isInteger(token.to) && token.from < token.to\n const from = covers ? positionInBlock(block, token.from) : undefined\n const to = from === undefined ? undefined : positionInBlock(block, token.to)\n if (from === undefined || to === undefined) {\n throw new RangeError(\n `The ${language} tokenizer produced ${token.kind} at [${token.from}, ${token.to}) in a block of ${text.length} characters`,\n )\n }\n found.push({ from, to, kind: token.kind })\n }\n })\n return found\n}\n","/**\n * The URL policy every importer shares (§70, §124 §10). A link's `href` and an image's `src`\n * arrive from pasted HTML or Markdown, which is untrusted, and the standard rendering writes\n * them into attributes, so each passes here before it can become a prop, and again before\n * the standard rendering writes it.\n */\n\n/** Schemes a link or a source may carry; anything else — `javascript:`, `data:` — is refused. */\nconst SAFE_SCHEMES = new Set(['http', 'https', 'mailto', 'tel'])\n\n/**\n * A URL safe to carry into props, or `undefined` when it is not. Control characters are\n * removed first, because `java\\tscript:` and a leading NUL are how a scheme check is\n * usually walked past; then a URL that names a scheme outside the allowlist is refused,\n * and one with no scheme — a relative path, a fragment, a protocol-relative URL — is\n * kept. The value is never interpreted, only copied, so what a policy leaves through is\n * still the application's to trust.\n */\nexport const safeUrl = (value: string | null): string | undefined => {\n if (value === null) return undefined\n const cleaned = value.replace(/[\\u0000-\\u001F\\u007F]/g, '').trim()\n if (cleaned.length === 0) return undefined\n const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(cleaned)?.[1]?.toLowerCase()\n return scheme === undefined || SAFE_SCHEMES.has(scheme) ? cleaned : undefined\n}\n","/**\n * The standard semantic vocabulary (§124 §2, §125): the node kinds and marks a\n * document uses to mean what Markdown and HTML also mean, so an interpreter is a\n * mapping from this vocabulary rather than a private one. Declarations only — no\n * renderers, no executable code (§34) — and an application spreads them into its Kit\n * and adds its own:\n *\n * ```ts\n * RichText.kit({\n * nodes: [...RichText.standardNodes, Callout],\n * marks: [...RichText.standardMarks, Highlight],\n * })\n * ```\n *\n * `Paragraph` and `Heading` are built-in text blocks, `Code` is the inline-code mark,\n * and the rest are ordinary declarations. `HardBreak` is deliberately absent: it is\n * inline content, and the model has no inline atoms yet (§116, deferred).\n */\nimport { Option, Schema } from 'effect'\nimport { ImageAsset } from 'foldkit-media'\nimport { markExtent } from './command.js'\nimport { blockContent, rangeStart, textContent, type Document, type Selection } from './document.js'\nimport { atom, block, blocksOf, node, type NodeDefinition } from './kit.js'\nimport { Bold, Code, Italic, mark, markProps, type MarkDef } from './marks.js'\nimport { rendering, type Rendering } from './rendering.js'\nimport { safeUrl } from './url.js'\n\n/**\n * A struck-through span. It expands `after`, so typing at its edge continues it, as\n * bold and italic do.\n */\nexport const Strikethrough = mark('Strikethrough', { expand: 'after' })\n\n/**\n * A hyperlink. Its `href` is a prop rather than a mark name, which is what lets the\n * serializer render a real `<a href>` (§121); it expands `none`, because text typed\n * after a link is new text, not a continuation of the link.\n */\nexport const Link = mark('Link', {\n Props: Schema.Struct({ href: Schema.String }),\n expand: 'none',\n})\n\n/** The link a selection starts in: its `href`, and the range of runs it spans. */\nexport interface LinkAt {\n /** The stored `href`, or `''` when the stored one is not a string. */\n readonly href: string\n readonly selection: Extract<Selection, { readonly type: 'Range' }>\n}\n\n/**\n * The link a selection starts in, which is what a link editor opens on: at a caret, the\n * link around it; over a range, the link its start is in. Undefined outside a link, and for\n * a node selection, which covers blocks rather than text.\n */\nexport const linkAt = (document: Document, selection: Selection | null): LinkAt | undefined => {\n if (selection?.type !== 'Range') return undefined\n const start = rangeStart(document, selection)\n const extent = start === undefined ? undefined : markExtent(document, start, Link.name)\n if (extent === undefined) return undefined\n const href = markProps(extent.mark)?.href\n return { href: typeof href === 'string' ? href : '', selection: extent.selection }\n}\n\n/** Every mark the standard vocabulary names, in menu order. */\nexport const standardMarks: ReadonlyArray<MarkDef> = [Bold, Italic, Code, Strikethrough, Link]\n\n/**\n * The standard node kinds. Constraints are what make a kind more than a name: a\n * `List` accepts only `ListItem`s and a `Table` only `TableRow`s, so `validate`\n * reports a document that says otherwise (§125); a `CodeBlock` carries text with no\n * formatting, and its `language` is a prop, not a mark.\n */\nexport const standardNodes: ReadonlyArray<NodeDefinition> = [\n block('Paragraph'),\n block('Heading'),\n node('Quote', { children: blockContent }),\n node('List', {\n // An ordered list, and where its numbering starts; both are Markdown's.\n Props: Schema.Struct({\n ordered: Schema.optional(Schema.Boolean),\n start: Schema.optional(Schema.Number),\n }),\n children: blocksOf('ListItem', 'TaskItem'),\n }),\n node('ListItem', { children: blockContent, within: ['List'] }),\n node('TaskItem', {\n Props: Schema.Struct({ checked: Schema.Boolean }),\n children: blockContent,\n // A task split off a done one is a new task, not a done one.\n splitProps: { checked: false },\n within: ['List'],\n }),\n node('CodeBlock', {\n Props: Schema.Struct({ language: Schema.optional(Schema.String) }),\n children: textContent,\n marks: 'none',\n lineBreaks: true,\n indents: true,\n }),\n atom('ThematicBreak'),\n atom('Image', {\n // What a figure needs beside its source: a caption under it, the width it is shown at in\n // CSS pixels, and which way it sits. The standard rendering draws the `img` alone; a\n // rendering that draws a figure reads the rest (`examples/richtext-playground`).\n // `asset` is what `src` names, its size, hash and placeholder, kept as stored (`null` for\n // what it lacks): known where the image entered (an upload, a file a reader added), it\n // lets a page hold the image's box before the file arrives. Optional, so a document saved\n // without it is as valid as ever.\n Props: Schema.Struct({\n src: Schema.String,\n alt: Schema.optional(Schema.String),\n caption: Schema.optional(Schema.String),\n width: Schema.optional(Schema.Number.check(Schema.isGreaterThan(0))),\n align: Schema.optional(Schema.Literals(['start', 'center', 'end'])),\n asset: Schema.optional(ImageAsset),\n }),\n }),\n node('Table', { children: blocksOf('TableRow') }),\n node('TableRow', {\n // GFM's first row is the header; saying so explicitly is what lets HTML and Markdown\n // agree about it instead of each assuming.\n Props: Schema.Struct({ header: Schema.optional(Schema.Boolean) }),\n children: blocksOf('TableCell'),\n within: ['Table'],\n }),\n // A cell's content stays in the cell: Backspace at its start lifts nothing out of it.\n node('TableCell', { children: blockContent, isolating: true, within: ['TableRow'] }),\n]\n\nconst decodeAsset = Schema.decodeUnknownOption(ImageAsset)\n\n/**\n * An `Image`'s `width` and `height` attributes from its props' `asset`, at its drawn `width`\n * when it has one, so a page keeps the box before the file arrives; none without facts. The\n * standard rendering writes them; a rendering of its own (a figure) spreads them on its `img`.\n * The facts are trusted to be `src`'s: whatever changes `src` replaces or clears `asset`.\n */\nexport const imageBox = (\n props: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, string>> =>\n Option.match(decodeAsset(props['asset']), {\n onNone: () => ({}),\n onSome: ({ width, height }) => {\n const drawn = props['width']\n const shown = typeof drawn === 'number' && drawn > 0 ? drawn : width\n return {\n width: String(Math.round(shown)),\n height: String(Math.round((shown * height) / width)),\n }\n },\n })\n\n/**\n * A URL attribute, or none when the value fails the URL policy. Import already applies the\n * policy, but a document also arrives decoded, synchronized, or edited through `SetMark`,\n * and this is where a `javascript:` href would become live.\n */\nconst urlAttribute = (name: string, value: unknown): Readonly<Record<string, string>> => {\n const safe = typeof value === 'string' ? safeUrl(value) : undefined\n return safe === undefined ? {} : { [name]: safe }\n}\n\n/**\n * How the standard vocabulary renders (§121): the element each kind is, with the props\n * that belong in attributes read from the block, so a `Link` is an `<a href>`, an `Image`\n * carries its source, and a `List` is an `<ol>` or a `<ul>`. The shipped marks already\n * nest in `strong`/`em`/`code`; this adds the two that do not. An application composes it\n * with `renderingOver` and names its own kinds beside it:\n *\n * ```ts\n * renderingOver(RichText.standardRendering, { nodes: { Callout: { tag: 'aside' } } })\n * ```\n */\nexport const standardRendering: Rendering = rendering({\n marks: {\n Strikethrough: { tag: 's', attributes: {} },\n Link: mark => ({ tag: 'a', attributes: urlAttribute('href', markProps(mark)?.href) }),\n },\n nodes: {\n Quote: { tag: 'blockquote', attributes: {} },\n List: block => {\n const ordered = block.props.ordered === true\n const start = block.props.start\n return {\n tag: ordered ? 'ol' : 'ul',\n attributes: ordered && typeof start === 'number' ? { start: String(start) } : {},\n }\n },\n ListItem: { tag: 'li', attributes: {} },\n TaskItem: block => ({\n tag: 'li',\n attributes: { 'data-task': block.props.checked === true ? 'checked' : 'unchecked' },\n }),\n CodeBlock: block => ({\n tag: 'pre',\n attributes: { 'data-language': String(block.props.language ?? '') },\n }),\n ThematicBreak: { tag: 'hr', attributes: {} },\n Image: block => ({\n tag: 'img',\n attributes: {\n ...urlAttribute('src', block.props.src),\n alt: String(block.props.alt ?? ''),\n ...imageBox(block.props),\n },\n }),\n Table: { tag: 'table', attributes: {}, inner: 'tbody' },\n // A row says it is the header; its cells do not have to be told apart by their parent.\n TableRow: block =>\n block.props.header === true\n ? { tag: 'tr', attributes: { 'data-header': '' } }\n : { tag: 'tr', attributes: {} },\n TableCell: { tag: 'td', attributes: {} },\n },\n})\n","import { Schema } from 'effect'\nimport {\n Block,\n NodeBlock,\n NodeId,\n Document,\n blockContent,\n textContent,\n type ContentMode,\n} from './document.js'\n\n/**\n * Migrations move semantic data forward when a deployment changes its\n * vocabulary (§73): a preserved node that is now implemented, a prop renamed, a\n * block kind replaced. They operate on blocks, never on DOM, and they run at a\n * boundary the application chooses — loading, publishing, or an explicit\n * upgrade — never automatically on every read.\n *\n * Two rules keep a migration safe to run anywhere:\n *\n * - **Identity survives.** A migration returns the same `id`, so positions,\n * references, and selections keep addressing the same node.\n * - **Declining is allowed.** Returning `undefined` keeps the block as it is,\n * which is what a migration does when the data is not its shape after all.\n */\nexport interface Migration {\n readonly name: string\n /** The type, kind, or preserved `originalType` this migration reads. */\n readonly from: string\n /** The kind it produces, for a report; the returned block is the truth. */\n readonly to?: string | undefined\n readonly migrate: (block: Block) => Block | undefined\n}\n\nexport interface MigrationApplied {\n readonly name: string\n readonly node: NodeId\n}\n\nexport interface MigrationReport {\n readonly document: Document\n /** Every block a migration rewrote, in the order it happened. */\n readonly applied: ReadonlyArray<MigrationApplied>\n /** Migrations that found no block of their `from` in this document. */\n readonly unused: ReadonlyArray<string>\n}\n\nconst matches = (block: Block, from: string): boolean =>\n block.type === 'Unknown'\n ? block.originalType === from\n : block.type === 'Node'\n ? block.kind === from\n : block.type === from\n\nconst decodeMigratedDocument = Schema.decodeUnknownSync(Document, { onExcessProperty: 'error' })\n\n/** Declares a migration, checking at construction that it is shaped like one. */\nexport const migration = (\n name: string,\n from: string,\n migrate: (block: Block) => Block | undefined,\n to?: string,\n): Migration => {\n if (name.length === 0) throw new Error('Migration.make: a migration needs a name')\n if (from.length === 0) throw new Error(`Migration \"${name}\": from must not be empty`)\n return { name, from, migrate, to }\n}\n\n/**\n * Runs one migration over a block list, recursing into containers so a nested\n * block is migrated where it sits. A later migration sees what an earlier one\n * produced, because the caller runs them in list order.\n */\nconst migrateBlocks = (\n blocks: ReadonlyArray<Block>,\n migration: Migration,\n applied: Array<MigrationApplied>,\n): { readonly blocks: ReadonlyArray<Block>; readonly changed: boolean } => {\n let changed = false\n const next = blocks.map(block => {\n let current = block\n if (current.type === 'Node' && current.blocks !== undefined) {\n const nested = migrateBlocks(current.blocks, migration, applied)\n if (nested.changed) {\n changed = true\n current = { ...current, blocks: nested.blocks }\n }\n }\n if (!matches(current, migration.from)) return current\n const migrated = migration.migrate(current)\n if (migrated === undefined) return current\n // A migration that changes a block's identity is a bug: it would silently\n // break every reference to that node.\n if (migrated.id !== current.id) {\n throw new Error(`Migration \"${migration.name}\" changed a block's identity`)\n }\n // What a migration returns becomes persisted content, so it must still\n // decode as a block: a migration cannot write non-JSON props or an\n // unknown shape into the document.\n try {\n Schema.decodeUnknownSync(Block, { onExcessProperty: 'error' })(migrated)\n } catch {\n throw new Error(`Migration \"${migration.name}\" produced an invalid block`)\n }\n applied.push({ name: migration.name, node: current.id })\n changed = true\n return migrated\n })\n return { blocks: changed ? next : blocks, changed }\n}\n\n/**\n * Runs each migration over every block it reads, in list order, descending into\n * containers. A migration that changes a block's identity is a bug and throws\n * rather than silently breaking every reference to that node.\n */\nexport const migrate = (\n document: Document,\n migrations: ReadonlyArray<Migration>,\n): MigrationReport => {\n const applied: Array<MigrationApplied> = []\n const unused: Array<string> = []\n let next = document\n for (const migration of migrations) {\n const result = migrateBlocks(next.children, migration, applied)\n if (!result.changed) {\n unused.push(migration.name)\n continue\n }\n next = { ...next, children: result.blocks }\n try {\n decodeMigratedDocument(next)\n } catch {\n throw new Error(`Migration \"${migration.name}\" produced an invalid document`)\n }\n }\n return { document: next, applied, unused }\n}\n\n/**\n * A migration from a preserved unknown block into a declared node kind: the\n * props are decoded by the target's own schema, and a block whose data does not\n * decode is left alone rather than half-converted. The target's content mode\n * decides whether the promoted node holds runs or (empty) nested blocks, so\n * promoting into a container kind produces a valid block rather than one the\n * Kit will call a mismatch.\n */\nexport const promoteUnknown = (\n name: string,\n from: string,\n to: string,\n Props: Schema.Codec<any, any, never>,\n children: ContentMode = textContent,\n): Migration =>\n migration(\n name,\n from,\n block => {\n if (block.type !== 'Unknown') return undefined\n const decoded = decodeProps(Props, block.props)\n if (decoded === undefined) return undefined\n const promoted: NodeBlock = {\n type: 'Node',\n kind: to,\n id: block.id,\n props: decoded,\n children: [],\n }\n return children === blockContent ? { ...promoted, blocks: [] } : promoted\n },\n to,\n )\n\nconst decodeProps = (\n Props: Schema.Codec<any, any, never>,\n props: Readonly<Record<string, unknown>>,\n): NodeBlock['props'] | undefined => {\n try {\n const decoded: unknown = Schema.decodeUnknownSync(Props)(props)\n // Persisted props stay JSON: a schema that produces something else is\n // declined rather than written into the document.\n return Schema.decodeUnknownSync(Schema.JsonObject)(decoded)\n } catch {\n return undefined\n }\n}\n\n/** A node block's props as the codec stores them: plain JSON, nothing more. */\nexport const nodeProps = (block: NodeBlock): Readonly<Record<string, unknown>> => block.props\n","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","/**\n * The document's outline: its headings in document order, which a table of contents draws, and\n * the section a selection is in. Both are reads; nothing here changes the document.\n */\nimport { eachBlock, rangeStart, type Document, type NodeId, type Selection } from './document.js'\n\n/** One heading: its identity, its level, and its text. */\nexport interface OutlineEntry {\n readonly node: NodeId\n readonly level: number\n readonly text: string\n}\n\n/** Every heading with text, in document order, inside containers too. */\nexport const outlineOf = (document: Document): ReadonlyArray<OutlineEntry> => {\n const entries: Array<OutlineEntry> = []\n eachBlock(document.children, block => {\n if (block.type !== 'Heading') return\n const text = block.children.map(run => run.text).join('')\n if (text.trim() !== '') entries.push({ node: block.id, level: block.level, text })\n })\n return entries\n}\n\n/**\n * The heading of the section the selection starts in: the last heading with text at or before\n * its block. Undefined with no selection, or before the first heading.\n */\nexport const sectionAt = (document: Document, selection: Selection | null): NodeId | undefined => {\n if (selection?.type !== 'Range') return undefined\n const start = rangeStart(document, selection)\n if (start === undefined) return undefined\n let last: NodeId | undefined\n let found: NodeId | undefined\n eachBlock(document.children, block => {\n if (block.type === 'Heading' && block.children.some(run => run.text.trim() !== '')) {\n last = block.id\n }\n if (block.children.some(run => run.id === start.node)) {\n found = last\n }\n })\n return found\n}\n","/**\n * Media beside the standard `Image`: a video and a sound played with the browser's own controls,\n * and a file to download. Opt-in vocabulary like footnotes: add `mediaNodes` to a kit and draw\n * them with `mediaRendering` under the rendering. Each is an atom holding where its media is\n * (`src`); where that is, a `data:` URL read from a file or a URL an upload returned, is the\n * application's to decide.\n */\nimport { Schema } from 'effect'\nimport { NodeId, type Block } from './document.js'\nimport { atom } from './kit.js'\nimport { rendering, type Rendering } from './rendering.js'\nimport { safeUrl } from './url.js'\n\nconst Width = Schema.optional(Schema.Number.check(Schema.isGreaterThan(0)))\n\n/** A video, played with the browser's controls, at `width` CSS pixels when it says. */\nexport const Video = atom('Video', {\n Props: Schema.Struct({ src: Schema.String, title: Schema.optional(Schema.String), width: Width }),\n})\n\n/** A sound, played with the browser's controls. */\nexport const Audio = atom('Audio', {\n Props: Schema.Struct({ src: Schema.String, title: Schema.optional(Schema.String) }),\n})\n\n/** A file to download, under its name, with its size and type when they are known. */\nexport const Attachment = atom('Attachment', {\n Props: Schema.Struct({\n src: Schema.String,\n name: Schema.String,\n size: Schema.optional(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0))),\n type: Schema.optional(Schema.String),\n }),\n})\n\nexport const mediaNodes = [Video, Audio, Attachment]\n\n/** Types a page could run as script or markup if one were ever opened rather than saved. */\nconst ACTIVE = /^(text\\/html|application\\/xhtml\\+xml|image\\/svg\\+xml|text\\/xml|application\\/xml)\\b/i\n\n/**\n * Where a media element may load from: what the URL policy allows, or a `data:` URL whose type\n * `accepts` admits. The policy refuses `data:` in general, since a link to one could carry a\n * page; a video's own bytes cannot.\n */\nconst mediaUrl = (value: unknown, accepts: (type: string) => boolean): string | undefined => {\n if (typeof value !== 'string') return undefined\n const data = /^data:([^;,]*)[;,]/i.exec(value.trim())\n if (data === null) return safeUrl(value)\n return accepts(data[1] ?? '') ? value.trim() : undefined\n}\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value : '')\n\n/** A size as a reader says it: `820 B`, `12 KB`, `3.4 MB`. */\nexport const fileSize = (bytes: number): string => {\n if (bytes < 1024) return `${bytes} B`\n if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`\n}\n\n/**\n * How media draws: a `video` or `audio` with `controls`, which loads only its metadata until it\n * is played, and an attachment as a download link showing its name and size. A source the policy\n * refuses leaves the element without one, so it draws nothing playable.\n */\nexport const mediaRendering: Rendering = rendering({\n nodes: {\n Video: block => {\n const src = mediaUrl(block.props.src, type => type.toLowerCase().startsWith('video/'))\n const width = block.props.width\n return {\n tag: 'video',\n attributes: {\n ...(src === undefined ? {} : { src }),\n controls: '',\n preload: 'metadata',\n title: text(block.props.title),\n ...(typeof width === 'number' ? { width: String(width) } : {}),\n },\n }\n },\n Audio: block => {\n const src = mediaUrl(block.props.src, type => type.toLowerCase().startsWith('audio/'))\n return {\n tag: 'audio',\n attributes: {\n ...(src === undefined ? {} : { src }),\n controls: '',\n preload: 'metadata',\n title: text(block.props.title),\n },\n }\n },\n Attachment: block => {\n const href = mediaUrl(block.props.src, type => !ACTIVE.test(type))\n const name = text(block.props.name)\n const size = block.props.size\n return {\n tag: 'a',\n attributes: {\n ...(href === undefined ? {} : { href }),\n download: name,\n 'data-attachment': '',\n },\n adornments: [\n { tag: 'span', attributes: { 'data-attachment-name': '' }, text: name },\n ...(typeof size === 'number'\n ? [{ tag: 'span', attributes: { 'data-attachment-size': '' }, text: fileSize(size) }]\n : []),\n ],\n }\n },\n },\n})\n\n/** A file a reader added, as its type says: where it is, and what it is called. */\nexport interface MediaFile {\n readonly src: string\n readonly name: string\n readonly type: string\n readonly size: number\n}\n\n/**\n * The block for a file a reader added: an `Image`, `Video` or `Audio` when its type is one, and\n * an `Attachment` otherwise. Its identity is a placeholder, which `InsertBlock` replaces.\n */\nexport const mediaBlock = (file: MediaFile): Block => {\n const family = file.type.toLowerCase().split('/')[0]\n const title = file.name.replace(/\\.[^.]+$/, '')\n const node = (kind: string, props: Readonly<Record<string, string | number>>): Block => ({\n type: 'Node',\n kind,\n id: NodeId.make('media'),\n props,\n children: [],\n })\n if (family === 'image') return node('Image', { src: file.src, alt: title })\n if (family === 'video') return node('Video', { src: file.src, title })\n if (family === 'audio') return node('Audio', { src: file.src, title })\n return node('Attachment', {\n src: file.src,\n name: file.name,\n size: file.size,\n ...(file.type === '' ? {} : { type: file.type }),\n })\n}\n"],"mappings":";;;;;AAGA,MAAa,SAAS,OAAO,eAAe,KAAK,OAAO,MAAM,yBAAyB,CAAC;;A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