Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composer-rich-text-doc.ts

652 lines20.7 KB

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