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

nativeMarkdownText.ts

769 lines20.9 KB

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