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

nativeMarkdownText.ts

782 lines21.3 KB

1import type { MarkdownNode } from "react-native-nitro-markdown/headless";
2​
3import type { SelectableMarkdownSkill } from "./SelectableMarkdownText.types";
4import {
5 resolveMarkdownInlineCodePresentation,
6 resolveMarkdownLinkPresentation,
7 type MarkdownFileIcon,
8} from "./markdownLinks";
9​
10export interface NativeMarkdownTextRun {
11 readonly text: string;
12 readonly bold?: boolean;
13 readonly italic?: boolean;
14 readonly strikethrough?: boolean;
15 readonly code?: boolean;
16 readonly href?: string;
17 readonly externalHost?: string;
18 readonly fileIcon?: MarkdownFileIcon;
19 readonly skillName?: string;
20 readonly skillLabel?: string;
21 readonly role?:
22 | "body"
23 | "heading"
24 | "list-marker"
25 | "list-break"
26 | "quote-marker"
27 | "code-block"
28 | "code-language"
29 | "divider"
30 | "spacer";
31 readonly headingLevel?: number;
32 readonly depth?: number;
33 readonly spacing?: number;
34 readonly firstLineHeadIndent?: number;
35 readonly headIndent?: number;
36 readonly paragraphSpacing?: number;
38​
39export type NativeMarkdownDocumentChunk =
40 | {
41 readonly kind: "selectable";
42 readonly key: string;
43 readonly node: MarkdownNode;
44 }
45 | {
46 readonly kind: "rich";
47 readonly key: string;
48 readonly node: MarkdownNode;
49 };
50​
51interface RunContext {
52 readonly bold: boolean;
53 readonly italic: boolean;
54 readonly strikethrough: boolean;
55 readonly code: boolean;
56 readonly href?: string;
57 readonly externalHost?: string;
58 readonly fileIcon?: MarkdownFileIcon;
59 readonly role?: NativeMarkdownTextRun["role"];
60 readonly headingLevel?: number;
61 readonly depth?: number;
62 readonly spacing?: number;
63 readonly firstLineHeadIndent?: number;
64 readonly headIndent?: number;
65 readonly paragraphSpacing?: number;
67​
68const EMPTY_CONTEXT: RunContext = {
69 bold: false,
70 italic: false,
71 strikethrough: false,
72 code: false,
73};
74​
75const INLINE_HTML_TAG_PATTERN = /<\/?(?:kbd|mark|sub|sup|u)(?:\s[^>]*)?>/gi;
76​
77function decodeCodePoint(codePoint: number, entity: string): string {
78 if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
79 return entity;
80 }
81 return String.fromCodePoint(codePoint);
83​
84function decodeHtmlEntitiesOnce(value: string): string {
85 return value.replace(
86 /&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
87 (entity, decimal: string | undefined, hexadecimal: string | undefined) => {
88 if (decimal) {
89 return decodeCodePoint(Number.parseInt(decimal, 10), entity);
90 }
91 if (hexadecimal) {
92 return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
93 }
94 switch (entity.toLowerCase()) {
95 case "&amp;":
96 return "&";
97 case "&apos;":
98 return "'";
99 case "&gt;":
100 return ">";
101 case "&lt;":
102 return "<";
103 case "&nbsp;":
104 return "\u00a0";
105 case "&quot;":
106 return '"';
107 default:
108 return entity;
109 }
110 },
111 );
113​
114function decodeHtmlEntities(value: string): string {
115 let decoded = value;
116 for (let pass = 0; pass < 2; pass += 1) {
117 const next = decodeHtmlEntitiesOnce(decoded);
118 if (next === decoded) {
119 break;
120 }
121 decoded = next;
122 }
123 return decoded;
125​
126function textNodeContent(value: string): string {
127 return decodeHtmlEntities(value).replace(INLINE_HTML_TAG_PATTERN, "");
129​
130function inlineHtmlText(value: string): string {
131 if (/^<br\s*\/?>$/i.test(value.trim())) {
132 return "\n";
133 }
134 return decodeHtmlEntities(value.replace(/<[^>]+>/g, ""));
136​
137function sameRunStyle(left: NativeMarkdownTextRun, right: NativeMarkdownTextRun): boolean {
138 return (
139 left.bold === right.bold &&
140 left.italic === right.italic &&
141 left.strikethrough === right.strikethrough &&
142 left.code === right.code &&
143 left.href === right.href &&
144 left.externalHost === right.externalHost &&
145 left.fileIcon === right.fileIcon &&
146 left.skillName === right.skillName &&
147 left.skillLabel === right.skillLabel &&
148 left.role === right.role &&
149 left.headingLevel === right.headingLevel &&
150 left.depth === right.depth &&
151 left.spacing === right.spacing &&
152 left.firstLineHeadIndent === right.firstLineHeadIndent &&
153 left.headIndent === right.headIndent &&
154 left.paragraphSpacing === right.paragraphSpacing
155 );
157​
158function appendRun(
159 runs: NativeMarkdownTextRun[],
160 text: string,
161 context: RunContext,
162): NativeMarkdownTextRun[] {
163 if (text.length === 0) {
164 return runs;
165 }
166​
167 const run: NativeMarkdownTextRun = {
168 text,
169 ...(context.bold ? { bold: true } : {}),
170 ...(context.italic ? { italic: true } : {}),
171 ...(context.strikethrough ? { strikethrough: true } : {}),
172 ...(context.code ? { code: true } : {}),
173 ...(context.href ? { href: context.href } : {}),
174 ...(context.externalHost ? { externalHost: context.externalHost } : {}),
175 ...(context.fileIcon ? { fileIcon: context.fileIcon } : {}),
176 ...(context.role ? { role: context.role } : {}),
177 ...(context.headingLevel ? { headingLevel: context.headingLevel } : {}),
178 ...(context.depth ? { depth: context.depth } : {}),
179 ...(context.spacing ? { spacing: context.spacing } : {}),
180 ...(context.firstLineHeadIndent !== undefined
181 ? { firstLineHeadIndent: context.firstLineHeadIndent }
182 : {}),
183 ...(context.headIndent !== undefined ? { headIndent: context.headIndent } : {}),
184 ...(context.paragraphSpacing !== undefined
185 ? { paragraphSpacing: context.paragraphSpacing }
186 : {}),
187 };
188 const previous = runs.at(-1);
189 if (previous && sameRunStyle(previous, run)) {
190 runs[runs.length - 1] = { ...previous, text: previous.text + run.text };
191 return runs;
192 }
193​
194 runs.push(run);
195 return runs;
197​
198const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g;
199​
200function formatSkillLabel(skill: SelectableMarkdownSkill): string {
201 const displayName = skill.displayName?.trim();
202 if (displayName) {
203 return displayName;
204 }
205 return skill.name
206 .split(/[\s:_-]+/)
207 .filter(Boolean)
208 .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
209 .join(" ");
211​
212function decorateSkillRuns(
213 runs: ReadonlyArray<NativeMarkdownTextRun>,
214 skills: ReadonlyArray<SelectableMarkdownSkill>,
215): ReadonlyArray<NativeMarkdownTextRun> {
216 if (skills.length === 0) {
217 return runs;
218 }
219 const skillByName = new Map(skills.map((skill) => [skill.name, skill]));
220 const decorated: NativeMarkdownTextRun[] = [];
221​
222 for (const run of runs) {
223 if (run.code || run.href || run.fileIcon || run.role === "code-block") {
224 decorated.push(run);
225 continue;
226 }
227​
228 let cursor = 0;
229 let matched = false;
230 for (const match of run.text.matchAll(SKILL_TOKEN_REGEX)) {
231 const prefix = match[1] ?? "";
232 const name = match[2] ?? "";
233 const skill = skillByName.get(name);
234 if (!skill) {
235 continue;
236 }
237 const start = (match.index ?? 0) + prefix.length;
238 const end = start + name.length + 1;
239 if (start > cursor) {
240 decorated.push({ ...run, text: run.text.slice(cursor, start) });
241 }
242 decorated.push({
243 ...run,
244 text: run.text.slice(start, end),
245 skillName: name,
246 skillLabel: formatSkillLabel(skill),
247 });
248 cursor = end;
249 matched = true;
250 }
251 if (!matched) {
252 decorated.push(run);
253 } else if (cursor < run.text.length) {
254 decorated.push({ ...run, text: run.text.slice(cursor) });
255 }
256 }
257​
258 return decorated;
260​
261function appendChildren(
262 runs: NativeMarkdownTextRun[],
263 node: MarkdownNode,
264 context: RunContext,
265): NativeMarkdownTextRun[] {
266 for (const child of node.children ?? []) {
267 appendNode(runs, child, context);
268 }
269 return runs;
271​
272function nodeTextContent(node: MarkdownNode): string {
273 if (node.content !== undefined) {
274 return node.content;
275 }
276 return (node.children ?? []).map(nodeTextContent).join("");
278​
279function appendNode(
280 runs: NativeMarkdownTextRun[],
281 node: MarkdownNode,
282 context: RunContext,
283): NativeMarkdownTextRun[] {
284 switch (node.type) {
285 case "text":
286 case "math_inline":
287 return appendRun(runs, textNodeContent(nodeTextContent(node)), context);
288 case "html_inline":
289 return appendRun(runs, inlineHtmlText(nodeTextContent(node)), context);
290 case "code_inline": {
291 const content = nodeTextContent(node);
292 const presentation = context.href ? null : resolveMarkdownInlineCodePresentation(content);
293 return presentation
294 ? appendRun(runs, presentation.label, {
295 ...context,
296 href: presentation.href,
297 fileIcon: presentation.icon,
298 })
299 : appendRun(runs, content, { ...context, code: true });
300 }
301 case "soft_break":
302 return appendRun(runs, " ", context);
303 case "line_break":
304 return appendRun(runs, "\n", context);
305 case "bold":
306 return appendChildren(runs, node, { ...context, bold: true });
307 case "italic":
308 return appendChildren(runs, node, { ...context, italic: true });
309 case "strikethrough":
310 return appendChildren(runs, node, { ...context, strikethrough: true });
311 case "link": {
312 const presentation = resolveMarkdownLinkPresentation(node.href ?? "");
313 if (presentation.kind === "file") {
314 return appendRun(runs, presentation.label, {
315 ...context,
316 href: presentation.href,
317 fileIcon: presentation.icon,
318 });
319 }
320 if (presentation.kind === "external") {
321 return appendChildren(runs, node, {
322 ...context,
323 href: presentation.href,
324 externalHost: presentation.host,
325 });
326 }
327 return appendChildren(runs, node, {
328 ...context,
329 ...(presentation.href ? { href: presentation.href } : {}),
330 });
331 }
332 case "image":
333 return appendRun(runs, node.alt ?? node.title ?? "", context);
334 default:
335 return appendChildren(runs, node, context);
336 }
338​
339export function nativeMarkdownTextRuns(node: MarkdownNode): ReadonlyArray<NativeMarkdownTextRun> {
340 return appendChildren([], node, EMPTY_CONTEXT);
342​
343export function nativeMarkdownWithPreservedSoftBreaks(node: MarkdownNode): MarkdownNode {
344 const children = node.children?.map(nativeMarkdownWithPreservedSoftBreaks);
345 return {
346 ...node,
347 ...(node.type === "soft_break" ? { type: "line_break" as const } : {}),
348 ...(children ? { children } : {}),
349 };
351​
352function appendBlockTerminator(
353 runs: NativeMarkdownTextRun[],
354 context: RunContext,
355): NativeMarkdownTextRun[] {
356 return appendRun(runs, "\n", context);
358​
359function appendSpacer(runs: NativeMarkdownTextRun[], spacing: number): NativeMarkdownTextRun[] {
360 return appendRun(runs, "\n", { ...EMPTY_CONTEXT, role: "spacer", spacing });
362​
363function appendInlineChildren(
364 runs: NativeMarkdownTextRun[],
365 node: MarkdownNode,
366 context: RunContext,
367): NativeMarkdownTextRun[] {
368 for (const child of node.children ?? []) {
369 appendNode(runs, child, context);
370 }
371 return runs;
373​
374function isInlineNode(node: MarkdownNode): boolean {
375 return (
376 node.type === "text" ||
377 node.type === "bold" ||
378 node.type === "italic" ||
379 node.type === "strikethrough" ||
380 node.type === "link" ||
381 node.type === "image" ||
382 node.type === "code_inline" ||
383 node.type === "math_inline" ||
384 node.type === "html_inline" ||
385 node.type === "soft_break" ||
386 node.type === "line_break"
387 );
389​
390export function nativeMarkdownListItemBlocks(node: MarkdownNode): ReadonlyArray<MarkdownNode> {
391 const blocks: MarkdownNode[] = [];
392 let inlineNodes: MarkdownNode[] = [];
393 const flushInlineNodes = () => {
394 if (inlineNodes.length === 0) {
395 return;
396 }
397 blocks.push({ type: "paragraph", children: inlineNodes });
398 inlineNodes = [];
399 };
400​
401 for (const child of node.children ?? []) {
402 if (isInlineNode(child)) {
403 inlineNodes.push(child);
404 continue;
405 }
406​
407 flushInlineNodes();
408 blocks.push(child);
409 }
410 flushInlineNodes();
411 return blocks;
413​
414function appendListItem(
415 runs: NativeMarkdownTextRun[],
416 node: MarkdownNode,
417 marker: string,
418 depth: number,
419 markerColumnWidth: number,
420): NativeMarkdownTextRun[] {
421 const firstLineHeadIndent = Math.max(0, depth - 1) * 20;
422 appendRun(runs, `${marker}\t`, {
423 ...EMPTY_CONTEXT,
424 role: "list-marker",
425 depth,
426 firstLineHeadIndent,
427 headIndent: firstLineHeadIndent + markerColumnWidth,
428 paragraphSpacing: 2,
429 });
430​
431 const children = node.children ?? [];
432 let wroteInlineContent = false;
433 for (const child of children) {
434 if (child.type === "paragraph") {
435 appendInlineChildren(runs, child, {
436 ...EMPTY_CONTEXT,
437 role: "body",
438 depth,
439 });
440 wroteInlineContent = true;
441 continue;
442 }
443 if (child.type === "list") {
444 if (wroteInlineContent) {
445 appendBlockTerminator(runs, {
446 ...EMPTY_CONTEXT,
447 role: "list-break",
448 depth,
449 spacing: 1,
450 });
451 }
452 appendList(runs, child, depth + 1);
453 wroteInlineContent = false;
454 continue;
455 }
456 if (isInlineNode(child)) {
457 appendNode(runs, child, {
458 ...EMPTY_CONTEXT,
459 role: "body",
460 depth,
461 });
462 wroteInlineContent = true;
463 continue;
464 }
465 appendDocumentBlock(runs, child, depth);
466 wroteInlineContent = true;
467 }
468​
469 if (wroteInlineContent) {
470 appendBlockTerminator(runs, {
471 ...EMPTY_CONTEXT,
472 role: "list-break",
473 depth,
474 spacing: depth === 1 ? 4 : 2,
475 });
476 }
477 return runs;
479​
480function appendList(
481 runs: NativeMarkdownTextRun[],
482 node: MarkdownNode,
483 depth: number,
484): NativeMarkdownTextRun[] {
485 const ordered = node.ordered ?? false;
486 const start = node.start ?? 1;
487 const children = node.children ?? [];
488 const markers = children.map((child, index) =>
489 child.type === "task_list_item"
490 ? child.checked
491 ? "☑︎"
492 : "☐︎"
493 : ordered
494 ? `${start + index}.`
495 : depth % 3 === 2
496 ? "◦"
497 : depth % 3 === 0
498 ? "▪︎"
499 : "•",
500 );
501 const markerWidth = ordered
502 ? Math.max(0, ...markers.map((marker) => Array.from(marker).length))
503 : 0;
504​
505 for (const [index, child] of children.entries()) {
506 const marker = markers[index] ?? "•";
507 const alignedMarker =
508 child.type === "task_list_item"
509 ? marker
510 : ordered
511 ? `${"\u2007".repeat(Math.max(0, markerWidth - Array.from(marker).length))}${marker}`
512 : marker;
513 const markerColumnWidth =
514 child.type === "task_list_item" ? 28 : ordered ? 10 + markerWidth * 8 : 24;
515 appendListItem(runs, child, alignedMarker, depth, markerColumnWidth);
516 }
517 return runs;
519​
520function appendQuoteBlock(
521 runs: NativeMarkdownTextRun[],
522 node: MarkdownNode,
523 depth: number,
524): NativeMarkdownTextRun[] {
525 for (const [index, child] of (node.children ?? []).entries()) {
526 if (index > 0) {
527 appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
528 }
529 appendRun(runs, "│\u00a0", {
530 ...EMPTY_CONTEXT,
531 role: "quote-marker",
532 depth,
533 });
534 if (child.type === "paragraph") {
535 appendInlineChildren(runs, child, {
536 ...EMPTY_CONTEXT,
537 role: "body",
538 depth,
539 });
540 } else {
541 appendDocumentBlock(runs, child, depth);
542 }
543 }
544 appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
545 return runs;
547​
548function appendTableRow(
549 runs: NativeMarkdownTextRun[],
550 node: MarkdownNode,
551 depth: number,
552): NativeMarkdownTextRun[] {
553 const cells = node.children ?? [];
554 for (const [index, cell] of cells.entries()) {
555 if (index > 0) {
556 appendRun(runs, "\u00a0│\u00a0", {
557 ...EMPTY_CONTEXT,
558 role: "divider",
559 depth,
560 });
561 }
562 appendInlineChildren(runs, cell, {
563 ...EMPTY_CONTEXT,
564 role: "body",
565 bold: cell.isHeader ?? false,
566 depth,
567 });
568 }
569 appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
570 return runs;
572​
573function appendTable(
574 runs: NativeMarkdownTextRun[],
575 node: MarkdownNode,
576 depth: number,
577): NativeMarkdownTextRun[] {
578 const visit = (child: MarkdownNode) => {
579 if (child.type === "table_row") {
580 appendTableRow(runs, child, depth);
581 return;
582 }
583 for (const nested of child.children ?? []) {
584 visit(nested);
585 }
586 };
587 visit(node);
588 return runs;
590​
591function appendDocumentBlock(
592 runs: NativeMarkdownTextRun[],
593 node: MarkdownNode,
594 depth = 0,
595): NativeMarkdownTextRun[] {
596 switch (node.type) {
597 case "document": {
598 const children = node.children ?? [];
599 for (const [index, child] of children.entries()) {
600 if (index > 0) {
601 const previous = children[index - 1];
602 appendSpacer(
603 runs,
604 child.type === "heading" ? 20 : previous?.type === "heading" ? 10 : 12,
605 );
606 }
607 appendDocumentBlock(runs, child, depth);
608 }
609 return runs;
610 }
611 case "heading": {
612 const context: RunContext = {
613 ...EMPTY_CONTEXT,
614 role: "heading",
615 headingLevel: node.level ?? 1,
616 depth,
617 };
618 appendInlineChildren(runs, node, context);
619 return appendBlockTerminator(runs, context);
620 }
621 case "paragraph": {
622 const context: RunContext = { ...EMPTY_CONTEXT, role: "body", depth };
623 appendInlineChildren(runs, node, context);
624 return appendBlockTerminator(runs, context);
625 }
626 case "list":
627 return appendList(runs, node, depth + 1);
628 case "blockquote":
629 return appendQuoteBlock(runs, node, depth);
630 case "code_block": {
631 if (node.language) {
632 appendRun(runs, `${node.language.toUpperCase()}\n`, {
633 ...EMPTY_CONTEXT,
634 role: "code-language",
635 code: true,
636 depth,
637 });
638 }
639 const content = nodeTextContent(node);
640 appendRun(runs, content, {
641 ...EMPTY_CONTEXT,
642 role: "code-block",
643 code: true,
644 depth,
645 });
646 if (!content.endsWith("\n")) {
647 appendBlockTerminator(runs, {
648 ...EMPTY_CONTEXT,
649 role: "code-block",
650 code: true,
651 depth,
652 });
653 }
654 return runs;
655 }
656 case "horizontal_rule":
657 appendRun(runs, "────────────────────────\n", {
658 ...EMPTY_CONTEXT,
659 role: "divider",
660 depth,
661 });
662 return runs;
663 case "table":
664 return appendTable(runs, node, depth);
665 case "html_block":
666 appendRun(runs, inlineHtmlText(nodeTextContent(node)), {
667 ...EMPTY_CONTEXT,
668 role: "body",
669 depth,
670 });
671 return appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
672 case "math_block":
673 appendRun(runs, nodeTextContent(node), { ...EMPTY_CONTEXT, role: "body", depth });
674 return appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
675 default:
676 appendInlineChildren(runs, node, { ...EMPTY_CONTEXT, role: "body", depth });
677 return appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
678 }
680​
681function containsRichBlock(node: MarkdownNode): boolean {
682 if (
683 node.type === "code_block" ||
684 node.type === "blockquote" ||
685 node.type === "table" ||
686 node.type === "image" ||
687 node.type === "horizontal_rule" ||
688 node.type === "html_block" ||
689 node.type === "math_block"
690 ) {
691 return true;
692 }
693 return (node.children ?? []).some(containsRichBlock);
695​
696export function nativeMarkdownDocumentChunks(
697 document: MarkdownNode,
698): ReadonlyArray<NativeMarkdownDocumentChunk> {
699 const chunks: NativeMarkdownDocumentChunk[] = [];
700 let selectableNodes: MarkdownNode[] = [];
701​
702 const flushSelectable = () => {
703 if (selectableNodes.length === 0) {
704 return;
705 }
706 const first = selectableNodes[0];
707 const last = selectableNodes.at(-1);
708 chunks.push({
709 kind: "selectable",
710 key: `selectable:${first?.beg ?? "start"}:${last?.end ?? "end"}`,
711 node: {
712 type: "document",
713 children: selectableNodes,
714 },
715 });
716 selectableNodes = [];
717 };
718​
719 for (const [index, child] of (document.children ?? []).entries()) {
720 if (!containsRichBlock(child)) {
721 selectableNodes.push(child);
722 continue;
723 }
724​
725 flushSelectable();
726 chunks.push({
727 kind: "rich",
728 key: `rich:${child.type}:${child.beg ?? index}:${child.end ?? index}`,
729 node: child,
730 });
731 }
732 flushSelectable();
733 return chunks;
735​
736function topLevelNodes(node: MarkdownNode): ReadonlyArray<MarkdownNode> {
737 return node.type === "document" ? (node.children ?? []) : [node];
739​
740export function nativeMarkdownChunkSpacing(
741 previous: NativeMarkdownDocumentChunk | undefined,
742 current: NativeMarkdownDocumentChunk,
743): number {
744 if (!previous) {
745 return 0;
746 }
747​
748 const previousLast = topLevelNodes(previous.node).at(-1);
749 const currentFirst = topLevelNodes(current.node)[0];
750​
751 if (currentFirst?.type === "heading") {
752 return 20;
753 }
754 if (previousLast?.type === "heading") {
755 return 10;
756 }
757 if (previousLast?.type === "list" && currentFirst?.type === "list") {
758 return 12;
759 }
760 return 14;
762​
763export function nativeMarkdownDocumentRuns(
764 node: MarkdownNode,
765 skills: ReadonlyArray<SelectableMarkdownSkill> = [],
766): ReadonlyArray<NativeMarkdownTextRun> {
767 const runs = appendDocumentBlock([], node);
768 while (runs.length > 0) {
769 const lastIndex = runs.length - 1;
770 const last = runs[lastIndex];
771 if (!last?.text.endsWith("\n")) {
772 break;
773 }
774 const text = last.text.slice(0, -1);
775 if (text.length === 0) {
776 runs.pop();
777 } else {
778 runs[lastIndex] = { ...last, text };
779 }
780 }
781 return decorateSkillRuns(runs, skills);