@pixerate/editor 0.59.0 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/agent/index.cjs +111 -38
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +30 -2
  4. package/dist/agent/index.d.ts +30 -2
  5. package/dist/agent/index.js +96 -23
  6. package/dist/agent/index.js.map +1 -1
  7. package/dist/agent-caret-BmYhQF7L.d.cts +106 -0
  8. package/dist/agent-caret-BmYhQF7L.d.ts +106 -0
  9. package/dist/animation-editor/index.cjs +85 -47
  10. package/dist/animation-editor/index.cjs.map +1 -1
  11. package/dist/animation-editor/index.d.cts +82 -2
  12. package/dist/animation-editor/index.d.ts +82 -2
  13. package/dist/animation-editor/index.js +84 -46
  14. package/dist/animation-editor/index.js.map +1 -1
  15. package/dist/{chunk-LMUDHBWR.js → chunk-4YFMSPBU.js} +2 -2
  16. package/dist/{chunk-3I6V7PI4.cjs → chunk-7ZSU4MQZ.cjs} +45 -45
  17. package/dist/{chunk-3I6V7PI4.cjs.map → chunk-7ZSU4MQZ.cjs.map} +1 -1
  18. package/dist/{chunk-WLVZ235X.js → chunk-OK7T2LHK.js} +229 -2
  19. package/dist/chunk-OK7T2LHK.js.map +1 -0
  20. package/dist/{chunk-AHCENCU4.cjs → chunk-T4XWVPJK.cjs} +253 -26
  21. package/dist/chunk-T4XWVPJK.cjs.map +1 -0
  22. package/dist/extensions/index.cjs +27 -3
  23. package/dist/extensions/index.cjs.map +1 -1
  24. package/dist/extensions/index.d.cts +2 -1
  25. package/dist/extensions/index.d.ts +2 -1
  26. package/dist/extensions/index.js +26 -2
  27. package/dist/{index-CTCc3m3C.d.ts → index-B16wbOn_.d.ts} +1 -0
  28. package/dist/{index-BcHyG0Wq.d.cts → index-BAt14aIU.d.cts} +1 -0
  29. package/dist/index.cjs +32 -8
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +3 -2
  32. package/dist/index.d.ts +3 -2
  33. package/dist/index.js +26 -2
  34. package/dist/index.js.map +1 -1
  35. package/package.json +1 -1
  36. package/dist/chunk-AHCENCU4.cjs.map +0 -1
  37. package/dist/chunk-WLVZ235X.js.map +0 -1
  38. /package/dist/{chunk-LMUDHBWR.js.map → chunk-4YFMSPBU.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/extensions/table/nesting.ts","../src/extensions/find-replace/pattern.ts","../src/extensions/find-replace/search.ts","../src/extensions/table/extension.ts","../src/extensions/chart/node-view.ts","../src/extensions/chart/chart-node.ts","../src/extensions/document-structure/utils.ts","../src/extensions/chart/sparkline-node.ts","../src/extensions/table/actions.ts"],"sourcesContent":["import { Fragment, Slice, type Node as ProsemirrorNode, type ResolvedPos } from \"@tiptap/pm/model\";\nimport { Plugin, PluginKey, Selection, type Transaction } from \"@tiptap/pm/state\";\nimport type { EditorView } from \"@tiptap/pm/view\";\nimport {\n CellSelection,\n __pastedCells,\n handlePaste as handleTablePaste,\n} from \"@tiptap/pm/tables\";\n\n/**\n * Set this meta on a transaction to let it create tables inside table cells\n * (the nesting guard leaves it alone), e.g. when loading legacy content\n * through a transaction that does not replace the whole document.\n */\nexport const ALLOW_NESTED_TABLES_META = \"allowNestedTables\";\n\nexport const tableNestingPluginKey = new PluginKey(\"tableNesting\");\n\nconst roleOf = (node: ProsemirrorNode) => node.type.spec.tableRole as string | undefined;\nconst isTableNode = (node: ProsemirrorNode) => roleOf(node) === \"table\";\n\n/** Depth of the outermost table around `$pos`, or `-1` outside tables. */\nexport function outermostTableDepth($pos: ResolvedPos): number {\n for (let d = 1; d <= $pos.depth; d++) if (isTableNode($pos.node(d))) return d;\n return -1;\n}\n\n/** Whether `$pos` lies inside a table cell or header cell. */\nexport function isInTableCell($pos: ResolvedPos): boolean {\n for (let d = $pos.depth; d > 0; d--) {\n const role = roleOf($pos.node(d));\n if (role === \"cell\" || role === \"header_cell\") return true;\n }\n return false;\n}\n\n/** Whether a slice or fragment contains a table node at any depth. */\nexport function sliceContainsTable(content: Slice | Fragment): boolean {\n const fragment = content instanceof Slice ? content.content : content;\n let found = false;\n fragment.descendants((node) => {\n if (found) return false;\n if (isTableNode(node)) found = true;\n return !found;\n });\n return found;\n}\n\n/**\n * Inserts `slice` right after the outermost table around `from` instead of\n * inside the cell, deleting `from`–`to` first when both lie in that table.\n * Returns the position right after the inserted content, or `null` (and\n * leaves `tr` unchanged) when `from` is not in a table.\n */\nexport function insertSliceAfterTable(tr: Transaction, from: number, to: number, slice: Slice): number | null {\n const $from = tr.doc.resolve(from);\n const depth = outermostTableDepth($from);\n if (depth < 0) return null;\n const tableStart = $from.before(depth);\n const tableEnd = $from.after(depth);\n if (to > from && to < tableEnd) {\n if (tr.selection instanceof CellSelection && tr.selection.from === from && tr.selection.to === to) {\n tr.deleteSelection();\n } else {\n tr.delete(from, to);\n }\n }\n const table = tr.doc.nodeAt(tableStart);\n if (!table) return null;\n const after = tableStart + table.nodeSize;\n const before = tr.doc.content.size;\n // A closed slice: the content becomes blocks of its own after the table\n // instead of merging into whatever follows it.\n tr.replace(after, after, new Slice(slice.content, 0, 0));\n return after + (tr.doc.content.size - before);\n}\n\n/**\n * Paste handling for slices that contain a table while the selection is in a\n * table: a cell selection or a pasted table (rows, cells) fills the cells from\n * the cursor (prosemirror-tables), and anything else that contains a table is\n * inserted after the outermost table, with the cursor at its end. Returns\n * `false` when the paste needs no special handling.\n */\nexport function handleTablePasteWithoutNesting(view: EditorView, event: ClipboardEvent | null, slice: Slice): boolean {\n const { state } = view;\n const { selection } = state;\n if (outermostTableDepth(selection.$from) < 0) return false;\n if (selection instanceof CellSelection || __pastedCells(slice)) {\n if (handleTablePaste(view, event as ClipboardEvent, slice)) return true;\n }\n if (!sliceContainsTable(slice)) return false;\n const tr = state.tr;\n const end = insertSliceAfterTable(tr, selection.from, selection.to, slice);\n if (end === null) return false;\n tr.setSelection(Selection.near(tr.doc.resolve(end), -1));\n view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n return true;\n}\n\n/**\n * Ranges of the final document that `transactions` changed, leaving out the\n * changes of skipped transactions (their steps still map the other ranges).\n */\nfunction changedRanges(transactions: readonly Transaction[], skip: (tr: Transaction) => boolean): [number, number][] {\n let ranges: [number, number][] = [];\n for (const tr of transactions) {\n const skipped = skip(tr);\n for (const step of tr.steps) {\n const map = step.getMap();\n // Content that later (skipped) steps insert at a range's edge is not\n // part of it; pure deletions leave nothing to check.\n ranges = ranges\n .map(([from, to]): [number, number] => [map.map(from, 1), map.map(to, -1)])\n .filter(([from, to]) => to > from);\n if (skipped) continue;\n map.forEach((_oldStart, _oldEnd, newStart, newEnd) => {\n if (newEnd > newStart) ranges.push([newStart, newEnd]);\n });\n }\n }\n return ranges;\n}\n\n/** Tables starting inside `ranges` that sit in a table cell. */\nfunction findNestedTables(doc: ProsemirrorNode, ranges: [number, number][]): number[] {\n const found = new Set<number>();\n for (const [from, to] of ranges) {\n doc.nodesBetween(from, to, (node, pos) => {\n if (!isTableNode(node) || pos < from) return true;\n if (isInTableCell(doc.resolve(pos))) {\n found.add(pos);\n return false;\n }\n return true;\n });\n }\n // A table inside another found table moves with it.\n const sorted = [...found].sort((a, b) => a - b);\n const outer: number[] = [];\n for (const pos of sorted) {\n const last = outer[outer.length - 1];\n if (last === undefined || pos >= last + doc.nodeAt(last)!.nodeSize) outer.push(pos);\n }\n return outer;\n}\n\n/**\n * Moves tables that sit in table cells (at positions in `ranges`) to right\n * after their outermost table, keeping their content, and repeats for tables\n * nested in the moved ones. A cell left without content gets an empty\n * paragraph. Returns whether `tr` changed.\n */\nexport function unnestTables(tr: Transaction, ranges: [number, number][]): boolean {\n let changed = false;\n for (let round = 0; round < 32 && ranges.length; round++) {\n const nested = findNestedTables(tr.doc, ranges);\n if (!nested.length) break;\n // Group by outermost table; handle later tables first so earlier\n // positions stay valid.\n const groups = new Map<number, number[]>();\n for (const pos of nested) {\n const $pos = tr.doc.resolve(pos);\n const outer = $pos.before(outermostTableDepth($pos));\n groups.set(outer, [...(groups.get(outer) ?? []), pos]);\n }\n const next: [number, number][] = [];\n for (const outer of [...groups.keys()].sort((a, b) => b - a)) {\n const positions = groups.get(outer)!;\n const nodes = positions.map((pos) => tr.doc.nodeAt(pos)!);\n for (let i = positions.length - 1; i >= 0; i--) {\n const pos = positions[i];\n const node = nodes[i];\n const $pos = tr.doc.resolve(pos);\n const parent = $pos.parent;\n const filler = parent.childCount === 1 ? parent.type.contentMatch.defaultType?.createAndFill() : null;\n if (filler) tr.replaceWith(pos, pos + node.nodeSize, filler);\n else tr.delete(pos, pos + node.nodeSize);\n }\n const table = tr.doc.nodeAt(outer)!;\n const after = outer + table.nodeSize;\n const fragment = Fragment.fromArray(nodes);\n tr.insert(after, fragment);\n // Later groups are before this one, so this range stays valid.\n next.push([after, after + fragment.size]);\n changed = true;\n }\n ranges = next;\n }\n return changed;\n}\n\n/**\n * Whether a transaction replaces the whole document (`setContent`, loading):\n * existing documents keep their nested tables.\n */\nfunction replacesDocument(tr: Transaction): boolean {\n return tr.steps.some((step, i) => {\n const { from, to } = step as unknown as { from?: number; to?: number };\n return from === 0 && to !== undefined && to >= tr.docs[i].content.size;\n });\n}\n\nconst skip = (tr: Transaction) =>\n !tr.docChanged ||\n tr.getMeta(ALLOW_NESTED_TABLES_META) === true ||\n // Undo/redo and remote collaborative changes restore what was there.\n !!tr.getMeta(\"history$\") ||\n !!tr.getMeta(\"y-sync$\") ||\n // Other plugins' housekeeping, e.g. Track Changes putting a deleted\n // (nested) table back so the deletion can be reviewed.\n !!tr.getMeta(\"appendedTransaction\") ||\n replacesDocument(tr);\n\n/**\n * Keeps tables out of table cells: paste handling (see\n * `handleTablePasteWithoutNesting`) plus a guard that moves any table a\n * local edit puts into a cell (`insertContent`, `insertTable`, drops) to\n * right after the outermost table. Documents that already contain nested\n * tables (initial content, `setContent`, undo/redo, collaboration, Track\n * Changes restoring a deleted table) are left as they are.\n */\nexport function createTableNestingPlugin(): Plugin {\n return new Plugin({\n key: tableNestingPluginKey,\n props: {\n handlePaste: (view, event, slice) => handleTablePasteWithoutNesting(view, event, slice),\n },\n appendTransaction(transactions, _oldState, newState) {\n if (transactions.every(skip)) return null;\n const ranges = changedRanges(transactions, skip);\n if (!ranges.length) return null;\n const tr = newState.tr;\n if (!unnestTables(tr, ranges)) return null;\n return tr;\n },\n });\n}\n","// Portions ported from wordcraft/crates/engine/src/cmd/find_pattern.rs and crates/engine/src/cmd/edit.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\n/**\n * Word's Find and Replace patterns: special characters (`^p`, `^t`, `^#` …),\n * the \"Use wildcards\" language (`?`, `*`, `[a-z]`, `[!x]`, `{n,m}`, `@`, `<`,\n * `>`, `( )`) and a raw regular-expression mode.\n *\n * Special and wildcard patterns are compiled to a small program run by a\n * Pike VM, which takes time linear in the text for a given pattern, so no\n * Find text can backtrack catastrophically (JavaScript's `RegExp` would). The\n * raw regex mode uses the native `RegExp` engine; it rejects nested\n * repetition and is bounded by the search budget between matches only.\n *\n * Pure TypeScript: no ProseMirror or DOM.\n */\n\n/** A paragraph mark in the searched text (`^p`). */\nexport const FIND_PARAGRAPH_MARK = \"\\r\";\n/** Longest Find what text, in characters. */\nexport const MAX_FIND_PATTERN_LENGTH = 1024;\n/** Largest count in `{n,m}`. */\nconst MAX_COUNT = 1000;\n/** Largest compiled program (instructions). Larger patterns are `too_complex`. */\nconst MAX_PROGRAM_SIZE = 20_000;\n\nexport interface FindOptions {\n matchCase?: boolean;\n /** Find whole words only (ignored with wildcards, like Word). */\n wholeWord?: boolean;\n /** The match must start a word. */\n matchPrefix?: boolean;\n /** The match must end a word. */\n matchSuffix?: boolean;\n /** Skip punctuation between the characters of the Find text. */\n ignorePunctuation?: boolean;\n /** Skip spaces and tabs between the characters of the Find text. */\n ignoreWhitespace?: boolean;\n /** Word's \"Use wildcards\". Always matches case. */\n wildcards?: boolean;\n /** A JavaScript regular expression (wins over `wildcards`). Replace text is literal. */\n regex?: boolean;\n /** Read the Find and Replace text literally: no `^` codes. */\n literal?: boolean;\n}\n\nexport type FindPatternErrorCode = \"too_long\" | \"invalid_pattern\" | \"too_complex\";\n\n/** Why a Find text cannot be used. Commands report it; they never throw it. */\nexport interface FindPatternError {\n code: FindPatternErrorCode;\n message: string;\n}\n\n/** One match in a searched string (UTF-16 offsets). */\nexport interface PatternMatch {\n start: number;\n end: number;\n /** Text of each group; index 0 is the whole match, unmatched groups are `undefined`. */\n groups: (string | undefined)[];\n}\n\n/** Shared limit on the work one search may do. */\nexport interface SearchBudget {\n /** `performance.now()`/`Date.now()` value after which the search stops. */\n deadline: number;\n /** VM steps left. */\n steps: number;\n /** Set once the budget ran out. */\n exhausted: boolean;\n}\n\nexport interface SearchBudgetOptions {\n /** Wall-clock limit in milliseconds (default 250). */\n timeLimitMs?: number;\n /** Pike VM thread steps (default 50 million). */\n maxSteps?: number;\n}\n\nconst now = (): number =>\n typeof performance !== \"undefined\" && typeof performance.now === \"function\"\n ? performance.now()\n : Date.now();\n\nexport function createSearchBudget(options: SearchBudgetOptions = {}): SearchBudget {\n return {\n deadline: now() + (options.timeLimitMs ?? 250),\n steps: options.maxSteps ?? 50_000_000,\n exhausted: false,\n };\n}\n\nexport interface CompiledFindPattern {\n mode: \"special\" | \"wildcards\" | \"regex\";\n /** The pattern can match a paragraph mark, so paragraphs must be read together. */\n spansParagraphs: boolean;\n caseInsensitive: boolean;\n /** Number of capture groups (not counting the whole match). */\n groupCount: number;\n /**\n * The leftmost match in `hay[start, end)`; text outside the range is\n * context for word assertions. `\"budget\"` when the budget ran out.\n */\n exec(hay: string, start: number, end: number, budget: SearchBudget): PatternMatch | null | \"budget\";\n}\n\nexport type CompileFindPatternResult =\n | { ok: true; pattern: CompiledFindPattern }\n | { ok: false; error: FindPatternError };\n\n// ---------------------------------------------------------------------------\n// Character tests\n// ---------------------------------------------------------------------------\n\n/** Tests a code point (and its case fold when matching ignores case). */\ntype CharTest = (cp: number, folded: number) => boolean;\n\nconst PARA = 13; // \"\\r\"\nconst ANY: CharTest = (cp) => cp !== PARA;\n\nconst LETTER = /\\p{L}/u;\nconst PUNCT = /\\p{P}/u;\nconst WORD = /[\\p{L}\\p{M}\\p{Nd}\\p{Pc}]/u;\n\nconst foldCache = new Map<number, number>();\n/** Simple (one code point to one code point) lower-case fold. */\nexport function foldCodePoint(cp: number): number {\n if (cp < 128) return cp >= 65 && cp <= 90 ? cp + 32 : cp;\n const cached = foldCache.get(cp);\n if (cached !== undefined) return cached;\n const lower = String.fromCodePoint(cp).toLowerCase();\n const folded = [...lower].length === 1 ? lower.codePointAt(0)! : cp;\n if (foldCache.size < 4096) foldCache.set(cp, folded);\n return folded;\n}\n\nfunction isWordChar(cp: number): boolean {\n if (cp < 0) return false;\n if (cp < 128) {\n return (cp >= 48 && cp <= 57) || (cp >= 65 && cp <= 90) || (cp >= 97 && cp <= 122) || cp === 95;\n }\n return WORD.test(String.fromCodePoint(cp));\n}\n\nconst isLetter = (cp: number) =>\n cp < 128 ? (cp >= 65 && cp <= 90) || (cp >= 97 && cp <= 122) : LETTER.test(String.fromCodePoint(cp));\n\nfunction isPunct(cp: number): boolean {\n if (cp < 128) {\n return (cp >= 33 && cp <= 47) || (cp >= 58 && cp <= 64) || (cp >= 91 && cp <= 96) || (cp >= 123 && cp <= 126);\n }\n return (cp >= 0x2010 && cp <= 0x2027) || cp === 0xa1 || cp === 0xbf || cp === 0xab || cp === 0xbb || PUNCT.test(String.fromCodePoint(cp));\n}\n\nconst isSpace = (cp: number) => cp === 32 || cp === 9 || cp === 0xa0;\n\n/** Code point before `pos` in `hay` (-1 at the start). */\nfunction cpBefore(hay: string, pos: number): number {\n if (pos <= 0) return -1;\n const low = hay.charCodeAt(pos - 1);\n if (low >= 0xdc00 && low <= 0xdfff && pos >= 2) {\n const high = hay.charCodeAt(pos - 2);\n if (high >= 0xd800 && high <= 0xdbff) return hay.codePointAt(pos - 2)!;\n }\n return low;\n}\n\nconst cpAt = (hay: string, pos: number): number => (pos < hay.length ? hay.codePointAt(pos)! : -1);\n\n// ---------------------------------------------------------------------------\n// Pattern AST\n// ---------------------------------------------------------------------------\n\ntype AssertKind = \"boundary\" | \"wordStart\" | \"wordEnd\";\n\ntype Node =\n | { k: \"char\"; test: CharTest }\n | { k: \"cat\"; items: Node[] }\n | { k: \"group\"; index: number; body: Node }\n | { k: \"rep\"; body: Node; min: number; max: number; lazy: boolean } // max -1 = unbounded\n | { k: \"assert\"; kind: AssertKind };\n\nclass PatternError extends Error {\n constructor(\n readonly code: FindPatternErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\nconst charNode = (test: CharTest): Node => ({ k: \"char\", test });\nconst exact = (cp: number): Node => charNode((c) => c === cp);\nconst literalNode = (cp: number, caseInsensitive: boolean): Node => {\n if (!caseInsensitive) return exact(cp);\n const f = foldCodePoint(cp);\n return charNode((_c, folded) => folded === f);\n};\nconst star = (body: Node, lazy: boolean): Node => ({ k: \"rep\", body, min: 0, max: -1, lazy });\n\n/** What a `^` code stands for in Find what. */\nfunction findCode(c: string): Node | null {\n switch (c) {\n case \"p\": return exact(PARA);\n case \"t\": return exact(9);\n case \"?\": return charNode(ANY);\n case \"#\": return charNode((cp) => cp >= 48 && cp <= 57);\n case \"$\": return charNode((cp) => isLetter(cp));\n case \"^\": return exact(94);\n case \"l\": return exact(10);\n case \"m\": return exact(0x0c);\n case \"n\": return exact(0x0e);\n case \"+\": return exact(0x2014);\n case \"=\": return exact(0x2013);\n case \"s\": return exact(0xa0);\n case \"~\": return exact(0x2011);\n case \"-\": return exact(0xad);\n case \"w\": return { k: \"rep\", body: charNode((cp) => isSpace(cp)), min: 1, max: -1, lazy: false };\n case \"g\": return exact(0xfffc);\n case \"%\": return exact(0xa7);\n case \"v\": return exact(0xb6);\n default: return null;\n }\n}\n\n/** What a `^` code stands for in Replace with. */\nfunction replaceCode(c: string): string | null {\n switch (c) {\n case \"p\": return FIND_PARAGRAPH_MARK;\n case \"t\": return \"\\t\";\n case \"^\": return \"^\";\n case \"l\": return \"\\n\";\n case \"m\": return \"\\u000c\";\n case \"n\": return \"\\u000e\";\n case \"+\": return \"\\u2014\";\n case \"=\": return \"\\u2013\";\n case \"s\": return \"\\u00a0\";\n case \"~\": return \"\\u2011\";\n case \"-\": return \"\\u00ad\";\n case \"%\": return \"\\u00a7\";\n case \"v\": return \"\\u00b6\";\n default: return null;\n }\n}\n\n/** A character code (`^13`, `^0151`, `^u8212`) as the character it stands for. */\nfunction codeChar(n: number): number | null {\n switch (n) {\n case 13: return PARA;\n case 11: return 10;\n case 12: return 0x0c;\n case 14: return 0x0e;\n case 30: return 0x2011;\n case 31: return 0xad;\n }\n if (n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff)) return null;\n // Control characters other than tab stand for nothing here.\n if ((n < 32 && n !== 9) || (n >= 0x7f && n < 0xa0)) return null;\n return n;\n}\n\n/** A numeric code after `^` starting at `chars[i]`: the code point and characters used. */\nfunction numericCode(chars: string[], i: number): { cp: number; used: number } | null {\n const unicode = chars[i] === \"u\";\n const start = unicode ? i + 1 : i;\n const max = unicode ? 5 : 4;\n let digits = \"\";\n for (let j = start; j < chars.length && digits.length < max && /[0-9]/.test(chars[j]); j++) digits += chars[j];\n if (!digits) return null;\n const cp = codeChar(parseInt(digits, 10));\n return cp === null ? null : { cp, used: start - i + digits.length };\n}\n\nconst toChars = (s: string): string[] => Array.from(s);\nconst cpOf = (ch: string): number => ch.codePointAt(0)!;\n\n/** Normal search: literal text with `^` codes, optionally skipping punctuation and white space. */\nfunction parseSpecial(query: string, o: FindOptions, caseInsensitive: boolean): { node: Node; spans: boolean } {\n const chars = toChars(query);\n const atoms: Node[] = [];\n let spans = false;\n let i = 0;\n while (i < chars.length) {\n const c = chars[i++];\n if (c === \"^\" && !o.literal && i < chars.length) {\n const n = chars[i];\n const code = findCode(n);\n if (code) {\n if (n === \"p\") spans = true;\n atoms.push(code);\n i++;\n continue;\n }\n const num = numericCode(chars, i);\n if (num) {\n if (num.cp === PARA) spans = true;\n atoms.push(literalNode(num.cp, caseInsensitive));\n i += num.used;\n continue;\n }\n // Not a code: the caret itself.\n }\n const cp = cpOf(c);\n if ((o.ignorePunctuation && isPunct(cp)) || (o.ignoreWhitespace && isSpace(cp))) continue;\n atoms.push(literalNode(cp, caseInsensitive));\n }\n const filler: CharTest | null =\n o.ignorePunctuation && o.ignoreWhitespace\n ? (cp) => isPunct(cp) || isSpace(cp)\n : o.ignorePunctuation\n ? (cp) => isPunct(cp)\n : o.ignoreWhitespace\n ? (cp) => isSpace(cp)\n : null;\n const items: Node[] = [];\n atoms.forEach((atom, index) => {\n if (index > 0 && filler) items.push(star(charNode(filler), false));\n items.push(atom);\n });\n return { node: { k: \"cat\", items }, spans };\n}\n\n/** `{n}`, `{n,}`, `{n,m}` (and `{,m}`). */\nfunction parseCount(body: string): { min: number; max: number } {\n const bad = () => new PatternError(\"invalid_pattern\", `{${body}} is not a valid count`);\n const num = (s: string): number | null => {\n const t = s.trim();\n if (!t) return null;\n if (!/^[0-9]+$/.test(t)) throw bad();\n const n = parseInt(t, 10);\n if (n > MAX_COUNT) throw new PatternError(\"invalid_pattern\", `counts go up to ${MAX_COUNT}`);\n return n;\n };\n const sep = body.search(/[,;]/);\n if (sep < 0) {\n const n = num(body);\n if (n === null) throw bad();\n return { min: n, max: n };\n }\n const a = num(body.slice(0, sep)) ?? 0;\n const b = num(body.slice(sep + 1));\n if (b !== null && b < a) throw bad();\n return { min: a, max: b ?? -1 };\n}\n\n/** `[abc]`, `[a-z]`, `[!x]`: the characters inside are literal. */\nfunction parseClass(inner: string[]): CharTest {\n let negated = false;\n if (inner[0] === \"!\") {\n negated = true;\n inner = inner.slice(1);\n }\n if (inner.length === 0) throw new PatternError(\"invalid_pattern\", \"[ ] needs at least one character\");\n const singles = new Set<number>();\n const ranges: [number, number][] = [];\n let i = 0;\n while (i < inner.length) {\n let c = inner[i];\n if (c === \"\\\\\" && i + 1 < inner.length) c = inner[++i];\n i++;\n if (inner[i] === \"-\" && i + 1 < inner.length) {\n const hi = inner[i + 1];\n if (cpOf(hi) < cpOf(c)) throw new PatternError(\"invalid_pattern\", `[${c}-${hi}] is not in ascending order`);\n ranges.push([cpOf(c), cpOf(hi)]);\n i += 2;\n } else {\n singles.add(cpOf(c));\n }\n }\n const inSet = (cp: number) => singles.has(cp) || ranges.some(([lo, hi]) => cp >= lo && cp <= hi);\n return negated ? (cp) => cp !== PARA && !inSet(cp) : (cp) => inSet(cp);\n}\n\n/** \"Use wildcards\" search. */\nfunction parseWildcards(query: string): { node: Node; spans: boolean; groups: number } {\n const chars = toChars(query);\n const stack: { items: Node[]; group: number }[] = [{ items: [], group: 0 }];\n let groups = 0;\n let spans = false;\n const top = () => stack[stack.length - 1].items;\n const quantify = (min: number, max: number, what: string) => {\n const items = top();\n const last = items[items.length - 1];\n if (!last || last.k === \"assert\" || last.k === \"rep\") {\n throw new PatternError(\"invalid_pattern\", `${what} needs something to repeat before it`);\n }\n items[items.length - 1] = { k: \"rep\", body: last, min, max, lazy: false };\n };\n let i = 0;\n while (i < chars.length) {\n const c = chars[i++];\n switch (c) {\n case \"?\":\n top().push(charNode(ANY));\n break;\n case \"*\":\n top().push(star(charNode(ANY), true));\n break;\n case \"@\":\n quantify(1, -1, \"@\");\n break;\n case \"<\":\n top().push({ k: \"assert\", kind: \"wordStart\" });\n break;\n case \">\":\n top().push({ k: \"assert\", kind: \"wordEnd\" });\n break;\n case \"(\":\n stack.push({ items: [], group: ++groups });\n break;\n case \")\": {\n if (stack.length === 1) throw new PatternError(\"invalid_pattern\", \"a ) has no opening (\");\n const frame = stack.pop()!;\n top().push({ k: \"group\", index: frame.group, body: { k: \"cat\", items: frame.items } });\n break;\n }\n case \"{\": {\n const end = chars.indexOf(\"}\", i);\n if (end < 0) throw new PatternError(\"invalid_pattern\", \"a { needs a closing }\");\n const { min, max } = parseCount(chars.slice(i, end).join(\"\"));\n quantify(min, max, `{${chars.slice(i, end).join(\"\")}}`);\n i = end + 1;\n break;\n }\n case \"[\": {\n const end = chars.indexOf(\"]\", i);\n if (end < 0) throw new PatternError(\"invalid_pattern\", \"a [ needs a closing ]\");\n top().push(charNode(parseClass(chars.slice(i, end))));\n i = end + 1;\n break;\n }\n case \"\\\\\": {\n if (i >= chars.length) {\n top().push(exact(92));\n } else if (/[0-9]/.test(chars[i])) {\n throw new PatternError(\"invalid_pattern\", \"back-references (\\\\1) work in Replace with, not in Find what\");\n } else {\n top().push(exact(cpOf(chars[i++])));\n }\n break;\n }\n case \"^\": {\n if (i >= chars.length) {\n top().push(exact(94));\n break;\n }\n const n = chars[i];\n const code = findCode(n);\n if (code) {\n if (n === \"p\") spans = true;\n top().push(code);\n i++;\n break;\n }\n const num = numericCode(chars, i);\n if (num) {\n if (num.cp === PARA) spans = true;\n top().push(exact(num.cp));\n i += num.used;\n } else {\n top().push(exact(94));\n }\n break;\n }\n default:\n top().push(exact(cpOf(c)));\n }\n }\n if (stack.length > 1) throw new PatternError(\"invalid_pattern\", \"a ( needs a closing )\");\n return { node: { k: \"cat\", items: stack[0].items }, spans, groups };\n}\n\n// ---------------------------------------------------------------------------\n// Program and Pike VM\n// ---------------------------------------------------------------------------\n\nenum Op {\n Char,\n Split,\n Jmp,\n Save,\n Assert,\n Match,\n}\n\ntype Inst =\n | { op: Op.Char; test: CharTest }\n | { op: Op.Split; x: number; y: number }\n | { op: Op.Jmp; x: number }\n | { op: Op.Save; n: number }\n | { op: Op.Assert; kind: AssertKind }\n | { op: Op.Match };\n\nfunction compileProgram(node: Node): Inst[] {\n const prog: Inst[] = [];\n const push = (inst: Inst): number => {\n if (prog.length >= MAX_PROGRAM_SIZE) {\n throw new PatternError(\"too_complex\", \"the pattern is too complex (too many repeats)\");\n }\n prog.push(inst);\n return prog.length - 1;\n };\n const emit = (n: Node): void => {\n switch (n.k) {\n case \"char\":\n push({ op: Op.Char, test: n.test });\n return;\n case \"cat\":\n n.items.forEach(emit);\n return;\n case \"group\":\n push({ op: Op.Save, n: 2 * n.index });\n emit(n.body);\n push({ op: Op.Save, n: 2 * n.index + 1 });\n return;\n case \"assert\":\n push({ op: Op.Assert, kind: n.kind });\n return;\n case \"rep\": {\n for (let k = 0; k < n.min; k++) emit(n.body);\n if (n.max < 0) {\n const split = push({ op: Op.Split, x: 0, y: 0 });\n emit(n.body);\n push({ op: Op.Jmp, x: split });\n const exit = prog.length;\n const inst = prog[split] as { op: Op.Split; x: number; y: number };\n inst.x = n.lazy ? exit : split + 1;\n inst.y = n.lazy ? split + 1 : exit;\n return;\n }\n const splits: number[] = [];\n for (let k = n.min; k < n.max; k++) {\n splits.push(push({ op: Op.Split, x: 0, y: 0 }));\n emit(n.body);\n }\n const exit = prog.length;\n for (const s of splits) {\n const inst = prog[s] as { op: Op.Split; x: number; y: number };\n inst.x = n.lazy ? exit : s + 1;\n inst.y = n.lazy ? s + 1 : exit;\n }\n return;\n }\n }\n };\n push({ op: Op.Save, n: 0 });\n emit(node);\n push({ op: Op.Save, n: 1 });\n push({ op: Op.Match });\n return prog;\n}\n\nfunction checkAssert(kind: AssertKind, hay: string, pos: number): boolean {\n const before = isWordChar(cpBefore(hay, pos));\n const after = isWordChar(cpAt(hay, pos));\n switch (kind) {\n case \"boundary\": return before !== after;\n case \"wordStart\": return !before && after;\n case \"wordEnd\": return before && !after;\n }\n}\n\n/**\n * Leftmost-first search (Perl/Rust priorities: greedy, lazy) with a Pike VM:\n * every position is visited once per live instruction, so time is\n * O(text × program) whatever the pattern.\n */\nfunction pikeExec(\n prog: Inst[],\n groupCount: number,\n caseInsensitive: boolean,\n hay: string,\n start: number,\n end: number,\n budget: SearchBudget,\n): PatternMatch | null | \"budget\" {\n const ncap = 2 * (groupCount + 1);\n const mark = new Int32Array(prog.length);\n let gen = 1;\n let clistPc: number[] = [];\n let clistCaps: Int32Array[] = [];\n let nlistPc: number[] = [];\n let nlistCaps: Int32Array[] = [];\n const stackPc: number[] = [];\n const stackCaps: Int32Array[] = [];\n let matched: Int32Array | null = null;\n const initial = new Int32Array(ncap).fill(-1);\n\n const add = (listPc: number[], listCaps: Int32Array[], pc0: number, caps0: Int32Array, pos: number) => {\n stackPc.push(pc0);\n stackCaps.push(caps0);\n while (stackPc.length) {\n const pc = stackPc.pop()!;\n const caps = stackCaps.pop()!;\n if (mark[pc] === gen) continue;\n mark[pc] = gen;\n const inst = prog[pc];\n switch (inst.op) {\n case Op.Jmp:\n stackPc.push(inst.x);\n stackCaps.push(caps);\n break;\n case Op.Split:\n stackPc.push(inst.y, inst.x);\n stackCaps.push(caps, caps);\n break;\n case Op.Save: {\n const next = caps.slice();\n next[inst.n] = pos;\n stackPc.push(pc + 1);\n stackCaps.push(next);\n break;\n }\n case Op.Assert:\n if (checkAssert(inst.kind, hay, pos)) {\n stackPc.push(pc + 1);\n stackCaps.push(caps);\n }\n break;\n default:\n listPc.push(pc);\n listCaps.push(caps);\n }\n }\n };\n\n let i = start;\n if (budget.steps <= 0 || now() > budget.deadline) {\n budget.exhausted = true;\n return \"budget\";\n }\n let steps = 0;\n for (;;) {\n if (!matched) add(clistPc, clistCaps, 0, initial, i);\n const cp = i < end ? hay.codePointAt(i)! : -1;\n const width = cp > 0xffff ? 2 : 1;\n if (clistPc.length === 0) {\n // Nothing alive here (e.g. an assertion failed at the start): move on.\n if (matched || i >= end) break;\n gen++;\n i += width;\n continue;\n }\n const folded = cp >= 0 && caseInsensitive ? foldCodePoint(cp) : cp;\n gen++;\n nlistPc = [];\n nlistCaps = [];\n for (let t = 0; t < clistPc.length; t++) {\n if (++steps >= 4096) {\n budget.steps -= steps;\n steps = 0;\n if (budget.steps <= 0 || now() > budget.deadline) {\n budget.exhausted = true;\n return \"budget\";\n }\n }\n const inst = prog[clistPc[t]];\n if (inst.op === Op.Char) {\n if (cp >= 0 && inst.test(cp, folded)) add(nlistPc, nlistCaps, clistPc[t] + 1, clistCaps[t], i + width);\n } else if (inst.op === Op.Match) {\n matched = clistCaps[t];\n // Lower-priority threads lose to this match.\n break;\n }\n }\n clistPc = nlistPc;\n clistCaps = nlistCaps;\n if (i >= end) break;\n i += width;\n }\n budget.steps -= steps;\n if (!matched) return null;\n const groups: (string | undefined)[] = [];\n for (let g = 0; g <= groupCount; g++) {\n const a = matched[2 * g];\n const b = matched[2 * g + 1];\n groups.push(a >= 0 && b >= 0 ? hay.slice(a, b) : undefined);\n }\n return { start: matched[0], end: matched[1], groups };\n}\n\n// ---------------------------------------------------------------------------\n// Raw regex mode\n// ---------------------------------------------------------------------------\n\nconst WORD_CLASS = \"[\\\\p{L}\\\\p{M}\\\\p{Nd}\\\\p{Pc}]\";\nconst REGEX_BOUNDARY = `(?:(?<=${WORD_CLASS})(?!${WORD_CLASS})|(?<!${WORD_CLASS})(?=${WORD_CLASS}))`;\n\n/**\n * Rejects a repeated group that itself contains a repeat (`(a+)+`, `(\\w*)*`),\n * the shape behind most catastrophic backtracking in `RegExp`.\n */\nfunction hasNestedRepeat(source: string): boolean {\n /** The quantifier at `i`: whether it repeats at all, and whether more than once. */\n const quantifierAt = (i: number): { repeats: boolean; many: boolean } => {\n const c = source[i];\n if (c === \"*\" || c === \"+\") return { repeats: true, many: true };\n if (c === \"{\") {\n const m = /^\\{(\\d*)(,?)(\\d*)\\}/.exec(source.slice(i));\n if (m) {\n const max = m[2] ? (m[3] ? Number(m[3]) : Infinity) : Number(m[1]);\n return { repeats: max > 1, many: max > 1 };\n }\n }\n return { repeats: false, many: false };\n };\n // For each open group: whether it contains a repeat.\n const stack: boolean[] = [];\n let inClass = false;\n for (let i = 0; i < source.length; i++) {\n const c = source[i];\n if (c === \"\\\\\") {\n i++;\n continue;\n }\n if (inClass) {\n if (c === \"]\") inClass = false;\n continue;\n }\n if (c === \"[\") {\n inClass = true;\n } else if (c === \"(\") {\n stack.push(false);\n } else if (c === \")\") {\n const inner = stack.pop() ?? false;\n const q = quantifierAt(i + 1);\n if (inner && q.many) return true;\n if (stack.length && (inner || q.repeats)) stack[stack.length - 1] = true;\n } else if (stack.length && quantifierAt(i).repeats) {\n stack[stack.length - 1] = true;\n }\n }\n return false;\n}\n\nfunction compileRegex(query: string, o: FindOptions): CompiledFindPattern {\n if (hasNestedRepeat(query)) {\n throw new PatternError(\n \"too_complex\",\n \"a repeated group containing a repeat, like (a+)+, can take exponential time; rewrite it without nesting\",\n );\n }\n let source = query;\n if (o.wholeWord || (o.matchPrefix && o.matchSuffix)) source = `${REGEX_BOUNDARY}(?:${query})${REGEX_BOUNDARY}`;\n else if (o.matchPrefix) source = `${REGEX_BOUNDARY}(?:${query})`;\n else if (o.matchSuffix) source = `(?:${query})${REGEX_BOUNDARY}`;\n let re: RegExp;\n try {\n re = new RegExp(source, o.matchCase ? \"gu\" : \"giu\");\n } catch (error) {\n throw new PatternError(\"invalid_pattern\", `bad pattern: ${error instanceof Error ? error.message : String(error)}`);\n }\n let slicedFor: { hay: string; end: number; text: string } | null = null;\n return {\n mode: \"regex\",\n spansParagraphs: false,\n caseInsensitive: !o.matchCase,\n groupCount: 0,\n exec(hay, start, end, budget) {\n if (now() > budget.deadline) {\n budget.exhausted = true;\n return \"budget\";\n }\n let text = hay;\n if (end < hay.length) {\n if (!slicedFor || slicedFor.hay !== hay || slicedFor.end !== end) {\n slicedFor = { hay, end, text: hay.slice(0, end) };\n }\n text = slicedFor.text;\n }\n re.lastIndex = start;\n const m = re.exec(text);\n if (!m) return null;\n return { start: m.index, end: m.index + m[0].length, groups: Array.from(m) };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/** Translates Word's Find what text. Never throws: invalid text returns `{ ok: false, error }`. */\nexport function compileFindPattern(query: string, options: FindOptions = {}): CompileFindPatternResult {\n try {\n if (Array.from(query).length > MAX_FIND_PATTERN_LENGTH) {\n throw new PatternError(\"too_long\", `the Find what text is longer than ${MAX_FIND_PATTERN_LENGTH} characters`);\n }\n if (options.regex) return { ok: true, pattern: compileRegex(query, options) };\n\n const wildcards = !!options.wildcards && !options.literal;\n // Word's wildcard search always matches case.\n const caseInsensitive = !options.matchCase && !wildcards;\n let node: Node;\n let spans: boolean;\n let groups = 0;\n if (wildcards) {\n ({ node, spans, groups } = parseWildcards(query));\n } else {\n ({ node, spans } = parseSpecial(query, options, caseInsensitive));\n const before = options.wholeWord || options.matchPrefix;\n const after = options.wholeWord || options.matchSuffix;\n if (before || after) {\n const items: Node[] = [];\n if (before) items.push({ k: \"assert\", kind: \"boundary\" });\n items.push(node);\n if (after) items.push({ k: \"assert\", kind: \"boundary\" });\n node = { k: \"cat\", items };\n }\n }\n const prog = compileProgram(node);\n return {\n ok: true,\n pattern: {\n mode: wildcards ? \"wildcards\" : \"special\",\n spansParagraphs: spans,\n caseInsensitive,\n groupCount: groups,\n exec: (hay, start, end, budget) => pikeExec(prog, groups, caseInsensitive, hay, start, end, budget),\n },\n };\n } catch (error) {\n if (error instanceof PatternError) return { ok: false, error: { code: error.code, message: error.message } };\n return { ok: false, error: { code: \"invalid_pattern\", message: error instanceof Error ? error.message : String(error) } };\n }\n}\n\nexport interface FindAllOptions {\n /**\n * Offsets where the live text breaks (e.g. where tracked-deleted text was\n * skipped): no match spans a cut.\n */\n cuts?: readonly number[];\n budget?: SearchBudget;\n /** Stop after this many matches (default 10 000). */\n maxMatches?: number;\n}\n\nexport interface FindAllResult {\n matches: PatternMatch[];\n /** The search stopped early (match cap or time budget). */\n truncated: boolean;\n}\n\n/**\n * Every non-empty match in `hay`, left to right, without overlaps. Empty\n * matches are stepped past so the search always moves on.\n */\nexport function findAllMatches(\n pattern: CompiledFindPattern,\n hay: string,\n options: FindAllOptions = {},\n): FindAllResult {\n const budget = options.budget ?? createSearchBudget();\n const maxMatches = options.maxMatches ?? 10_000;\n const cuts = [...(options.cuts ?? []), hay.length].sort((a, b) => a - b);\n const matches: PatternMatch[] = [];\n let from = 0;\n for (const cut of cuts) {\n if (cut <= from) continue;\n let pos = from;\n from = cut;\n for (;;) {\n const m = pattern.exec(hay, pos, cut, budget);\n if (m === \"budget\") return { matches, truncated: true };\n if (!m) break;\n const empty = m.end === m.start;\n const next = empty ? m.end + (cpAt(hay, m.end) > 0xffff ? 2 : 1) : m.end;\n if (next > cut) break;\n pos = next;\n if (empty) continue;\n matches.push(m);\n if (matches.length >= maxMatches) return { matches, truncated: true };\n }\n }\n return { matches, truncated: false };\n}\n\n/** A piece of Replace with text. */\nexport type ReplacePiece =\n | { type: \"text\"; text: string }\n /** `^&`: the text found. */\n | { type: \"found\" }\n /** `\\n` with wildcards: group `n`. */\n | { type: \"group\"; index: number }\n /** `^c`: the clipboard. */\n | { type: \"clipboard\" };\n\n/** Reads Replace with text: `^` codes (unless `literal`), and `\\1`–`\\9` with wildcards. Regex mode is literal. */\nexport function parseReplacement(replacement: string, options: FindOptions = {}): ReplacePiece[] {\n if (options.literal || options.regex) return replacement ? [{ type: \"text\", text: replacement }] : [];\n const chars = toChars(replacement);\n const out: ReplacePiece[] = [];\n let cur = \"\";\n const flush = () => {\n if (cur) out.push({ type: \"text\", text: cur });\n cur = \"\";\n };\n let i = 0;\n while (i < chars.length) {\n const c = chars[i++];\n if (c === \"\\\\\" && options.wildcards && i < chars.length) {\n const d = chars[i];\n if (/[1-9]/.test(d)) {\n flush();\n out.push({ type: \"group\", index: Number(d) });\n } else {\n cur += d;\n }\n i++;\n continue;\n }\n if (c === \"^\" && i < chars.length) {\n const n = chars[i];\n if (n === \"&\" || n === \"c\") {\n flush();\n out.push(n === \"&\" ? { type: \"found\" } : { type: \"clipboard\" });\n i++;\n continue;\n }\n const code = replaceCode(n);\n if (code !== null) {\n cur += code;\n i++;\n continue;\n }\n const num = numericCode(chars, i);\n if (num) {\n cur += String.fromCodePoint(num.cp);\n i += num.used;\n continue;\n }\n }\n cur += c;\n }\n flush();\n return out;\n}\n\n/** Fills in Replace with text for one match. Paragraph marks in the result are `\\r`. */\nexport function expandReplacement(pieces: readonly ReplacePiece[], match: PatternMatch, clipboardText = \"\"): string {\n let out = \"\";\n for (const piece of pieces) {\n switch (piece.type) {\n case \"text\":\n out += piece.text;\n break;\n case \"found\":\n out += match.groups[0] ?? \"\";\n break;\n case \"group\":\n out += match.groups[piece.index] ?? \"\";\n break;\n case \"clipboard\":\n out += clipboardText.replace(/\\r\\n/g, \"\\r\").replace(/\\n/g, \"\\r\");\n break;\n }\n }\n return out;\n}\n","// Portions ported from wordcraft/crates/engine/src/cmd/edit.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport type { Mark as ProsemirrorMark, Node as ProsemirrorNode, Schema } from \"@tiptap/pm/model\";\nimport type { Transaction } from \"@tiptap/pm/state\";\nimport {\n FIND_PARAGRAPH_MARK,\n compileFindPattern,\n createSearchBudget,\n expandReplacement,\n findAllMatches,\n parseReplacement,\n type FindOptions,\n type FindPatternError,\n} from \"./pattern\";\n\n/** Name of the tracked-deletion mark (see `track-changes.ts`); deleted text is not searched. */\nconst DELETION_MARK = \"deletion\";\n/** Review marks the replacement text does not inherit from the found text. */\nconst DROPPED_REPLACEMENT_MARKS = new Set([DELETION_MARK, \"formatChange\"]);\n/** Stands for an inline node other than text or a hard break (`^g`). */\nconst OBJECT_CHAR = \"\\ufffc\";\n\nexport interface FindMatch {\n /** Document position of the first matched character. */\n from: number;\n /** Document position after the last matched character. */\n to: number;\n /** The matched text (`\\r` for paragraph marks, `\\n` for hard breaks). */\n text: string;\n /** The Replace with text for this match (`\\r` splits paragraphs). */\n replacement: string;\n}\n\nexport interface DocumentSearchOptions {\n /** Replace with text (`^&`, `^c`, `\\1`…). */\n replacement?: string;\n /** Text of `^c` in the replacement. */\n clipboardText?: string;\n /** Wall-clock budget for the whole search (default 250 ms). */\n timeLimitMs?: number;\n /** Match cap (default 10 000). */\n maxMatches?: number;\n}\n\nexport interface DocumentSearchResult {\n matches: FindMatch[];\n /** The search stopped early at the match cap or time budget. */\n truncated: boolean;\n error: FindPatternError | null;\n}\n\ninterface Block {\n node: ProsemirrorNode;\n pos: number;\n parent: ProsemirrorNode | null;\n index: number;\n}\n\n/**\n * Finds `query` in a document. Each textblock is read as text without\n * tracked-deleted runs (a deletion \"cuts\" the text, so no match spans it, but\n * word boundaries see the live text on both sides); a pattern that can match\n * `^p` reads runs of sibling textblocks as one text with `\\r` between them.\n */\nexport function searchDocument(\n doc: ProsemirrorNode,\n query: string,\n options: FindOptions = {},\n searchOptions: DocumentSearchOptions = {},\n): DocumentSearchResult {\n if (!query) return { matches: [], truncated: false, error: null };\n const compiled = compileFindPattern(query, options);\n if (!compiled.ok) return { matches: [], truncated: false, error: compiled.error };\n const pattern = compiled.pattern;\n const pieces = parseReplacement(searchOptions.replacement ?? \"\", options);\n const budget = createSearchBudget({ timeLimitMs: searchOptions.timeLimitMs });\n const maxMatches = searchOptions.maxMatches ?? 10_000;\n\n const blocks: Block[] = [];\n doc.descendants((node, pos, parent, index) => {\n if (!node.isTextblock) return true;\n blocks.push({ node, pos, parent, index });\n return false;\n });\n\n // Textblocks read as one text: consecutive siblings when the pattern spans paragraphs.\n const chunks: Block[][] = [];\n blocks.forEach((block, i) => {\n const prev = blocks[i - 1];\n const joins =\n pattern.spansParagraphs && prev && prev.parent === block.parent && prev.index + 1 === block.index;\n if (joins) chunks[chunks.length - 1].push(block);\n else chunks.push([block]);\n });\n\n const matches: FindMatch[] = [];\n let truncated = false;\n for (const chunk of chunks) {\n let hay = \"\";\n // Document position of each hay offset, and the position after it.\n const posOf: number[] = [];\n const endOf: number[] = [];\n const cuts: number[] = [];\n chunk.forEach((block, k) => {\n const contentStart = block.pos + 1;\n block.node.forEach((child, offset) => {\n const at = contentStart + offset;\n if (child.marks.some((m) => m.type.name === DELETION_MARK)) {\n if (cuts[cuts.length - 1] !== hay.length) cuts.push(hay.length);\n return;\n }\n if (child.isText) {\n const text = child.text ?? \"\";\n for (let j = 0; j < text.length; j++) {\n posOf.push(at + j);\n endOf.push(at + j + 1);\n }\n hay += text;\n } else {\n posOf.push(at);\n endOf.push(at + child.nodeSize);\n hay += child.type.name === \"hardBreak\" ? \"\\n\" : OBJECT_CHAR;\n }\n });\n const next = chunk[k + 1];\n if (next) {\n posOf.push(contentStart + block.node.content.size);\n endOf.push(next.pos + 1);\n hay += FIND_PARAGRAPH_MARK;\n }\n });\n if (!hay) continue;\n const result = findAllMatches(pattern, hay, {\n cuts,\n budget,\n maxMatches: maxMatches - matches.length,\n });\n for (const m of result.matches) {\n matches.push({\n from: posOf[m.start],\n to: endOf[m.end - 1],\n text: m.groups[0] ?? hay.slice(m.start, m.end),\n replacement: expandReplacement(pieces, m, searchOptions.clipboardText ?? \"\"),\n });\n }\n if (result.truncated) {\n truncated = true;\n break;\n }\n }\n return { matches, truncated, error: null };\n}\n\n/** Marks the replacement for a match inherits: the found text's, minus tracked-change marks. */\nfunction replacementMarks(doc: ProsemirrorNode, from: number, to: number): readonly ProsemirrorMark[] {\n const $from = doc.resolve(from);\n const node = from < to ? $from.nodeAfter : null;\n const marks = node ? node.marks : $from.marks();\n return marks.filter((m) => !DROPPED_REPLACEMENT_MARKS.has(m.type.name));\n}\n\n/** Inline content for a piece of replacement text: `\\n` becomes a hard break when the schema has one. */\nfunction inlineContent(schema: Schema, text: string, marks: readonly ProsemirrorMark[]): ProsemirrorNode[] {\n const nodes: ProsemirrorNode[] = [];\n const hardBreak = schema.nodes.hardBreak;\n const parts = hardBreak ? text.split(\"\\n\") : [text];\n parts.forEach((part, i) => {\n if (i > 0) nodes.push(hardBreak.create(null, null, marks));\n if (part) nodes.push(schema.text(part, marks));\n });\n return nodes;\n}\n\n/**\n * Replaces matches in one transaction, last first so earlier positions stay\n * valid. A paragraph mark (`\\r` or U+2029) in a replacement splits the\n * paragraph. Returns the mapped end of each replacement (in match order).\n */\nexport function applyReplacements(tr: Transaction, matches: readonly FindMatch[]): number[] {\n const ends: number[] = new Array(matches.length);\n const schema = tr.doc.type.schema;\n for (let i = matches.length - 1; i >= 0; i--) {\n const { from, to, replacement } = matches[i];\n const marks = replacementMarks(tr.doc, from, to);\n const parts = replacement.split(/[\\r\\u2029]/);\n const stepsBefore = tr.steps.length;\n const first = inlineContent(schema, parts[0], marks);\n if (first.length) tr.replaceWith(from, to, first);\n else if (to > from) tr.delete(from, to);\n let pos = tr.mapping.slice(stepsBefore).map(to, 1);\n for (let k = 1; k < parts.length; k++) {\n tr.split(pos);\n pos += 2;\n const content = inlineContent(schema, parts[k], marks);\n if (content.length) {\n tr.insert(pos, content);\n pos += content.reduce((size, node) => size + node.nodeSize, 0);\n }\n }\n // Positions of later replacements were already mapped; record this one's end\n // and shift the later ends by what this replacement changed.\n const map = tr.mapping.slice(stepsBefore);\n for (let j = i + 1; j < matches.length; j++) ends[j] = map.map(ends[j], 1);\n ends[i] = pos;\n }\n return ends;\n}\n","import { getHTMLFromFragment, type Extensions } from \"@tiptap/core\";\nimport { Fragment, type Node as ProsemirrorNode } from \"@tiptap/pm/model\";\nimport * as _Table from \"@tiptap/extension-table\";\nimport * as _TableRow from \"@tiptap/extension-table-row\";\nimport * as _TableHeader from \"@tiptap/extension-table-header\";\nimport * as _TableCell from \"@tiptap/extension-table-cell\";\nimport { createTableNestingPlugin } from \"./nesting\";\n\nconst resolveExt = (mod: any, name: string) =>\n mod?.[name] || mod?.default?.[name] || mod?.default?.default || mod?.default || mod;\n\nconst BaseTable = resolveExt(_Table, \"Table\");\nconst BaseTableRow = resolveExt(_TableRow, \"TableRow\");\nconst BaseTableHeader = resolveExt(_TableHeader, \"TableHeader\");\nconst BaseTableCell = resolveExt(_TableCell, \"TableCell\");\n\n/** Horizontal alignment of a table cell (`align` attribute). */\nexport type TableCellAlignment = \"left\" | \"center\" | \"right\" | \"justify\";\n\nconst ALIGNMENTS = new Set<TableCellAlignment>([\"left\", \"center\", \"right\", \"justify\"]);\n\n/** Returns a valid cell alignment, or `null`. */\nexport function normalizeTableCellAlignment(value: unknown): TableCellAlignment | null {\n const v = typeof value === \"string\" ? value.trim().toLowerCase() : \"\";\n return ALIGNMENTS.has(v as TableCellAlignment) ? (v as TableCellAlignment) : null;\n}\n\n/**\n * Color values allowed as a cell background: hex, `rgb()/rgba()/hsl()/hsla()`\n * with numeric arguments, or a CSS color keyword. Anything else (e.g.\n * `url(...)`, `expression(...)`, `;`) is rejected because the value ends up in\n * a `style` attribute.\n */\nconst COLOR_REGEX =\n /^(?:#[0-9a-f]{3,8}|(?:rgb|rgba|hsl|hsla)\\(\\s*[-0-9.%\\s,/deg]+\\)|[a-z]{3,20})$/i;\n\n/** Returns a safe CSS color for a cell background, or `null`. */\nexport function normalizeTableCellColor(value: unknown): string | null {\n const v = typeof value === \"string\" ? value.trim() : \"\";\n if (!v || v.length > 64 || !COLOR_REGEX.test(v)) return null;\n if (/^(?:inherit|initial|unset|revert|transparent)$/i.test(v)) return null;\n return v;\n}\n\n/** Cell attributes added on top of TipTap's `colspan` / `rowspan` / `colwidth`. */\nconst cellAttributes = () => ({\n align: {\n default: null,\n parseHTML: (element: HTMLElement) =>\n normalizeTableCellAlignment(element.style?.textAlign || element.getAttribute(\"align\")),\n renderHTML: (attrs: Record<string, any>) => {\n const align = normalizeTableCellAlignment(attrs.align);\n return align ? { style: `text-align: ${align}` } : {};\n },\n },\n backgroundColor: {\n default: null,\n parseHTML: (element: HTMLElement) =>\n normalizeTableCellColor(\n element.getAttribute(\"data-background-color\") ||\n element.style?.backgroundColor ||\n element.getAttribute(\"bgcolor\"),\n ),\n renderHTML: (attrs: Record<string, any>) => {\n const color = normalizeTableCellColor(attrs.backgroundColor);\n return color ? { style: `background-color: ${color}`, \"data-background-color\": color } : {};\n },\n },\n});\n\n// ---------------------------------------------------------------------------\n// Markdown (tiptap-markdown)\n// ---------------------------------------------------------------------------\n\nconst children = (node: ProsemirrorNode) => {\n const list: ProsemirrorNode[] = [];\n node.forEach((child) => list.push(child));\n return list;\n};\n\nconst hasSpan = (cell: ProsemirrorNode) => (cell.attrs.colspan ?? 1) > 1 || (cell.attrs.rowspan ?? 1) > 1;\n\n/**\n * Whether a table can be written as a GFM pipe table: the first row is all\n * header cells, the other rows have none, no cell spans rows or columns, and\n * every cell holds a single paragraph.\n */\nexport function isGfmTable(node: ProsemirrorNode): boolean {\n const rows = children(node);\n if (rows.length === 0) return false;\n const width = rows[0].childCount;\n return rows.every(\n (row, r) =>\n row.childCount === width &&\n children(row).every(\n (cell) =>\n (r === 0 ? cell.type.name === \"tableHeader\" : cell.type.name === \"tableCell\") &&\n !hasSpan(cell) &&\n cell.childCount === 1 &&\n cell.firstChild!.type.name === \"paragraph\",\n ),\n );\n}\n\nconst DELIMITERS: Record<string, string> = { left: \":---\", center: \":---:\", right: \"---:\" };\n\n/**\n * tiptap-markdown serializer for tables: GFM pipe tables (with column\n * alignment from the header cells and `|` escaped) when `isGfmTable`, HTML\n * otherwise (spans, header columns, multi-paragraph cells).\n */\nfunction serializeTableMarkdown(state: any, node: ProsemirrorNode) {\n if (!isGfmTable(node)) {\n const html = getHTMLFromFragment(Fragment.from(node), node.type.schema);\n // An HTML block must start on its own line and contain no blank lines.\n state.write(html.replace(/\\n{2,}/g, \"\\n\"));\n state.closeBlock(node);\n return;\n }\n const previous = state.inTable;\n state.inTable = true;\n children(node).forEach((row, r) => {\n if (r) state.ensureNewLine();\n state.write(\"| \");\n children(row).forEach((cell, c) => {\n if (c) state.write(\" | \");\n const paragraph = cell.firstChild!;\n // Render in place (mid-line, so no block prefix is added), then escape\n // the cell's pipes and line breaks, which would end the cell or row.\n const start = state.out.length;\n if (paragraph.childCount) state.renderInline(paragraph);\n const text: string = state.out.slice(start);\n state.out = state.out.slice(0, start) + text.replace(/\\n/g, \" \").replace(/\\|/g, \"\\\\|\");\n });\n state.write(\" |\");\n if (r === 0) {\n const delimiter = children(row).map((cell) => DELIMITERS[cell.attrs.align] ?? \"---\");\n state.ensureNewLine();\n state.write(`| ${delimiter.join(\" | \")} |`);\n }\n });\n state.inTable = previous;\n state.closeBlock(node);\n}\n\n// ---------------------------------------------------------------------------\n// Extensions\n// ---------------------------------------------------------------------------\n\nexport interface RichTextTableOptions {\n /** Drag column borders to resize columns (stored as `colwidth`). Default `true`. */\n resizable: boolean;\n /** Width of the resize handle in pixels. Default 5. */\n handleWidth: number;\n /** Minimum cell width in pixels. Default 25. */\n cellMinWidth: number;\n /** Whether the last column can be resized. Default `true`. */\n lastColumnResizable: boolean;\n /** Allow selecting the whole table as a node (click its border, Esc from a cell selection). Default `true`. */\n allowTableNodeSelection: boolean;\n /** HTML attributes of the `<table>` element. */\n HTMLAttributes: Record<string, any>;\n /** HTML attributes of `<td>` elements. */\n cellHTMLAttributes: Record<string, any>;\n /** HTML attributes of `<th>` elements. */\n headerHTMLAttributes: Record<string, any>;\n /** HTML attributes of `<tr>` elements. */\n rowHTMLAttributes: Record<string, any>;\n}\n\nexport const DEFAULT_TABLE_OPTIONS: RichTextTableOptions = {\n resizable: true,\n handleWidth: 5,\n cellMinWidth: 25,\n lastColumnResizable: true,\n allowTableNodeSelection: true,\n HTMLAttributes: { class: \"pixerate-table\" },\n cellHTMLAttributes: {},\n headerHTMLAttributes: {},\n rowHTMLAttributes: {},\n};\n\n/**\n * TipTap's `Table` with the GFM-aware markdown serializer and the nesting\n * guard (`createTableNestingPlugin`): tables are never pasted, imported or\n * inserted into table cells.\n */\nexport const Table = BaseTable.extend({\n addStorage() {\n return { markdown: { serialize: serializeTableMarkdown } };\n },\n addProseMirrorPlugins() {\n return [...(this.parent?.() ?? []), createTableNestingPlugin()];\n },\n});\n\nexport const TableRow = BaseTableRow;\n\n/** TipTap's `TableCell` plus `align` and `backgroundColor` attributes. */\nexport const TableCell = BaseTableCell.extend({\n addAttributes() {\n return { ...this.parent?.(), ...cellAttributes() };\n },\n});\n\n/** TipTap's `TableHeader` plus `align` and `backgroundColor` attributes. */\nexport const TableHeader = BaseTableHeader.extend({\n addAttributes() {\n return { ...this.parent?.(), ...cellAttributes() };\n },\n});\n\n/**\n * The table extensions (`table`, `tableRow`, `tableHeader`, `tableCell`)\n * configured for rich documents: resizable columns, header rows, columns and\n * cells, `colspan` / `rowspan` from imported HTML, cell alignment and\n * background, table node selection and GFM markdown. `createRichTextPreset`\n * adds them unless `table: false`.\n */\nexport function createTableExtensions(options: Partial<RichTextTableOptions> = {}): Extensions {\n const o = { ...DEFAULT_TABLE_OPTIONS, ...options };\n return [\n Table.configure({\n resizable: o.resizable,\n handleWidth: o.handleWidth,\n cellMinWidth: o.cellMinWidth,\n lastColumnResizable: o.lastColumnResizable,\n allowTableNodeSelection: o.allowTableNodeSelection,\n HTMLAttributes: o.HTMLAttributes,\n }),\n TableRow.configure({ HTMLAttributes: o.rowHTMLAttributes }),\n TableHeader.configure({ HTMLAttributes: o.headerHTMLAttributes }),\n TableCell.configure({ HTMLAttributes: o.cellHTMLAttributes }),\n ];\n}\n","import type { Editor, NodeViewRendererProps } from \"@tiptap/core\";\nimport { DOMSerializer, type DOMOutputSpec, type Node as ProsemirrorNode } from \"@tiptap/pm/model\";\nimport { NodeSelection } from \"@tiptap/pm/state\";\nimport type { NodeView } from \"@tiptap/pm/view\";\nimport { ChartController } from \"../../chart/controller\";\nimport type { ChartSpec } from \"../../chart/types\";\n\n/** What a framework chart node view draws. A new object is passed on every change. */\nexport interface ChartNodeViewState {\n /** The chart's id in the document. */\n id: string | null;\n /** Edits the chart: changes are written back to the document when no gesture is running. */\n controller: ChartController;\n /** Width in pixels, or null to fill the line. */\n width: number | null;\n /** Height in pixels. */\n height: number;\n /** The editor is editable (a read-only editor never opens the inspector). */\n editable: boolean;\n /** The node is selected. */\n selected: boolean;\n /** The inspector is open. */\n editing: boolean;\n /** Opens (selecting the node) or closes the inspector. Ignored while the editor is read-only. */\n setEditing: (editing: boolean) => void;\n /** Changes the chart's size (one undo step). */\n setSize: (size: { width?: number | null; height?: number }) => void;\n}\n\n/** A mounted framework component. */\nexport interface ChartNodeViewRenderer {\n update(state: ChartNodeViewState): void;\n destroy(): void;\n}\n\n/** Mounts a framework component into a chart node view's element. */\nexport type ChartNodeViewMount = (dom: HTMLElement, state: ChartNodeViewState) => ChartNodeViewRenderer;\n\nconst specKey = (spec: unknown) => JSON.stringify(spec);\n\n/**\n * The ProseMirror side of a chart node view, shared by the React and Svelte packages: it\n * keeps a `ChartController` in step with the node (undo, collaboration and agent edits load\n * into it), writes the controller's edits back as document transactions once any gesture\n * has ended, and lets the inspector's inputs keep their events while it is open.\n */\nexport class ChartNodeView implements NodeView {\n readonly dom: HTMLElement;\n private node: ProsemirrorNode;\n private readonly editor: Editor;\n private readonly getPos: () => number | undefined;\n private readonly controller: ChartController;\n private readonly renderer: ChartNodeViewRenderer | null;\n private readonly unsubscribe: () => void;\n private editing = false;\n private selected = false;\n private editable: boolean;\n private key: string;\n\n constructor(\n props: Pick<NodeViewRendererProps, \"editor\" | \"node\" | \"getPos\">,\n mount: ChartNodeViewMount | null,\n private readonly renderStatic: (node: ProsemirrorNode) => DOMOutputSpec,\n ) {\n this.editor = props.editor;\n this.node = props.node;\n this.getPos = typeof props.getPos === \"function\" ? (props.getPos as () => number | undefined) : () => undefined;\n this.editable = this.editor.isEditable;\n this.dom = document.createElement(\"div\");\n this.dom.className = \"pixerate-chart-node\";\n this.dom.setAttribute(\"data-type\", \"chart\");\n this.dom.contentEditable = \"false\";\n this.syncAttributes();\n this.key = specKey(this.node.attrs.spec);\n this.controller = new ChartController({ spec: this.node.attrs.spec });\n this.unsubscribe = this.controller.subscribe((state) => {\n if (!state.gesture) this.writeBack();\n });\n this.editor.on(\"update\", this.onEditorUpdate);\n this.renderer = mount ? mount(this.dom, this.viewState()) : null;\n if (!mount) this.drawStatic();\n }\n\n private viewState(): ChartNodeViewState {\n return {\n id: this.node.attrs.id ?? null,\n controller: this.controller,\n width: this.node.attrs.width ?? null,\n height: this.node.attrs.height,\n editable: this.editable,\n selected: this.selected,\n editing: this.editing,\n setEditing: this.setEditing,\n setSize: this.setSize,\n };\n }\n\n private render() {\n if (this.renderer) this.renderer.update(this.viewState());\n else this.drawStatic();\n this.dom.toggleAttribute(\"data-editing\", this.editing);\n }\n\n private drawStatic() {\n const { dom } = DOMSerializer.renderSpec(document, this.renderStatic(this.node));\n this.dom.replaceChildren(dom);\n }\n\n private syncAttributes() {\n if (this.node.attrs.id) this.dom.setAttribute(\"data-chart-id\", this.node.attrs.id);\n else this.dom.removeAttribute(\"data-chart-id\");\n }\n\n private onEditorUpdate = () => {\n if (this.editor.isEditable === this.editable) return;\n this.editable = this.editor.isEditable;\n if (!this.editable) this.editing = false;\n this.render();\n };\n\n /** Writes the controller's spec into the node, if it changed. */\n private writeBack() {\n const spec = this.controller.toJSON();\n const key = specKey(spec);\n if (key === this.key) return;\n const pos = this.getPos();\n if (typeof pos !== \"number\" || this.editor.isDestroyed) return;\n this.key = key;\n this.editor.view.dispatch(this.editor.state.tr.setNodeMarkup(pos, undefined, { ...this.node.attrs, spec }));\n }\n\n setEditing = (editing: boolean) => {\n if (editing && !this.editor.isEditable) return;\n if (editing && !this.selected) {\n const pos = this.getPos();\n if (typeof pos === \"number\") {\n this.editor.view.dispatch(this.editor.state.tr.setSelection(NodeSelection.create(this.editor.state.doc, pos)));\n }\n }\n if (this.editing === editing) return;\n this.editing = editing;\n this.render();\n };\n\n setSize = (size: { width?: number | null; height?: number }) => {\n const pos = this.getPos();\n if (typeof pos !== \"number\" || !this.editor.isEditable) return;\n this.editor.view.dispatch(this.editor.state.tr.setNodeMarkup(pos, undefined, { ...this.node.attrs, ...size }));\n };\n\n update(node: ProsemirrorNode): boolean {\n if (node.type !== this.node.type) return false;\n this.node = node;\n this.syncAttributes();\n const key = specKey(node.attrs.spec);\n if (key !== this.key) {\n this.key = key;\n // Undo, an agent tool or a collaborator changed the chart: show it as the new start.\n if (specKey(this.controller.toJSON()) !== key) this.controller.load(node.attrs.spec as ChartSpec, { clearHistory: true });\n }\n this.render();\n return true;\n }\n\n selectNode() {\n this.selected = true;\n this.dom.classList.add(\"ProseMirror-selectednode\");\n this.render();\n }\n\n deselectNode() {\n this.selected = false;\n this.editing = false;\n this.dom.classList.remove(\"ProseMirror-selectednode\");\n this.render();\n }\n\n /** The inspector's inputs, buttons and chart gestures keep their events while it is open. */\n stopEvent(event: Event): boolean {\n if (!this.editing) return false;\n return !(event.type === \"dragstart\" && event.target === this.dom);\n }\n\n ignoreMutation(): boolean {\n return true;\n }\n\n destroy() {\n this.editor.off(\"update\", this.onEditorUpdate);\n this.unsubscribe();\n this.renderer?.destroy();\n this.controller.destroy();\n }\n}\n\n/**\n * A TipTap node view factory for the `chart` node. `mount` draws the framework component\n * (`null`: the static SVG, redrawn when the spec changes).\n */\nexport function createChartNodeView(\n mount: ChartNodeViewMount | null,\n renderStatic: (node: ProsemirrorNode) => DOMOutputSpec,\n) {\n return (props: NodeViewRendererProps): NodeView => new ChartNodeView(props, mount, renderStatic);\n}\n","import { Node, mergeAttributes, type Editor } from \"@tiptap/core\";\nimport type { Node as ProsemirrorNode } from \"@tiptap/pm/model\";\nimport { Plugin, PluginKey, type EditorState, type Transaction } from \"@tiptap/pm/state\";\nimport { chartFromMermaid, chartToMermaid } from \"../../chart/mermaid\";\nimport { DEFAULT_CHART_THEME, normalizeChartSpec } from \"../../chart/spec\";\nimport { chartSceneToDomSpec, type ChartDomSpec } from \"../../chart/svg\";\nimport { layoutChart } from \"../../chart/layout\";\nimport { describeChart } from \"../../chart/summary\";\nimport type { ChartSpec, ChartTheme } from \"../../chart/types\";\nimport {\n generateStructureId,\n STRUCTURE_PRIORITY,\n syncInitialContent,\n transactionsInsert,\n} from \"../document-structure/utils\";\nimport { createChartNodeView, type ChartNodeViewMount } from \"./node-view\";\n\nexport interface ChartNodeOptions {\n HTMLAttributes: Record<string, any>;\n /**\n * Draws the chart inside the editor with a framework component (the React and Svelte\n * packages export one). Without it the editor shows the static SVG from `renderHTML`.\n */\n nodeView: ChartNodeViewMount | null;\n /** Colours of the static SVG in exported HTML (default `DEFAULT_CHART_THEME`). */\n theme: Partial<ChartTheme>;\n /** Width of the static SVG when the node has no `width` (default 640). */\n defaultWidth: number;\n /** Height of new charts in pixels (default 320). */\n defaultHeight: number;\n /** Generates ids for charts that have none (default `chart-xxxxxxxx`). */\n generateId: () => string;\n}\n\nexport interface InsertChartOptions {\n /** Any partial or saved chart spec; it is normalized (see `normalizeChartSpec`). */\n spec: Partial<ChartSpec> | unknown;\n /** Width in pixels, or null to fill the line (default null). */\n width?: number | null;\n /** Height in pixels (default `defaultHeight`). */\n height?: number;\n /** Id to use (default: generated). */\n id?: string;\n}\n\ndeclare module \"@tiptap/core\" {\n interface Commands<ReturnType> {\n chart: {\n /** Inserts a chart block at the selection. */\n insertChart: (options: InsertChartOptions) => ReturnType;\n /** Replaces the spec (and optionally the size) of the chart with this id. */\n updateChart: (\n id: string,\n changes: { spec?: Partial<ChartSpec> | unknown; width?: number | null; height?: number },\n ) => ReturnType;\n };\n }\n}\n\nexport const chartPluginKey = new PluginKey(\"chartNode\");\n\n/** A chart in a document: its node, id and position. */\nexport interface DocumentChart {\n id: string | null;\n pos: number;\n node: ProsemirrorNode;\n spec: ChartSpec;\n}\n\n/** Every chart node in a document, in order. */\nexport function getDocumentCharts(doc: ProsemirrorNode, typeName = \"chart\"): DocumentChart[] {\n const charts: DocumentChart[] = [];\n doc.descendants((node, pos) => {\n if (node.type.name === typeName) {\n charts.push({ id: node.attrs.id ?? null, pos, node, spec: node.attrs.spec });\n return false;\n }\n return !node.isTextblock;\n });\n return charts;\n}\n\n/** Whether the editor's schema has the chart node (`createRichTextPreset({ chart: true })`). */\nexport function isChartEnabled(editor: Pick<Editor, \"schema\"> | null | undefined): boolean {\n return !!editor?.schema?.nodes?.chart;\n}\n\n/** Reads a chart spec from JSON text (or an object), or `null` when it is not a chart. */\nfunction readSpec(value: unknown): ChartSpec | null {\n let input = value;\n if (typeof value === \"string\") {\n try {\n input = JSON.parse(value);\n } catch {\n return null;\n }\n }\n if (!input || typeof input !== \"object\" || Array.isArray(input)) return null;\n return normalizeChartSpec(input).spec;\n}\n\nconst readSize = (value: string | null): number | null => {\n const n = value === null ? NaN : Number(value);\n return Number.isFinite(n) && n >= 50 && n <= 4096 ? n : null;\n};\n\n/** Gives charts without an id, or with a duplicate one (after a copy), a fresh id. */\nfunction syncChartIds(state: EditorState, typeName: string, generateId: () => string): Transaction | null {\n const seen = new Set<string>();\n let tr: Transaction | null = null;\n for (const chart of getDocumentCharts(state.doc, typeName)) {\n if (chart.id && !seen.has(chart.id)) {\n seen.add(chart.id);\n continue;\n }\n let id = generateId();\n while (seen.has(id)) id = generateId();\n seen.add(id);\n tr = tr ?? state.tr;\n tr.setNodeMarkup(chart.pos, undefined, { ...chart.node.attrs, id });\n }\n return tr?.setMeta(\"addToHistory\", false) ?? null;\n}\n\n/** The static SVG of a chart node, as a `DOMOutputSpec`. */\nexport function staticChartSvg(\n node: ProsemirrorNode,\n options: Pick<ChartNodeOptions, \"theme\" | \"defaultWidth\" | \"defaultHeight\">,\n): ChartDomSpec {\n const spec: ChartSpec = node.attrs.spec;\n const width = node.attrs.width ?? options.defaultWidth;\n const height = node.attrs.height ?? options.defaultHeight;\n const scene = layoutChart(spec, { width, height, theme: options.theme, selection: null });\n return chartSceneToDomSpec(scene, {\n ariaLabel: spec.title || \"Chart\",\n description: describeChart(spec),\n attrs: { style: \"max-width: 100%; height: auto; display: block\" },\n });\n}\n\n/** The longest run of backticks in `text`, so a fence can be one longer. */\nconst longestBacktickRun = (text: string) =>\n Math.max(0, ...Array.from(text.matchAll(/`+/g), (m) => m[0].length));\n\n/**\n * A chart block. Stores a `ChartSpec` as its `spec` attribute (JSON in `data-chart`) with\n * an id, an optional width and a height.\n *\n * - **HTML**: `<div data-type=\"chart\" data-chart=\"{…}\">` holding a static SVG drawn with\n * `chartSceneToDomSpec`, so exported HTML shows the chart without script.\n * - **Markdown**: a ` ```mermaid ` block written with `chartToMermaid` (its `%% @pixerate`\n * line keeps everything Mermaid cannot hold); `xychart-beta`, `pie` and `radar-beta`\n * blocks parse back into charts. Other Mermaid diagrams stay code blocks.\n * - **In the editor**: pass a `nodeView` (React and Svelte export one) for a live chart that\n * opens the chart inspector on click; without one the static SVG is shown.\n */\nexport const Chart = Node.create<ChartNodeOptions>({\n name: \"chart\",\n priority: STRUCTURE_PRIORITY,\n group: \"block\",\n atom: true,\n selectable: true,\n draggable: true,\n\n addOptions() {\n return {\n HTMLAttributes: {},\n nodeView: null,\n theme: DEFAULT_CHART_THEME,\n defaultWidth: 640,\n defaultHeight: 320,\n generateId: () => generateStructureId(\"chart\"),\n };\n },\n\n addAttributes() {\n return {\n id: {\n default: null,\n parseHTML: (element: HTMLElement) => element.getAttribute(\"data-chart-id\") || null,\n renderHTML: (attributes: Record<string, any>) =>\n attributes.id ? { \"data-chart-id\": attributes.id } : {},\n },\n spec: {\n default: normalizeChartSpec({}).spec,\n // null (no `data-chart`) keeps what the parse rule found, e.g. a mermaid block's spec.\n parseHTML: (element: HTMLElement) => readSpec(element.getAttribute(\"data-chart\")),\n renderHTML: (attributes: Record<string, any>) => ({\n \"data-chart\": JSON.stringify(attributes.spec),\n }),\n },\n width: {\n default: null,\n parseHTML: (element: HTMLElement) => readSize(element.getAttribute(\"data-width\")),\n renderHTML: (attributes: Record<string, any>) =>\n attributes.width ? { \"data-width\": String(attributes.width) } : {},\n },\n height: {\n default: this.options.defaultHeight,\n parseHTML: (element: HTMLElement) => readSize(element.getAttribute(\"data-height\")),\n renderHTML: (attributes: Record<string, any>) => ({\n \"data-height\": String(attributes.height),\n }),\n },\n };\n },\n\n parseHTML() {\n return [\n {\n tag: 'div[data-type=\"chart\"]',\n priority: 60,\n // A missing or broken spec falls through, so the fallback content inside (e.g. a\n // DOCX import's caption and data table) is kept instead.\n getAttrs: (element) => (readSpec((element as HTMLElement).getAttribute(\"data-chart\")) ? null : false),\n },\n {\n // ```mermaid blocks (from markdown) that hold a chart; other diagrams stay code.\n tag: \"pre\",\n priority: 60,\n getAttrs: (element) => {\n const code = (element as HTMLElement).querySelector(\"code\");\n const language = code?.getAttribute(\"class\") ?? (element as HTMLElement).getAttribute(\"data-language\") ?? \"\";\n if (!/(?:^|\\s)language-mermaid(?:\\s|$)/.test(language) && language !== \"mermaid\") return false;\n const result = chartFromMermaid((code ?? element).textContent ?? \"\");\n return result.family ? { spec: result.spec } : false;\n },\n },\n ];\n },\n\n renderHTML({ node, HTMLAttributes }) {\n const svg = staticChartSvg(node, this.options);\n return [\n \"div\",\n mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {\n \"data-type\": \"chart\",\n class: \"pixerate-chart\",\n }),\n svg as any,\n ];\n },\n\n renderText({ node }) {\n return `[Chart: ${node.attrs.spec?.title || \"untitled\"}]`;\n },\n\n addStorage() {\n return {\n markdown: {\n serialize(state: any, node: ProsemirrorNode) {\n const text = chartToMermaid(node.attrs.spec);\n const fence = \"`\".repeat(Math.max(3, longestBacktickRun(text) + 1));\n state.write(`${fence}mermaid\\n`);\n state.text(text, false);\n state.ensureNewLine();\n state.write(fence);\n state.closeBlock(node);\n },\n parse: {\n // markdown-it renders ```mermaid as <pre><code class=\"language-mermaid\">, which\n // `parseHTML` reads.\n },\n },\n };\n },\n\n addCommands() {\n return {\n insertChart:\n (options) =>\n ({ commands }) =>\n commands.insertContent({\n type: this.name,\n attrs: {\n id: options.id ?? this.options.generateId(),\n spec: normalizeChartSpec(options.spec ?? {}).spec,\n width: options.width ?? null,\n height: options.height ?? this.options.defaultHeight,\n },\n }),\n updateChart:\n (id, changes) =>\n ({ state, tr, dispatch }) => {\n const chart = getDocumentCharts(state.doc, this.name).find((c) => c.id === id);\n if (!chart) return false;\n if (dispatch) {\n tr.setNodeMarkup(chart.pos, undefined, {\n ...chart.node.attrs,\n ...(changes.spec !== undefined ? { spec: normalizeChartSpec(changes.spec).spec } : {}),\n ...(changes.width !== undefined ? { width: changes.width } : {}),\n ...(changes.height !== undefined ? { height: changes.height } : {}),\n });\n }\n return true;\n },\n };\n },\n\n addNodeView() {\n return createChartNodeView(this.options.nodeView, (node) => staticChartSvg(node, this.options));\n },\n\n addProseMirrorPlugins() {\n const { name } = this;\n const { generateId } = this.options;\n return [\n new Plugin({\n key: chartPluginKey,\n appendTransaction: (transactions, _oldState, newState) => {\n if (!transactions.some((tr) => tr.docChanged)) return null;\n if (!transactionsInsert(transactions, [name])) return null;\n return syncChartIds(newState, name, generateId);\n },\n }),\n ];\n },\n\n onBeforeCreate() {\n const { generateId } = this.options;\n syncInitialContent(this.editor, (state) => syncChartIds(state, this.name, generateId));\n },\n});\n","import { createDocument, type Editor } from \"@tiptap/core\";\nimport type { Node as ProsemirrorNode } from \"@tiptap/pm/model\";\nimport { EditorState, type Transaction } from \"@tiptap/pm/state\";\nimport { ReplaceAroundStep, ReplaceStep } from \"@tiptap/pm/transform\";\n\nlet idCounter = 0;\n\n/**\n * Generates a short, document-unique-enough id (`prefix-xxxxxxxx`). Ids are\n * stored in the document, so they must not depend on positions or text.\n */\nexport function generateStructureId(prefix: string): string {\n idCounter = (idCounter + 1) % 1296;\n const random = Math.random().toString(36).slice(2, 8).padEnd(6, \"0\");\n return `${prefix}-${random}${idCounter.toString(36).padStart(2, \"0\")}`;\n}\n\n/**\n * Returns true if any transaction inserted content containing one of the given\n * node or mark type names. Used to skip whole-document scans for transactions\n * that cannot have introduced the nodes a plugin tracks.\n */\nexport function transactionsInsert(\n transactions: readonly Transaction[],\n typeNames: readonly string[],\n): boolean {\n for (const tr of transactions) {\n for (const step of tr.steps) {\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {\n // Mark and attribute steps can add bookmarks or retarget nodes.\n const mark = (step as any).mark;\n if (mark && typeNames.includes(mark.type.name)) return true;\n continue;\n }\n let found = false;\n step.slice.content.descendants((node) => {\n if (found) return false;\n if (\n typeNames.includes(node.type.name) ||\n node.marks.some((m) => typeNames.includes(m.type.name))\n ) {\n found = true;\n }\n return !found;\n });\n if (found) return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true if the document contains a node (or mark) of one of the types.\n */\nexport function docContains(\n doc: ProsemirrorNode,\n typeNames: readonly string[],\n): boolean {\n let found = false;\n doc.descendants((node) => {\n if (found) return false;\n if (\n typeNames.includes(node.type.name) ||\n node.marks.some((m) => typeNames.includes(m.type.name))\n ) {\n found = true;\n }\n return !found;\n });\n return found;\n}\n\n/**\n * Plugin state spec that tracks whether the document contains any of the given\n * node or mark types. A document without them is only rescanned when a\n * transaction inserts one, so plugins can skip their sync pass cheaply.\n */\nexport function presenceStateSpec(typeNames: readonly string[]) {\n return {\n init: (_config: unknown, state: EditorState) =>\n docContains(state.doc, typeNames),\n apply: (\n tr: Transaction,\n present: boolean,\n _oldState: EditorState,\n newState: EditorState,\n ) => {\n if (!tr.docChanged) return present;\n if (!present && !transactionsInsert([tr], typeNames)) return false;\n return docContains(newState.doc, typeNames);\n },\n };\n}\n\n/**\n * Shallow array equality using a per-item comparator.\n */\nexport function arraysEqual<T>(\n a: readonly T[],\n b: readonly T[],\n eq: (x: T, y: T) => boolean,\n): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!eq(a[i], b[i])) return false;\n }\n return true;\n}\n\n/**\n * Scrolls the DOM node at a document position into view, if the editor is\n * mounted in a browser. Errors from detached or headless views are ignored.\n */\nexport function scrollDomAtPos(\n view: any,\n pos: number,\n behavior: ScrollBehavior = \"smooth\",\n): void {\n try {\n const dom = view?.nodeDOM?.(pos) as HTMLElement | null;\n if (dom && typeof dom.scrollIntoView === \"function\") {\n dom.scrollIntoView({ block: \"start\", behavior });\n }\n } catch {\n // Headless editors (no DOM) cannot scroll.\n }\n}\n\n/**\n * Applies a sync pass to the editor's initial content. `appendTransaction`\n * does not run for the initial document and TipTap's `create` event fires\n * asynchronously, so derived state (heading ids, TOC entries, footnote\n * numbers) is computed in `onBeforeCreate` instead: the content is parsed,\n * fixed, and handed back to TipTap as a node. Extensions calling this must\n * have a priority below the Markdown extension's (50), so that markdown\n * content has already been converted to HTML.\n */\nexport function syncInitialContent(\n editor: Editor,\n sync: (state: EditorState) => Transaction | null,\n): void {\n const { content } = editor.options;\n if (content == null || content === \"\") return;\n try {\n const doc = createDocument(content as any, editor.schema, editor.options.parseOptions, {\n errorOnInvalidContent: false,\n });\n const tr = sync(EditorState.create({ doc }));\n if (tr?.docChanged) editor.options.content = tr.doc as any;\n } catch {\n // Leave invalid content to TipTap's own handling.\n }\n}\n\n/** Priority for extensions that use `syncInitialContent` (below Markdown's 50). */\nexport const STRUCTURE_PRIORITY = 45;\n","import { Node, mergeAttributes } from \"@tiptap/core\";\nimport type { Node as ProsemirrorNode } from \"@tiptap/pm/model\";\nimport { layoutSparkline, type ChartSparklineKind } from \"../../chart/sparkline\";\nimport { chartSceneToDomSpec } from \"../../chart/svg\";\nimport type { ChartValue } from \"../../chart/types\";\n\nexport const SPARKLINE_KINDS: readonly ChartSparklineKind[] = [\"line\", \"column\", \"win-loss\"];\n/** Most values a sparkline node keeps. */\nexport const MAX_SPARKLINE_VALUES = 1000;\n\nexport interface SparklineNodeOptions {\n HTMLAttributes: Record<string, any>;\n /** Line, positive column and win colour (default the first palette colour). */\n color: string;\n /** Negative column and loss colour. */\n negativeColor: string;\n}\n\nexport interface InsertSparklineOptions {\n values: readonly (number | null)[];\n kind?: ChartSparklineKind;\n /** Width in pixels (default 80). */\n width?: number;\n /** Height in pixels (default 18). */\n height?: number;\n /** CSS colour (default: the extension's `color`). */\n color?: string | null;\n /** Accessible label (default: first and last value). */\n label?: string | null;\n}\n\ndeclare module \"@tiptap/core\" {\n interface Commands<ReturnType> {\n sparkline: {\n /** Inserts a word-sized chart at the selection. */\n insertSparkline: (options: InsertSparklineOptions) => ReturnType;\n };\n }\n}\n\n/** Cleans sparkline values: finite numbers or null, at most `MAX_SPARKLINE_VALUES`. */\nexport function normalizeSparklineValues(values: unknown): ChartValue[] {\n if (!Array.isArray(values)) return [];\n return values\n .slice(0, MAX_SPARKLINE_VALUES)\n .map((v) => (typeof v === \"number\" && Number.isFinite(v) ? v : null));\n}\n\nfunction readValues(text: string | null): ChartValue[] {\n if (!text) return [];\n try {\n return normalizeSparklineValues(JSON.parse(text));\n } catch {\n return normalizeSparklineValues(text.split(/[\\s,]+/).filter(Boolean).map(Number));\n }\n}\n\nconst readNumber = (text: string | null, fallback: number, max: number) => {\n const n = text === null ? NaN : Number(text);\n return Number.isFinite(n) && n >= 4 && n <= max ? n : fallback;\n};\n\n/** The accessible label of a sparkline node. */\nexport function sparklineLabel(node: ProsemirrorNode): string {\n if (node.attrs.label) return node.attrs.label;\n const present = (node.attrs.values as ChartValue[]).filter((v): v is number => v !== null);\n return present.length ? `Trend from ${present[0]} to ${present[present.length - 1]}` : \"No data\";\n}\n\n/**\n * An inline, word-sized chart (`line`, `column` or `win-loss`) drawn as SVG in the text.\n * HTML: `<span data-type=\"sparkline\" data-values=\"[…]\" data-kind=\"line\">`; markdown keeps the\n * same span (the markdown sanitizer allows `span` with `data-*` attributes).\n */\nexport const Sparkline = Node.create<SparklineNodeOptions>({\n name: \"sparkline\",\n group: \"inline\",\n inline: true,\n atom: true,\n selectable: true,\n\n addOptions() {\n return { HTMLAttributes: {}, color: \"#4269d0\", negativeColor: \"#e5484d\" };\n },\n\n addAttributes() {\n return {\n values: {\n default: [],\n parseHTML: (element: HTMLElement) => readValues(element.getAttribute(\"data-values\")),\n renderHTML: (attributes: Record<string, any>) => ({ \"data-values\": JSON.stringify(attributes.values ?? []) }),\n },\n kind: {\n default: \"line\",\n parseHTML: (element: HTMLElement) => {\n const kind = element.getAttribute(\"data-kind\") as ChartSparklineKind;\n return SPARKLINE_KINDS.includes(kind) ? kind : \"line\";\n },\n renderHTML: (attributes: Record<string, any>) => ({ \"data-kind\": attributes.kind }),\n },\n width: {\n default: 80,\n parseHTML: (element: HTMLElement) => readNumber(element.getAttribute(\"data-width\"), 80, 1000),\n renderHTML: (attributes: Record<string, any>) => ({ \"data-width\": String(attributes.width) }),\n },\n height: {\n default: 18,\n parseHTML: (element: HTMLElement) => readNumber(element.getAttribute(\"data-height\"), 18, 200),\n renderHTML: (attributes: Record<string, any>) => ({ \"data-height\": String(attributes.height) }),\n },\n color: {\n default: null,\n parseHTML: (element: HTMLElement) => element.getAttribute(\"data-color\") || null,\n renderHTML: (attributes: Record<string, any>) => (attributes.color ? { \"data-color\": attributes.color } : {}),\n },\n label: {\n default: null,\n parseHTML: (element: HTMLElement) => element.getAttribute(\"data-label\") || null,\n renderHTML: (attributes: Record<string, any>) => (attributes.label ? { \"data-label\": attributes.label } : {}),\n },\n };\n },\n\n parseHTML() {\n return [{ tag: 'span[data-type=\"sparkline\"]', priority: 60 }];\n },\n\n renderHTML({ node, HTMLAttributes }) {\n const scene = layoutSparkline(node.attrs.values, {\n kind: node.attrs.kind,\n width: node.attrs.width,\n height: node.attrs.height,\n color: node.attrs.color ?? this.options.color,\n negativeColor: this.options.negativeColor,\n });\n const svg = chartSceneToDomSpec(scene, {\n ariaLabel: sparklineLabel(node),\n attrs: { style: \"display: inline-block; vertical-align: middle\" },\n });\n return [\n \"span\",\n mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {\n \"data-type\": \"sparkline\",\n class: \"pixerate-sparkline\",\n }),\n svg as any,\n ];\n },\n\n renderText({ node }) {\n return `[${sparklineLabel(node)}]`;\n },\n\n addStorage() {\n return {\n markdown: {\n serialize(state: any, node: ProsemirrorNode) {\n const attr = (name: string, value: unknown) =>\n value === null || value === undefined\n ? \"\"\n : ` ${name}=\"${String(value).replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\")}\"`;\n state.write(\n `<span data-type=\"sparkline\"${attr(\"data-values\", JSON.stringify(node.attrs.values))}${attr(\"data-kind\", node.attrs.kind)}${attr(\"data-width\", node.attrs.width)}${attr(\"data-height\", node.attrs.height)}${attr(\"data-color\", node.attrs.color)}${attr(\"data-label\", node.attrs.label)}></span>`,\n );\n },\n parse: {},\n },\n };\n },\n\n addCommands() {\n return {\n insertSparkline:\n (options) =>\n ({ commands }) =>\n commands.insertContent({\n type: this.name,\n attrs: {\n values: normalizeSparklineValues(options.values),\n kind: options.kind && SPARKLINE_KINDS.includes(options.kind) ? options.kind : \"line\",\n width: options.width ?? 80,\n height: options.height ?? 18,\n color: options.color ?? null,\n label: options.label ?? null,\n },\n }),\n };\n },\n});\n","import type { Editor } from \"@tiptap/core\";\nimport type { EditorState } from \"@tiptap/pm/state\";\nimport { CellSelection, isInTable, selectedRect } from \"@tiptap/pm/tables\";\nimport { isTrackChangesEnabled } from \"../track-changes\";\nimport {\n normalizeTableCellAlignment,\n normalizeTableCellColor,\n type TableCellAlignment,\n} from \"./extension\";\n\n/** Table operations shared by the command registry, the toolbars and agent tools. */\nexport type TableAction =\n | \"insertTable\"\n | \"addRowBefore\"\n | \"addRowAfter\"\n | \"deleteRow\"\n | \"addColumnBefore\"\n | \"addColumnAfter\"\n | \"deleteColumn\"\n | \"deleteTable\"\n | \"mergeCells\"\n | \"splitCell\"\n | \"toggleHeaderRow\"\n | \"toggleHeaderColumn\"\n | \"toggleHeaderCell\"\n | \"goToNextCell\"\n | \"goToPreviousCell\"\n | \"setCellAlignment\"\n | \"setCellBackground\";\n\n/** Parameters of `insertTable`, `setCellAlignment` and `setCellBackground`. */\nexport interface TableActionParams {\n /** `insertTable`: number of rows (1–100, default 3). */\n rows?: number;\n /** `insertTable`: number of columns (1–50, default 3). */\n cols?: number;\n /** `insertTable`: make the first row a header row (default `true`). */\n withHeaderRow?: boolean;\n /** `setCellAlignment`: `left`, `center`, `right`, `justify`, or `null` to clear. */\n align?: TableCellAlignment | null;\n /** `setCellBackground`: a CSS color, or `null` to clear. */\n color?: string | null;\n}\n\nexport interface TableActionInfo {\n action: TableAction;\n label: string;\n description: string;\n keywords: readonly string[];\n}\n\n/** Every table action with its label, in toolbar order. */\nexport const TABLE_ACTIONS: readonly TableActionInfo[] = [\n { action: \"insertTable\", label: \"Insert Table\", description: \"Inserts a table (rows, cols, withHeaderRow) at the cursor.\", keywords: [\"table\", \"grid\", \"new\"] },\n { action: \"addRowBefore\", label: \"Insert Row Above\", description: \"Adds a row above the current row.\", keywords: [\"row\", \"add\", \"above\"] },\n { action: \"addRowAfter\", label: \"Insert Row Below\", description: \"Adds a row below the current row.\", keywords: [\"row\", \"add\", \"below\"] },\n { action: \"deleteRow\", label: \"Delete Row\", description: \"Deletes the selected rows.\", keywords: [\"row\", \"remove\"] },\n { action: \"addColumnBefore\", label: \"Insert Column Left\", description: \"Adds a column left of the current column.\", keywords: [\"column\", \"add\", \"left\", \"before\"] },\n { action: \"addColumnAfter\", label: \"Insert Column Right\", description: \"Adds a column right of the current column.\", keywords: [\"column\", \"add\", \"right\", \"after\"] },\n { action: \"deleteColumn\", label: \"Delete Column\", description: \"Deletes the selected columns.\", keywords: [\"column\", \"remove\"] },\n { action: \"deleteTable\", label: \"Delete Table\", description: \"Deletes the table around the cursor.\", keywords: [\"table\", \"remove\"] },\n { action: \"mergeCells\", label: \"Merge Cells\", description: \"Merges the selected cells into one.\", keywords: [\"combine\", \"join\", \"span\"] },\n { action: \"splitCell\", label: \"Split Cell\", description: \"Splits a merged cell back into single cells.\", keywords: [\"unmerge\", \"span\"] },\n { action: \"toggleHeaderRow\", label: \"Toggle Header Row\", description: \"Turns the first row into header cells, or back.\", keywords: [\"header\", \"row\", \"th\"] },\n { action: \"toggleHeaderColumn\", label: \"Toggle Header Column\", description: \"Turns the first column into header cells, or back.\", keywords: [\"header\", \"column\", \"th\"] },\n { action: \"toggleHeaderCell\", label: \"Toggle Header Cell\", description: \"Turns the selected cells into header cells, or back.\", keywords: [\"header\", \"cell\", \"th\"] },\n { action: \"goToNextCell\", label: \"Next Cell\", description: \"Moves the cursor to the next cell.\", keywords: [\"tab\", \"navigate\"] },\n { action: \"goToPreviousCell\", label: \"Previous Cell\", description: \"Moves the cursor to the previous cell.\", keywords: [\"shift tab\", \"navigate\"] },\n { action: \"setCellAlignment\", label: \"Align Cells…\", description: \"Sets the horizontal alignment (align: left | center | right | justify | null) of the selected cells.\", keywords: [\"align\", \"left\", \"center\", \"right\"] },\n { action: \"setCellBackground\", label: \"Cell Background…\", description: \"Sets the background color (color: CSS color or null) of the selected cells.\", keywords: [\"shading\", \"fill\", \"color\"] },\n];\n\n/** A button of the table toolbars (`TableToolbar` in React and Svelte). */\nexport interface TableToolbarItem {\n /** Unique id (also the button's `data-action`). */\n id: string;\n action: TableAction;\n params?: TableActionParams;\n /** Short button text. */\n label: string;\n /** Accessible name and tooltip. */\n title: string;\n /** Items of one group are separated from the next group. */\n group: string;\n /** Toggle buttons: whether the button shows as pressed. */\n active?: (state: TableState) => boolean;\n}\n\n/** The default table toolbar: rows, columns, cells, headers, alignment, delete. */\nexport const DEFAULT_TABLE_TOOLBAR: readonly TableToolbarItem[] = [\n { id: \"addRowBefore\", action: \"addRowBefore\", label: \"+ Row ↑\", title: \"Insert row above\", group: \"rows\" },\n { id: \"addRowAfter\", action: \"addRowAfter\", label: \"+ Row ↓\", title: \"Insert row below\", group: \"rows\" },\n { id: \"deleteRow\", action: \"deleteRow\", label: \"− Row\", title: \"Delete row\", group: \"rows\" },\n { id: \"addColumnBefore\", action: \"addColumnBefore\", label: \"+ Col ←\", title: \"Insert column left\", group: \"columns\" },\n { id: \"addColumnAfter\", action: \"addColumnAfter\", label: \"+ Col →\", title: \"Insert column right\", group: \"columns\" },\n { id: \"deleteColumn\", action: \"deleteColumn\", label: \"− Col\", title: \"Delete column\", group: \"columns\" },\n { id: \"mergeCells\", action: \"mergeCells\", label: \"Merge\", title: \"Merge cells\", group: \"cells\" },\n { id: \"splitCell\", action: \"splitCell\", label: \"Split\", title: \"Split cell\", group: \"cells\" },\n { id: \"toggleHeaderRow\", action: \"toggleHeaderRow\", label: \"Header row\", title: \"Toggle header row\", group: \"headers\", active: (s) => s.headerRow },\n { id: \"toggleHeaderColumn\", action: \"toggleHeaderColumn\", label: \"Header col\", title: \"Toggle header column\", group: \"headers\", active: (s) => s.headerColumn },\n { id: \"toggleHeaderCell\", action: \"toggleHeaderCell\", label: \"Header cell\", title: \"Toggle header cell\", group: \"headers\", active: (s) => s.headerCell },\n { id: \"alignLeft\", action: \"setCellAlignment\", params: { align: \"left\" }, label: \"Left\", title: \"Align cell left\", group: \"align\", active: (s) => s.cellAlignment === \"left\" },\n { id: \"alignCenter\", action: \"setCellAlignment\", params: { align: \"center\" }, label: \"Center\", title: \"Align cell center\", group: \"align\", active: (s) => s.cellAlignment === \"center\" },\n { id: \"alignRight\", action: \"setCellAlignment\", params: { align: \"right\" }, label: \"Right\", title: \"Align cell right\", group: \"align\", active: (s) => s.cellAlignment === \"right\" },\n { id: \"deleteTable\", action: \"deleteTable\", label: \"Delete table\", title: \"Delete table\", group: \"table\" },\n];\n\nexport const MAX_TABLE_ROWS = 100;\nexport const MAX_TABLE_COLUMNS = 50;\n\nconst live = (editor: Editor | null | undefined): editor is Editor => !!editor && !editor.isDestroyed;\n\n/** Whether the editor's schema has the table nodes (`createRichTextPreset({ table })`). */\nexport function isTableEnabled(editor: Editor | null | undefined): boolean {\n return live(editor) && !!editor.schema.nodes.table && !!editor.schema.nodes.tableRow;\n}\n\n/** Whether the selection (cursor, text or cell selection) is inside a table. */\nexport function isSelectionInTable(state: EditorState): boolean {\n if (!state.schema.nodes.table) return false;\n return state.selection instanceof CellSelection || isInTable(state);\n}\n\n/**\n * `shouldShow` for a table bubble menu (TipTap's `BubbleMenuPlugin`): shown\n * while an editable editor's selection is in a table, even a collapsed cursor.\n */\nexport function shouldShowTableBubbleMenu({ editor, state }: { editor: Editor; state: EditorState }): boolean {\n return editor.isEditable && isSelectionInTable(state);\n}\n\nconst isInt = (value: unknown, min: number, max: number) =>\n typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max;\n\nconst can = (editor: Editor, run: (chain: any) => any): boolean => {\n try {\n return !!run(editor.can().chain()).run();\n } catch {\n return false;\n }\n};\n\n/**\n * Whether a table action can run: `true`, or the reason it cannot (e.g.\n * \"Place the cursor in a table first.\").\n */\nexport function getTableActionState(\n editor: Editor | null | undefined,\n action: TableAction,\n params: TableActionParams = {},\n): true | string {\n if (!live(editor)) return \"The editor is not available.\";\n if (!isTableEnabled(editor)) return \"Tables are not enabled in this editor.\";\n if (!editor.isEditable) return \"The editor is read-only.\";\n const state = editor.state;\n const inTable = isSelectionInTable(state);\n\n if (action === \"insertTable\") {\n if (inTable) return \"Tables cannot be nested: move the cursor out of the table first.\";\n if (params.rows !== undefined && !isInt(params.rows, 1, MAX_TABLE_ROWS)) {\n return `Rows must be a whole number from 1 to ${MAX_TABLE_ROWS}.`;\n }\n if (params.cols !== undefined && !isInt(params.cols, 1, MAX_TABLE_COLUMNS)) {\n return `Columns must be a whole number from 1 to ${MAX_TABLE_COLUMNS}.`;\n }\n return can(editor, (c) => c.insertTable({ rows: 1, cols: 1 })) ? true : \"A table cannot be inserted here.\";\n }\n\n if (!inTable) return \"Place the cursor in a table first.\";\n\n switch (action) {\n case \"mergeCells\":\n case \"splitCell\": {\n if (isTrackChangesEnabled(editor)) {\n return `${action === \"mergeCells\" ? \"Merging\" : \"Splitting\"} cells cannot be tracked: turn off Track Changes first.`;\n }\n if (action === \"mergeCells\") {\n return can(editor, (c) => c.mergeCells()) ? true : \"Select two or more adjacent cells to merge.\";\n }\n return can(editor, (c) => c.splitCell()) ? true : \"Only a merged cell can be split.\";\n }\n case \"deleteRow\":\n case \"deleteColumn\": {\n // prosemirror-tables only refuses to delete every row/column when dispatching.\n const rect = selectedRect(state);\n const all = action === \"deleteRow\"\n ? rect.top === 0 && rect.bottom === rect.map.height\n : rect.left === 0 && rect.right === rect.map.width;\n const what = action === \"deleteRow\" ? \"rows\" : \"columns\";\n if (all || !can(editor, (c) => c[action]())) return `These are all the ${what}: delete the table instead.`;\n return true;\n }\n case \"goToNextCell\":\n return can(editor, (c) => c.goToNextCell()) ? true : \"This is the last cell.\";\n case \"goToPreviousCell\":\n return can(editor, (c) => c.goToPreviousCell()) ? true : \"This is the first cell.\";\n case \"setCellAlignment\":\n if (params.align !== undefined && params.align !== null && !normalizeTableCellAlignment(params.align)) {\n return 'Alignment must be \"left\", \"center\", \"right\", \"justify\" or null.';\n }\n if (!editor.schema.nodes.tableCell?.spec.attrs?.align) return \"Cell alignment is not supported by this schema.\";\n return true;\n case \"setCellBackground\":\n if (params.color !== undefined && params.color !== null && !normalizeTableCellColor(params.color)) {\n return \"Color must be a CSS color such as #fde68a, rgb(…) or a color name, or null.\";\n }\n if (!editor.schema.nodes.tableCell?.spec.attrs?.backgroundColor) return \"Cell backgrounds are not supported by this schema.\";\n return true;\n default:\n return can(editor, (c) => c[action]()) ? true : \"This table action is not available here.\";\n }\n}\n\nexport interface RunTableActionOptions {\n /** Focus the editor (toolbars). Default `false`. */\n focus?: boolean;\n}\n\n/**\n * Runs a table action. Returns `false` (and changes nothing) when it cannot\n * run; check `getTableActionState` for the reason.\n */\nexport function runTableAction(\n editor: Editor | null | undefined,\n action: TableAction,\n params: TableActionParams = {},\n options: RunTableActionOptions = {},\n): boolean {\n if (getTableActionState(editor, action, params) !== true) return false;\n const ed = editor as Editor;\n let chain: any = ed.chain();\n if (options.focus) chain = chain.focus();\n switch (action) {\n case \"insertTable\":\n chain = chain.insertTable({\n rows: params.rows ?? 3,\n cols: params.cols ?? 3,\n withHeaderRow: params.withHeaderRow ?? true,\n });\n break;\n case \"setCellAlignment\":\n chain = chain.setCellAttribute(\"align\", normalizeTableCellAlignment(params.align));\n break;\n case \"setCellBackground\":\n chain = chain.setCellAttribute(\"backgroundColor\", normalizeTableCellColor(params.color));\n break;\n default:\n chain = chain[action]();\n }\n return !!chain.run();\n}\n\nexport interface TableActionStatus {\n enabled: boolean;\n /** Why the action cannot run (only when `enabled` is false). */\n reason?: string;\n}\n\n/** The table at the selection and what can be done there. */\nexport interface TableState {\n /** The schema has tables. */\n enabled: boolean;\n /** The selection is inside a table. */\n inTable: boolean;\n /** Cells are selected (a `CellSelection`). */\n cellSelection: boolean;\n /** Size of the table (0 outside a table). */\n rows: number;\n columns: number;\n /** Row and column (0-based) of the selection's first cell, or -1. */\n row: number;\n column: number;\n /** The first row / first column are all header cells. */\n headerRow: boolean;\n headerColumn: boolean;\n /** The cell at the selection is a header cell. */\n headerCell: boolean;\n /** Alignment / background of the cell at the selection. */\n cellAlignment: TableCellAlignment | null;\n cellBackground: string | null;\n /** Enablement of every action (with the default params). */\n actions: Record<TableAction, TableActionStatus>;\n}\n\nconst NO_ACTIONS = Object.fromEntries(\n TABLE_ACTIONS.map(({ action }) => [action, { enabled: false, reason: \"The editor is not available.\" }]),\n) as Record<TableAction, TableActionStatus>;\n\nexport const EMPTY_TABLE_STATE: TableState = Object.freeze({\n enabled: false,\n inTable: false,\n cellSelection: false,\n rows: 0,\n columns: 0,\n row: -1,\n column: -1,\n headerRow: false,\n headerColumn: false,\n headerCell: false,\n cellAlignment: null,\n cellBackground: null,\n actions: NO_ACTIONS,\n}) as TableState;\n\n/** Computes the table state at the editor's selection. */\nexport function getTableState(editor: Editor | null | undefined): TableState {\n if (!live(editor)) return EMPTY_TABLE_STATE;\n const actions = Object.fromEntries(\n TABLE_ACTIONS.map(({ action }) => {\n const result = getTableActionState(editor, action);\n return [action, result === true ? { enabled: true } : { enabled: false, reason: result }];\n }),\n ) as Record<TableAction, TableActionStatus>;\n const state = editor.state;\n const base: TableState = { ...EMPTY_TABLE_STATE, enabled: isTableEnabled(editor), actions };\n if (!base.enabled || !isSelectionInTable(state)) return base;\n try {\n const rect = selectedRect(state);\n const { map, table } = rect;\n const cellAt = (row: number, col: number) => table.nodeAt(map.map[row * map.width + col]);\n const allHeaders = (positions: number[]) =>\n positions.length > 0 && positions.every((pos) => table.nodeAt(pos)?.type.name === \"tableHeader\");\n const firstRow = map.cellsInRect({ left: 0, right: map.width, top: 0, bottom: 1 });\n const firstColumn = map.cellsInRect({ left: 0, right: 1, top: 0, bottom: map.height });\n const cell = cellAt(rect.top, rect.left);\n return {\n ...base,\n inTable: true,\n cellSelection: state.selection instanceof CellSelection,\n rows: map.height,\n columns: map.width,\n row: rect.top,\n column: rect.left,\n headerRow: allHeaders(firstRow),\n headerColumn: allHeaders(firstColumn),\n headerCell: cell?.type.name === \"tableHeader\",\n cellAlignment: normalizeTableCellAlignment(cell?.attrs.align),\n cellBackground: normalizeTableCellColor(cell?.attrs.backgroundColor),\n };\n } catch {\n return { ...base, inTable: true };\n }\n}\n\nconst stateKey = (state: TableState) => JSON.stringify(state);\n\nexport interface TableStore {\n getSnapshot(): TableState;\n subscribe(listener: () => void): () => void;\n destroy(): void;\n}\n\n/**\n * An external store of `getTableState(editor)` for UI bindings (React's\n * `useSyncExternalStore`, Svelte runes). The snapshot object only changes\n * when the state does, and the store listens to the editor only while it\n * has subscribers.\n */\nexport function createTableStore(editor: Editor | null | undefined): TableStore {\n const listeners = new Set<() => void>();\n let snapshot = getTableState(editor);\n let key = stateKey(snapshot);\n\n const update = () => {\n const next = getTableState(editor);\n const nextKey = stateKey(next);\n if (nextKey === key) return;\n snapshot = next;\n key = nextKey;\n listeners.forEach((listener) => listener());\n };\n const detach = () => {\n editor?.off(\"transaction\", update);\n editor?.off(\"update\", update);\n editor?.off(\"focus\", update);\n editor?.off(\"destroy\", update);\n };\n\n return {\n getSnapshot: () => {\n if (!listeners.size) {\n const next = getTableState(editor);\n const nextKey = stateKey(next);\n if (nextKey !== key) {\n snapshot = next;\n key = nextKey;\n }\n }\n return snapshot;\n },\n subscribe(listener) {\n if (!listeners.size && editor) {\n update();\n editor.on(\"transaction\", update);\n // `setEditable` emits `update` without a transaction.\n editor.on(\"update\", update);\n editor.on(\"focus\", update);\n editor.on(\"destroy\", update);\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (!listeners.size) detach();\n };\n },\n destroy() {\n detach();\n listeners.clear();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,UAAU,aAA6D;AAChF,SAAS,QAAQ,WAAW,iBAAmC;AAE/D;AAAA,EACE;AAAA,EACA;AAAA,EACA,eAAe;AAAA,OACV;AAOA,IAAM,2BAA2B;AAEjC,IAAM,wBAAwB,IAAI,UAAU,cAAc;AAEjE,IAAM,SAAS,CAAC,SAA0B,KAAK,KAAK,KAAK;AACzD,IAAM,cAAc,CAAC,SAA0B,OAAO,IAAI,MAAM;AAGzD,SAAS,oBAAoB,MAA2B;AAC7D,WAAS,IAAI,GAAG,KAAK,KAAK,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MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,UAAU,UAAU;AAClB,UAAI,CAAC,UAAU,QAAQ,QAAQ;AAC7B,eAAO;AACP,eAAO,GAAG,eAAe,MAAM;AAE/B,eAAO,GAAG,UAAU,MAAM;AAC1B,eAAO,GAAG,SAAS,MAAM;AACzB,eAAO,GAAG,WAAW,MAAM;AAAA,MAC7B;AACA,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM;AACX,kBAAU,OAAO,QAAQ;AACzB,YAAI,CAAC,UAAU,KAAM,QAAO;AAAA,MAC9B;AAAA,IACF;AAAA,IACA,UAAU;AACR,aAAO;AACP,gBAAU,MAAM;AAAA,IAClB;AAAA,EACF;AACF;","names":["skip","exit","Fragment","Fragment","Plugin","PluginKey","PluginKey","Plugin","Node","mergeAttributes","Node","mergeAttributes","CellSelection","CellSelection"]}