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

nativeMarkdownText.ts

965 lines28.6 KB

1import type { MarkdownNode } from "react-native-nitro-markdown/headless";
2import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
3import { imageMimeType } from "@t3tools/shared/image";
4import { videoMimeType } from "@t3tools/shared/video";
5/**
6 * Every accent shares a lightness so no kind reads heavier than another; only hue carries
7 * identity. These are the sRGB form of the same OKLCH set web uses, so a chip looks the
8 * same on every surface. See `composerInlineChip.ts`.
9 */
10const CONTEXT_CHIP_PRESENTATIONS = {
11 image: { accent: "#d55665", symbol: "photo" },
12 video: { accent: "#d06217", symbol: "play.rectangle" },
13 file: { accent: "#0090cd", symbol: "doc" },
14 mention: { accent: "#0096af", symbol: "doc" },
15 terminal: { accent: "#009f6e", symbol: "terminal" },
16 element: { accent: "#b87501", symbol: "cursorarrow.click" },
17 "preview-annotation": { accent: "#b87501", symbol: "cursorarrow.click" },
18 "review-comment": { accent: "#8a70dd", symbol: "text.bubble" },
19 "pull-request": { accent: "#7079e4", symbol: "git-pull-request" },
20 skill: { accent: "#b261be", symbol: "cube" },
21 thread: { accent: "#009c96", symbol: "text.bubble" },
22} as const;
23​
24/**
25 * The size an attachment chip reports beside its name, matching web. Rendered as its own
26 * smaller run, so it carries no separator. Only attachment-backed records have bytes.
27 */
28export function composerChipSizeSuffix(record?: {
29 readonly kind?: string;
30 readonly sizeBytes?: number;
31}): string {
32 if (record?.kind !== "file" && record?.kind !== "image") return "";
33 return typeof record.sizeBytes === "number" ? formatAttachmentSize(record.sizeBytes) : "";
35​
36/**
37 * A pull request chip is coloured by what the pull request *is*, the way web colours it and
38 * the way the forge itself does: green open, grey draft, purple merged, red closed. The glyph
39 * stays the same across all four, as it does on web — state is carried by colour alone.
40 */
41const PULL_REQUEST_CHIP_PRESENTATIONS = {
42 open: { accent: "#009f6e", symbol: "git-pull-request" },
43 draft: { accent: "#7f8793", symbol: "git-pull-request" },
44 merged: { accent: "#8a70dd", symbol: "git-pull-request" },
45 closed: { accent: "#d55665", symbol: "git-pull-request" },
46} as const;
47​
48export function contextChipPresentation(
49 kind: string,
50 record?: {
51 readonly kind?: string;
52 readonly name?: string;
53 readonly mimeType?: string;
54 readonly sectionId?: string;
55 readonly pullRequest?: {
56 readonly state?: string;
57 readonly isDraft?: boolean;
58 };
59 },
60) {
61 const presentationKind =
62 kind === "file" &&
63 videoMimeType({
64 name: record?.name ?? "",
65 mimeType: record?.mimeType ?? "",
66 })
67 ? "video"
68 : // A picture chosen through the file picker is typed `file`, but it is still a
69 // picture: it reads as one to the user and should not wear the generic file chip.
70 kind === "file" &&
71 imageMimeType({ name: record?.name ?? "", mimeType: record?.mimeType ?? "" }) !== null
72 ? "image"
73 : kind === "review-comment" && record?.sectionId?.startsWith("pull-request:")
74 ? "pull-request"
75 : kind;
76 if (presentationKind === "pull-request") {
77 const pullRequest = record?.pullRequest;
78 const state =
79 pullRequest?.state === "open" && pullRequest.isDraft === true
80 ? "draft"
81 : (pullRequest?.state ?? "");
82 if (Object.hasOwn(PULL_REQUEST_CHIP_PRESENTATIONS, state)) {
83 return PULL_REQUEST_CHIP_PRESENTATIONS[state as keyof typeof PULL_REQUEST_CHIP_PRESENTATIONS];
84 }
85 }
86 return Object.hasOwn(CONTEXT_CHIP_PRESENTATIONS, presentationKind)
87 ? CONTEXT_CHIP_PRESENTATIONS[presentationKind as keyof typeof CONTEXT_CHIP_PRESENTATIONS]
88 : CONTEXT_CHIP_PRESENTATIONS.file;
90import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
91import {
92 formatComposerContextReference,
93 parseComposerContextHref,
94} from "@t3tools/shared/composerContextReferences";
95​
96/** Native selections count UTF-16 display units, including each inline image placeholder. */
97export function nativeMarkdownContextCopyRanges(
98 runs: ReadonlyArray<{
99 readonly run: {
100 readonly href?: string;
101 readonly text: string;
102 readonly skillName?: string;
103 readonly fileIcon?: string;
104 readonly sourceText?: string;
105 };
106 readonly text: string;
107 readonly inlineImageLength: number;
108 }>,
109) {
110 let offset = 0;
111 return runs.flatMap(({ run, text, inlineImageLength }) => {
112 const start = offset;
113 offset += text.length + inlineImageLength;
114 const reference = parseComposerContextHref(run.href ?? "");
115 const source = reference
116 ? formatComposerContextReference({ ...reference, label: run.text })
117 : run.skillName
118 ? `$${run.skillName}`
119 : run.fileIcon && run.href
120 ? (run.sourceText ?? `[${run.text}](<${run.href}>)`)
121 : null;
122 return source === null ? [] : [{ start, end: offset, text: source }];
123 });
125​
126import type { SelectableMarkdownSkill } from "./SelectableMarkdownText.types";
127import {
128 resolveMarkdownInlineCodePresentation,
129 resolveMarkdownLinkPresentation,
130 type MarkdownFileIcon,
131} from "./markdownLinks";
132​
133export interface NativeMarkdownTextRun {
134 readonly text: string;
135 readonly bold?: boolean;
136 readonly italic?: boolean;
137 readonly strikethrough?: boolean;
138 readonly code?: boolean;
139 readonly href?: string;
140 readonly externalHost?: string;
141 readonly fileIcon?: MarkdownFileIcon;
142 readonly skillName?: string;
143 readonly skillLabel?: string;
144 readonly sourceText?: string;
145 readonly role?:
146 | "body"
147 | "heading"
148 | "list-marker"
149 | "list-break"
150 | "quote-marker"
151 | "code-block"
152 | "code-language"
153 | "divider"
154 | "spacer";
155 readonly headingLevel?: number;
156 readonly depth?: number;
157 readonly spacing?: number;
158 readonly firstLineHeadIndent?: number;
159 readonly headIndent?: number;
160 readonly paragraphSpacing?: number;
162​
163export type NativeMarkdownDocumentChunk =
164 | {
165 readonly kind: "selectable";
166 readonly key: string;
167 readonly node: MarkdownNode;
168 }
169 | {
170 readonly kind: "rich";
171 readonly key: string;
172 readonly node: MarkdownNode;
173 };
174​
175interface RunContext {
176 readonly bold: boolean;
177 readonly italic: boolean;
178 readonly strikethrough: boolean;
179 readonly code: boolean;
180 readonly href?: string;
181 readonly externalHost?: string;
182 readonly fileIcon?: MarkdownFileIcon;
183 readonly role?: NativeMarkdownTextRun["role"];
184 readonly headingLevel?: number;
185 readonly depth?: number;
186 readonly spacing?: number;
187 readonly firstLineHeadIndent?: number;
188 readonly headIndent?: number;
189 readonly paragraphSpacing?: number;
191​
192const EMPTY_CONTEXT: RunContext = {
193 bold: false,
194 italic: false,
195 strikethrough: false,
196 code: false,
197};
198​
199const INLINE_HTML_TAG_PATTERN = /<\/?(?:kbd|mark|sub|sup|u)(?:\s[^>]*)?>/gi;
200​
201function decodeCodePoint(codePoint: number, entity: string): string {
202 if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
203 return entity;
204 }
205 return String.fromCodePoint(codePoint);
207​
208function decodeHtmlEntitiesOnce(value: string): string {
209 return value.replace(
210 /&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
211 (entity, decimal: string | undefined, hexadecimal: string | undefined) => {
212 if (decimal) {
213 return decodeCodePoint(Number.parseInt(decimal, 10), entity);
214 }
215 if (hexadecimal) {
216 return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
217 }
218 switch (entity.toLowerCase()) {
219 case "&amp;":
220 return "&";
221 case "&apos;":
222 return "'";
223 case "&gt;":
224 return ">";
225 case "&lt;":
226 return "<";
227 case "&nbsp;":
228 return "\u00a0";
229 case "&quot;":
230 return '"';
231 default:
232 return entity;
233 }
234 },
235 );
237​
238function decodeHtmlEntities(value: string): string {
239 let decoded = value;
240 for (let pass = 0; pass < 2; pass += 1) {
241 const next = decodeHtmlEntitiesOnce(decoded);
242 if (next === decoded) {
243 break;
244 }
245 decoded = next;
246 }
247 return decoded;
249​
250function textNodeContent(value: string): string {
251 return decodeHtmlEntities(value).replace(INLINE_HTML_TAG_PATTERN, "");
253​
254function inlineHtmlText(value: string): string {
255 if (/^<br\s*\/?>$/i.test(value.trim())) {
256 return "\n";
257 }
258 return decodeHtmlEntities(value.replace(/<[^>]+>/g, ""));
260​
261function sameRunStyle(left: NativeMarkdownTextRun, right: NativeMarkdownTextRun): boolean {
262 return (
263 left.bold === right.bold &&
264 left.italic === right.italic &&
265 left.strikethrough === right.strikethrough &&
266 left.code === right.code &&
267 left.href === right.href &&
268 left.externalHost === right.externalHost &&
269 left.fileIcon === right.fileIcon &&
270 left.skillName === right.skillName &&
271 left.skillLabel === right.skillLabel &&
272 left.role === right.role &&
273 left.headingLevel === right.headingLevel &&
274 left.depth === right.depth &&
275 left.spacing === right.spacing &&
276 left.firstLineHeadIndent === right.firstLineHeadIndent &&
277 left.headIndent === right.headIndent &&
278 left.paragraphSpacing === right.paragraphSpacing
279 );
281​
282function appendRun(
283 runs: NativeMarkdownTextRun[],
284 text: string,
285 context: RunContext,
286): NativeMarkdownTextRun[] {
287 if (text.length === 0) {
288 return runs;
289 }
290​
291 const run: NativeMarkdownTextRun = {
292 text,
293 ...(context.bold ? { bold: true } : {}),
294 ...(context.italic ? { italic: true } : {}),
295 ...(context.strikethrough ? { strikethrough: true } : {}),
296 ...(context.code ? { code: true } : {}),
297 ...(context.href ? { href: context.href } : {}),
298 ...(context.externalHost ? { externalHost: context.externalHost } : {}),
299 ...(context.fileIcon ? { fileIcon: context.fileIcon } : {}),
300 ...(context.role ? { role: context.role } : {}),
301 ...(context.headingLevel ? { headingLevel: context.headingLevel } : {}),
302 ...(context.depth ? { depth: context.depth } : {}),
303 ...(context.spacing ? { spacing: context.spacing } : {}),
304 ...(context.firstLineHeadIndent !== undefined
305 ? { firstLineHeadIndent: context.firstLineHeadIndent }
306 : {}),
307 ...(context.headIndent !== undefined ? { headIndent: context.headIndent } : {}),
308 ...(context.paragraphSpacing !== undefined
309 ? { paragraphSpacing: context.paragraphSpacing }
310 : {}),
311 };
312 const previous = runs.at(-1);
313 if (previous && sameRunStyle(previous, run)) {
314 runs[runs.length - 1] = { ...previous, text: previous.text + run.text };
315 return runs;
316 }
317​
318 runs.push(run);
319 return runs;
321​
322const SKILL_TOKEN_REGEX =
323 /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/gu;
324​
325function formatSkillLabel(skill: SelectableMarkdownSkill): string {
326 const displayName = skill.displayName?.trim();
327 if (displayName) {
328 return displayName;
329 }
330 return skill.name
331 .split(/[\s:_-]+/)
332 .filter(Boolean)
333 .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
334 .join(" ");
336​
337function decorateSkillRuns(
338 runs: ReadonlyArray<NativeMarkdownTextRun>,
339 skills: ReadonlyArray<SelectableMarkdownSkill>,
340): ReadonlyArray<NativeMarkdownTextRun> {
341 if (skills.length === 0) {
342 return runs;
343 }
344 const skillByName = new Map(skills.map((skill) => [skill.name, skill]));
345 const decorated: NativeMarkdownTextRun[] = [];
346​
347 for (const run of runs) {
348 if (run.code || run.href || run.fileIcon || run.role === "code-block") {
349 decorated.push(run);
350 continue;
351 }
352​
353 let cursor = 0;
354 let matched = false;
355 for (const match of run.text.matchAll(SKILL_TOKEN_REGEX)) {
356 const prefix = match[1] ?? "";
357 const name = match[2] ?? "";
358 const skill = skillByName.get(name);
359 if (!skill) {
360 continue;
361 }
362 const start = (match.index ?? 0) + prefix.length;
363 const end = (match.index ?? 0) + match[0].length;
364 if (start > cursor) {
365 decorated.push({ ...run, text: run.text.slice(cursor, start) });
366 }
367 decorated.push({
368 ...run,
369 text: run.text.slice(start, end),
370 skillName: name,
371 skillLabel: formatSkillLabel(skill),
372 });
373 cursor = end;
374 matched = true;
375 }
376 if (!matched) {
377 decorated.push(run);
378 } else if (cursor < run.text.length) {
379 decorated.push({ ...run, text: run.text.slice(cursor) });
380 }
381 }
382​
383 return decorated;
385​
386function decorateMentionRuns(runs: ReadonlyArray<NativeMarkdownTextRun>) {
387 return runs.flatMap((run) => {
388 if (run.code || run.href || run.skillName || run.role === "code-block") return [run];
389 const decorated: NativeMarkdownTextRun[] = [];
390 let cursor = 0;
391 for (const token of collectComposerInlineTokens(`${run.text} `)) {
392 if (token.type !== "mention" || !token.source.startsWith("@")) continue;
393 // Sentence punctuation is not part of an unquoted file reference.
394 const path = token.source.startsWith('@"')
395 ? token.value
396 : token.value.replace(/[.,;!?]+$/, "");
397 const presentation = resolveMarkdownLinkPresentation(path);
398 if (presentation.kind !== "file") continue;
399 const end = token.end - (token.value.length - path.length);
400 if (token.start > cursor)
401 decorated.push({ ...run, text: run.text.slice(cursor, token.start) });
402 decorated.push({
403 ...run,
404 text: presentation.label,
405 href: presentation.href,
406 fileIcon: presentation.icon,
407 sourceText: run.text.slice(token.start, end),
408 });
409 cursor = end;
410 }
411 if (cursor < run.text.length) decorated.push({ ...run, text: run.text.slice(cursor) });
412 return decorated;
413 });
415​
416function appendChildren(
417 runs: NativeMarkdownTextRun[],
418 node: MarkdownNode,
419 context: RunContext,
420): NativeMarkdownTextRun[] {
421 for (const child of node.children ?? []) {
422 appendNode(runs, child, context);
423 }
424 return runs;
426​
427function nodeTextContent(node: MarkdownNode): string {
428 if (node.content !== undefined) {
429 return node.content;
430 }
431 return (node.children ?? []).map(nodeTextContent).join("");
433​
434function appendNode(
435 runs: NativeMarkdownTextRun[],
436 node: MarkdownNode,
437 context: RunContext,
438): NativeMarkdownTextRun[] {
439 switch (node.type) {
440 case "text":
441 case "math_inline":
442 return appendRun(runs, textNodeContent(nodeTextContent(node)), context);
443 case "html_inline":
444 return appendRun(runs, inlineHtmlText(nodeTextContent(node)), context);
445 case "code_inline": {
446 const content = nodeTextContent(node);
447 const presentation = context.href ? null : resolveMarkdownInlineCodePresentation(content);
448 return presentation
449 ? appendRun(runs, presentation.label, {
450 ...context,
451 href: presentation.href,
452 fileIcon: presentation.icon,
453 })
454 : appendRun(runs, content, { ...context, code: true });
455 }
456 case "soft_break":
457 return appendRun(runs, " ", context);
458 case "line_break":
459 return appendRun(runs, "\n", context);
460 case "bold":
461 return appendChildren(runs, node, { ...context, bold: true });
462 case "italic":
463 return appendChildren(runs, node, { ...context, italic: true });
464 case "strikethrough":
465 return appendChildren(runs, node, { ...context, strikethrough: true });
466 case "link": {
467 const reference = parseComposerContextHref(node.href ?? "");
468 if (reference) {
469 // Build the link in isolation: adjacent links with the same href and
470 // style would otherwise merge into one run, collapsing two chips and
471 // their copy ranges into a single reference with a combined label.
472 const referenceRuns: NativeMarkdownTextRun[] = [];
473 appendChildren(referenceRuns, node, {
474 ...context,
475 href: node.href,
476 fileIcon:
477 reference.kind === "image" ? "image" : reference.kind === "terminal" ? "bash" : "text",
478 });
479 runs.push(...referenceRuns);
480 return runs;
481 }
482 const presentation = resolveMarkdownLinkPresentation(node.href ?? "");
483 if (presentation.kind === "file") {
484 return appendRun(runs, presentation.label, {
485 ...context,
486 href: presentation.href,
487 fileIcon: presentation.icon,
488 });
489 }
490 if (presentation.kind === "external") {
491 return appendChildren(runs, node, {
492 ...context,
493 href: presentation.href,
494 externalHost: presentation.host,
495 });
496 }
497 return appendChildren(runs, node, {
498 ...context,
499 ...(presentation.href ? { href: presentation.href } : {}),
500 });
501 }
502 case "image":
503 return appendRun(runs, node.alt ?? node.title ?? "", context);
504 default:
505 return appendChildren(runs, node, context);
506 }
508​
509export function nativeMarkdownTextRuns(node: MarkdownNode): ReadonlyArray<NativeMarkdownTextRun> {
510 return appendChildren([], node, EMPTY_CONTEXT);
512​
513export function nativeMarkdownWithPreservedSoftBreaks(node: MarkdownNode): MarkdownNode {
514 const children = node.children?.map(nativeMarkdownWithPreservedSoftBreaks);
515 return {
516 ...node,
517 ...(node.type === "soft_break" ? { type: "line_break" as const } : {}),
518 ...(children ? { children } : {}),
519 };
521​
522function appendBlockTerminator(
523 runs: NativeMarkdownTextRun[],
524 context: RunContext,
525): NativeMarkdownTextRun[] {
526 return appendRun(runs, "\n", context);
528​
529function appendSpacer(runs: NativeMarkdownTextRun[], spacing: number): NativeMarkdownTextRun[] {
530 return appendRun(runs, "\n", { ...EMPTY_CONTEXT, role: "spacer", spacing });
532​
533function appendInlineChildren(
534 runs: NativeMarkdownTextRun[],
535 node: MarkdownNode,
536 context: RunContext,
537): NativeMarkdownTextRun[] {
538 for (const child of node.children ?? []) {
539 appendNode(runs, child, context);
540 }
541 return runs;
543​
544function isInlineNode(node: MarkdownNode): boolean {
545 return (
546 node.type === "text" ||
547 node.type === "bold" ||
548 node.type === "italic" ||
549 node.type === "strikethrough" ||
550 node.type === "link" ||
551 node.type === "image" ||
552 node.type === "code_inline" ||
553 node.type === "math_inline" ||
554 node.type === "html_inline" ||
555 node.type === "soft_break" ||
556 node.type === "line_break"
557 );
559​
560export function nativeMarkdownListItemBlocks(node: MarkdownNode): ReadonlyArray<MarkdownNode> {
561 const blocks: MarkdownNode[] = [];
562 let inlineNodes: MarkdownNode[] = [];
563 const flushInlineNodes = () => {
564 if (inlineNodes.length === 0) {
565 return;
566 }
567 blocks.push({ type: "paragraph", children: inlineNodes });
568 inlineNodes = [];
569 };
570​
571 for (const child of node.children ?? []) {
572 if (isInlineNode(child)) {
573 inlineNodes.push(child);
574 continue;
575 }
576​
577 flushInlineNodes();
578 blocks.push(child);
579 }
580 flushInlineNodes();
581 return blocks;
583​
584function appendListItem(
585 runs: NativeMarkdownTextRun[],
586 node: MarkdownNode,
587 marker: string,
588 depth: number,
589 markerColumnWidth: number,
590): NativeMarkdownTextRun[] {
591 const firstLineHeadIndent = Math.max(0, depth - 1) * 20;
592 appendRun(runs, `${marker}\t`, {
593 ...EMPTY_CONTEXT,
594 role: "list-marker",
595 depth,
596 firstLineHeadIndent,
597 headIndent: firstLineHeadIndent + markerColumnWidth,
598 paragraphSpacing: 2,
599 });
600​
601 const children = node.children ?? [];
602 let wroteInlineContent = false;
603 for (const child of children) {
604 if (child.type === "paragraph") {
605 appendInlineChildren(runs, child, {
606 ...EMPTY_CONTEXT,
607 role: "body",
608 depth,
609 });
610 wroteInlineContent = true;
611 continue;
612 }
613 if (child.type === "list") {
614 if (wroteInlineContent) {
615 appendBlockTerminator(runs, {
616 ...EMPTY_CONTEXT,
617 role: "list-break",
618 depth,
619 spacing: 1,
620 });
621 }
622 appendList(runs, child, depth + 1);
623 wroteInlineContent = false;
624 continue;
625 }
626 if (isInlineNode(child)) {
627 appendNode(runs, child, {
628 ...EMPTY_CONTEXT,
629 role: "body",
630 depth,
631 });
632 wroteInlineContent = true;
633 continue;
634 }
635 appendDocumentBlock(runs, child, depth);
636 wroteInlineContent = true;
637 }
638​
639 if (wroteInlineContent) {
640 appendBlockTerminator(runs, {
641 ...EMPTY_CONTEXT,
642 role: "list-break",
643 depth,
644 spacing: depth === 1 ? 4 : 2,
645 });
646 }
647 return runs;
649​
650function appendList(
651 runs: NativeMarkdownTextRun[],
652 node: MarkdownNode,
653 depth: number,
654): NativeMarkdownTextRun[] {
655 const ordered = node.ordered ?? false;
656 const start = node.start ?? 1;
657 const children = node.children ?? [];
658 const markers = children.map((child, index) =>
659 child.type === "task_list_item"
660 ? child.checked
661 ? "☑︎"
662 : "☐︎"
663 : ordered
664 ? `${start + index}.`
665 : depth % 3 === 2
666 ? "◦"
667 : depth % 3 === 0
668 ? "▪︎"
669 : "•",
670 );
671 const markerWidth = ordered
672 ? Math.max(0, ...markers.map((marker) => Array.from(marker).length))
673 : 0;
674​
675 for (const [index, child] of children.entries()) {
676 const marker = markers[index] ?? "•";
677 const alignedMarker =
678 child.type === "task_list_item"
679 ? marker
680 : ordered
681 ? `${"\u2007".repeat(Math.max(0, markerWidth - Array.from(marker).length))}${marker}`
682 : marker;
683 const markerColumnWidth =
684 child.type === "task_list_item" ? 28 : ordered ? 10 + markerWidth * 8 : 24;
685 appendListItem(runs, child, alignedMarker, depth, markerColumnWidth);
686 }
687 return runs;
689​
690function appendQuoteBlock(
691 runs: NativeMarkdownTextRun[],
692 node: MarkdownNode,
693 depth: number,
694): NativeMarkdownTextRun[] {
695 for (const [index, child] of (node.children ?? []).entries()) {
696 if (index > 0) {
697 appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
698 }
699 appendRun(runs, "│\u00a0", {
700 ...EMPTY_CONTEXT,
701 role: "quote-marker",
702 depth,
703 });
704 if (child.type === "paragraph") {
705 appendInlineChildren(runs, child, {
706 ...EMPTY_CONTEXT,
707 role: "body",
708 depth,
709 });
710 } else {
711 appendDocumentBlock(runs, child, depth);
712 }
713 }
714 appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
715 return runs;
717​
718function appendTableRow(
719 runs: NativeMarkdownTextRun[],
720 node: MarkdownNode,
721 depth: number,
722): NativeMarkdownTextRun[] {
723 const cells = node.children ?? [];
724 for (const [index, cell] of cells.entries()) {
725 if (index > 0) {
726 appendRun(runs, "\u00a0│\u00a0", {
727 ...EMPTY_CONTEXT,
728 role: "divider",
729 depth,
730 });
731 }
732 appendInlineChildren(runs, cell, {
733 ...EMPTY_CONTEXT,
734 role: "body",
735 bold: cell.isHeader ?? false,
736 depth,
737 });
738 }
739 appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
740 return runs;
742​
743function appendTable(
744 runs: NativeMarkdownTextRun[],
745 node: MarkdownNode,
746 depth: number,
747): NativeMarkdownTextRun[] {
748 const visit = (child: MarkdownNode) => {
749 if (child.type === "table_row") {
750 appendTableRow(runs, child, depth);
751 return;
752 }
753 for (const nested of child.children ?? []) {
754 visit(nested);
755 }
756 };
757 visit(node);
758 return runs;
760​
761function appendDocumentBlock(
762 runs: NativeMarkdownTextRun[],
763 node: MarkdownNode,
764 depth = 0,
765): NativeMarkdownTextRun[] {
766 switch (node.type) {
767 case "document": {
768 const children = node.children ?? [];
769 for (const [index, child] of children.entries()) {
770 if (index > 0) {
771 const previous = children[index - 1];
772 appendSpacer(
773 runs,
774 child.type === "heading" ? 20 : previous?.type === "heading" ? 10 : 12,
775 );
776 }
777 appendDocumentBlock(runs, child, depth);
778 }
779 return runs;
780 }
781 case "heading": {
782 const context: RunContext = {
783 ...EMPTY_CONTEXT,
784 role: "heading",
785 headingLevel: node.level ?? 1,
786 depth,
787 };
788 appendInlineChildren(runs, node, context);
789 return appendBlockTerminator(runs, context);
790 }
791 case "paragraph": {
792 const context: RunContext = { ...EMPTY_CONTEXT, role: "body", depth };
793 appendInlineChildren(runs, node, context);
794 return appendBlockTerminator(runs, context);
795 }
796 case "list":
797 return appendList(runs, node, depth + 1);
798 case "blockquote":
799 return appendQuoteBlock(runs, node, depth);
800 case "code_block": {
801 if (node.language) {
802 appendRun(runs, `${node.language.toUpperCase()}\n`, {
803 ...EMPTY_CONTEXT,
804 role: "code-language",
805 code: true,
806 depth,
807 });
808 }
809 const content = nodeTextContent(node);
810 appendRun(runs, content, {
811 ...EMPTY_CONTEXT,
812 role: "code-block",
813 code: true,
814 depth,
815 });
816 if (!content.endsWith("\n")) {
817 appendBlockTerminator(runs, {
818 ...EMPTY_CONTEXT,
819 role: "code-block",
820 code: true,
821 depth,
822 });
823 }
824 return runs;
825 }
826 case "horizontal_rule":
827 appendRun(runs, "────────────────────────\n", {
828 ...EMPTY_CONTEXT,
829 role: "divider",
830 depth,
831 });
832 return runs;
833 case "table":
834 return appendTable(runs, node, depth);
835 case "html_block":
836 appendRun(runs, inlineHtmlText(nodeTextContent(node)), {
837 ...EMPTY_CONTEXT,
838 role: "body",
839 depth,
840 });
841 return appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
842 case "math_block":
843 appendRun(runs, nodeTextContent(node), { ...EMPTY_CONTEXT, role: "body", depth });
844 return appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
845 default:
846 appendInlineChildren(runs, node, { ...EMPTY_CONTEXT, role: "body", depth });
847 return appendBlockTerminator(runs, { ...EMPTY_CONTEXT, role: "body", depth });
848 }
850​
851function containsRichBlock(node: MarkdownNode): boolean {
852 if (
853 node.type === "code_block" ||
854 node.type === "blockquote" ||
855 node.type === "table" ||
856 node.type === "image" ||
857 node.type === "horizontal_rule" ||
858 node.type === "html_block" ||
859 node.type === "math_block"
860 ) {
861 return true;
862 }
863 return (node.children ?? []).some(containsRichBlock);
865​
866/**
867 * Sibling identity for React keys. A source offset survives appends while the
868 * document streams; the child index is the fallback for offset-free nodes. The
869 * two never share a namespace, so a positioned node cannot collide with an
870 * offset-free sibling whose index happens to equal its offset.
871 */
872export function nativeMarkdownNodePosition(node: MarkdownNode, index: number): string {
873 return node.beg === undefined ? `index:${index}` : `offset:${node.beg}`;
875​
876export function nativeMarkdownDocumentChunks(
877 document: MarkdownNode,
878): ReadonlyArray<NativeMarkdownDocumentChunk> {
879 const chunks: NativeMarkdownDocumentChunk[] = [];
880 let selectableNodes: MarkdownNode[] = [];
881 let selectableStart = 0;
882​
883 const flushSelectable = () => {
884 const first = selectableNodes[0];
885 if (!first) {
886 return;
887 }
888 chunks.push({
889 kind: "selectable",
890 key: `selectable:${nativeMarkdownNodePosition(first, selectableStart)}`,
891 node: {
892 type: "document",
893 children: selectableNodes,
894 },
895 });
896 selectableNodes = [];
897 };
898​
899 for (const [index, child] of (document.children ?? []).entries()) {
900 if (!containsRichBlock(child)) {
901 if (selectableNodes.length === 0) {
902 selectableStart = index;
903 }
904 selectableNodes.push(child);
905 continue;
906 }
907​
908 flushSelectable();
909 chunks.push({
910 kind: "rich",
911 key: `rich:${child.type}:${nativeMarkdownNodePosition(child, index)}`,
912 node: child,
913 });
914 }
915 flushSelectable();
916 return chunks;
918​
919function topLevelNodes(node: MarkdownNode): ReadonlyArray<MarkdownNode> {
920 return node.type === "document" ? (node.children ?? []) : [node];
922​
923export function nativeMarkdownChunkSpacing(
924 previous: NativeMarkdownDocumentChunk | undefined,
925 current: NativeMarkdownDocumentChunk,
926): number {
927 if (!previous) {
928 return 0;
929 }
930​
931 const previousLast = topLevelNodes(previous.node).at(-1);
932 const currentFirst = topLevelNodes(current.node)[0];
933​
934 if (currentFirst?.type === "heading") {
935 return 20;
936 }
937 if (previousLast?.type === "heading") {
938 return 10;
939 }
940 if (previousLast?.type === "list" && currentFirst?.type === "list") {
941 return 12;
942 }
943 return 14;
945​
946export function nativeMarkdownDocumentRuns(
947 node: MarkdownNode,
948 skills: ReadonlyArray<SelectableMarkdownSkill> = [],
949): ReadonlyArray<NativeMarkdownTextRun> {
950 const runs = appendDocumentBlock([], node);
951 while (runs.length > 0) {
952 const lastIndex = runs.length - 1;
953 const last = runs[lastIndex];
954 if (!last?.text.endsWith("\n")) {
955 break;
956 }
957 const text = last.text.slice(0, -1);
958 if (text.length === 0) {
959 runs.pop();
960 } else {
961 runs[lastIndex] = { ...last, text };
962 }
963 }
964 return decorateMentionRuns(decorateSkillRuns(runs, skills));