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