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

nativeMarkdownText.ts

1,061 lines32.3 KB

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