The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,960 lines 66 KB
Raw
1 import { joinTextblockBackward, joinTextblockForward } from "@tiptap/pm/commands";
2 import {
3 Fragment,
4 Mark,
5 type MarkType,
6 type Node as ProseMirrorNode,
7 type ResolvedPos,
8 } from "@tiptap/pm/model";
9 import {
10 Bold,
11 starInputRegex as boldStarInputRegex,
12 underscoreInputRegex as boldUnderscoreInputRegex,
13 } from "@tiptap/extension-bold";
14 import { Code } from "@tiptap/extension-code";
15 import { Blockquote } from "@tiptap/extension-blockquote";
16 import { CodeBlock } from "@tiptap/extension-code-block";
17 import { Heading } from "@tiptap/extension-heading";
18 import { HorizontalRule } from "@tiptap/extension-horizontal-rule";
19 import { Italic, starInputRegex, starPasteRegex } from "@tiptap/extension-italic";
20 import {
21 combineTransactionSteps,
22 getChangedRanges,
23 type Command,
24 type Editor,
25 InputRule,
26 markInputRule,
27 markPasteRule,
28 mergeAttributes,
29 } from "@tiptap/core";
30 import { isHistoryTransaction } from "@tiptap/pm/history";
31 import { canJoin, findWrapping } from "@tiptap/pm/transform";
32 import { BulletList, ListItem, OrderedList } from "@tiptap/extension-list";
33 import { Strike, inputRegex as strikeInputRegex } from "@tiptap/extension-strike";
34 import { TaskItem } from "@tiptap/extension-task-item";
35 import { TaskList } from "@tiptap/extension-task-list";
36 import {
37 type EditorState,
38 Plugin,
39 PluginKey,
40 Selection,
41 TextSelection,
42 type Transaction,
43 } from "@tiptap/pm/state";
44 import { ReplaceStep } from "@tiptap/pm/transform";
45
46 import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
47 import { nextOrderedMarkerText } from "~/composer-list-continuation";
48 import {
49 MARKDOWN_SOURCE_MARK,
50 parseInlineMarkdown,
51 RICH_TEXT_DELIMITERS,
52 type RichTextMark,
53 } from "~/composer-rich-text";
54 import { collectInlineContextIds } from "~/lib/composerContextReferences";
55 import { composerMathRanges } from "@t3tools/shared/composerInlineTokens";
56
57 export type SkillMeta = { label: string; description: string | null };
58
59 export type IsKnownModel = (instanceId: string, model: string) => boolean;
60
61 interface ChipResolver {
62 skill: (name: string) => SkillMeta | null;
63 model: IsKnownModel;
64 }
65
66 const NO_MODELS: IsKnownModel = () => false;
67
68 const MARK_NESTING_ORDER: RichTextMark[] = ["strike", "bold", "italic", "code"];
69
70 const MARK_TO_TIPTAP: Record<RichTextMark, string> = {
71 bold: "bold",
72 italic: "italic",
73 strike: "strike",
74 code: "code",
75 };
76
77 const TIPTAP_TO_MARK: Record<string, RichTextMark> = {
78 bold: "bold",
79 italic: "italic",
80 strike: "strike",
81 code: "code",
82 };
83
84 type CodePair = { from: number; to: number };
85
86 const codePairKey = new PluginKey<CodePair[]>("typedBacktickPairs");
87
88 // Input rules only see text before the caret, so filling an already typed
89 // pair needs a separate exit handler. Only typed pairs opt into that handler.
90 function codePairCaretPlugin(type: MarkType) {
91 return new Plugin<CodePair[]>({
92 key: codePairKey,
93 state: {
94 init: () => [],
95 apply(tr, pairs) {
96 const mapped = pairs.flatMap((pair) => {
97 const from = tr.mapping.mapResult(pair.from, 1);
98 const to = tr.mapping.mapResult(pair.to, -1);
99 return from.deleted || to.deleted ? [] : [{ from: from.pos, to: to.pos }];
100 });
101 const typed = (tr.getMeta(codePairKey) as CodePair | undefined) ?? composedCodePair(tr);
102 return typed ? [...mapped, typed] : mapped;
103 },
104 },
105 props: {
106 handleTextInput(view, from, to, text, insert) {
107 if (view.composing || from !== to || text !== "`") return false;
108 const $from = view.state.doc.resolve(from);
109 if (!$from.parent.isTextblock || $from.parent.type.spec.code) return false;
110 if (touchesMarkdownSource(view.state, from, to)) return false;
111 const before = $from.nodeBefore?.text ?? "";
112 if (closesBacktickPair($from)) {
113 view.dispatch(insert().setMeta(codePairKey, { from: from - 1, to: from + 1 }));
114 return true;
115 }
116 if (before.endsWith("`")) return false;
117
118 // The opening tick can be typed after the closing one. Input rules
119 // cannot recognize that pair because they only read before the caret.
120 const after = $from.parent.textBetween(
121 $from.parentOffset,
122 $from.parent.content.size,
123 "\n",
124 "\n",
125 );
126 const match = /^([^`\n]+)`(?!`)/.exec(after);
127 if (!match) return false;
128 const end = from + match[1]!.length;
129 let plain = true;
130 view.state.doc.nodesBetween(from, end + 1, (node) => {
131 if (node.isInline && (!node.isText || node.marks.length > 0)) plain = false;
132 });
133 if (!plain) return false;
134 const tr = insert()
135 .delete(end + 1, end + 2)
136 .delete(from, from + 1);
137 tr.addMark(from, end, type.create());
138 tr.setSelection(TextSelection.create(tr.doc, from));
139 tr.addStoredMark(type.create());
140 view.dispatch(tr);
141 return true;
142 },
143 },
144 appendTransaction(transactions, oldState, state) {
145 if (!state.selection.empty || oldState.selection.from === state.selection.from) return null;
146 if (transactions.some((tr) => tr.docChanged)) return null;
147 const pair = codePairKey.getState(state)?.find(({ to }) => to === state.selection.from);
148 if (!pair) return null;
149 const $start = state.doc.resolve(pair.from);
150 const $end = state.selection.$from;
151 if (!$start.sameParent($end) || $start.parent.type.spec.code) return null;
152 if (
153 $start.nodeBefore?.text?.endsWith("`") ||
154 $end.nodeAfter?.text?.startsWith("`") ||
155 !/^`[^`]+`$/.test(state.doc.textBetween(pair.from, pair.to))
156 ) {
157 return null;
158 }
159 let plain = true;
160 state.doc.nodesBetween(pair.from, pair.to, (node) => {
161 if (node.isInline && (!node.isText || node.marks.length > 0)) plain = false;
162 });
163 if (!plain) return null;
164 const tr = state.tr.delete(pair.to - 1, pair.to).delete(pair.from, pair.from + 1);
165 tr.addMark(pair.from, pair.to - 2, type.create());
166 tr.setSelection(TextSelection.create(tr.doc, pair.to - 2));
167 tr.removeStoredMark(type);
168 return tr;
169 },
170 });
171 }
172
173 /**
174 * Whether a backtick typed at `$pos` would complete an empty `` pair. The
175 * backtick before `$pos` only opens one when earlier backticks are all paired.
176 */
177 function closesBacktickPair($pos: ResolvedPos): boolean {
178 return (
179 $pos.parent.isTextblock &&
180 !$pos.parent.type.spec.code &&
181 /(^|[^`])`$/.test($pos.nodeBefore?.text ?? "") &&
182 literalBackticksBefore($pos) % 2 === 1
183 );
184 }
185
186 /**
187 * Layouts where backtick is a dead key type it through composition, and the
188 * pair handler above skips composing input. Read the pair
189 * from the composed insert instead; dispatching mid-composition would break it.
190 */
191 function composedCodePair(tr: Transaction): CodePair | undefined {
192 if (tr.getMeta("composition") === undefined || tr.steps.length !== 1) {
193 return undefined;
194 }
195
196 const step = tr.steps[0];
197 if (!(step instanceof ReplaceStep) || step.from !== step.to || step.slice.size !== 1) {
198 return undefined;
199 }
200
201 if (step.slice.content.firstChild?.text !== "`") {
202 return undefined;
203 }
204
205 if (!closesBacktickPair(tr.before.resolve(step.from))) {
206 return undefined;
207 }
208
209 return { from: step.from - 1, to: step.from + 1 };
210 }
211
212 /**
213 * Tiptap's code mark excludes every other mark, which rejects the `bold+code`
214 * spans markdown like `**\`x\`**` parses into and drops the whole insert.
215 */
216 export const ComposerCodeExtension = Code.extend({
217 excludes: "code",
218 // The forward arrow leaves code through the caret stops at styled edges, so
219 // the stock exit (inserting a space at the end of a line) is not needed.
220 exitable: false,
221 // Code reads left to right inside an Arabic or Hebrew line, and the isolate
222 // keeps its punctuation from trading places with the text around it.
223 addOptions() {
224 return { ...this.parent!(), HTMLAttributes: { dir: "ltr" } };
225 },
226 addProseMirrorPlugins() {
227 return [...(this.parent?.() ?? []), codePairCaretPlugin(this.type)];
228 },
229 // Tiptap's rule reads back from the caret, so after a literal `enabled` the
230 // next typed backtick would reuse its closing backtick and wrap ` and ` in
231 // code. Backticks pair left to right, so skip an opener that closes a pair.
232 addInputRules() {
233 return (this.parent?.() ?? []).map(
234 (rule) =>
235 new InputRule({
236 find: rule.find,
237 undoable: rule.undoable,
238 handler: (props) => {
239 if (
240 literalBackticksBefore(props.state.doc.resolve(props.range.from)) % 2 === 1 ||
241 touchesMarkdownSource(props.state, props.range.from, props.range.to)
242 ) {
243 return null;
244 }
245
246 return rule.handler(props);
247 },
248 }),
249 );
250 },
251 });
252
253 /** Counts backticks typed as plain text before `$pos` in its textblock; code text never pairs. */
254 function literalBackticksBefore($pos: ResolvedPos): number {
255 let count = 0;
256 $pos.parent.forEach((node, offset) => {
257 if (offset >= $pos.parentOffset) return;
258 if (!node.isText) {
259 count = 0;
260 return;
261 }
262 if (node.marks.some((mark) => mark.type.spec.code)) return;
263
264 const text = node.text!.slice(0, $pos.parentOffset - offset);
265 count += [...text.matchAll(/(?<!`)`(?!`)/g)].length;
266 });
267 return count;
268 }
269
270 /**
271 * Whether `from`-`to`, or the caret at `from`, is in shown Markdown source.
272 * Typed delimiters there stay text until the caret leaves and the source is parsed.
273 */
274 function touchesMarkdownSource(state: EditorState, from: number, to: number): boolean {
275 const type = state.schema.marks[MARKDOWN_SOURCE_MARK];
276 if (!type) return false;
277 if (from < to) return state.doc.rangeHasMark(from, to, type);
278 const $pos = state.doc.resolve(from);
279 return [$pos.nodeBefore, $pos.nodeAfter].some((node) => node && type.isInSet(node.marks));
280 }
281
282 // Code permits nested emphasis, so Tiptap's exclusion check cannot protect literal delimiters.
283 function markInputRuleOutsideCode(find: RegExp, type: MarkType) {
284 const rule = markInputRule({ find, type });
285 return new InputRule({
286 find,
287 handler: (props) => {
288 const { state, range, match } = props;
289 const code = state.schema.marks.code;
290 const content = match[match.length - 1] ?? "";
291 const textStart = range.from + match[0].indexOf(content);
292 const textEnd = textStart + content.length;
293 if (touchesMarkdownSource(state, range.from, range.to)) return null;
294 if (
295 code &&
296 (state.doc.rangeHasMark(range.from + match[0].search(/\S/), textStart, code) ||
297 state.doc.rangeHasMark(textEnd, state.selection.from, code))
298 ) {
299 return null;
300 }
301 return rule.handler(props);
302 },
303 });
304 }
305
306 const SURROUND_MARKS: Record<string, string> = { "`": "code", "*": "italic", _: "italic" };
307
308 export function surroundSelectionWithMark(
309 state: EditorState,
310 from: number,
311 to: number,
312 marker: string,
313 ) {
314 const markType = state.schema.marks[SURROUND_MARKS[marker] ?? ""];
315 if (!markType || touchesMarkdownSource(state, from, to)) return null;
316 const $from = state.doc.resolve(from);
317 if (!$from.sameParent(state.doc.resolve(to)) || !$from.parent.type.allowsMarkType(markType)) {
318 return null;
319 }
320 // Inline markdown cannot span lines, so keep literal wrapping across hard breaks.
321 let crossesLine = false;
322 state.doc.nodesBetween(from, to, (node) => {
323 if (node.type.name === "hardBreak") crossesLine = true;
324 return !crossesLine;
325 });
326 if (crossesLine) return null;
327 const tr = state.tr.addMark(from, to, markType.create());
328 // Nearby delimiters can change how the saved span parses. Atoms are opaque
329 // to inline markdown, so use a placeholder instead of parsing their sources.
330 const children: ProseMirrorNode[] = [];
331 tr.doc.resolve(from).parent.forEach((node) => {
332 children.push(
333 node.isAtom && !node.isText && node.type.name !== "hardBreak"
334 ? state.schema.text("\uFFFC", node.marks)
335 : node,
336 );
337 });
338 const paragraph = state.schema.nodes.paragraph!.create(null, children);
339 const markdown = serializeEditorDoc(state.doc.type.create(null, paragraph)).value;
340 const rebuilt = buildTiptapContent(markdown, () => null, { blocks: false });
341 const restored = state.schema.nodeFromJSON({ type: "doc", content: rebuilt });
342 return paragraph.content.eq(restored.firstChild!.content) ? tr : null;
343 }
344
345 /**
346 * The composer writes italic as `*text*`, so it keeps only the `*` shortcuts.
347 * Tiptap's `_text_` rules fire on the `_` in names like `node_modules` and
348 * italicize back to an earlier `_build`, even one inside a code span.
349 */
350 export const ComposerItalicExtension = Italic.extend({
351 addInputRules() {
352 return [markInputRuleOutsideCode(starInputRegex, this.type)];
353 },
354 addPasteRules() {
355 return [markPasteRule({ find: starPasteRegex, type: this.type })];
356 },
357 });
358
359 export const ComposerBoldExtension = Bold.extend({
360 addInputRules() {
361 return [
362 markInputRuleOutsideCode(boldStarInputRegex, this.type),
363 markInputRuleOutsideCode(boldUnderscoreInputRegex, this.type),
364 ];
365 },
366 });
367
368 export const ComposerStrikeExtension = Strike.extend({
369 addInputRules() {
370 return [markInputRuleOutsideCode(strikeInputRegex, this.type)];
371 },
372 });
373
374 /**
375 * Tiptap's block chords can nest blocks inside quotes that the serializer cannot write,
376 * silently dropping their text from stored drafts.
377 */
378 function withoutBlockChords<Shortcuts extends Record<string, unknown>>(
379 shortcuts: Shortcuts | undefined,
380 drop: readonly string[],
381 ): Shortcuts {
382 return Object.fromEntries(
383 Object.entries(shortcuts ?? {}).filter(([key]) => !drop.includes(key)),
384 ) as Shortcuts;
385 }
386
387 // Markdown supports one paragraph followed by nested lists per item.
388 const LIST_ITEM_CONTENT = "paragraph list*";
389
390 /** Task lists come from `- [ ]` alone; Mod-Shift-9 would nest one in a quote. */
391 export const ComposerTaskListExtension = TaskList.extend({
392 addKeyboardShortcuts() {
393 return withoutBlockChords(this.parent?.(), ["Mod-Shift-9"]);
394 },
395 });
396
397 /** Tiptap's nesting shortcuts leave indent unchanged, so rebuilding the draft undoes them. */
398 const LIST_NESTING_KEYS = ["Tab", "Shift-Tab"];
399
400 export const ComposerTaskItemExtension = TaskItem.extend({
401 content: LIST_ITEM_CONTENT,
402 addAttributes() {
403 return {
404 ...this.parent?.(),
405 indent: { default: "" },
406 markerSpace: { default: " " },
407 contentSpace: { default: null },
408 };
409 },
410 addKeyboardShortcuts() {
411 return withoutBlockChords(this.parent?.(), LIST_NESTING_KEYS);
412 },
413 }).configure({ nested: true });
414
415 export const ComposerCodeBlockExtension = CodeBlock.extend({
416 addAttributes() {
417 return {
418 ...this.parent?.(),
419 language: { default: "" },
420 fence: { default: "```" },
421 close: { default: "\n```" },
422 };
423 },
424 addKeyboardShortcuts() {
425 return {
426 ...withoutBlockChords(this.parent?.(), ["Mod-Alt-c"]),
427 Backspace: () => unwrapCodeBlockAtStart(this.editor),
428 };
429 },
430 });
431
432 // Joining with the previous line would lose the fence and leave stray code lines.
433 function unwrapCodeBlockAtStart(editor: Editor): boolean {
434 const { $from, empty } = editor.state.selection;
435 if (!empty || $from.parent.type.name !== "codeBlock" || $from.parentOffset !== 0) return false;
436 const { schema } = editor.state;
437 const paragraphs = $from.parent.textContent
438 .split("\n")
439 .map((line) => schema.nodes.paragraph!.create(null, line ? schema.text(line) : null));
440 const start = $from.before();
441 const tr = editor.state.tr.replaceWith(start, $from.after(), paragraphs);
442 editor.view.dispatch(tr.setSelection(TextSelection.create(tr.doc, start + 1)));
443 return true;
444 }
445
446 function codeBlockSource(
447 node: ProseMirrorNode,
448 followed: boolean,
449 ): {
450 open: string;
451 content: string;
452 close: string;
453 } {
454 const attrs = node.attrs as Record<string, unknown>;
455 let fence = typeof attrs.fence === "string" && attrs.fence ? attrs.fence : "```";
456 const language = typeof attrs.language === "string" ? attrs.language : "";
457 let close = typeof attrs.close === "string" ? attrs.close : "";
458 const content = node.textContent;
459 // Use a longer fence when code contains a closing fence.
460 const longest = Math.max(
461 0,
462 ...content
463 .split("\n")
464 .filter((line) => isClosingFence(line, fence))
465 .map((line) => /^[`~]+/.exec(line)![0].length),
466 );
467 if (longest > 0) {
468 fence = fence[0]!.repeat(longest + 1);
469 if (close) close = `\n${fence}`;
470 }
471 // Close before a following block so rebuilding does not absorb it as code.
472 if (!close && followed) close = `\n${fence}`;
473 return { open: `${fence}${language}${content ? "\n" : ""}`, content, close };
474 }
475
476 const ComposerListItemExtension = ListItem.extend({
477 content: LIST_ITEM_CONTENT,
478 addAttributes() {
479 return {
480 ...this.parent?.(),
481 indent: { default: "" },
482 marker: { default: "-" },
483 space: { default: " " },
484 };
485 },
486 addKeyboardShortcuts() {
487 return {
488 ...withoutBlockChords(this.parent?.(), LIST_NESTING_KEYS),
489 // Replacing Tiptap's Backspace drops its undoInputRule, which keeps a just-typed "+ " literal.
490 Backspace: () => this.editor.commands.undoInputRule() || backspaceAcrossList(this.editor),
491 Delete: () => deleteAcrossList(this.editor),
492 };
493 },
494 // ProseMirror can reuse the parent list when only an item's marker changes.
495 // Item metadata lets CSS resize its gutter through CommonMark's nine-digit limit.
496 renderHTML({ node, HTMLAttributes }) {
497 const marker = String(node.attrs.marker);
498 return [
499 "li",
500 mergeAttributes(HTMLAttributes, {
501 "data-marker": marker,
502 "data-marker-width": Math.min(marker.length, 10),
503 }),
504 0,
505 ];
506 },
507 });
508
509 export const ComposerListExtensions = [
510 BulletList.extend({
511 addProseMirrorPlugins() {
512 return [
513 ...(this.parent?.() ?? []),
514 listNormalizationPlugin(() => this.editor.view.composing),
515 ];
516 },
517 addKeyboardShortcuts() {
518 return withoutBlockChords(this.parent?.(), ["Mod-Shift-8"]);
519 },
520 }),
521 OrderedList.extend({
522 addKeyboardShortcuts() {
523 return withoutBlockChords(this.parent?.(), ["Mod-Shift-7"]);
524 },
525 }),
526 ComposerListItemExtension,
527 ];
528
529 const ComposerBlockquoteExtension = Blockquote.extend({
530 content: "paragraph+",
531 addAttributes() {
532 return { ...this.parent?.(), prefix: { default: "> " } };
533 },
534 addKeyboardShortcuts() {
535 return withoutBlockChords(this.parent?.(), ["Mod-Shift-b"]);
536 },
537 });
538
539 const ComposerHorizontalRuleExtension = HorizontalRule.extend({
540 addAttributes() {
541 return { ...this.parent?.(), source: { default: "---" } };
542 },
543 addProseMirrorPlugins() {
544 return [
545 ...(this.parent?.() ?? []),
546 new Plugin({
547 appendTransaction: (transactions, _, state) => {
548 if (!transactions.some((tr) => tr.docChanged)) return null;
549 if (state.doc.lastChild?.type.name !== "horizontalRule") return null;
550 return state.tr.insert(state.doc.content.size, state.schema.nodes.paragraph!.create());
551 },
552 }),
553 ];
554 },
555 });
556
557 function isTrailingLineAfterRule(doc: ProseMirrorNode, index: number): boolean {
558 const block = doc.child(index);
559 return (
560 index === doc.childCount - 1 &&
561 index > 0 &&
562 block.type.name === "paragraph" &&
563 block.content.size === 0 &&
564 doc.child(index - 1).type.name === "horizontalRule"
565 );
566 }
567
568 const ComposerHeadingExtension = Heading.extend({
569 addAttributes() {
570 return { ...this.parent?.(), space: { default: " " } };
571 },
572 addKeyboardShortcuts() {
573 return {};
574 },
575 });
576
577 export const ComposerBlockExtensions = [
578 ComposerBlockquoteExtension,
579 ComposerHorizontalRuleExtension,
580 ComposerHeadingExtension,
581 ];
582
583 function randomNodeKey(): string {
584 return `tiptap-${Math.random().toString(36).slice(2)}`;
585 }
586
587 interface TaskLinePrefix {
588 indent: string;
589 checked: boolean;
590 markerSpace: string;
591 contentSpace: string;
592 }
593
594 function parseTaskPrefix(head: string): { prefix: TaskLinePrefix; markerLength: number } | null {
595 const match = head.match(/^([ \t]*)-([ \t]+)\[([ xX])\]([ \t]*)/);
596 if (!match) return null;
597 const after = head.slice(match[0].length);
598 if (after.length > 0 && !match[4]) return null;
599 return {
600 prefix: {
601 indent: match[1] ?? "",
602 checked: (match[3] ?? " ").toLowerCase() === "x",
603 markerSpace: match[2]!,
604 contentSpace: match[4]!,
605 },
606 markerLength: match[0].length,
607 };
608 }
609
610 export function parseOpeningFence(line: string): { fence: string; language: string } | null {
611 // Unlike `.`, `[^\n]` accepts the stored \r in CRLF lines.
612 const match = /^(`{3,}|~{3,})([^\n]*)$/.exec(line);
613 if (!match) return null;
614 const fence = match[1]!;
615 const language = match[2]!;
616 if (fence.startsWith("`") && language.includes("`")) return null;
617 return { fence, language };
618 }
619
620 export function isClosingFence(line: string, fence: string): boolean {
621 const match = /^(`{3,}|~{3,})[ \t]*\r?$/.exec(line);
622 if (!match) return false;
623 const run = match[1]!;
624 return run[0] === fence[0] && run.length >= fence.length;
625 }
626
627 type ListLinePrefix =
628 | ({ kind: "task" } & TaskLinePrefix)
629 | { kind: "bullet" | "ordered"; indent: string; marker: string; space: string };
630
631 function parseListPrefix(line: string): { prefix: ListLinePrefix; markerLength: number } | null {
632 const task = parseTaskPrefix(line);
633 if (task) return { prefix: { kind: "task", ...task.prefix }, markerLength: task.markerLength };
634 const ordered = /^([ \t]*)(\d+[.)])((?:[ \t]+)|$)/.exec(line);
635 if (ordered) {
636 return {
637 prefix: { kind: "ordered", indent: ordered[1]!, marker: ordered[2]!, space: ordered[3]! },
638 markerLength: ordered[0].length,
639 };
640 }
641 const bullet = /^([ \t]*)([-*+])((?:[ \t]+)|$)/.exec(line);
642 if (bullet) {
643 return {
644 prefix: { kind: "bullet", indent: bullet[1]!, marker: bullet[2]!, space: bullet[3]! },
645 markerLength: bullet[0].length,
646 };
647 }
648 return null;
649 }
650
651 /** Only changed top-level paragraphs can acquire a literal list prefix outside an input rule. */
652 function listNormalizationPlugin(isComposing: () => boolean) {
653 let pending = new Set<number>();
654 const key = new PluginKey("composerListNormalization");
655 return new Plugin({
656 key,
657 props: {
658 handleDOMEvents: {
659 // ProseMirror tags the DOM flush after compositionend as composition, so nothing else would normalize.
660 compositionend(view) {
661 setTimeout(() => {
662 if (!view.isDestroyed && !view.composing && pending.size > 0) {
663 view.dispatch(view.state.tr);
664 }
665 });
666 return false;
667 },
668 },
669 },
670 appendTransaction(transactions, oldState, state) {
671 // Tiptap's undoInputRule (Backspace right after a rule) restores the typed text on purpose.
672 const undoesInputRule = oldState.plugins.some(
673 (plugin) => plugin.spec.isInputRules && plugin.getState(oldState),
674 );
675 if (undoesInputRule || transactions.some(isHistoryTransaction)) {
676 pending.clear();
677 return null;
678 }
679 if (pending.size === 0 && !transactions.some((tr) => tr.docChanged)) return null;
680 const changes = combineTransactionSteps(oldState.doc, [...transactions]);
681 pending = new Set(
682 [...pending].flatMap((pos) => {
683 const mapped = changes.mapping.mapResult(pos, 1);
684 return mapped.deleted ? [] : [mapped.pos];
685 }),
686 );
687 for (const { newRange } of getChangedRanges(changes)) {
688 state.doc.nodesBetween(newRange.from, newRange.to, (node, pos) => {
689 if (node.type.name !== "paragraph") return false;
690 const parsed = parseListPrefix(paragraphText(node));
691 // Typing after a marker left literal keeps it literal; only an edit reaching the marker converts.
692 if (parsed && newRange.from <= pos + 1 + parsed.markerLength) pending.add(pos);
693 return false;
694 });
695 }
696 // The next non-composition transaction can normalize after the browser finishes its DOM edits.
697 if (isComposing() || transactions.some((tr) => tr.getMeta("composition") != null))
698 return null;
699
700 const tr = state.tr;
701 for (const pos of [...pending].sort((a, b) => b - a)) {
702 pending.delete(pos);
703 if (state.doc.resolve(pos).depth !== 0) continue;
704 const node = state.doc.nodeAt(pos);
705 if (node?.type.name !== "paragraph") continue;
706 const text = paragraphText(node);
707 const parsed = parseListPrefix(text);
708 // Input rules only introduce unindented top-level lists; keep the same boundary here.
709 if (!parsed || parsed.prefix.indent) continue;
710 const { prefix, markerLength } = parsed;
711 if (
712 Object.values(state.schema.marks).some((mark) => node.rangeHasMark(0, markerLength, mark))
713 )
714 continue;
715 const active = state.selection.$from.depth === 1 && state.selection.$from.before(1) === pos;
716 const content = text.slice(markerLength);
717 // Keep `- ` and unfinished task markers literal while the user is entering the gesture.
718 if (
719 active &&
720 (prefix.kind === "task"
721 ? !prefix.contentSpace
722 : prefix.kind === "bullet" &&
723 prefix.marker === "-" &&
724 (!content || /^\[(?:[ xX]\]?)?$/.test(content)))
725 ) {
726 pending.add(pos);
727 continue;
728 }
729 if (prefix.kind !== "task" && !prefix.space) continue;
730 const listType =
731 state.schema.nodes[
732 prefix.kind === "task"
733 ? "taskList"
734 : prefix.kind === "ordered"
735 ? "orderedList"
736 : "bulletList"
737 ];
738 if (!listType) continue;
739 const attrs =
740 prefix.kind === "ordered" ? { start: Number.parseInt(prefix.marker, 10) || 1 } : {};
741 const $from = tr.doc.resolve(pos + 1);
742 const range = $from.blockRange();
743 const wrapping = range && findWrapping(range, listType, attrs);
744 if (!range || !wrapping) continue;
745 tr.wrap(range, wrapping);
746 tr.setNodeMarkup(
747 pos + 1,
748 undefined,
749 prefix.kind === "task"
750 ? {
751 checked: prefix.checked,
752 indent: prefix.indent,
753 markerSpace: prefix.markerSpace,
754 contentSpace: prefix.contentSpace,
755 }
756 : { indent: prefix.indent, marker: prefix.marker, space: prefix.space },
757 );
758 tr.delete(pos + 3, pos + 3 + markerLength);
759 joinCompatibleLists(tr, pos + tr.doc.nodeAt(pos)!.nodeSize);
760 joinCompatibleLists(tr, pos);
761 }
762 pending = new Set([...pending].map((pos) => tr.mapping.map(pos, 1)));
763 return tr.docChanged ? tr : null;
764 },
765 });
766 }
767
768 function paragraphText(node: ProseMirrorNode): string {
769 return node.textBetween(0, node.content.size, undefined, "\ufffc");
770 }
771
772 /** Rebuilding from Markdown merges adjacent lists of one type whose markers share a delimiter. */
773 function joinCompatibleLists(tr: Transaction, pos: number): void {
774 const $pos = tr.doc.resolve(pos);
775 const before = $pos.nodeBefore;
776 const after = $pos.nodeAfter;
777 const delimiter = (list: ProseMirrorNode) =>
778 String(list.firstChild?.attrs.marker ?? "").slice(-1);
779 if (
780 before &&
781 after &&
782 before.type === after.type &&
783 delimiter(before) === delimiter(after) &&
784 canJoin(tr.doc, pos)
785 ) {
786 tr.join(pos);
787 }
788 }
789
790 function listKey(prefix: ListLinePrefix): string {
791 if (prefix.kind === "task") return "task";
792 if (prefix.kind === "ordered") return `ordered:${prefix.marker.slice(-1)}`;
793 return `bullet:${prefix.marker}`;
794 }
795
796 type InlineJson = Record<string, unknown>;
797 type AtomJson = { type: string; attrs: Record<string, unknown> };
798
799 interface DocLine {
800 list: ListLinePrefix | null;
801 inline: InlineJson[];
802 }
803
804 /** Null for a `$name` or `model:` reference the resolver does not know: it stays editable text. */
805 function atomJsonForSegment(
806 segment: Exclude<ReturnType<typeof splitPromptIntoComposerSegments>[number], { type: "text" }>,
807 chips: ChipResolver,
808 ): AtomJson | null {
809 if (segment.type === "mention") {
810 return {
811 type: "composer-mention",
812 attrs: { path: segment.path, source: segment.source },
813 };
814 }
815 if (segment.type === "skill") {
816 const meta = chips.skill(segment.name);
817 if (!meta) return null;
818 return {
819 type: "composer-skill",
820 attrs: {
821 skillName: segment.name,
822 skillLabel: meta.label,
823 skillDescription: meta.description,
824 },
825 };
826 }
827 if (segment.type === "model") {
828 if (!chips.model(segment.instanceId, segment.model)) return null;
829 return {
830 type: "composer-model",
831 attrs: { instanceId: segment.instanceId, model: segment.model, source: segment.source },
832 };
833 }
834 if (segment.type === "citation") {
835 return {
836 type: "composer-citation",
837 attrs: { citation: segment.citation, source: segment.source, citeKey: randomNodeKey() },
838 };
839 }
840 return {
841 type: "composer-context-reference",
842 attrs: {
843 kind: segment.kind,
844 contextId: segment.contextId,
845 label: segment.label,
846 source: segment.source,
847 },
848 };
849 }
850
851 interface PendingItem {
852 prefix: ListLinePrefix;
853 content: InlineJson[];
854 children: PendingList[];
855 }
856
857 interface PendingList {
858 key: string;
859 items: PendingItem[];
860 }
861
862 function listJson(list: PendingList): InlineJson {
863 const first = list.items[0]!.prefix;
864 const items = list.items.map((item) => {
865 const content = [
866 { type: "paragraph", content: item.content },
867 ...item.children.map((child) => listJson(child)),
868 ];
869 if (item.prefix.kind === "task") {
870 return {
871 type: "taskItem",
872 attrs: {
873 checked: item.prefix.checked,
874 indent: item.prefix.indent,
875 markerSpace: item.prefix.markerSpace,
876 contentSpace: item.prefix.contentSpace,
877 },
878 content,
879 };
880 }
881 return {
882 type: "listItem",
883 attrs: { indent: item.prefix.indent, marker: item.prefix.marker, space: item.prefix.space },
884 content,
885 };
886 });
887 if (first.kind === "task") return { type: "taskList", content: items };
888 if (first.kind === "ordered") {
889 return {
890 type: "orderedList",
891 attrs: { start: Number.parseInt(first.marker, 10) || 1 },
892 content: items,
893 };
894 }
895 return { type: "bulletList", content: items };
896 }
897
898 function textJsonForSpan(text: string, marks: RichTextMark[]): Record<string, unknown> {
899 const json: Record<string, unknown> = { type: "text", text };
900 if (marks.length > 0) {
901 json.marks = [...marks]
902 .sort((a, b) => MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b))
903 .map((mark) => ({ type: MARK_TO_TIPTAP[mark] }));
904 }
905 return json;
906 }
907
908 /** Keeps literalLength leading characters unstyled so path queries reach file search unchanged. */
909 export function buildTiptapContent(
910 value: string,
911 skillLabelFor: (name: string) => SkillMeta | null,
912 options?: {
913 styling?: boolean;
914 blocks?: boolean;
915 literalText?: boolean;
916 literalLength?: number;
917 isKnownModel?: IsKnownModel;
918 },
919 ): Record<string, unknown>[] {
920 const chips = { skill: skillLabelFor, model: options?.isKnownModel ?? NO_MODELS };
921 if (options?.literalText) {
922 return value.split("\n").map((line) => ({
923 type: "paragraph",
924 ...(line ? { content: [{ type: "text", text: line }] } : {}),
925 }));
926 }
927 const styling = options?.styling ?? true;
928 const blockSyntax = styling && (options?.blocks ?? true);
929 let sentinel = "\uFFFC";
930 for (let codePoint = 0xe000; value.includes(sentinel); codePoint += 1) {
931 sentinel = String.fromCodePoint(codePoint);
932 }
933 const atoms: InlineJson[] = [];
934 const atomSources: string[] = [];
935 const literal = value.slice(0, options?.literalLength ?? 0);
936 const remainder = value.slice(literal.length);
937 const formulas = composerMathRanges(remainder);
938 let offset = 0;
939 const chunks: Array<{ text: string } | { source: string }> = [];
940 for (const formula of formulas) {
941 chunks.push({ text: remainder.slice(offset, formula.start) }, { source: formula.source });
942 offset = formula.end;
943 }
944 chunks.push({ text: remainder.slice(offset) });
945 // Math stays editable source. Shield its commands and Markdown-like markers
946 // from styling and context-chip parsing, then restore ordinary text nodes.
947 const text = chunks
948 .map((chunk) => {
949 if ("source" in chunk) {
950 atoms.push(textJsonForSpan(chunk.source, []));
951 atomSources.push(chunk.source);
952 return sentinel;
953 }
954 return splitPromptIntoComposerSegments(chunk.text)
955 .map((segment) => {
956 if (segment.type === "text") return segment.text;
957 const atom = atomJsonForSegment(segment, chips);
958 if (!atom) return segment.source;
959 atoms.push(atom);
960 atomSources.push(segment.source);
961 return sentinel;
962 })
963 .join("");
964 })
965 .join("");
966 let atomIndex = 0;
967 const buildInline = (content: string): InlineJson[] => {
968 const spans = styling ? parseInlineMarkdown(content) : [{ text: content, marks: [] }];
969 const inline: InlineJson[] = [];
970 for (const span of spans) {
971 span.text.split(sentinel).forEach((piece, index) => {
972 if (index > 0) {
973 const atom = atoms[atomIndex++]!;
974 inline.push({ ...atom, marks: textJsonForSpan("", span.marks).marks });
975 }
976 if (piece) inline.push(textJsonForSpan(piece, span.marks));
977 });
978 }
979 return inline;
980 };
981 const buildDocLine = (line: string): DocLine => {
982 const parsed = blockSyntax ? parseListPrefix(line) : null;
983 const content = parsed ? line.slice(parsed.markerLength) : line;
984 return { list: parsed?.prefix ?? null, inline: buildInline(content) };
985 };
986
987 const sourceLines = text.split("\n");
988 const entries: (
989 | { code: Record<string, unknown> }
990 | { rule: string }
991 | { heading: { level: number; space: string; inline: InlineJson[] } }
992 | { quote: { prefix: string; inline: InlineJson[] } }
993 | { line: DocLine }
994 )[] = [];
995 const restoreSources = (line: string) =>
996 line.split(sentinel).reduce((joined, piece, index) => {
997 if (index === 0) return piece;
998 atomIndex += 1;
999 return joined + atomSources[atomIndex - 1]! + piece;
1000 }, "");
1001
1002 for (let index = 0; index < sourceLines.length; index += 1) {
1003 const line = sourceLines[index]!;
1004 if (index === 0 && literal) {
1005 entries.push({
1006 line: { list: null, inline: [textJsonForSpan(literal, []), ...buildInline(line)] },
1007 });
1008 continue;
1009 }
1010 const opening = blockSyntax ? parseOpeningFence(line) : null;
1011 if (!opening) {
1012 if (blockSyntax && /^([-*_])(?:[ \t]*\1){2,}[ \t]*\r?$/.test(line)) {
1013 entries.push({ rule: line });
1014 continue;
1015 }
1016 const heading = blockSyntax ? /^(#{1,6})([ \t]+)([^\n]*)$/.exec(line) : null;
1017 if (heading) {
1018 entries.push({
1019 heading: {
1020 level: heading[1]!.length,
1021 space: heading[2]!,
1022 inline: buildInline(heading[3]!),
1023 },
1024 });
1025 continue;
1026 }
1027 const quote = blockSyntax ? /^(>[ \t]*)([^\n]*)$/.exec(line) : null;
1028 if (quote) entries.push({ quote: { prefix: quote[1]!, inline: buildInline(quote[2]!) } });
1029 else entries.push({ line: buildDocLine(line) });
1030 continue;
1031 }
1032 const language = restoreSources(opening.language);
1033 const body: string[] = [];
1034 let cursor = index + 1;
1035 let close = "";
1036 while (cursor < sourceLines.length) {
1037 const candidate = sourceLines[cursor]!;
1038 if (isClosingFence(candidate, opening.fence)) {
1039 close = `\n${candidate}`;
1040 break;
1041 }
1042 body.push(restoreSources(candidate));
1043 cursor += 1;
1044 }
1045 const closed = cursor < sourceLines.length;
1046 const content = body.join("\n");
1047 entries.push({
1048 code: {
1049 type: "codeBlock",
1050 attrs: { language, fence: opening.fence, close },
1051 ...(content ? { content: [{ type: "text", text: content }] } : {}),
1052 },
1053 });
1054 index = closed ? cursor : sourceLines.length;
1055 }
1056
1057 const blocks: Record<string, unknown>[] = [];
1058 let rootLists: PendingList[] = [];
1059 let stack: { indent: string; list: PendingList; container: PendingList[] }[] = [];
1060 const flushLists = () => {
1061 for (const list of rootLists) blocks.push(listJson(list));
1062 rootLists = [];
1063 stack = [];
1064 };
1065 const openList = (container: PendingList[], key: string): PendingList => {
1066 const list = { key, items: [] };
1067 container.push(list);
1068 return list;
1069 };
1070 let openQuote: { prefix: string; content: InlineJson[][] } | null = null;
1071 const flushQuote = () => {
1072 if (!openQuote) return;
1073 blocks.push({
1074 type: "blockquote",
1075 attrs: { prefix: openQuote.prefix },
1076 content: openQuote.content.map((inline) => ({ type: "paragraph", content: inline })),
1077 });
1078 openQuote = null;
1079 };
1080 const isProseLine = (entry: (typeof entries)[number] | undefined, empty: boolean) =>
1081 entry !== undefined &&
1082 "line" in entry &&
1083 !entry.line.list &&
1084 (entry.line.inline.length === 0) === empty;
1085 for (const [entryIndex, entry] of entries.entries()) {
1086 if ("quote" in entry) {
1087 flushLists();
1088 if (openQuote && openQuote.prefix !== entry.quote.prefix) flushQuote();
1089 openQuote ??= { prefix: entry.quote.prefix, content: [] };
1090 openQuote.content.push(entry.quote.inline);
1091 continue;
1092 }
1093 // The serializer separates a quote or list from the prose after it with one blank line; it is not an empty paragraph.
1094 // After a list it precedes any empty paragraphs the user left, so those survive.
1095 let proseIndex = entryIndex + 1;
1096 if (openQuote === null && rootLists.length > 0 && isProseLine(entry, true)) {
1097 while (isProseLine(entries[proseIndex], true)) proseIndex += 1;
1098 }
1099 const blockSeparator =
1100 (openQuote !== null || rootLists.length > 0) &&
1101 isProseLine(entry, true) &&
1102 isProseLine(entries[proseIndex], false);
1103 flushQuote();
1104 if (blockSeparator) {
1105 flushLists();
1106 continue;
1107 }
1108 if ("code" in entry) {
1109 flushLists();
1110 blocks.push(entry.code);
1111 continue;
1112 }
1113 if ("rule" in entry) {
1114 flushLists();
1115 blocks.push({ type: "horizontalRule", attrs: { source: entry.rule } });
1116 continue;
1117 }
1118 if ("heading" in entry) {
1119 flushLists();
1120 blocks.push({
1121 type: "heading",
1122 attrs: { level: entry.heading.level, space: entry.heading.space },
1123 content: entry.heading.inline,
1124 });
1125 continue;
1126 }
1127 const line = entry.line;
1128 if (!line.list) {
1129 flushLists();
1130 blocks.push({ type: "paragraph", content: line.inline });
1131 continue;
1132 }
1133 const item: PendingItem = { prefix: line.list, content: line.inline, children: [] };
1134 const key = listKey(line.list);
1135 const indent = line.list.indent;
1136 for (;;) {
1137 const top = stack[stack.length - 1];
1138 if (!top) {
1139 stack.push({ indent, list: openList(rootLists, key), container: rootLists });
1140 continue;
1141 }
1142 if (top.indent === indent) {
1143 if (top.list.key !== key) top.list = openList(top.container, key);
1144 top.list.items.push(item);
1145 break;
1146 }
1147 if (top.indent !== "" && !indent.startsWith(top.indent)) {
1148 if (stack.length > 1) {
1149 stack.pop();
1150 continue;
1151 }
1152 top.indent = indent;
1153 if (top.list.key !== key) top.list = openList(top.container, key);
1154 top.list.items.push(item);
1155 break;
1156 }
1157 const parent = top.list.items[top.list.items.length - 1];
1158 if (!parent) {
1159 top.list.items.push(item);
1160 break;
1161 }
1162 const list = openList(parent.children, key);
1163 stack.push({ indent, list, container: parent.children });
1164 list.items.push(item);
1165 break;
1166 }
1167 }
1168 flushQuote();
1169 flushLists();
1170 return blocks;
1171 }
1172
1173 export function buildDocJson(
1174 value: string,
1175 skillLabelFor: (name: string) => SkillMeta | null,
1176 options?: { styling?: boolean; literalText?: boolean; isKnownModel?: IsKnownModel },
1177 ) {
1178 const content = buildTiptapContent(value, skillLabelFor, options);
1179 if (content.at(-1)?.type === "horizontalRule") content.push({ type: "paragraph" });
1180 return { type: "doc", content };
1181 }
1182
1183 export interface RichRun {
1184 kind: "text" | "token" | "break" | "prefix";
1185 /** Flat document offset (atoms count 1, markers excluded). */
1186 flatStart: number;
1187 docLen: number;
1188 /** Markdown length (tokens expand to their source). */
1189 mdLen: number;
1190 openLen: number;
1191 closeLen: number;
1192 pmPos: number;
1193 mdStart: number;
1194 nodeName?: string;
1195 }
1196
1197 // Shared by every caller that serializes the same doc, so it must not be mutated.
1198 export interface RichDocMap {
1199 readonly value: string;
1200 readonly runs: ReadonlyArray<Readonly<RichRun>>;
1201 readonly docLength: number;
1202 readonly contextIds: ReadonlyArray<string>;
1203 }
1204
1205 function readAtomSource(node: ProseMirrorNode): string {
1206 const attrs = node.attrs as Record<string, unknown>;
1207 switch (node.type.name) {
1208 case "composer-mention":
1209 case "composer-model":
1210 case "composer-citation":
1211 case "composer-context-reference":
1212 return typeof attrs.source === "string" ? attrs.source : "";
1213 case "composer-skill": {
1214 const name = typeof attrs.skillName === "string" ? attrs.skillName : "";
1215 return name ? `$${name}` : "";
1216 }
1217 default:
1218 return "";
1219 }
1220 }
1221
1222 interface RichAccumulator {
1223 runs: RichRun[];
1224 value: string;
1225 flat: number;
1226 md: number;
1227 }
1228
1229 function pushBreakRun(acc: RichAccumulator, position?: number): void {
1230 const previous = acc.runs[acc.runs.length - 1];
1231 const pmPos = position ?? (previous ? previous.pmPos + previous.docLen : 1);
1232 acc.runs.push({
1233 kind: "break",
1234 flatStart: acc.flat,
1235 docLen: 1,
1236 mdLen: 1,
1237 openLen: 0,
1238 closeLen: 0,
1239 pmPos,
1240 mdStart: acc.md,
1241 });
1242 acc.value += "\n";
1243 acc.flat += 1;
1244 acc.md += 1;
1245 }
1246
1247 function horizontalRuleSource(block: ProseMirrorNode): string {
1248 const source = (block.attrs as Record<string, unknown>).source;
1249 return typeof source === "string" && source ? source : "---";
1250 }
1251
1252 // A blank line keeps prose out of a quote or list (lazy continuation) and a dash rule from
1253 // underlining the line above into a setext heading; an empty paragraph already separates them.
1254 function needsBlankLineBetween(blocks: readonly ProseMirrorNode[], index: number): boolean {
1255 const previous = blocks[index - 1]!;
1256 const block = blocks[index]!;
1257 const isEmptyParagraph = (node: ProseMirrorNode | undefined) =>
1258 node?.type.name === "paragraph" && node.content.size === 0;
1259 if (LIST_NODE_NAMES.has(previous.type.name)) {
1260 let next = index;
1261 while (isEmptyParagraph(blocks[next])) next += 1;
1262 return blocks[next]?.type.name === "paragraph";
1263 }
1264 if (previous.type.name === "blockquote") {
1265 return block.type.name === "paragraph" && block.content.size > 0;
1266 }
1267 return (
1268 block.type.name === "horizontalRule" &&
1269 previous.type.name === "paragraph" &&
1270 previous.content.size > 0 &&
1271 /^-+[ \t]*\r?$/.test(horizontalRuleSource(block))
1272 );
1273 }
1274
1275 // Blank-line runs own no document characters; offsets clamp to the start of the next block.
1276 function pushBlankLineRun(acc: RichAccumulator, pmPos: number): void {
1277 acc.runs.push({
1278 kind: "prefix",
1279 flatStart: acc.flat,
1280 docLen: 0,
1281 mdLen: 1,
1282 openLen: 0,
1283 closeLen: 0,
1284 pmPos,
1285 mdStart: acc.md,
1286 });
1287 acc.value += "\n";
1288 acc.md += 1;
1289 }
1290
1291 // Moves an offset into a parsed `value` past the blank lines its serialization inserted,
1292 // treating other differences (`__` written as `**`) as same-length rewrites. When the two
1293 // strings do not align that way end to end, the offset is returned unmapped.
1294 export function serializedMarkdownOffset(
1295 value: string,
1296 serialized: string,
1297 offset: number,
1298 ): number {
1299 if (value === serialized) return offset;
1300 let index = 0;
1301 let mapped = 0;
1302 let target = -1;
1303 while (index < value.length && mapped < serialized.length) {
1304 if (index === offset && target < 0) target = mapped;
1305 if (value[index] === serialized[mapped] || serialized[mapped] !== "\n") index += 1;
1306 mapped += 1;
1307 }
1308 if (index !== value.length || mapped !== serialized.length) return offset;
1309 return target < 0 ? mapped + (offset - index) : target;
1310 }
1311
1312 function appendInlineRuns(
1313 container: ProseMirrorNode,
1314 contentStart: number,
1315 acc: RichAccumulator,
1316 ): void {
1317 const children: ProseMirrorNode[] = [];
1318 container.forEach((child) => {
1319 if (!child.isText || child.marks.some((mark) => mark.type.name === "code")) {
1320 children.push(child);
1321 return;
1322 }
1323 const text = child.text!;
1324 const start = text.length - text.trimStart().length;
1325 const end = Math.max(start, text.trimEnd().length);
1326 let offset = 0;
1327 for (const boundary of [start, end, text.length]) {
1328 if (boundary > offset) children.push(child.cut(offset, boundary));
1329 offset = boundary;
1330 }
1331 });
1332 for (const mark of MARK_NESTING_ORDER) {
1333 if (mark === "code") continue;
1334 for (const direction of [1, -1]) {
1335 let hasContent = false;
1336 for (
1337 let index = direction === 1 ? 0 : children.length - 1;
1338 index >= 0 && index < children.length;
1339 index += direction
1340 ) {
1341 const child = children[index]!;
1342 if (
1343 child.type.name === "hardBreak" ||
1344 !child.marks.some((item) => item.type.name === mark)
1345 ) {
1346 hasContent = false;
1347 } else if (
1348 child.isText &&
1349 !child.marks.some((item) => item.type.name === "code") &&
1350 /^\s+$/.test(child.text!)
1351 ) {
1352 if (!hasContent)
1353 children[index] = child.mark(child.marks.filter((item) => item.type.name !== mark));
1354 } else {
1355 hasContent = true;
1356 }
1357 }
1358 }
1359 }
1360 const markEnds = new Map<RichTextMark, number>();
1361 const orderedMarks: RichTextMark[][] = [];
1362 for (let index = children.length - 1; index >= 0; index -= 1) {
1363 const child = children[index]!;
1364 const marks =
1365 child.type.name === "hardBreak"
1366 ? []
1367 : child.marks
1368 .map((mark) => TIPTAP_TO_MARK[mark.type.name])
1369 .filter((mark): mark is RichTextMark => Boolean(mark));
1370 for (const mark of MARK_NESTING_ORDER) {
1371 if (!marks.includes(mark)) markEnds.delete(mark);
1372 else if (!markEnds.has(mark)) markEnds.set(mark, index);
1373 }
1374 orderedMarks[index] = marks.sort(
1375 (a, b) =>
1376 markEnds.get(b)! - markEnds.get(a)! ||
1377 MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b),
1378 );
1379 }
1380 for (let index = 1; index < orderedMarks.length; index += 1) {
1381 const marks = orderedMarks[index]!;
1382 const retained: RichTextMark[] = [];
1383 for (const mark of orderedMarks[index - 1]!) {
1384 if (!marks.includes(mark)) break;
1385 retained.push(mark);
1386 }
1387 orderedMarks[index] = [...retained, ...marks.filter((mark) => !retained.includes(mark))];
1388 }
1389 const commonLength = (left: RichTextMark[], right: RichTextMark[]) => {
1390 let index = 0;
1391 while (index < left.length && left[index] === right[index]) index += 1;
1392 return index;
1393 };
1394 let inlineOffset = 0;
1395 children.forEach((child, index) => {
1396 const pmPos = contentStart + inlineOffset;
1397 inlineOffset += child.nodeSize;
1398 if (child.type.name === "hardBreak") {
1399 pushBreakRun(acc, pmPos);
1400 return;
1401 }
1402 const marks = orderedMarks[index]!;
1403 const open = marks
1404 .slice(commonLength(marks, orderedMarks[index - 1] ?? []))
1405 .map((mark) => RICH_TEXT_DELIMITERS[mark])
1406 .join("");
1407 const close = marks
1408 .slice(commonLength(marks, orderedMarks[index + 1] ?? []))
1409 .toReversed()
1410 .map((mark) => RICH_TEXT_DELIMITERS[mark])
1411 .join("");
1412 const source = child.isText ? child.text! : readAtomSource(child);
1413 const docLen = child.isText ? source.length : 1;
1414 const mdText = open + source + close;
1415 acc.runs.push({
1416 kind: child.isText ? "text" : "token",
1417 flatStart: acc.flat,
1418 docLen,
1419 mdLen: mdText.length,
1420 openLen: open.length,
1421 closeLen: close.length,
1422 pmPos,
1423 mdStart: acc.md,
1424 ...(child.isText ? {} : { nodeName: child.type.name }),
1425 });
1426 acc.value += mdText;
1427 acc.flat += docLen;
1428 acc.md += mdText.length;
1429 });
1430 if (children.length === 0) {
1431 acc.runs.push({
1432 kind: "text",
1433 flatStart: acc.flat,
1434 docLen: 0,
1435 mdLen: 0,
1436 openLen: 0,
1437 closeLen: 0,
1438 pmPos: contentStart,
1439 mdStart: acc.md,
1440 });
1441 }
1442 }
1443
1444 const LIST_NODE_NAMES = new Set(["taskList", "bulletList", "orderedList"]);
1445 const LIST_ITEM_NODE_NAMES = new Set(["taskItem", "listItem"]);
1446
1447 // Tiptap leaves indent and marker attributes unchanged when moving items; rebuilding would undo the move.
1448 function alignListItemWithSiblings(tr: Transaction, itemType: string): void {
1449 const $pos = tr.selection.$from;
1450 if ($pos.depth < 3 || $pos.node(-1).type.name !== itemType) return;
1451 const item = $pos.node(-1);
1452 const list = $pos.node(-2);
1453 const index = $pos.index(-2);
1454 const sibling =
1455 index > 0 ? list.child(index - 1) : index + 1 < list.childCount ? list.child(index + 1) : null;
1456 if (!sibling) return;
1457 const attrs: Record<string, unknown> = { ...item.attrs, indent: sibling.attrs.indent };
1458 if (item.type.name === "taskItem") {
1459 attrs.markerSpace = sibling.attrs.markerSpace;
1460 } else {
1461 const marker = typeof sibling.attrs.marker === "string" ? sibling.attrs.marker : "-";
1462 attrs.marker = index > 0 && /^\d+[.)]$/.test(marker) ? nextOrderedMarkerText(marker) : marker;
1463 }
1464 tr.setNodeMarkup($pos.before(-1), undefined, attrs);
1465 if (typeof attrs.marker === "string" && /^\d+[.)]$/.test(attrs.marker)) {
1466 renumberFollowingItems(tr, $pos.before(-2), index, attrs.marker);
1467 }
1468 }
1469
1470 function renumberFollowingItems(
1471 tr: Transaction,
1472 listPos: number,
1473 index: number,
1474 marker: string,
1475 ): void {
1476 const list = tr.doc.nodeAt(listPos);
1477 if (!list) return;
1478 let pos = listPos + 1;
1479 let previous = marker;
1480 list.forEach((child, _, childIndex) => {
1481 if (childIndex > index) {
1482 previous = nextOrderedMarkerText(previous);
1483 if (child.attrs.marker !== previous) {
1484 tr.setNodeMarkup(pos, undefined, { ...child.attrs, marker: previous });
1485 }
1486 }
1487 pos += child.nodeSize;
1488 });
1489 }
1490
1491 /** `prepare` runs first in the same transaction, which the split then reads. */
1492 export function splitOrLiftListItem(editor: Editor, prepare: Command): boolean {
1493 const $from = editor.state.selection.$from;
1494 const itemType = listItemTypeAt($from);
1495 if (!itemType) return false;
1496 const empty = $from.parent.content.size === 0;
1497 const move: Command = ({ commands, tr }) => {
1498 const moved =
1499 commands.splitListItem(
1500 itemType,
1501 itemType === "taskItem" ? { checked: false } : { space: " " },
1502 ) ||
1503 (empty && commands.liftListItem(itemType));
1504 if (moved) alignListItemWithSiblings(tr, itemType);
1505 return moved;
1506 };
1507 return editor.can().command(move) && editor.chain().command(prepare).command(move).run();
1508 }
1509
1510 export function convertBulletItemToTask(
1511 tr: Transaction,
1512 from: number,
1513 to: number,
1514 checked: boolean,
1515 ): void {
1516 tr.delete(from, to);
1517 const $pos = tr.doc.resolve(from);
1518 const item = $pos.node(-1);
1519 const list = $pos.node(-2);
1520 const index = $pos.index(-2);
1521 const { schema } = tr.doc.type;
1522 const before: ProseMirrorNode[] = [];
1523 const after: ProseMirrorNode[] = [];
1524 list.forEach((child, _, childIndex) => {
1525 if (childIndex < index) before.push(child);
1526 else if (childIndex > index) after.push(child);
1527 });
1528 const markerSpace =
1529 typeof item.attrs.space === "string" && item.attrs.space ? item.attrs.space : " ";
1530 const task = schema.nodes.taskItem!.create(
1531 { checked, indent: item.attrs.indent, markerSpace },
1532 item.content,
1533 );
1534 const lists = [
1535 ...(before.length > 0 ? [list.copy(Fragment.from(before))] : []),
1536 schema.nodes.taskList!.create(null, task),
1537 ...(after.length > 0 ? [list.copy(Fragment.from(after))] : []),
1538 ];
1539 const listStart = $pos.before(-2);
1540 tr.replaceWith(listStart, listStart + list.nodeSize, lists);
1541 const caret = listStart + (before.length > 0 ? lists[0]!.nodeSize : 0) + 3;
1542 tr.setSelection(TextSelection.create(tr.doc, caret));
1543 }
1544
1545 function listItemTypeAt($pos: ResolvedPos): "listItem" | "taskItem" | null {
1546 const name = $pos.depth > 1 ? $pos.node(-1).type.name : null;
1547 return name === "listItem" || name === "taskItem" ? name : null;
1548 }
1549
1550 /**
1551 * Tiptap's list keymap, which StarterKit loads, does both by moving nodes
1552 * without touching their indent or marker, so the composer turns it off.
1553 */
1554 function backspaceAcrossList(editor: Editor): boolean {
1555 const { state } = editor;
1556 const { $from, empty } = state.selection;
1557 if (!empty || $from.parentOffset !== 0) return false;
1558 const itemType = listItemTypeAt($from);
1559 if (itemType && $from.index(-1) === 0) {
1560 const lift: Command = ({ commands, tr }) => {
1561 const moved = commands.liftListItem(itemType);
1562 if (moved) alignListItemWithSiblings(tr, itemType);
1563 return moved;
1564 };
1565 // can() skips the schema check and can accept tasks with no parent list to lift into.
1566 // Those join the line above; joinBackward would re-nest them or select the parent line.
1567 return editor.chain().command(lift).run() || joinTextblockBackward(state, editor.view.dispatch);
1568 }
1569 const before = $from.depth === 1 ? $from.node(0).maybeChild($from.index(0) - 1) : null;
1570 if (before && LIST_NODE_NAMES.has(before.type.name) && $from.parent.type.name !== "codeBlock") {
1571 return joinTextblockBackward(state, editor.view.dispatch);
1572 }
1573 return false;
1574 }
1575
1576 /**
1577 * Tiptap's default would instead nest the next item, or a whole list, under
1578 * this one at its old indent.
1579 */
1580 function deleteAcrossList(editor: Editor): boolean {
1581 const { state } = editor;
1582 const { $from, empty } = state.selection;
1583 if (!empty || !$from.parent.isTextblock || $from.depth === 0) return false;
1584 if ($from.parentOffset !== $from.parent.content.size) return false;
1585 const next = Selection.findFrom(state.doc.resolve($from.after()), 1, true);
1586 if (!next) return false;
1587 if (next.$from.parent.type.name === "codeBlock") return $from.parent.type.name !== "codeBlock";
1588 if (!listItemTypeAt($from) && !listItemTypeAt(next.$from)) return false;
1589 return joinTextblockForward(state, editor.view.dispatch);
1590 }
1591
1592 function listItemPrefix(item: ProseMirrorNode, empty: boolean): string {
1593 const attrs = item.attrs as Record<string, unknown>;
1594 const indent = typeof attrs.indent === "string" ? attrs.indent : "";
1595 if (item.type.name === "taskItem") {
1596 const markerSpace = typeof attrs.markerSpace === "string" ? attrs.markerSpace : " ";
1597 const contentSpace =
1598 typeof attrs.contentSpace === "string"
1599 ? attrs.contentSpace || (empty ? "" : " ")
1600 : empty
1601 ? ""
1602 : " ";
1603 return `${indent}-${markerSpace}[${attrs.checked === true ? "x" : " "}]${contentSpace}`;
1604 }
1605 const marker = typeof attrs.marker === "string" && attrs.marker ? attrs.marker : "-";
1606 const space =
1607 typeof attrs.space === "string" ? attrs.space || (empty ? "" : " ") : empty ? "" : " ";
1608 return `${indent}${marker}${space}`;
1609 }
1610
1611 function walkList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator): void {
1612 let itemPos = listStart + 1;
1613 let firstItem = true;
1614 list.content.forEach((item) => {
1615 if (!firstItem) pushBreakRun(acc);
1616 firstItem = false;
1617 const itemContentStart = itemPos + 1;
1618 const first = item.firstChild;
1619 const empty = first?.type.name === "paragraph" && first.content.childCount === 0;
1620 const prefix = listItemPrefix(item, empty);
1621 acc.runs.push({
1622 kind: "prefix",
1623 flatStart: acc.flat,
1624 docLen: 0,
1625 mdLen: prefix.length,
1626 openLen: 0,
1627 closeLen: 0,
1628 pmPos: itemContentStart + 1,
1629 mdStart: acc.md,
1630 });
1631 acc.value += prefix;
1632 acc.md += prefix.length;
1633 let childPos = itemContentStart;
1634 let firstBlock = true;
1635 item.content.forEach((child) => {
1636 if (!firstBlock) pushBreakRun(acc);
1637 firstBlock = false;
1638 if (LIST_NODE_NAMES.has(child.type.name)) {
1639 walkList(child, childPos, acc);
1640 } else if (child.type.name === "paragraph") {
1641 appendInlineRuns(child, childPos + 1, acc);
1642 }
1643 childPos += child.nodeSize;
1644 });
1645 itemPos += item.nodeSize;
1646 });
1647 }
1648
1649 function appendCodeBlockRun(
1650 block: ProseMirrorNode,
1651 pmPos: number,
1652 followed: boolean,
1653 acc: RichAccumulator,
1654 ): void {
1655 const { open, content, close } = codeBlockSource(block, followed);
1656 const mdLen = open.length + content.length + close.length;
1657 acc.runs.push({
1658 kind: "text",
1659 flatStart: acc.flat,
1660 docLen: content.length,
1661 mdLen,
1662 openLen: open.length,
1663 closeLen: close.length,
1664 pmPos,
1665 mdStart: acc.md,
1666 nodeName: "codeBlock",
1667 });
1668 acc.flat += content.length;
1669 acc.md += mdLen;
1670 acc.value += open + content + close;
1671 }
1672
1673 function walkBlockquote(quote: ProseMirrorNode, quoteStart: number, acc: RichAccumulator): void {
1674 const attrs = quote.attrs as Record<string, unknown>;
1675 const prefix = typeof attrs.prefix === "string" ? attrs.prefix : "> ";
1676 let childPos = quoteStart + 1;
1677 let firstLine = true;
1678 quote.content.forEach((child) => {
1679 if (!firstLine) pushBreakRun(acc);
1680 firstLine = false;
1681 acc.runs.push({
1682 kind: "prefix",
1683 flatStart: acc.flat,
1684 docLen: 0,
1685 mdLen: prefix.length,
1686 openLen: 0,
1687 closeLen: 0,
1688 pmPos: childPos + 1,
1689 mdStart: acc.md,
1690 });
1691 acc.value += prefix;
1692 acc.md += prefix.length;
1693 if (child.type.name === "paragraph") appendInlineRuns(child, childPos + 1, acc);
1694 childPos += child.nodeSize;
1695 });
1696 }
1697
1698 /** Restores list and quote markers omitted by slices that contain only shared-block content. */
1699 export function serializeSelection(doc: ProseMirrorNode, from: number, to: number): string {
1700 const slice = doc.slice(from, to);
1701 const $from = doc.resolve(from);
1702 let depth = $from.sharedDepth(to);
1703 let content: Fragment | ProseMirrorNode = slice.content;
1704 if (slice.content.firstChild?.isInline) {
1705 content = doc.type.schema.nodes.paragraph!.create(null, slice.content);
1706 } else {
1707 while (depth > 0) {
1708 const shared = $from.node(depth);
1709 content = shared.copy(Fragment.from(content));
1710 if (!LIST_ITEM_NODE_NAMES.has(shared.type.name)) break;
1711 depth -= 1;
1712 }
1713 }
1714 return serializeEditorDoc(doc.type.create(null, content)).value;
1715 }
1716
1717 // Docs are immutable, and one keystroke serializes the same doc from the marker
1718 // plugin, onUpdate, and onSelectionUpdate.
1719 const serializedDocs = new WeakMap<ProseMirrorNode, RichDocMap>();
1720
1721 export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {
1722 let map = serializedDocs.get(doc);
1723 if (!map) {
1724 map = serializeDoc(doc);
1725 serializedDocs.set(doc, map);
1726 }
1727 return map;
1728 }
1729
1730 function serializeDoc(doc: ProseMirrorNode): RichDocMap {
1731 const acc: RichAccumulator = { runs: [], value: "", flat: 0, md: 0 };
1732 const blocks: ProseMirrorNode[] = [];
1733 doc.content.forEach((node) => {
1734 blocks.push(node);
1735 });
1736
1737 let pmBlockStart = 0;
1738 blocks.forEach((block, blockIndex) => {
1739 if (blockIndex > 0 && !isTrailingLineAfterRule(doc, blockIndex)) pushBreakRun(acc);
1740 if (blockIndex > 0 && needsBlankLineBetween(blocks, blockIndex)) {
1741 pushBlankLineRun(acc, pmBlockStart + 1);
1742 }
1743 if (LIST_NODE_NAMES.has(block.type.name)) {
1744 walkList(block, pmBlockStart, acc);
1745 } else if (block.type.name === "codeBlock") {
1746 appendCodeBlockRun(block, pmBlockStart + 1, blockIndex < blocks.length - 1, acc);
1747 } else if (block.type.name === "blockquote") {
1748 walkBlockquote(block, pmBlockStart, acc);
1749 } else if (block.type.name === "heading") {
1750 const attrs = block.attrs as Record<string, unknown>;
1751 const level = typeof attrs.level === "number" ? attrs.level : 1;
1752 const space = typeof attrs.space === "string" ? attrs.space : " ";
1753 const prefix = `${"#".repeat(level)}${space}`;
1754 acc.runs.push({
1755 kind: "prefix",
1756 flatStart: acc.flat,
1757 docLen: 0,
1758 mdLen: prefix.length,
1759 openLen: 0,
1760 closeLen: 0,
1761 pmPos: pmBlockStart + 1,
1762 mdStart: acc.md,
1763 });
1764 acc.value += prefix;
1765 acc.md += prefix.length;
1766 appendInlineRuns(block, pmBlockStart + 1, acc);
1767 } else if (block.type.name === "horizontalRule") {
1768 const source = horizontalRuleSource(block);
1769 acc.runs.push({
1770 kind: "prefix",
1771 flatStart: acc.flat,
1772 docLen: 0,
1773 mdLen: source.length,
1774 openLen: 0,
1775 closeLen: 0,
1776 pmPos: pmBlockStart + block.nodeSize,
1777 mdStart: acc.md,
1778 });
1779 acc.value += source;
1780 acc.md += source.length;
1781 } else if (block.type.name === "paragraph") {
1782 appendInlineRuns(block, pmBlockStart + 1, acc);
1783 }
1784 pmBlockStart += block.nodeSize;
1785 });
1786
1787 return {
1788 value: acc.value,
1789 runs: acc.runs,
1790 docLength: acc.flat,
1791 contextIds: Array.from(new Set(collectInlineContextIds(acc.value))),
1792 };
1793 }
1794
1795 export interface SkillChipReplacement {
1796 from: number;
1797 to: number;
1798 node: ProseMirrorNode;
1799 }
1800
1801 function isStaleChip(node: ProseMirrorNode, chips: ChipResolver): boolean {
1802 const { skillName, instanceId, model } = node.attrs as Record<string, unknown>;
1803 if (node.type.name === "composer-skill") {
1804 return typeof skillName === "string" && skillName !== "" && !chips.skill(skillName);
1805 }
1806 if (node.type.name === "composer-model") return !chips.model(String(instanceId), String(model));
1807 return false;
1808 }
1809
1810 /**
1811 * Use the same Markdown token boundaries as draft restoration. Apply edits
1812 * last-first so positions stay valid and unrelated citation nodes keep their keys.
1813 */
1814 export function skillChipReplacements(
1815 doc: ProseMirrorNode,
1816 skillLabelFor: (name: string) => SkillMeta | null,
1817 isKnownModel: IsKnownModel = NO_MODELS,
1818 ): SkillChipReplacement[] {
1819 const chips = { skill: skillLabelFor, model: isKnownModel };
1820 const schema = doc.type.schema;
1821 const replacements: SkillChipReplacement[] = [];
1822 doc.descendants((node, pos) => {
1823 if (!isStaleChip(node, chips)) return;
1824 replacements.push({
1825 from: pos,
1826 to: pos + node.nodeSize,
1827 node: schema.text(readAtomSource(node), node.marks),
1828 });
1829 });
1830 const map = serializeEditorDoc(doc);
1831 let end = 0;
1832 for (const segment of splitPromptIntoComposerSegments(map.value)) {
1833 const start = end;
1834 end += segment.type === "text" ? segment.text.length : segment.source.length;
1835 if (segment.type !== "skill" && segment.type !== "model") continue;
1836 const atom = atomJsonForSegment(segment, chips);
1837 const type = atom && schema.nodes[atom.type];
1838 if (!atom || !type) continue;
1839 // Only text needs converting; an existing chip is a token run.
1840 const run = map.runs.find(
1841 (candidate) =>
1842 candidate.kind === "text" &&
1843 candidate.nodeName !== "codeBlock" &&
1844 start >= candidate.mdStart + candidate.openLen &&
1845 end <= candidate.mdStart + candidate.openLen + candidate.docLen,
1846 );
1847 if (!run) continue;
1848 const from = run.pmPos + (start - run.mdStart - run.openLen);
1849 replacements.push({
1850 from,
1851 to: from + segment.source.length,
1852 node: type.create(atom.attrs, null, doc.nodeAt(from)?.marks),
1853 });
1854 }
1855 return replacements.sort((left, right) => right.from - left.from);
1856 }
1857
1858 // Run ends belong to the next run, except code ends must stay inside their closing fence.
1859 function runOwnsOffset(run: RichRun, flatOffset: number): boolean {
1860 const end = run.flatStart + run.docLen;
1861 return flatOffset < end || (flatOffset === end && run.nodeName === "codeBlock");
1862 }
1863
1864 export function flatToMarkdown(map: RichDocMap, flatOffset: number): number {
1865 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
1866 for (const run of map.runs) {
1867 if (runOwnsOffset(run, bounded)) {
1868 if (run.kind === "text" || run.kind === "token") {
1869 return run.mdStart + run.openLen + (bounded - run.flatStart);
1870 }
1871 return run.mdStart + (bounded - run.flatStart);
1872 }
1873 }
1874 const last = map.runs[map.runs.length - 1];
1875 return last ? last.mdStart + last.mdLen : 0;
1876 }
1877
1878 export function markdownToFlat(map: RichDocMap, markdownOffset: number): number {
1879 for (const run of map.runs) {
1880 if (markdownOffset < run.mdStart + run.mdLen) {
1881 if (run.kind === "prefix") return run.flatStart;
1882 if (run.kind === "text" || run.kind === "token") {
1883 const within = markdownOffset - run.mdStart;
1884 if (within <= run.openLen) return run.flatStart;
1885 // A chip is one document position however long its source is.
1886 if (run.kind === "token" || within >= run.openLen + run.docLen) {
1887 return run.flatStart + run.docLen;
1888 }
1889 return run.flatStart + (within - run.openLen);
1890 }
1891 return run.flatStart + (markdownOffset - run.mdStart);
1892 }
1893 }
1894 return map.docLength;
1895 }
1896
1897 export function flatToPm(map: RichDocMap, flatOffset: number): number {
1898 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
1899 for (const run of map.runs) {
1900 if (bounded < run.flatStart + run.docLen) {
1901 return run.pmPos + (bounded - run.flatStart);
1902 }
1903 }
1904 const last = map.runs[map.runs.length - 1];
1905 if (!last) return 1;
1906 return last.pmPos + last.docLen;
1907 }
1908
1909 export function pmToFlat(map: RichDocMap, pmPos: number): number {
1910 for (const run of map.runs) {
1911 if (pmPos >= run.pmPos && pmPos <= run.pmPos + run.docLen) {
1912 if (run.kind === "token" && pmPos === run.pmPos + run.docLen) {
1913 return run.flatStart + run.docLen;
1914 }
1915 return run.flatStart + Math.min(pmPos - run.pmPos, run.docLen);
1916 }
1917 }
1918 let best = 0;
1919 for (const run of map.runs) {
1920 if (run.pmPos <= pmPos) best = run.flatStart + run.docLen;
1921 }
1922 return Math.max(0, Math.min(best, map.docLength));
1923 }
1924
1925 // Styled boundaries need two caret stops at one position, one for each side's marks.
1926
1927 // Shown Markdown source has real characters at its edges, so it needs no extra stop.
1928 function styleMarks(marks: readonly Mark[]): readonly Mark[] {
1929 return marks.filter((mark) => mark.type.name !== MARKDOWN_SOURCE_MARK);
1930 }
1931
1932 function styledEdge(state: EditorState) {
1933 const { selection } = state;
1934 if (!selection.empty) return null;
1935 const { $from } = selection;
1936 if (!$from.parent.inlineContent) return null;
1937 const before = styleMarks($from.nodeBefore?.marks ?? Mark.none);
1938 const after = styleMarks($from.nodeAfter?.marks ?? Mark.none);
1939 if (Mark.sameSet(before, after)) return null;
1940 return { before, after, current: styleMarks(state.storedMarks ?? $from.marks()) };
1941 }
1942
1943 export function caretTakesMarksBefore(state: EditorState): boolean {
1944 const edge = styledEdge(state);
1945 return edge !== null && Mark.sameSet(edge.current, edge.before);
1946 }
1947
1948 export function stepCaretAcrossStyledEdge(
1949 state: EditorState,
1950 direction: -1 | 1,
1951 ): Transaction | null {
1952 const edge = styledEdge(state);
1953 if (!edge) return null;
1954 if (!Mark.sameSet(edge.current, edge.before) && !Mark.sameSet(edge.current, edge.after)) {
1955 return null;
1956 }
1957 const target = direction === -1 ? edge.before : edge.after;
1958 if (Mark.sameSet(edge.current, target)) return null;
1959 return state.tr.setStoredMarks(target);
1960 }