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