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