Open History to see the last commit
1import { joinBackward, joinTextblockBackward, joinTextblockForward } from "@tiptap/pm/commands";
2import { Fragment, Mark, type Node as ProseMirrorNode, type ResolvedPos } from "@tiptap/pm/model";
3import { Code } from "@tiptap/extension-code";
4import { Blockquote } from "@tiptap/extension-blockquote";
5import { CodeBlock } from "@tiptap/extension-code-block";
6import { Heading } from "@tiptap/extension-heading";
7import { HorizontalRule } from "@tiptap/extension-horizontal-rule";
8import { type Command, type Editor, mergeAttributes } from "@tiptap/core";
9import { BulletList, ListItem, OrderedList } from "@tiptap/extension-list";
10import { TaskItem } from "@tiptap/extension-task-item";
11import { TaskList } from "@tiptap/extension-task-list";
12import {
13 type EditorState,
14 Plugin,
15 Selection,
16 TextSelection,
17 type Transaction,
18} from "@tiptap/pm/state";
19
20import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
21import { nextOrderedMarkerText } from "~/composer-list-continuation";
22import { parseInlineMarkdown, RICH_TEXT_DELIMITERS, type RichTextMark } from "~/composer-rich-text";
23import { collectInlineContextIds } from "~/lib/composerContextReferences";
24
25export type SkillMeta = { label: string; description: string | null };
26
27const MARK_NESTING_ORDER: RichTextMark[] = ["strike", "bold", "italic", "code"];
28
29const MARK_TO_TIPTAP: Record<RichTextMark, string> = {
30 bold: "bold",
31 italic: "italic",
32 strike: "strike",
33 code: "code",
34};
35
36const TIPTAP_TO_MARK: Record<string, RichTextMark> = {
37 bold: "bold",
38 italic: "italic",
39 strike: "strike",
40 code: "code",
41};
42
43/**
44 * Tiptap's code mark excludes every other mark, which rejects the `bold+code`
45 * spans markdown like `**\`x\`**` parses into and drops the whole insert.
46 */
47export const ComposerCodeExtension = Code.extend({
48 excludes: "code",
49 // ArrowRight leaves code through the caret stops at styled edges, so the
50 // stock exit (inserting a space at the end of a line) is not needed.
51 exitable: false,
52});
53
54/**
55 * Tiptap's block extensions each bind a chord that turns the current block into
56 * their node (Mod-Shift-8 for a list, Mod-Alt-c for a fence, and so on). The
57 * composer does not offer them, and they are not harmless: run inside a quote
58 * they nest a block the quote serializer cannot write, and the text in it drops
59 * out of the stored draft.
60 */
61function withoutBlockChords<Shortcuts extends Record<string, unknown>>(
62 shortcuts: Shortcuts | undefined,
63 drop: readonly string[],
64): Shortcuts {
65 return Object.fromEntries(
66 Object.entries(shortcuts ?? {}).filter(([key]) => !drop.includes(key)),
67 ) as Shortcuts;
68}
69
70/**
71 * What a list item may hold: its own line, then nested lists. That is all the
72 * Markdown can write, so ProseMirror refuses any join, wrap or paste that
73 * would put a second line or another block into an item.
74 */
75const LIST_ITEM_CONTENT = "paragraph list*";
76
77/** Task lists come from `- [ ]` alone; Mod-Shift-9 would nest one in a quote. */
78export const ComposerTaskListExtension = TaskList.extend({
79 addKeyboardShortcuts() {
80 return withoutBlockChords(this.parent?.(), ["Mod-Shift-9"]);
81 },
82});
83
84/**
85 * Tiptap's Tab and Shift-Tab sink and lift an item without touching its
86 * `indent`, so the stored draft keeps the old nesting and the next rebuild
87 * undoes the move.
88 */
89const LIST_NESTING_KEYS = ["Tab", "Shift-Tab"];
90
91export const ComposerTaskItemExtension = TaskItem.extend({
92 content: LIST_ITEM_CONTENT,
93 addAttributes() {
94 return {
95 ...this.parent?.(),
96 indent: { default: "" },
97 markerSpace: { default: " " },
98 contentSpace: { default: null },
99 };
100 },
101 addKeyboardShortcuts() {
102 return withoutBlockChords(this.parent?.(), LIST_NESTING_KEYS);
103 },
104}).configure({ nested: true });
105
106export const ComposerCodeBlockExtension = CodeBlock.extend({
107 addAttributes() {
108 return {
109 ...this.parent?.(),
110 language: { default: "" },
111 fence: { default: "```" },
112 close: { default: "\n```" },
113 };
114 },
115 addKeyboardShortcuts() {
116 return {
117 ...withoutBlockChords(this.parent?.(), ["Mod-Alt-c"]),
118 Backspace: () => unwrapCodeBlockAtStart(this.editor),
119 };
120 },
121});
122
123/**
124 * Joining the code onto the line above instead would drop the fence from the
125 * draft and leave the rest of the code as stray lines.
126 */
127function unwrapCodeBlockAtStart(editor: Editor): boolean {
128 const { $from, empty } = editor.state.selection;
129 if (!empty || $from.parent.type.name !== "codeBlock" || $from.parentOffset !== 0) return false;
130 const { schema } = editor.state;
131 const paragraphs = $from.parent.textContent
132 .split("\n")
133 .map((line) => schema.nodes.paragraph!.create(null, line ? schema.text(line) : null));
134 const start = $from.before();
135 const tr = editor.state.tr.replaceWith(start, $from.after(), paragraphs);
136 editor.view.dispatch(tr.setSelection(TextSelection.create(tr.doc, start + 1)));
137 return true;
138}
139
140function codeBlockSource(
141 node: ProseMirrorNode,
142 followed: boolean,
143): {
144 open: string;
145 content: string;
146 close: string;
147} {
148 const attrs = node.attrs as Record<string, unknown>;
149 let fence = typeof attrs.fence === "string" && attrs.fence ? attrs.fence : "```";
150 const language = typeof attrs.language === "string" ? attrs.language : "";
151 let close = typeof attrs.close === "string" ? attrs.close : "";
152 const content = node.textContent;
153 // Code holding a line that would close the fence, such as a pasted fence, is
154 // written inside a longer one, so the agent reads all of it as code.
155 const longest = Math.max(
156 0,
157 ...content
158 .split("\n")
159 .filter((line) => isClosingFence(line, fence))
160 .map((line) => /^[`~]+/.exec(line)![0].length),
161 );
162 if (longest > 0) {
163 fence = fence[0]!.repeat(longest + 1);
164 if (close) close = `\n${fence}`;
165 }
166 // An unclosed fence runs to the end of the draft, so with a block after it
167 // the fence is written closed, or the next rebuild would read that block as code.
168 if (!close && followed) close = `\n${fence}`;
169 return { open: `${fence}${language}${content ? "\n" : ""}`, content, close };
170}
171
172const ComposerListItemExtension = ListItem.extend({
173 content: LIST_ITEM_CONTENT,
174 addAttributes() {
175 return {
176 ...this.parent?.(),
177 indent: { default: "" },
178 marker: { default: "-" },
179 space: { default: " " },
180 };
181 },
182 addKeyboardShortcuts() {
183 return {
184 ...withoutBlockChords(this.parent?.(), LIST_NESTING_KEYS),
185 Backspace: () => backspaceAcrossList(this.editor),
186 Delete: () => deleteAcrossList(this.editor),
187 };
188 },
189 renderHTML({ node, HTMLAttributes }) {
190 return ["li", mergeAttributes(HTMLAttributes, { "data-marker": node.attrs.marker }), 0];
191 },
192});
193
194export const ComposerListExtensions = [
195 BulletList.extend({
196 addKeyboardShortcuts() {
197 return withoutBlockChords(this.parent?.(), ["Mod-Shift-8"]);
198 },
199 }),
200 OrderedList.extend({
201 addKeyboardShortcuts() {
202 return withoutBlockChords(this.parent?.(), ["Mod-Shift-7"]);
203 },
204 }),
205 ComposerListItemExtension,
206];
207
208const ComposerBlockquoteExtension = Blockquote.extend({
209 content: "paragraph+",
210 addAttributes() {
211 return { ...this.parent?.(), prefix: { default: "> " } };
212 },
213 addKeyboardShortcuts() {
214 return withoutBlockChords(this.parent?.(), ["Mod-Shift-b"]);
215 },
216});
217
218const ComposerHorizontalRuleExtension = HorizontalRule.extend({
219 addAttributes() {
220 return { ...this.parent?.(), source: { default: "---" } };
221 },
222 addProseMirrorPlugins() {
223 return [
224 ...(this.parent?.() ?? []),
225 new Plugin({
226 appendTransaction: (transactions, _, state) => {
227 if (!transactions.some((tr) => tr.docChanged)) return null;
228 if (state.doc.lastChild?.type.name !== "horizontalRule") return null;
229 return state.tr.insert(state.doc.content.size, state.schema.nodes.paragraph!.create());
230 },
231 }),
232 ];
233 },
234});
235
236function isTrailingLineAfterRule(doc: ProseMirrorNode, index: number): boolean {
237 const block = doc.child(index);
238 return (
239 index === doc.childCount - 1 &&
240 index > 0 &&
241 block.type.name === "paragraph" &&
242 block.content.size === 0 &&
243 doc.child(index - 1).type.name === "horizontalRule"
244 );
245}
246
247const ComposerHeadingExtension = Heading.extend({
248 addAttributes() {
249 return { ...this.parent?.(), space: { default: " " } };
250 },
251 addKeyboardShortcuts() {
252 return {};
253 },
254});
255
256export const ComposerBlockExtensions = [
257 ComposerBlockquoteExtension,
258 ComposerHorizontalRuleExtension,
259 ComposerHeadingExtension,
260];
261
262function randomNodeKey(): string {
263 return `tiptap-${Math.random().toString(36).slice(2)}`;
264}
265
266interface TaskLinePrefix {
267 indent: string;
268 checked: boolean;
269 markerSpace: string;
270 contentSpace: string;
271}
272
273function parseTaskPrefix(head: string): { prefix: TaskLinePrefix; markerLength: number } | null {
274 const match = head.match(/^([ \t]*)-([ \t]+)\[([ xX])\]([ \t]*)/);
275 if (!match) return null;
276 const after = head.slice(match[0].length);
277 if (after.length > 0 && !match[4]) return null;
278 return {
279 prefix: {
280 indent: match[1] ?? "",
281 checked: (match[3] ?? " ").toLowerCase() === "x",
282 markerSpace: match[2]!,
283 contentSpace: match[4]!,
284 },
285 markerLength: match[0].length,
286 };
287}
288
289export function parseOpeningFence(line: string): { fence: string; language: string } | null {
290 // `[^\n]` rather than `.`, here and in the block rules: a CRLF draft's lines
291 // end in `\r`, which `.` refuses, and the `\r` stays in the stored text.
292 const match = /^(`{3,}|~{3,})([^\n]*)$/.exec(line);
293 if (!match) return null;
294 const fence = match[1]!;
295 const language = match[2]!;
296 if (fence.startsWith("`") && language.includes("`")) return null;
297 return { fence, language };
298}
299
300export function isClosingFence(line: string, fence: string): boolean {
301 const match = /^(`{3,}|~{3,})[ \t]*\r?$/.exec(line);
302 if (!match) return false;
303 const run = match[1]!;
304 return run[0] === fence[0] && run.length >= fence.length;
305}
306
307type ListLinePrefix =
308 | ({ kind: "task" } & TaskLinePrefix)
309 | { kind: "bullet" | "ordered"; indent: string; marker: string; space: string };
310
311/**
312 * The same grammar the literal continuation uses, so plain and rich mode agree
313 * on what a list line is: a task first (it also looks like a bullet), then an
314 * ordered marker, then a bullet.
315 */
316function parseListPrefix(line: string): { prefix: ListLinePrefix; markerLength: number } | null {
317 const task = parseTaskPrefix(line);
318 if (task) return { prefix: { kind: "task", ...task.prefix }, markerLength: task.markerLength };
319 const ordered = /^([ \t]*)(\d+[.)])((?:[ \t]+)|$)/.exec(line);
320 if (ordered) {
321 return {
322 prefix: { kind: "ordered", indent: ordered[1]!, marker: ordered[2]!, space: ordered[3]! },
323 markerLength: ordered[0].length,
324 };
325 }
326 const bullet = /^([ \t]*)([-*+])((?:[ \t]+)|$)/.exec(line);
327 if (bullet) {
328 return {
329 prefix: { kind: "bullet", indent: bullet[1]!, marker: bullet[2]!, space: bullet[3]! },
330 markerLength: bullet[0].length,
331 };
332 }
333 return null;
334}
335
336function listKey(prefix: ListLinePrefix): string {
337 if (prefix.kind === "task") return "task";
338 if (prefix.kind === "ordered") return `ordered:${prefix.marker.slice(-1)}`;
339 return `bullet:${prefix.marker}`;
340}
341
342type InlineJson = Record<string, unknown>;
343
344interface DocLine {
345 list: ListLinePrefix | null;
346 inline: InlineJson[];
347}
348
349function atomJsonForSegment(
350 segment: Exclude<ReturnType<typeof splitPromptIntoComposerSegments>[number], { type: "text" }>,
351 skillLabelFor: (name: string) => SkillMeta,
352): InlineJson {
353 if (segment.type === "mention") {
354 return {
355 type: "composer-mention",
356 attrs: { path: segment.path, source: segment.source },
357 };
358 }
359 if (segment.type === "skill") {
360 const meta = skillLabelFor(segment.name);
361 return {
362 type: "composer-skill",
363 attrs: {
364 skillName: segment.name,
365 skillLabel: meta.label,
366 skillDescription: meta.description,
367 },
368 };
369 }
370 if (segment.type === "citation") {
371 return {
372 type: "composer-citation",
373 attrs: { citation: segment.citation, source: segment.source, citeKey: randomNodeKey() },
374 };
375 }
376 return {
377 type: "composer-context-reference",
378 attrs: {
379 kind: segment.kind,
380 contextId: segment.contextId,
381 label: segment.label,
382 source: segment.source,
383 },
384 };
385}
386
387interface PendingItem {
388 prefix: ListLinePrefix;
389 content: InlineJson[];
390 children: PendingList[];
391}
392
393interface PendingList {
394 key: string;
395 items: PendingItem[];
396}
397
398function listJson(list: PendingList): InlineJson {
399 const first = list.items[0]!.prefix;
400 const items = list.items.map((item) => {
401 const content = [
402 { type: "paragraph", content: item.content },
403 ...item.children.map((child) => listJson(child)),
404 ];
405 if (item.prefix.kind === "task") {
406 return {
407 type: "taskItem",
408 attrs: {
409 checked: item.prefix.checked,
410 indent: item.prefix.indent,
411 markerSpace: item.prefix.markerSpace,
412 contentSpace: item.prefix.contentSpace,
413 },
414 content,
415 };
416 }
417 return {
418 type: "listItem",
419 attrs: { indent: item.prefix.indent, marker: item.prefix.marker, space: item.prefix.space },
420 content,
421 };
422 });
423 if (first.kind === "task") return { type: "taskList", content: items };
424 if (first.kind === "ordered") {
425 return {
426 type: "orderedList",
427 attrs: { start: Number.parseInt(first.marker, 10) || 1 },
428 content: items,
429 };
430 }
431 return { type: "bulletList", content: items };
432}
433
434function textJsonForSpan(text: string, marks: RichTextMark[]): Record<string, unknown> {
435 const json: Record<string, unknown> = { type: "text", text };
436 if (marks.length > 0) {
437 json.marks = [...marks]
438 .sort((a, b) => MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b))
439 .map((mark) => ({ type: MARK_TO_TIPTAP[mark] }));
440 }
441 return json;
442}
443
444/**
445 * `literalLength` keeps that many leading characters as plain text, for a paste
446 * that continues a path query: markers inside a path such as `src/__init__.py`
447 * must reach file search unstyled.
448 */
449export function buildTiptapContent(
450 value: string,
451 skillLabelFor: (name: string) => SkillMeta,
452 options?: { styling?: boolean; blocks?: boolean; literalText?: boolean; literalLength?: number },
453): Record<string, unknown>[] {
454 if (options?.literalText) {
455 return value.split("\n").map((line) => ({
456 type: "paragraph",
457 ...(line ? { content: [{ type: "text", text: line }] } : {}),
458 }));
459 }
460 const styling = options?.styling ?? true;
461 const blockSyntax = styling && (options?.blocks ?? true);
462 let sentinel = "\uFFFC";
463 for (let codePoint = 0xe000; value.includes(sentinel); codePoint += 1) {
464 sentinel = String.fromCodePoint(codePoint);
465 }
466 const atoms: InlineJson[] = [];
467 const atomSources: string[] = [];
468 const literal = value.slice(0, options?.literalLength ?? 0);
469 const text = splitPromptIntoComposerSegments(value.slice(literal.length))
470 .map((segment) => {
471 if (segment.type === "text") return segment.text;
472 atoms.push(atomJsonForSegment(segment, skillLabelFor));
473 atomSources.push(segment.source);
474 return sentinel;
475 })
476 .join("");
477 let atomIndex = 0;
478 const buildInline = (content: string): InlineJson[] => {
479 const spans = styling ? parseInlineMarkdown(content) : [{ text: content, marks: [] }];
480 const inline: InlineJson[] = [];
481 for (const span of spans) {
482 span.text.split(sentinel).forEach((piece, index) => {
483 if (index > 0) {
484 const atom = atoms[atomIndex++]!;
485 inline.push({ ...atom, marks: textJsonForSpan("", span.marks).marks });
486 }
487 if (piece) inline.push(textJsonForSpan(piece, span.marks));
488 });
489 }
490 return inline;
491 };
492 const buildDocLine = (line: string): DocLine => {
493 const parsed = blockSyntax ? parseListPrefix(line) : null;
494 const content = parsed ? line.slice(parsed.markerLength) : line;
495 return { list: parsed?.prefix ?? null, inline: buildInline(content) };
496 };
497
498 const sourceLines = text.split("\n");
499 const entries: (
500 | { code: Record<string, unknown> }
501 | { rule: string }
502 | { heading: { level: number; space: string; inline: InlineJson[] } }
503 | { quote: { prefix: string; inline: InlineJson[] } }
504 | { line: DocLine }
505 )[] = [];
506 const restoreSources = (line: string) =>
507 line.split(sentinel).reduce((joined, piece, index) => {
508 if (index === 0) return piece;
509 atomIndex += 1;
510 return joined + atomSources[atomIndex - 1]! + piece;
511 }, "");
512
513 for (let index = 0; index < sourceLines.length; index += 1) {
514 const line = sourceLines[index]!;
515 if (index === 0 && literal) {
516 entries.push({
517 line: { list: null, inline: [textJsonForSpan(literal, []), ...buildInline(line)] },
518 });
519 continue;
520 }
521 const opening = blockSyntax ? parseOpeningFence(line) : null;
522 if (!opening) {
523 if (blockSyntax && /^([-*_])(?:[ \t]*\1){2,}[ \t]*\r?$/.test(line)) {
524 entries.push({ rule: line });
525 continue;
526 }
527 const heading = blockSyntax ? /^(#{1,6})([ \t]+)([^\n]*)$/.exec(line) : null;
528 if (heading) {
529 entries.push({
530 heading: {
531 level: heading[1]!.length,
532 space: heading[2]!,
533 inline: buildInline(heading[3]!),
534 },
535 });
536 continue;
537 }
538 const quote = blockSyntax ? /^(>[ \t]*)([^\n]*)$/.exec(line) : null;
539 if (quote) entries.push({ quote: { prefix: quote[1]!, inline: buildInline(quote[2]!) } });
540 else entries.push({ line: buildDocLine(line) });
541 continue;
542 }
543 const language = restoreSources(opening.language);
544 const body: string[] = [];
545 let cursor = index + 1;
546 let close = "";
547 while (cursor < sourceLines.length) {
548 const candidate = sourceLines[cursor]!;
549 if (isClosingFence(candidate, opening.fence)) {
550 close = `\n${candidate}`;
551 break;
552 }
553 body.push(restoreSources(candidate));
554 cursor += 1;
555 }
556 const closed = cursor < sourceLines.length;
557 const content = body.join("\n");
558 entries.push({
559 code: {
560 type: "codeBlock",
561 attrs: { language, fence: opening.fence, close },
562 ...(content ? { content: [{ type: "text", text: content }] } : {}),
563 },
564 });
565 index = closed ? cursor : sourceLines.length;
566 }
567
568 const blocks: Record<string, unknown>[] = [];
569 let rootLists: PendingList[] = [];
570 let stack: { indent: string; list: PendingList; container: PendingList[] }[] = [];
571 const flushLists = () => {
572 for (const list of rootLists) blocks.push(listJson(list));
573 rootLists = [];
574 stack = [];
575 };
576 const openList = (container: PendingList[], key: string): PendingList => {
577 const list = { key, items: [] };
578 container.push(list);
579 return list;
580 };
581 let openQuote: { prefix: string; content: InlineJson[][] } | null = null;
582 const flushQuote = () => {
583 if (!openQuote) return;
584 blocks.push({
585 type: "blockquote",
586 attrs: { prefix: openQuote.prefix },
587 content: openQuote.content.map((inline) => ({ type: "paragraph", content: inline })),
588 });
589 openQuote = null;
590 };
591 for (const entry of entries) {
592 if ("quote" in entry) {
593 flushLists();
594 if (openQuote && openQuote.prefix !== entry.quote.prefix) flushQuote();
595 openQuote ??= { prefix: entry.quote.prefix, content: [] };
596 openQuote.content.push(entry.quote.inline);
597 continue;
598 }
599 flushQuote();
600 if ("code" in entry) {
601 flushLists();
602 blocks.push(entry.code);
603 continue;
604 }
605 if ("rule" in entry) {
606 flushLists();
607 blocks.push({ type: "horizontalRule", attrs: { source: entry.rule } });
608 continue;
609 }
610 if ("heading" in entry) {
611 flushLists();
612 blocks.push({
613 type: "heading",
614 attrs: { level: entry.heading.level, space: entry.heading.space },
615 content: entry.heading.inline,
616 });
617 continue;
618 }
619 const line = entry.line;
620 if (!line.list) {
621 flushLists();
622 blocks.push({ type: "paragraph", content: line.inline });
623 continue;
624 }
625 const item: PendingItem = { prefix: line.list, content: line.inline, children: [] };
626 const key = listKey(line.list);
627 const indent = line.list.indent;
628 for (;;) {
629 const top = stack[stack.length - 1];
630 if (!top) {
631 stack.push({ indent, list: openList(rootLists, key), container: rootLists });
632 continue;
633 }
634 if (top.indent === indent) {
635 if (top.list.key !== key) top.list = openList(top.container, key);
636 top.list.items.push(item);
637 break;
638 }
639 if (top.indent !== "" && !indent.startsWith(top.indent)) {
640 if (stack.length > 1) {
641 stack.pop();
642 continue;
643 }
644 top.indent = indent;
645 if (top.list.key !== key) top.list = openList(top.container, key);
646 top.list.items.push(item);
647 break;
648 }
649 const parent = top.list.items[top.list.items.length - 1];
650 if (!parent) {
651 top.list.items.push(item);
652 break;
653 }
654 const list = openList(parent.children, key);
655 stack.push({ indent, list, container: parent.children });
656 list.items.push(item);
657 break;
658 }
659 }
660 flushQuote();
661 flushLists();
662 return blocks;
663}
664
665export function buildDocJson(
666 value: string,
667 skillLabelFor: (name: string) => SkillMeta,
668 options?: { styling?: boolean; literalText?: boolean },
669) {
670 const content = buildTiptapContent(value, skillLabelFor, options);
671 if (content.at(-1)?.type === "horizontalRule") content.push({ type: "paragraph" });
672 return { type: "doc", content };
673}
674
675export interface RichRun {
676 kind: "text" | "token" | "break" | "prefix";
677 /** Flat document offset (atoms count 1, markers excluded). */
678 flatStart: number;
679 docLen: number;
680 /** Collapsed cursor length (markers literal, tokens count 1). */
681 collapsedLen: number;
682 /** Markdown length (tokens expand to their source). */
683 mdLen: number;
684 openLen: number;
685 closeLen: number;
686 pmPos: number;
687 mdStart: number;
688 collapsedStart: number;
689 nodeName?: string;
690}
691
692export interface RichDocMap {
693 value: string;
694 runs: RichRun[];
695 docLength: number;
696 contextIds: string[];
697}
698
699function readAtomSource(node: ProseMirrorNode): string {
700 const attrs = node.attrs as Record<string, unknown>;
701 switch (node.type.name) {
702 case "composer-mention":
703 case "composer-citation":
704 case "composer-context-reference":
705 return typeof attrs.source === "string" ? attrs.source : "";
706 case "composer-skill": {
707 const name = typeof attrs.skillName === "string" ? attrs.skillName : "";
708 return name ? `$${name}` : "";
709 }
710 default:
711 return "";
712 }
713}
714
715interface RichAccumulator {
716 runs: RichRun[];
717 value: string;
718 flat: number;
719 collapsed: number;
720 md: number;
721}
722
723function pushBreakRun(acc: RichAccumulator, position?: number): void {
724 const previous = acc.runs[acc.runs.length - 1];
725 const pmPos = position ?? (previous ? previous.pmPos + previous.docLen : 1);
726 acc.runs.push({
727 kind: "break",
728 flatStart: acc.flat,
729 docLen: 1,
730 collapsedLen: 1,
731 mdLen: 1,
732 openLen: 0,
733 closeLen: 0,
734 pmPos,
735 mdStart: acc.md,
736 collapsedStart: acc.collapsed,
737 });
738 acc.value += "\n";
739 acc.flat += 1;
740 acc.collapsed += 1;
741 acc.md += 1;
742}
743
744/**
745 * A paragraph on the line right after a quote reads as part of it in Markdown
746 * (a lazy continuation), so the draft writes a blank line between them. An empty
747 * paragraph is that blank line already.
748 */
749function needsBlankLineAfterQuote(previous: ProseMirrorNode, block: ProseMirrorNode): boolean {
750 return (
751 previous.type.name === "blockquote" && block.type.name === "paragraph" && block.content.size > 0
752 );
753}
754
755/**
756 * That blank line, as a run that owns no document characters, like a marker:
757 * offsets inside it clamp to the start of the paragraph.
758 */
759function pushBlankLineRun(acc: RichAccumulator, pmPos: number): void {
760 acc.runs.push({
761 kind: "prefix",
762 flatStart: acc.flat,
763 docLen: 0,
764 collapsedLen: 1,
765 mdLen: 1,
766 openLen: 0,
767 closeLen: 0,
768 pmPos,
769 mdStart: acc.md,
770 collapsedStart: acc.collapsed,
771 });
772 acc.value += "\n";
773 acc.collapsed += 1;
774 acc.md += 1;
775}
776
777function appendInlineRuns(
778 container: ProseMirrorNode,
779 contentStart: number,
780 acc: RichAccumulator,
781): void {
782 const children: ProseMirrorNode[] = [];
783 container.forEach((child) => {
784 if (!child.isText || child.marks.some((mark) => mark.type.name === "code")) {
785 children.push(child);
786 return;
787 }
788 const text = child.text!;
789 const start = text.length - text.trimStart().length;
790 const end = Math.max(start, text.trimEnd().length);
791 let offset = 0;
792 for (const boundary of [start, end, text.length]) {
793 if (boundary > offset) children.push(child.cut(offset, boundary));
794 offset = boundary;
795 }
796 });
797 for (const mark of MARK_NESTING_ORDER) {
798 if (mark === "code") continue;
799 for (const direction of [1, -1]) {
800 let hasContent = false;
801 for (
802 let index = direction === 1 ? 0 : children.length - 1;
803 index >= 0 && index < children.length;
804 index += direction
805 ) {
806 const child = children[index]!;
807 if (
808 child.type.name === "hardBreak" ||
809 !child.marks.some((item) => item.type.name === mark)
810 ) {
811 hasContent = false;
812 } else if (
813 child.isText &&
814 !child.marks.some((item) => item.type.name === "code") &&
815 /^\s+$/.test(child.text!)
816 ) {
817 if (!hasContent)
818 children[index] = child.mark(child.marks.filter((item) => item.type.name !== mark));
819 } else {
820 hasContent = true;
821 }
822 }
823 }
824 }
825 const markEnds = new Map<RichTextMark, number>();
826 const orderedMarks: RichTextMark[][] = [];
827 for (let index = children.length - 1; index >= 0; index -= 1) {
828 const child = children[index]!;
829 const marks =
830 child.type.name === "hardBreak"
831 ? []
832 : child.marks
833 .map((mark) => TIPTAP_TO_MARK[mark.type.name])
834 .filter((mark): mark is RichTextMark => Boolean(mark));
835 for (const mark of MARK_NESTING_ORDER) {
836 if (!marks.includes(mark)) markEnds.delete(mark);
837 else if (!markEnds.has(mark)) markEnds.set(mark, index);
838 }
839 orderedMarks[index] = marks.sort(
840 (a, b) =>
841 markEnds.get(b)! - markEnds.get(a)! ||
842 MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b),
843 );
844 }
845 for (let index = 1; index < orderedMarks.length; index += 1) {
846 const marks = orderedMarks[index]!;
847 const retained: RichTextMark[] = [];
848 for (const mark of orderedMarks[index - 1]!) {
849 if (!marks.includes(mark)) break;
850 retained.push(mark);
851 }
852 orderedMarks[index] = [...retained, ...marks.filter((mark) => !retained.includes(mark))];
853 }
854 const commonLength = (left: RichTextMark[], right: RichTextMark[]) => {
855 let index = 0;
856 while (index < left.length && left[index] === right[index]) index += 1;
857 return index;
858 };
859 let inlineOffset = 0;
860 children.forEach((child, index) => {
861 const pmPos = contentStart + inlineOffset;
862 inlineOffset += child.nodeSize;
863 if (child.type.name === "hardBreak") {
864 pushBreakRun(acc, pmPos);
865 return;
866 }
867 const marks = orderedMarks[index]!;
868 const open = marks
869 .slice(commonLength(marks, orderedMarks[index - 1] ?? []))
870 .map((mark) => RICH_TEXT_DELIMITERS[mark])
871 .join("");
872 const close = marks
873 .slice(commonLength(marks, orderedMarks[index + 1] ?? []))
874 .toReversed()
875 .map((mark) => RICH_TEXT_DELIMITERS[mark])
876 .join("");
877 const source = child.isText ? child.text! : readAtomSource(child);
878 const docLen = child.isText ? source.length : 1;
879 const mdText = open + source + close;
880 const collapsedLen = open.length + docLen + close.length;
881 acc.runs.push({
882 kind: child.isText ? "text" : "token",
883 flatStart: acc.flat,
884 docLen,
885 collapsedLen,
886 mdLen: mdText.length,
887 openLen: open.length,
888 closeLen: close.length,
889 pmPos,
890 mdStart: acc.md,
891 collapsedStart: acc.collapsed,
892 ...(child.isText ? {} : { nodeName: child.type.name }),
893 });
894 acc.value += mdText;
895 acc.flat += docLen;
896 acc.collapsed += collapsedLen;
897 acc.md += mdText.length;
898 });
899 if (children.length === 0) {
900 acc.runs.push({
901 kind: "text",
902 flatStart: acc.flat,
903 docLen: 0,
904 collapsedLen: 0,
905 mdLen: 0,
906 openLen: 0,
907 closeLen: 0,
908 pmPos: contentStart,
909 mdStart: acc.md,
910 collapsedStart: acc.collapsed,
911 });
912 }
913}
914
915const LIST_NODE_NAMES = new Set(["taskList", "bulletList", "orderedList"]);
916const LIST_ITEM_NODE_NAMES = new Set(["taskItem", "listItem"]);
917
918/**
919 * Tiptap moves items between lists without touching these attributes, so without
920 * this the stored draft keeps an outdented item at its old depth, and the next
921 * rebuild nests it again.
922 */
923function alignListItemWithSiblings(tr: Transaction, itemType: string): void {
924 const $pos = tr.selection.$from;
925 if ($pos.depth < 3 || $pos.node(-1).type.name !== itemType) return;
926 const item = $pos.node(-1);
927 const list = $pos.node(-2);
928 const index = $pos.index(-2);
929 const sibling =
930 index > 0 ? list.child(index - 1) : index + 1 < list.childCount ? list.child(index + 1) : null;
931 if (!sibling) return;
932 const attrs: Record<string, unknown> = { ...item.attrs, indent: sibling.attrs.indent };
933 if (item.type.name === "taskItem") {
934 attrs.markerSpace = sibling.attrs.markerSpace;
935 } else {
936 const marker = typeof sibling.attrs.marker === "string" ? sibling.attrs.marker : "-";
937 attrs.marker = index > 0 && /^\d+[.)]$/.test(marker) ? nextOrderedMarkerText(marker) : marker;
938 }
939 tr.setNodeMarkup($pos.before(-1), undefined, attrs);
940 if (typeof attrs.marker === "string" && /^\d+[.)]$/.test(attrs.marker)) {
941 renumberFollowingItems(tr, $pos.before(-2), index, attrs.marker);
942 }
943}
944
945function renumberFollowingItems(
946 tr: Transaction,
947 listPos: number,
948 index: number,
949 marker: string,
950): void {
951 const list = tr.doc.nodeAt(listPos);
952 if (!list) return;
953 let pos = listPos + 1;
954 let previous = marker;
955 list.forEach((child, _, childIndex) => {
956 if (childIndex > index) {
957 previous = nextOrderedMarkerText(previous);
958 if (child.attrs.marker !== previous) {
959 tr.setNodeMarkup(pos, undefined, { ...child.attrs, marker: previous });
960 }
961 }
962 pos += child.nodeSize;
963 });
964}
965
966export function splitOrLiftListItem(editor: Editor): boolean {
967 const $from = editor.state.selection.$from;
968 const itemType = listItemTypeAt($from);
969 if (!itemType) return false;
970 const empty = $from.parent.content.size === 0;
971 const move: Command = ({ commands, tr }) => {
972 const moved =
973 commands.splitListItem(
974 itemType,
975 itemType === "taskItem" ? { checked: false } : { space: " " },
976 ) ||
977 (empty && commands.liftListItem(itemType));
978 if (moved) alignListItemWithSiblings(tr, itemType);
979 return moved;
980 };
981 return editor.can().command(move) && editor.chain().command(move).run();
982}
983
984export function convertBulletItemToTask(
985 tr: Transaction,
986 from: number,
987 to: number,
988 checked: boolean,
989): void {
990 tr.delete(from, to);
991 const $pos = tr.doc.resolve(from);
992 const item = $pos.node(-1);
993 const list = $pos.node(-2);
994 const index = $pos.index(-2);
995 const { schema } = tr.doc.type;
996 const before: ProseMirrorNode[] = [];
997 const after: ProseMirrorNode[] = [];
998 list.forEach((child, _, childIndex) => {
999 if (childIndex < index) before.push(child);
1000 else if (childIndex > index) after.push(child);
1001 });
1002 const markerSpace =
1003 typeof item.attrs.space === "string" && item.attrs.space ? item.attrs.space : " ";
1004 const task = schema.nodes.taskItem!.create(
1005 { checked, indent: item.attrs.indent, markerSpace },
1006 item.content,
1007 );
1008 const lists = [
1009 ...(before.length > 0 ? [list.copy(Fragment.from(before))] : []),
1010 schema.nodes.taskList!.create(null, task),
1011 ...(after.length > 0 ? [list.copy(Fragment.from(after))] : []),
1012 ];
1013 const listStart = $pos.before(-2);
1014 tr.replaceWith(listStart, listStart + list.nodeSize, lists);
1015 const caret = listStart + (before.length > 0 ? lists[0]!.nodeSize : 0) + 3;
1016 tr.setSelection(TextSelection.create(tr.doc, caret));
1017}
1018
1019function listItemTypeAt($pos: ResolvedPos): "listItem" | "taskItem" | null {
1020 const name = $pos.depth > 1 ? $pos.node(-1).type.name : null;
1021 return name === "listItem" || name === "taskItem" ? name : null;
1022}
1023
1024/**
1025 * Tiptap's list keymap, which StarterKit loads, does both by moving nodes
1026 * without touching their indent or marker, so the composer turns it off.
1027 */
1028export function backspaceAcrossList(editor: Editor): boolean {
1029 const { state } = editor;
1030 const { $from, empty } = state.selection;
1031 if (!empty || $from.parentOffset !== 0) return false;
1032 const itemType = listItemTypeAt($from);
1033 if (itemType && $from.index(-1) === 0) {
1034 const lift: Command = ({ commands, tr }) => {
1035 const moved = commands.liftListItem(itemType);
1036 if (moved) alignListItemWithSiblings(tr, itemType);
1037 return moved;
1038 };
1039 // Not `can()` first: a dry run of the lift skips the schema check, so it
1040 // says yes to a task under a bullet, which has no list to lift into.
1041 return editor.chain().command(lift).run() || joinBackward(state, editor.view.dispatch);
1042 }
1043 const before = $from.depth === 1 ? $from.node(0).maybeChild($from.index(0) - 1) : null;
1044 if (before && LIST_NODE_NAMES.has(before.type.name) && $from.parent.type.name !== "codeBlock") {
1045 return joinTextblockBackward(state, editor.view.dispatch);
1046 }
1047 return false;
1048}
1049
1050/**
1051 * Tiptap's default would instead nest the next item, or a whole list, under
1052 * this one at its old indent.
1053 */
1054export function deleteAcrossList(editor: Editor): boolean {
1055 const { state } = editor;
1056 const { $from, empty } = state.selection;
1057 if (!empty || !$from.parent.isTextblock || $from.depth === 0) return false;
1058 if ($from.parentOffset !== $from.parent.content.size) return false;
1059 const next = Selection.findFrom(state.doc.resolve($from.after()), 1, true);
1060 if (!next) return false;
1061 if (next.$from.parent.type.name === "codeBlock") return $from.parent.type.name !== "codeBlock";
1062 if (!listItemTypeAt($from) && !listItemTypeAt(next.$from)) return false;
1063 return joinTextblockForward(state, editor.view.dispatch);
1064}
1065
1066function listItemPrefix(item: ProseMirrorNode, empty: boolean): string {
1067 const attrs = item.attrs as Record<string, unknown>;
1068 const indent = typeof attrs.indent === "string" ? attrs.indent : "";
1069 if (item.type.name === "taskItem") {
1070 const markerSpace = typeof attrs.markerSpace === "string" ? attrs.markerSpace : " ";
1071 const contentSpace =
1072 typeof attrs.contentSpace === "string"
1073 ? attrs.contentSpace || (empty ? "" : " ")
1074 : empty
1075 ? ""
1076 : " ";
1077 return `${indent}-${markerSpace}[${attrs.checked === true ? "x" : " "}]${contentSpace}`;
1078 }
1079 const marker = typeof attrs.marker === "string" && attrs.marker ? attrs.marker : "-";
1080 const space =
1081 typeof attrs.space === "string" ? attrs.space || (empty ? "" : " ") : empty ? "" : " ";
1082 return `${indent}${marker}${space}`;
1083}
1084
1085function walkList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator): void {
1086 let itemPos = listStart + 1;
1087 let firstItem = true;
1088 list.content.forEach((item) => {
1089 if (!firstItem) pushBreakRun(acc);
1090 firstItem = false;
1091 const itemContentStart = itemPos + 1;
1092 const first = item.firstChild;
1093 const empty = first?.type.name === "paragraph" && first.content.childCount === 0;
1094 const prefix = listItemPrefix(item, empty);
1095 acc.runs.push({
1096 kind: "prefix",
1097 flatStart: acc.flat,
1098 docLen: 0,
1099 collapsedLen: prefix.length,
1100 mdLen: prefix.length,
1101 openLen: 0,
1102 closeLen: 0,
1103 pmPos: itemContentStart + 1,
1104 mdStart: acc.md,
1105 collapsedStart: acc.collapsed,
1106 });
1107 acc.value += prefix;
1108 acc.collapsed += prefix.length;
1109 acc.md += prefix.length;
1110 let childPos = itemContentStart;
1111 let firstBlock = true;
1112 item.content.forEach((child) => {
1113 if (!firstBlock) pushBreakRun(acc);
1114 firstBlock = false;
1115 if (LIST_NODE_NAMES.has(child.type.name)) {
1116 walkList(child, childPos, acc);
1117 } else if (child.type.name === "paragraph") {
1118 appendInlineRuns(child, childPos + 1, acc);
1119 }
1120 childPos += child.nodeSize;
1121 });
1122 itemPos += item.nodeSize;
1123 });
1124}
1125
1126/**
1127 * The code is literal text in the editor, but the draft store still counts a
1128 * chip's source in it as one cursor position, as it does everywhere. So the
1129 * run splits at each chip source, which spans its characters in the document
1130 * and one position in the collapsed space.
1131 */
1132function appendCodeBlockRun(
1133 block: ProseMirrorNode,
1134 pmPos: number,
1135 followed: boolean,
1136 acc: RichAccumulator,
1137): void {
1138 const { open, content, close } = codeBlockSource(block, followed);
1139 const pieces = content
1140 ? splitPromptIntoComposerSegments(content).map((segment) =>
1141 segment.type === "text"
1142 ? { length: segment.text.length, collapsedLen: segment.text.length }
1143 : { length: segment.source.length, collapsedLen: 1 },
1144 )
1145 : [{ length: 0, collapsedLen: 0 }];
1146 let offset = 0;
1147 pieces.forEach((piece, index) => {
1148 const openLen = index === 0 ? open.length : 0;
1149 const closeLen = index === pieces.length - 1 ? close.length : 0;
1150 const collapsedLen = openLen + piece.collapsedLen + closeLen;
1151 const mdLen = openLen + piece.length + closeLen;
1152 acc.runs.push({
1153 kind: "text",
1154 flatStart: acc.flat,
1155 docLen: piece.length,
1156 collapsedLen,
1157 mdLen,
1158 openLen,
1159 closeLen,
1160 pmPos: pmPos + offset,
1161 mdStart: acc.md,
1162 collapsedStart: acc.collapsed,
1163 nodeName: "codeBlock",
1164 });
1165 offset += piece.length;
1166 acc.flat += piece.length;
1167 acc.collapsed += collapsedLen;
1168 acc.md += mdLen;
1169 });
1170 acc.value += open + content + close;
1171}
1172
1173function walkBlockquote(quote: ProseMirrorNode, quoteStart: number, acc: RichAccumulator): void {
1174 const attrs = quote.attrs as Record<string, unknown>;
1175 const prefix = typeof attrs.prefix === "string" ? attrs.prefix : "> ";
1176 let childPos = quoteStart + 1;
1177 let firstLine = true;
1178 quote.content.forEach((child) => {
1179 if (!firstLine) pushBreakRun(acc);
1180 firstLine = false;
1181 acc.runs.push({
1182 kind: "prefix",
1183 flatStart: acc.flat,
1184 docLen: 0,
1185 collapsedLen: prefix.length,
1186 mdLen: prefix.length,
1187 openLen: 0,
1188 closeLen: 0,
1189 pmPos: childPos + 1,
1190 mdStart: acc.md,
1191 collapsedStart: acc.collapsed,
1192 });
1193 acc.value += prefix;
1194 acc.collapsed += prefix.length;
1195 acc.md += prefix.length;
1196 if (child.type.name === "paragraph") appendInlineRuns(child, childPos + 1, acc);
1197 childPos += child.nodeSize;
1198 });
1199}
1200
1201/**
1202 * A slice holds only the content of the blocks the ends share, so items or
1203 * quote lines arrive without the list or quote that writes their markers.
1204 */
1205export function serializeSelection(doc: ProseMirrorNode, from: number, to: number): string {
1206 const slice = doc.slice(from, to);
1207 const $from = doc.resolve(from);
1208 let depth = $from.sharedDepth(to);
1209 let content: Fragment | ProseMirrorNode = slice.content;
1210 if (slice.content.firstChild?.isInline) {
1211 content = doc.type.schema.nodes.paragraph!.create(null, slice.content);
1212 } else {
1213 while (depth > 0) {
1214 const shared = $from.node(depth);
1215 content = shared.copy(Fragment.from(content));
1216 if (!LIST_ITEM_NODE_NAMES.has(shared.type.name)) break;
1217 depth -= 1;
1218 }
1219 }
1220 return serializeEditorDoc(doc.type.create(null, content)).value;
1221}
1222
1223export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {
1224 const acc: RichAccumulator = { runs: [], value: "", flat: 0, collapsed: 0, md: 0 };
1225 const blocks: ProseMirrorNode[] = [];
1226 doc.content.forEach((node) => {
1227 blocks.push(node);
1228 });
1229
1230 let pmBlockStart = 0;
1231 blocks.forEach((block, blockIndex) => {
1232 if (blockIndex > 0 && !isTrailingLineAfterRule(doc, blockIndex)) pushBreakRun(acc);
1233 if (blockIndex > 0 && needsBlankLineAfterQuote(blocks[blockIndex - 1]!, block)) {
1234 pushBlankLineRun(acc, pmBlockStart + 1);
1235 }
1236 if (LIST_NODE_NAMES.has(block.type.name)) {
1237 walkList(block, pmBlockStart, acc);
1238 } else if (block.type.name === "codeBlock") {
1239 appendCodeBlockRun(block, pmBlockStart + 1, blockIndex < blocks.length - 1, acc);
1240 } else if (block.type.name === "blockquote") {
1241 walkBlockquote(block, pmBlockStart, acc);
1242 } else if (block.type.name === "heading") {
1243 const attrs = block.attrs as Record<string, unknown>;
1244 const level = typeof attrs.level === "number" ? attrs.level : 1;
1245 const space = typeof attrs.space === "string" ? attrs.space : " ";
1246 const prefix = `${"#".repeat(level)}${space}`;
1247 acc.runs.push({
1248 kind: "prefix",
1249 flatStart: acc.flat,
1250 docLen: 0,
1251 collapsedLen: prefix.length,
1252 mdLen: prefix.length,
1253 openLen: 0,
1254 closeLen: 0,
1255 pmPos: pmBlockStart + 1,
1256 mdStart: acc.md,
1257 collapsedStart: acc.collapsed,
1258 });
1259 acc.value += prefix;
1260 acc.collapsed += prefix.length;
1261 acc.md += prefix.length;
1262 appendInlineRuns(block, pmBlockStart + 1, acc);
1263 } else if (block.type.name === "horizontalRule") {
1264 const attrs = block.attrs as Record<string, unknown>;
1265 const source = typeof attrs.source === "string" && attrs.source ? attrs.source : "---";
1266 acc.runs.push({
1267 kind: "prefix",
1268 flatStart: acc.flat,
1269 docLen: 0,
1270 collapsedLen: source.length,
1271 mdLen: source.length,
1272 openLen: 0,
1273 closeLen: 0,
1274 pmPos: pmBlockStart + block.nodeSize,
1275 mdStart: acc.md,
1276 collapsedStart: acc.collapsed,
1277 });
1278 acc.value += source;
1279 acc.collapsed += source.length;
1280 acc.md += source.length;
1281 } else if (block.type.name === "paragraph") {
1282 appendInlineRuns(block, pmBlockStart + 1, acc);
1283 }
1284 pmBlockStart += block.nodeSize;
1285 });
1286
1287 return {
1288 value: acc.value,
1289 runs: acc.runs,
1290 docLength: acc.flat,
1291 contextIds: Array.from(new Set(collectInlineContextIds(acc.value))),
1292 };
1293}
1294
1295function lastRunEnd(map: RichDocMap, space: "collapsed" | "md"): number {
1296 const last = map.runs[map.runs.length - 1];
1297 if (!last) return 0;
1298 return space === "collapsed"
1299 ? last.collapsedStart + last.collapsedLen
1300 : last.mdStart + last.mdLen;
1301}
1302
1303/**
1304 * The end of a run belongs to the next run, which is how the end of `**bold**`
1305 * lands after its markers. A fence is the exception: its close is a line of its
1306 * own, so the end of the code stays inside the block rather than jumping past
1307 * the closing fence.
1308 */
1309function runOwnsOffset(run: RichRun, flatOffset: number): boolean {
1310 const end = run.flatStart + run.docLen;
1311 return flatOffset < end || (flatOffset === end && run.nodeName === "codeBlock");
1312}
1313
1314export function flatToCollapsed(map: RichDocMap, flatOffset: number): number {
1315 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
1316 for (const run of map.runs) {
1317 if (runOwnsOffset(run, bounded)) {
1318 if (run.kind === "text" || run.kind === "token") {
1319 const within = Math.min(
1320 bounded - run.flatStart,
1321 run.collapsedLen - run.openLen - run.closeLen,
1322 );
1323 return run.collapsedStart + run.openLen + within;
1324 }
1325 return run.collapsedStart + (bounded - run.flatStart);
1326 }
1327 }
1328 return lastRunEnd(map, "collapsed");
1329}
1330
1331export function flatToMarkdown(map: RichDocMap, flatOffset: number): number {
1332 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
1333 for (const run of map.runs) {
1334 if (runOwnsOffset(run, bounded)) {
1335 if (run.kind === "text" || run.kind === "token") {
1336 return run.mdStart + run.openLen + (bounded - run.flatStart);
1337 }
1338 return run.mdStart + (bounded - run.flatStart);
1339 }
1340 }
1341 return lastRunEnd(map, "md");
1342}
1343
1344export function collapsedToFlat(map: RichDocMap, collapsedOffset: number): number {
1345 for (const run of map.runs) {
1346 if (collapsedOffset < run.collapsedStart + run.collapsedLen) {
1347 if (run.kind === "prefix") return run.flatStart;
1348 if (run.kind === "text" || run.kind === "token") {
1349 const within = collapsedOffset - run.collapsedStart;
1350 const contentLen = run.collapsedLen - run.openLen - run.closeLen;
1351 if (within <= run.openLen) return run.flatStart;
1352 if (within >= run.openLen + contentLen) return run.flatStart + run.docLen;
1353 return run.flatStart + (within - run.openLen);
1354 }
1355 return run.flatStart + (collapsedOffset - run.collapsedStart);
1356 }
1357 }
1358 return map.docLength;
1359}
1360
1361export function flatToPm(map: RichDocMap, flatOffset: number): number {
1362 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
1363 for (const run of map.runs) {
1364 if (bounded < run.flatStart + run.docLen) {
1365 return run.pmPos + (bounded - run.flatStart);
1366 }
1367 }
1368 const last = map.runs[map.runs.length - 1];
1369 if (!last) return 1;
1370 return last.pmPos + last.docLen;
1371}
1372
1373export function pmToFlat(map: RichDocMap, pmPos: number): number {
1374 for (const run of map.runs) {
1375 if (pmPos >= run.pmPos && pmPos <= run.pmPos + run.docLen) {
1376 if (run.kind === "token" && pmPos === run.pmPos + run.docLen) {
1377 return run.flatStart + run.docLen;
1378 }
1379 return run.flatStart + Math.min(pmPos - run.pmPos, run.docLen);
1380 }
1381 }
1382 let best = 0;
1383 for (const run of map.runs) {
1384 if (run.pmPos <= pmPos) best = run.flatStart + run.docLen;
1385 }
1386 return Math.max(0, Math.min(best, map.docLength));
1387}
1388
1389// Markers are decorations, not text, so the position where styled text meets
1390// unstyled text (or a paragraph edge) is a single document position. The caret
1391// gets two stops there: one that types with the marks before the edge and one
1392// that types with the marks after it.
1393
1394function styledEdge(state: EditorState) {
1395 const { selection } = state;
1396 if (!selection.empty) return null;
1397 const { $from } = selection;
1398 if (!$from.parent.inlineContent) return null;
1399 const before = $from.nodeBefore?.marks ?? Mark.none;
1400 const after = $from.nodeAfter?.marks ?? Mark.none;
1401 if (Mark.sameSet(before, after)) return null;
1402 return { before, after, current: state.storedMarks ?? $from.marks() };
1403}
1404
1405export function caretTakesMarksBefore(state: EditorState): boolean {
1406 const edge = styledEdge(state);
1407 return edge !== null && Mark.sameSet(edge.current, edge.before);
1408}
1409
1410/**
1411 * Returns null when there is no stop to take, so the arrow key moves the caret
1412 * as usual.
1413 */
1414export function stepCaretAcrossStyledEdge(
1415 state: EditorState,
1416 direction: -1 | 1,
1417): Transaction | null {
1418 const edge = styledEdge(state);
1419 if (!edge) return null;
1420 if (!Mark.sameSet(edge.current, edge.before) && !Mark.sameSet(edge.current, edge.after)) {
1421 return null;
1422 }
1423 const target = direction === -1 ? edge.before : edge.after;
1424 if (Mark.sameSet(edge.current, target)) return null;
1425 return state.tr.setStoredMarks(target);
1426}