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

composer-rich-text.ts

189 lines6.7 KB

1export type RichTextMark = "bold" | "italic" | "strike" | "code";
2​
3interface RichTextSpan {
4 text: string;
5 marks: RichTextMark[];
6}
7​
8export const RICH_TEXT_DELIMITERS: Record<RichTextMark, string> = {
9 bold: "**",
10 italic: "*",
11 strike: "~~",
12 code: "`",
13};
14​
15/** A run of `text` from `start` to `end` that parses with `marks`. */
16interface SourcePiece {
17 start: number;
18 end: number;
19 marks: RichTextMark[];
21​
22function sameMarks(left: readonly RichTextMark[], right: readonly RichTextMark[]): boolean {
23 return left.length === right.length && left.every((mark, index) => mark === right[index]);
25​
26// Brackets, quotes, commas, and Markdown delimiters end a URL or path token; a lone `~` does not.
27const PATH_TOKEN = /(?:[\p{L}\p{N}_/.:@%+=&?#-]|(?<!~)~(?!~))+/gu;
28const FILE_EXTENSION = /^\.[a-z][a-z0-9]*(?::\d+){0,2}$/i;
29// `_yes_/_no_`: each side of a slash is its own emphasis span, so the word is not a path.
30const EMPHASIS_ALTERNATIVES = /^_[^/]+_(?:\/_[^/]+_)+$/;
31​
32/**
33 * Starts of underscore runs that belong to a URL, path, or filename, not to emphasis.
34 * A run ending the token stays a delimiter so emphasis wrapped around the token still closes.
35 */
36function literalUnderscoreRuns(text: string): Set<number> {
37 const literal = new Set<number>();
38 if (!text.includes("_")) return literal;
39 for (const match of text.matchAll(PATH_TOKEN)) {
40 const token = match[0];
41 let bodyEnd = token.length;
42 while (bodyEnd > 0 && ".:?".includes(token[bodyEnd - 1]!)) bodyEnd -= 1;
43 if (EMPHASIS_ALTERNATIVES.test(token.slice(0, bodyEnd))) continue;
44 while (bodyEnd > 0 && token[bodyEnd - 1] === "_") bodyEnd -= 1;
45 const body = token.slice(0, bodyEnd);
46 // A slash alone is prose (`and/_or_`); a path also has a dot, a scheme or port, or a root.
47 const isPath = body.includes("/")
48 ? /^~?\/|[.:]/.test(body)
49 : FILE_EXTENSION.test(body.slice(body.lastIndexOf(".")));
50 if (!isPath) continue;
51 let closesInside = false;
52 let start = body.indexOf("_");
53 while (start !== -1) {
54 let end = start;
55 while (body[end] === "_") end += 1;
56 if (start > 0) {
57 literal.add(match.index + start);
58 closesInside ||= !/\w/.test(body[end]!);
59 }
60 start = body.indexOf("_", end);
61 }
62 // A leading run could only pair with a run inside the name, as in `__init__.py`.
63 if (closesInside && body[0] === "_") literal.add(match.index);
64 }
65 return literal;
67​
68// Pieces keep source offsets, so callers can map parsed text back onto the
69// characters it came from; parsing only drops delimiters.
70function parseInlineMarkdownPieces(text: string): SourcePiece[] {
71 const literalRuns = literalUnderscoreRuns(text);
72 const root: SourcePiece[] = [];
73 const stack: { delimiter: string; mark: RichTextMark; start: number; pieces: SourcePiece[] }[] =
74 [];
75 const push = (start: number, end: number, marks: RichTextMark[] = []) => {
76 if (end <= start) return;
77 const pieces = stack.at(-1)?.pieces ?? root;
78 const last = pieces.at(-1);
79 if (last?.end === start && sameMarks(last.marks, marks)) last.end = end;
80 else pieces.push({ start, end, marks });
81 };
82 let index = 0;
83 while (index < text.length) {
84 const char = text[index]!;
85 if (char === "\\") {
86 push(index, Math.min(index + 2, text.length));
87 index += 2;
88 continue;
89 }
90 if (char === "`") {
91 const run = text.slice(index).match(/^`+/)![0];
92 const close = text.indexOf(run, index + run.length);
93 if (
94 run.length === 1 &&
95 close > index + 1 &&
96 !text.slice(index, close).includes("\n") &&
97 text[close + 1] !== "`"
98 ) {
99 push(index + 1, close, ["code"]);
100 index = close + 1;
101 } else {
102 push(index, index + run.length);
103 index += run.length;
104 }
105 continue;
106 }
107 if (char !== "*" && char !== "_" && char !== "~") {
108 push(index, index + 1);
109 index += 1;
110 continue;
111 }
112 let end = index;
113 while (text[end] === char) end += 1;
114 if (literalRuns.has(index)) {
115 push(index, end);
116 index = end;
117 continue;
118 }
119 const before = text[index - 1] ?? "";
120 const after = text[end] ?? "";
121 const canClose = before !== "" && !/\s/.test(before) && (char !== "_" || !/\w/.test(after));
122 const canOpen = after !== "" && !/\s/.test(after) && (char !== "_" || !/\w/.test(before));
123 while (index < end) {
124 const top = stack.at(-1);
125 const opensNestedBold =
126 top?.mark === "italic" &&
127 end - index === 2 &&
128 canOpen &&
129 (char === "*" || char === "_") &&
130 !stack.some((frame) => frame.mark === "bold");
131 if (
132 !opensNestedBold &&
133 canClose &&
134 top &&
135 text.startsWith(top.delimiter, index) &&
136 index + top.delimiter.length <= end
137 ) {
138 stack.pop();
139 for (const piece of top.pieces) push(piece.start, piece.end, [top.mark, ...piece.marks]);
140 index += top.delimiter.length;
141 } else if (canOpen && (char !== "~" || end - index >= 2)) {
142 const length = char === "~" || end - index >= 2 ? 2 : 1;
143 const mark = char === "~" ? "strike" : length === 2 ? "bold" : "italic";
144 // Prevent self-nesting, including alternate delimiters, to bound the stack by supported styles.
145 if (stack.some((frame) => frame.mark === mark)) {
146 push(index, end);
147 index = end;
148 continue;
149 }
150 stack.push({ delimiter: char.repeat(length), mark, start: index, pieces: [] });
151 index += length;
152 } else {
153 push(index, end);
154 index = end;
155 }
156 }
157 }
158 while (stack.length > 0) {
159 const frame = stack.pop()!;
160 push(frame.start, frame.start + frame.delimiter.length);
161 for (const piece of frame.pieces) push(piece.start, piece.end, piece.marks);
162 }
163 return root;
165​
166export function parseInlineMarkdown(text: string): RichTextSpan[] {
167 const spans: RichTextSpan[] = [];
168 for (const { start, end, marks } of parseInlineMarkdownPieces(text)) {
169 const last = spans.at(-1);
170 if (last && sameMarks(last.marks, marks)) {
171 last.text += text.slice(start, end);
172 } else {
173 spans.push({ text: text.slice(start, end), marks });
174 }
175 }
176 return spans;
178​
179/** Marks text the composer shows as editable Markdown source while the caret is in it. */
180export const MARKDOWN_SOURCE_MARK = "markdownSource";
181​
182/** Marks for each UTF-16 unit of `text`, or null for a delimiter that parsing drops. */
183export function inlineMarkdownUnitMarks(text: string): Array<RichTextMark[] | null> {
184 const result: Array<RichTextMark[] | null> = Array.from({ length: text.length }, () => null);
185 for (const { start, end, marks } of parseInlineMarkdownPieces(text)) {
186 result.fill(marks, start, end);
187 }
188 return result;