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

composer-rich-text.ts

131 lines4.4 KB

1/**
2 * Inline markdown styling for the rich text composer.
3 *
4 * The composer's stored prompt stays plain markdown (`**bold**`), while the
5 * Tiptap surface renders styled text. These helpers translate between the two:
6 * parsing markdown into marked spans for the document, serializing marked
7 * spans back to markdown in the document serializer.
8 *
9 * Deliberately small: bold, italic, strikethrough, and inline code only.
10 * Unmatched markers stay literal text so nothing the user typed is ever lost.
11 */
12​
13export type RichTextMark = "bold" | "italic" | "strike" | "code";
14​
15interface RichTextSpan {
16 text: string;
17 marks: RichTextMark[];
19​
20export const RICH_TEXT_DELIMITERS: Record<RichTextMark, string> = {
21 bold: "**",
22 italic: "*",
23 strike: "~~",
24 code: "`",
25};
26​
27function pushSpan(spans: RichTextSpan[], text: string, marks: RichTextMark[]): void {
28 if (!text) return;
29 const last = spans[spans.length - 1];
30 if (
31 last &&
32 last.marks.length === marks.length &&
33 last.marks.every((mark, index) => mark === marks[index])
34 ) {
35 last.text += text;
36 } else {
37 spans.push({ text, marks });
38 }
40​
41/** Parse the supported inline styles, leaving unmatched and escaped markers literal. */
42export function parseInlineMarkdown(text: string): RichTextSpan[] {
43 const root: RichTextSpan[] = [];
44 const stack: { delimiter: string; mark: RichTextMark; spans: RichTextSpan[] }[] = [];
45 const current = () => stack.at(-1)?.spans ?? root;
46 let index = 0;
47 while (index < text.length) {
48 const char = text[index]!;
49 if (char === "\\") {
50 pushSpan(current(), text.slice(index, index + 2), []);
51 index += 2;
52 continue;
53 }
54 if (char === "`") {
55 // Multi-backtick code stays literal; a single-backtick span owns its contents.
56 const run = text.slice(index).match(/^`+/)![0];
57 const close = text.indexOf(run, index + run.length);
58 if (
59 run.length === 1 &&
60 close > index + 1 &&
61 !text.slice(index, close).includes("\n") &&
62 text[close + 1] !== "`"
63 ) {
64 pushSpan(current(), text.slice(index + 1, close), ["code"]);
65 index = close + 1;
66 } else {
67 pushSpan(current(), run, []);
68 index += run.length;
69 }
70 continue;
71 }
72 if (char !== "*" && char !== "_" && char !== "~") {
73 pushSpan(current(), char, []);
74 index += 1;
75 continue;
76 }
77 let end = index;
78 while (text[end] === char) end += 1;
79 const before = text[index - 1] ?? "";
80 const after = text[end] ?? "";
81 const canClose = before !== "" && !/\s/.test(before) && (char !== "_" || !/\w/.test(after));
82 const canOpen = after !== "" && !/\s/.test(after) && (char !== "_" || !/\w/.test(before));
83 while (index < end) {
84 const top = stack.at(-1);
85 // Inside italic, a double marker opens bold before closing the single
86 // marker. Once bold is active, closing runs unwind both styles.
87 const opensNestedBold =
88 top?.mark === "italic" &&
89 end - index === 2 &&
90 canOpen &&
91 (char === "*" || char === "_") &&
92 !stack.some((frame) => frame.mark === "bold");
93 if (
94 !opensNestedBold &&
95 canClose &&
96 top &&
97 text.startsWith(top.delimiter, index) &&
98 index + top.delimiter.length <= end
99 ) {
100 stack.pop();
101 for (const span of top.spans) pushSpan(current(), span.text, [top.mark, ...span.marks]);
102 index += top.delimiter.length;
103 } else if (canOpen && (char !== "~" || end - index >= 2)) {
104 const length = char === "~" || end - index >= 2 ? 2 : 1;
105 const mark = char === "~" ? "strike" : length === 2 ? "bold" : "italic";
106 // A mark cannot nest inside itself, including alternate delimiters.
107 // This bounds the stack to the supported styles for arbitrary input.
108 if (stack.some((frame) => frame.mark === mark)) {
109 pushSpan(current(), text.slice(index, end), []);
110 index = end;
111 continue;
112 }
113 stack.push({
114 delimiter: char.repeat(length),
115 mark,
116 spans: [],
117 });
118 index += length;
119 } else {
120 pushSpan(current(), text.slice(index, end), []);
121 index = end;
122 }
123 }
124 }
125 while (stack.length > 0) {
126 const frame = stack.pop()!;
127 pushSpan(current(), frame.delimiter, []);
128 for (const span of frame.spans) pushSpan(current(), span.text, span.marks);
129 }
130 return root;