Open History to see the last commit
1import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
2import { TaskItem } from "@tiptap/extension-task-item";
3
4import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
5import { parseInlineMarkdown, RICH_TEXT_DELIMITERS, type RichTextMark } from "~/composer-rich-text";
6import { collectInlineContextIds } from "~/lib/composerContextReferences";
7
8/**
9 * Pure document model for the rich text (Tiptap) composer.
10 *
11 * The stored prompt stays markdown (`**bold**`, `@file` chips as canonical
12 * links). The Tiptap document holds styled text plus inline atom chips, so
13 * this module translates both ways and maps cursor offsets between the three
14 * coordinate spaces the composer speaks:
15 *
16 * - flat document offsets (styled markers excluded, chips count 1),
17 * - collapsed cursor offsets (markers literal, chips count 1 — the coordinate
18 * the draft store and mention detection use),
19 * - markdown offsets (markers literal, chips expand to their source).
20 *
21 * DOM-free on purpose: unit tests build a real ProseMirror document from the
22 * JSON this produces and assert the round trip without a browser.
23 */
24
25export type SkillMeta = { label: string; description: string | null };
26
27/** Outermost mark first, so closers mirror openers when nested. */
28const MARK_NESTING_ORDER: RichTextMark[] = ["strike", "bold", "italic", "code"];
29
30const MARK_TO_TIPTAP: Record<RichTextMark, string> = {
31 bold: "bold",
32 italic: "italic",
33 strike: "strike",
34 code: "code",
35};
36
37const TIPTAP_TO_MARK: Record<string, RichTextMark> = {
38 bold: "bold",
39 italic: "italic",
40 strike: "strike",
41 code: "code",
42};
43
44/**
45 * Task list items keep their exact source indent in an attribute so nesting
46 * round-trips byte-identically. Checkbox case (`[X]`) normalizes to `[x]` —
47 * the same fixed-point deal as `__bold__` becoming `**bold**`.
48 */
49export const ComposerTaskItemExtension = TaskItem.extend({
50 addAttributes() {
51 return {
52 ...this.parent?.(),
53 indent: { default: "" },
54 markerSpace: { default: " " },
55 contentSpace: { default: null },
56 };
57 },
58}).configure({ nested: true });
59
60function randomNodeKey(): string {
61 return `tiptap-${Math.random().toString(36).slice(2)}`;
62}
63
64interface TaskLinePrefix {
65 indent: string;
66 checked: boolean;
67 markerSpace: string;
68 contentSpace: string;
69}
70
71function parseTaskPrefix(head: string): { prefix: TaskLinePrefix; markerLength: number } | null {
72 const match = head.match(/^([ \t]*)-([ \t]+)\[([ xX])\]([ \t]*)/);
73 if (!match) return null;
74 const after = head.slice(match[0].length);
75 if (after.length > 0 && !match[4]) return null;
76 return {
77 prefix: {
78 indent: match[1] ?? "",
79 checked: (match[3] ?? " ").toLowerCase() === "x",
80 markerSpace: match[2]!,
81 contentSpace: match[4]!,
82 },
83 markerLength: match[0].length,
84 };
85}
86
87type InlineJson = Record<string, unknown>;
88
89interface DocLine {
90 task: TaskLinePrefix | null;
91 inline: InlineJson[];
92}
93
94function atomJsonForSegment(
95 segment: Exclude<ReturnType<typeof splitPromptIntoComposerSegments>[number], { type: "text" }>,
96 skillLabelFor: (name: string) => SkillMeta,
97): InlineJson {
98 if (segment.type === "mention") {
99 return {
100 type: "composer-mention",
101 attrs: { path: segment.path, source: segment.source },
102 };
103 }
104 if (segment.type === "skill") {
105 const meta = skillLabelFor(segment.name);
106 return {
107 type: "composer-skill",
108 attrs: {
109 skillName: segment.name,
110 skillLabel: meta.label,
111 skillDescription: meta.description,
112 },
113 };
114 }
115 if (segment.type === "citation") {
116 return {
117 type: "composer-citation",
118 attrs: { citation: segment.citation, source: segment.source, citeKey: randomNodeKey() },
119 };
120 }
121 return {
122 type: "composer-context-reference",
123 attrs: {
124 kind: segment.kind,
125 contextId: segment.contextId,
126 label: segment.label,
127 source: segment.source,
128 },
129 };
130}
131
132interface PendingTaskItem extends TaskLinePrefix {
133 content: InlineJson[];
134 children: PendingTaskItem[];
135}
136
137function taskListJson(items: PendingTaskItem[]): InlineJson {
138 return {
139 type: "taskList",
140 content: items.map((item) => ({
141 type: "taskItem",
142 attrs: {
143 checked: item.checked,
144 indent: item.indent,
145 markerSpace: item.markerSpace,
146 contentSpace: item.contentSpace,
147 },
148 content: [
149 { type: "paragraph", content: item.content },
150 ...(item.children.length > 0 ? [taskListJson(item.children)] : []),
151 ],
152 })),
153 };
154}
155
156function textJsonForSpan(text: string, marks: RichTextMark[]): Record<string, unknown> {
157 const json: Record<string, unknown> = { type: "text", text };
158 if (marks.length > 0) {
159 json.marks = [...marks]
160 .sort((a, b) => MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b))
161 .map((mark) => ({ type: MARK_TO_TIPTAP[mark] }));
162 }
163 return json;
164}
165
166export function buildTiptapContent(
167 value: string,
168 skillLabelFor: (name: string) => SkillMeta,
169 options?: { styling?: boolean },
170): Record<string, unknown>[] {
171 const styling = options?.styling ?? true;
172 // Hide token source from the markdown parser, then restore the atoms with
173 // the marks of their surrounding text. Choose a sentinel absent from input.
174 let sentinel = "\uFFFC";
175 for (let codePoint = 0xe000; value.includes(sentinel); codePoint += 1) {
176 sentinel = String.fromCodePoint(codePoint);
177 }
178 const atoms: InlineJson[] = [];
179 const text = splitPromptIntoComposerSegments(value)
180 .map((segment) => {
181 if (segment.type === "text") return segment.text;
182 atoms.push(atomJsonForSegment(segment, skillLabelFor));
183 return sentinel;
184 })
185 .join("");
186 let atomIndex = 0;
187 const lines: DocLine[] = text.split("\n").map((line) => {
188 const parsed = styling ? parseTaskPrefix(line) : null;
189 const content = parsed ? line.slice(parsed.markerLength) : line;
190 const spans = styling ? parseInlineMarkdown(content) : [{ text: content, marks: [] }];
191 const inline: InlineJson[] = [];
192 for (const span of spans) {
193 span.text.split(sentinel).forEach((piece, index) => {
194 if (index > 0) {
195 const atom = atoms[atomIndex++]!;
196 inline.push({ ...atom, marks: textJsonForSpan("", span.marks).marks });
197 }
198 if (piece) inline.push(textJsonForSpan(piece, span.marks));
199 });
200 }
201 return { task: parsed?.prefix ?? null, inline };
202 });
203
204 // Pass 2: consecutive task lines group into (possibly nested) task lists
205 // by indent prefix; everything else stays a paragraph.
206 const blocks: Record<string, unknown>[] = [];
207 let stack: { indent: string; items: PendingTaskItem[] }[] = [];
208 const flushTasks = () => {
209 if (stack.length > 0) {
210 blocks.push(taskListJson(stack[0]!.items));
211 stack = [];
212 }
213 };
214 for (const line of lines) {
215 if (!line.task) {
216 flushTasks();
217 blocks.push({ type: "paragraph", content: line.inline });
218 continue;
219 }
220 const item: PendingTaskItem = {
221 ...line.task,
222 content: line.inline,
223 children: [],
224 };
225 for (;;) {
226 const top = stack[stack.length - 1];
227 if (!top) {
228 // A leading indented item with no parent flattens but keeps indent.
229 stack.push({ indent: item.indent, items: [] });
230 continue;
231 }
232 if (top.indent === item.indent) {
233 top.items.push(item);
234 break;
235 }
236 if (top.indent !== "" && !item.indent.startsWith(top.indent)) {
237 if (stack.length > 1) {
238 stack.pop();
239 continue;
240 }
241 top.indent = item.indent;
242 top.items.push(item);
243 break;
244 }
245 const parent = top.items[top.items.length - 1];
246 if (!parent) {
247 top.items.push(item);
248 break;
249 }
250 parent.children.push(item);
251 stack.push({ indent: item.indent, items: parent.children });
252 break;
253 }
254 }
255 flushTasks();
256 return blocks;
257}
258
259export function buildDocJson(
260 value: string,
261 skillLabelFor: (name: string) => SkillMeta,
262 options?: { styling?: boolean },
263) {
264 return { type: "doc", content: buildTiptapContent(value, skillLabelFor, options) };
265}
266
267export interface RichRun {
268 kind: "text" | "token" | "break" | "prefix";
269 /** Flat document offset (atoms count 1, markers excluded). */
270 flatStart: number;
271 docLen: number;
272 /** Collapsed cursor length (markers literal, tokens count 1). */
273 collapsedLen: number;
274 /** Markdown length (tokens expand to their source). */
275 mdLen: number;
276 /** Marker layout inside text runs. */
277 openLen: number;
278 closeLen: number;
279 /** ProseMirror position of the run start. */
280 pmPos: number;
281 mdStart: number;
282 collapsedStart: number;
283 nodeName?: string;
284}
285
286export interface RichDocMap {
287 value: string;
288 runs: RichRun[];
289 docLength: number;
290 contextIds: string[];
291}
292
293function readAtomSource(node: ProseMirrorNode): string {
294 const attrs = node.attrs as Record<string, unknown>;
295 switch (node.type.name) {
296 case "composer-mention":
297 case "composer-citation":
298 case "composer-context-reference":
299 return typeof attrs.source === "string" ? attrs.source : "";
300 case "composer-skill": {
301 const name = typeof attrs.skillName === "string" ? attrs.skillName : "";
302 return name ? `$${name}` : "";
303 }
304 default:
305 return "";
306 }
307}
308
309interface RichAccumulator {
310 runs: RichRun[];
311 value: string;
312 flat: number;
313 collapsed: number;
314 md: number;
315}
316
317function pushBreakRun(acc: RichAccumulator, position?: number): void {
318 const previous = acc.runs[acc.runs.length - 1];
319 const pmPos = position ?? (previous ? previous.pmPos + previous.docLen : 1);
320 // Block boundary: one newline in every coordinate space.
321 acc.runs.push({
322 kind: "break",
323 flatStart: acc.flat,
324 docLen: 1,
325 collapsedLen: 1,
326 mdLen: 1,
327 openLen: 0,
328 closeLen: 0,
329 pmPos,
330 mdStart: acc.md,
331 collapsedStart: acc.collapsed,
332 });
333 acc.value += "\n";
334 acc.flat += 1;
335 acc.collapsed += 1;
336 acc.md += 1;
337}
338
339function appendInlineRuns(
340 container: ProseMirrorNode,
341 contentStart: number,
342 acc: RichAccumulator,
343): void {
344 const children: ProseMirrorNode[] = [];
345 container.forEach((child) => {
346 if (!child.isText || child.marks.some((mark) => mark.type.name === "code")) {
347 children.push(child);
348 return;
349 }
350 // Separate boundary whitespace so delimiters can move past it without
351 // changing the document offsets or marks on the visible text.
352 const text = child.text!;
353 const start = text.length - text.trimStart().length;
354 const end = Math.max(start, text.trimEnd().length);
355 let offset = 0;
356 for (const boundary of [start, end, text.length]) {
357 if (boundary > offset) children.push(child.cut(offset, boundary));
358 offset = boundary;
359 }
360 });
361 // Emphasis cannot open or close next to whitespace. Retain a whitespace
362 // mark only when its range has visible content on both sides.
363 for (const mark of MARK_NESTING_ORDER) {
364 if (mark === "code") continue;
365 for (const direction of [1, -1]) {
366 let hasContent = false;
367 for (
368 let index = direction === 1 ? 0 : children.length - 1;
369 index >= 0 && index < children.length;
370 index += direction
371 ) {
372 const child = children[index]!;
373 if (
374 child.type.name === "hardBreak" ||
375 !child.marks.some((item) => item.type.name === mark)
376 ) {
377 hasContent = false;
378 } else if (
379 child.isText &&
380 !child.marks.some((item) => item.type.name === "code") &&
381 /^\s+$/.test(child.text!)
382 ) {
383 if (!hasContent)
384 children[index] = child.mark(child.marks.filter((item) => item.type.name !== mark));
385 } else {
386 hasContent = true;
387 }
388 }
389 }
390 }
391 // Longer shared marks surround shorter ones. This keeps both nested
392 // formatting and formatting across chips inside a single delimiter pair.
393 const markEnds = new Map<RichTextMark, number>();
394 const orderedMarks: RichTextMark[][] = [];
395 for (let index = children.length - 1; index >= 0; index -= 1) {
396 const child = children[index]!;
397 const marks =
398 child.type.name === "hardBreak"
399 ? []
400 : child.marks
401 .map((mark) => TIPTAP_TO_MARK[mark.type.name])
402 .filter((mark): mark is RichTextMark => Boolean(mark));
403 for (const mark of MARK_NESTING_ORDER) {
404 if (!marks.includes(mark)) markEnds.delete(mark);
405 else if (!markEnds.has(mark)) markEnds.set(mark, index);
406 }
407 orderedMarks[index] = marks.sort(
408 (a, b) =>
409 markEnds.get(b)! - markEnds.get(a)! ||
410 MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b),
411 );
412 }
413 for (let index = 1; index < orderedMarks.length; index += 1) {
414 const marks = orderedMarks[index]!;
415 const retained: RichTextMark[] = [];
416 for (const mark of orderedMarks[index - 1]!) {
417 if (!marks.includes(mark)) break;
418 retained.push(mark);
419 }
420 orderedMarks[index] = [...retained, ...marks.filter((mark) => !retained.includes(mark))];
421 }
422 const commonLength = (left: RichTextMark[], right: RichTextMark[]) => {
423 let index = 0;
424 while (index < left.length && left[index] === right[index]) index += 1;
425 return index;
426 };
427 let inlineOffset = 0;
428 children.forEach((child, index) => {
429 const pmPos = contentStart + inlineOffset;
430 inlineOffset += child.nodeSize;
431 if (child.type.name === "hardBreak") {
432 pushBreakRun(acc, pmPos);
433 return;
434 }
435 const marks = orderedMarks[index]!;
436 const open = marks
437 .slice(commonLength(marks, orderedMarks[index - 1] ?? []))
438 .map((mark) => RICH_TEXT_DELIMITERS[mark])
439 .join("");
440 const close = marks
441 .slice(commonLength(marks, orderedMarks[index + 1] ?? []))
442 .toReversed()
443 .map((mark) => RICH_TEXT_DELIMITERS[mark])
444 .join("");
445 const source = child.isText ? child.text! : readAtomSource(child);
446 const docLen = child.isText ? source.length : 1;
447 const mdText = open + source + close;
448 const collapsedLen = open.length + docLen + close.length;
449 acc.runs.push({
450 kind: child.isText ? "text" : "token",
451 flatStart: acc.flat,
452 docLen,
453 collapsedLen,
454 mdLen: mdText.length,
455 openLen: open.length,
456 closeLen: close.length,
457 pmPos,
458 mdStart: acc.md,
459 collapsedStart: acc.collapsed,
460 ...(child.isText ? {} : { nodeName: child.type.name }),
461 });
462 acc.value += mdText;
463 acc.flat += docLen;
464 acc.collapsed += collapsedLen;
465 acc.md += mdText.length;
466 });
467 // Empty paragraphs have an editable position even though they emit no text.
468 if (children.length === 0) {
469 acc.runs.push({
470 kind: "text",
471 flatStart: acc.flat,
472 docLen: 0,
473 collapsedLen: 0,
474 mdLen: 0,
475 openLen: 0,
476 closeLen: 0,
477 pmPos: contentStart,
478 mdStart: acc.md,
479 collapsedStart: acc.collapsed,
480 });
481 }
482}
483
484function walkTaskList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator): void {
485 let itemPos = listStart + 1;
486 let firstItem = true;
487 list.content.forEach((item) => {
488 // Sibling items are separated by one newline in every coordinate space.
489 if (!firstItem) pushBreakRun(acc);
490 firstItem = false;
491 const itemContentStart = itemPos + 1;
492 const first = item.firstChild;
493 const empty = first?.type.name === "paragraph" && first.content.childCount === 0;
494 const attrs = item.attrs as Record<string, unknown>;
495 const indent = typeof attrs.indent === "string" ? attrs.indent : "";
496 const markerSpace = typeof attrs.markerSpace === "string" ? attrs.markerSpace : " ";
497 const contentSpace =
498 typeof attrs.contentSpace === "string"
499 ? attrs.contentSpace || (empty ? "" : " ")
500 : empty
501 ? ""
502 : " ";
503 const prefix = `${indent}-${markerSpace}[${attrs.checked === true ? "x" : " "}]${contentSpace}`;
504 // The checkbox owns no document characters; every prefix offset clamps
505 // to the start of the item text, exactly like style markers.
506 acc.runs.push({
507 kind: "prefix",
508 flatStart: acc.flat,
509 docLen: 0,
510 collapsedLen: prefix.length,
511 mdLen: prefix.length,
512 openLen: 0,
513 closeLen: 0,
514 pmPos: itemContentStart + 1,
515 mdStart: acc.md,
516 collapsedStart: acc.collapsed,
517 });
518 acc.value += prefix;
519 acc.collapsed += prefix.length;
520 acc.md += prefix.length;
521 let childPos = itemContentStart;
522 let firstBlock = true;
523 item.content.forEach((child) => {
524 if (!firstBlock) pushBreakRun(acc);
525 firstBlock = false;
526 if (child.type.name === "taskList") {
527 walkTaskList(child, childPos, acc);
528 } else if (child.type.name === "paragraph") {
529 appendInlineRuns(child, childPos + 1, acc);
530 }
531 childPos += child.nodeSize;
532 });
533 itemPos += item.nodeSize;
534 });
535}
536
537export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {
538 const acc: RichAccumulator = { runs: [], value: "", flat: 0, collapsed: 0, md: 0 };
539 const blocks: ProseMirrorNode[] = [];
540 doc.content.forEach((node) => {
541 blocks.push(node);
542 });
543
544 let pmBlockStart = 0;
545 blocks.forEach((block, blockIndex) => {
546 if (blockIndex > 0) pushBreakRun(acc);
547 if (block.type.name === "taskList") {
548 walkTaskList(block, pmBlockStart, acc);
549 } else if (block.type.name === "paragraph") {
550 appendInlineRuns(block, pmBlockStart + 1, acc);
551 }
552 pmBlockStart += block.nodeSize;
553 });
554
555 return {
556 value: acc.value,
557 runs: acc.runs,
558 docLength: acc.flat,
559 contextIds: Array.from(new Set(collectInlineContextIds(acc.value))),
560 };
561}
562
563function lastRunEnd(map: RichDocMap, space: "collapsed" | "md"): number {
564 const last = map.runs[map.runs.length - 1];
565 if (!last) return 0;
566 return space === "collapsed"
567 ? last.collapsedStart + last.collapsedLen
568 : last.mdStart + last.mdLen;
569}
570
571export function flatToCollapsed(map: RichDocMap, flatOffset: number): number {
572 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
573 for (const run of map.runs) {
574 if (bounded < run.flatStart + run.docLen) {
575 if (run.kind === "text" || run.kind === "token") {
576 return run.collapsedStart + run.openLen + (bounded - run.flatStart);
577 }
578 return run.collapsedStart + (bounded - run.flatStart);
579 }
580 }
581 return lastRunEnd(map, "collapsed");
582}
583
584export function flatToMarkdown(map: RichDocMap, flatOffset: number): number {
585 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
586 for (const run of map.runs) {
587 if (bounded < run.flatStart + run.docLen) {
588 if (run.kind === "text" || run.kind === "token") {
589 return run.mdStart + run.openLen + (bounded - run.flatStart);
590 }
591 return run.mdStart + (bounded - run.flatStart);
592 }
593 }
594 return lastRunEnd(map, "md");
595}
596
597export function collapsedToFlat(map: RichDocMap, collapsedOffset: number): number {
598 for (const run of map.runs) {
599 if (collapsedOffset < run.collapsedStart + run.collapsedLen) {
600 // Checkbox prefixes and style markers are shown, never edited: every
601 // offset inside them clamps to the adjacent document position.
602 if (run.kind === "prefix") return run.flatStart;
603 if (run.kind === "text" || run.kind === "token") {
604 const within = collapsedOffset - run.collapsedStart;
605 // Marker characters clamp to the styled edge: they are shown, never edited.
606 if (within <= run.openLen) return run.flatStart;
607 if (within >= run.openLen + run.docLen) return run.flatStart + run.docLen;
608 return run.flatStart + (within - run.openLen);
609 }
610 return run.flatStart + (collapsedOffset - run.collapsedStart);
611 }
612 }
613 return map.docLength;
614}
615
616export function flatToPm(map: RichDocMap, flatOffset: number): number {
617 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
618 for (const run of map.runs) {
619 if (bounded < run.flatStart + run.docLen) {
620 return run.pmPos + (bounded - run.flatStart);
621 }
622 }
623 const last = map.runs[map.runs.length - 1];
624 if (!last) return 1;
625 return last.pmPos + last.docLen;
626}
627
628export function pmToFlat(map: RichDocMap, pmPos: number): number {
629 for (const run of map.runs) {
630 if (pmPos >= run.pmPos && pmPos <= run.pmPos + run.docLen) {
631 // A position on a chip's trailing edge belongs after the chip.
632 if (run.kind === "token" && pmPos === run.pmPos + run.docLen) {
633 return run.flatStart + run.docLen;
634 }
635 return run.flatStart + Math.min(pmPos - run.pmPos, run.docLen);
636 }
637 }
638 // A paragraph boundary position belongs to the newline between paragraphs.
639 let best = 0;
640 for (const run of map.runs) {
641 if (run.pmPos <= pmPos) best = run.flatStart + run.docLen;
642 }
643 return Math.max(0, Math.min(best, map.docLength));
644}