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

markdownDocument.ts

636 lines24.6 KB

1import type { Root, RootContent } from "mdast";
2import { unified, type Processor } from "unified";
3import remarkParse from "remark-parse";
4import remarkGfm from "remark-gfm";
5import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPaths";
6import {
7 absoluteFilePathMatches,
8 inlineCodeFilePathCandidate,
9 parseMarkdownFileLink,
10} from "@t3tools/shared/markdownLinks";
11import { isWindowsAbsolutePath } from "@t3tools/shared/path";
12import { hasRightToLeftLetter, textDirection } from "@t3tools/shared/textDirection";
13import { getCachedMarkdownAst } from "./markdownParseCache";
14​
15const rawParser = unified().use(remarkParse).use(remarkGfm).use(remarkKeepWindowsProsePaths);
16const parser = {
17 parse(markdown: string): Root {
18 return getCachedMarkdownAst(markdown, (input) => rawParser.parse(input));
19 },
20};
21​
22export function parseMarkdownAst(markdown: string): Root {
23 return parser.parse(markdown);
25export type MarkdownNode = Root | RootContent;
26​
27interface MarkdownEdit {
28 readonly start: number;
29 readonly end: number;
30 readonly content: string;
32​
33function applyMarkdownEdits(markdown: string, edits: MarkdownEdit[]): string {
34 if (edits.length === 0) return markdown;
35 const parts: string[] = [];
36 let offset = 0;
37 // AST traversal emits disjoint edits in source order.
38 for (const edit of edits) {
39 parts.push(markdown.slice(offset, edit.start), edit.content);
40 offset = edit.end;
41 }
42 parts.push(markdown.slice(offset));
43 return parts.join("");
45​
46function decodeCodePoint(codePoint: number, entity: string): string {
47 if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
48 return entity;
49 }
50 return String.fromCodePoint(codePoint);
52​
53export function decodeHtmlEntities(value: string): string {
54 return value.replace(
55 /&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
56 (entity, decimal: string | undefined, hexadecimal: string | undefined) => {
57 if (decimal) {
58 return decodeCodePoint(Number.parseInt(decimal, 10), entity);
59 }
60 if (hexadecimal) {
61 return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
62 }
63 switch (entity.toLowerCase()) {
64 case "&amp;":
65 return "&";
66 case "&apos;":
67 return "'";
68 case "&gt;":
69 return ">";
70 case "&lt;":
71 return "<";
72 case "&nbsp;":
73 return "\u00a0";
74 case "&quot;":
75 return '"';
76 default:
77 return entity;
78 }
79 },
80 );
82​
83const HTML_TAG = /<!--[\s\S]*?-->|<\/?[a-z](?:[^>"']|"[^"]*"|'[^']*')*>/gi;
84​
85function attribute(tag: string, name: string): string | null {
86 const attributes = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
87 for (const match of tag.matchAll(attributes)) {
88 if (match[1]?.toLowerCase() === name) {
89 return decodeHtmlEntities(match[2] ?? match[3] ?? match[4] ?? "");
90 }
91 }
92 return null;
94​
95function markdownDestination(url: string): string {
96 return `<${url.replace(/&/g, "\\&").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C").replace(/\n/g, "")}>`;
98​
99const ANCHOR_TAG = /^<\/?a[\s/>]/i;
100​
101/** Replacements for the anchor tags still ahead, and how many emitted links are open. */
102type AnchorState = { readonly pending: string[]; open: number };
103​
104// Code spans keep their text; an odd trailing backslash would escape the closing "]".
105function escapeLinkLabel(text: string): string {
106 return text
107 .replace(/(`+)[\s\S]*?\1|\\*[[\]]/g, (match) =>
108 match.startsWith("`") || match.length % 2 === 0
109 ? match
110 : `${match.slice(0, -1)}\\${match.slice(-1)}`,
111 )
112 .replace(/\\+$/, (slashes) => (slashes.length % 2 ? `${slashes}\\` : slashes));
114​
115// An unescaped "!" before the inserted "[" would turn the link into an image.
116function bangBefore(text: string, index: number): boolean {
117 if (text[index - 1] !== "!") return false;
118 let backslashes = 0;
119 while (text[index - 2 - backslashes] === "\\") backslashes += 1;
120 return backslashes % 2 === 0;
122​
123/**
124 * Pairs `<a>` tags in order. Only a closed anchor with an http(s) or mailto href becomes a
125 * Markdown link; any other anchor keeps its text unlinked.
126 */
127function anchorMarkdown(tags: readonly string[]): AnchorState {
128 const replacements = tags.map(() => "");
129 const open: Array<{ index: number; href: string | undefined }> = [];
130 tags.forEach((tag, index) => {
131 if (tag[1] !== "/") {
132 const href = attribute(tag, "href")?.trim();
133 open.push({ index, href: href && /^(?:https?|mailto):/i.test(href) ? href : undefined });
134 return;
135 }
136 const opening = open.pop();
137 if (!opening?.href) return;
138 replacements[opening.index] = "[";
139 replacements[index] = `](${markdownDestination(opening.href)})`;
140 });
141 return { pending: replacements, open: 0 };
143​
144export function markdownHtmlTags(content: string): RegExpExecArray[] {
145 // An HTML block such as <details> can also contain Markdown fences and code spans.
146 const codeRanges: Array<{ start: number; end: number }> = [];
147 const tags = [...content.matchAll(HTML_TAG)];
148 let tagIndex = 0;
149 const delimiters = [...content.matchAll(/`+|~{3,}/g)].filter((delimiter) => {
150 while (tags[tagIndex] && tags[tagIndex]!.index + tags[tagIndex]![0].length <= delimiter.index)
151 tagIndex += 1;
152 const tag = tags[tagIndex];
153 return !tag || delimiter.index < tag.index;
154 });
155 for (let index = 0; index < delimiters.length; index += 1) {
156 const opening = delimiters[index]!;
157 const lineStart = content.lastIndexOf("\n", opening.index - 1) + 1;
158 const fenced =
159 opening[0].length >= 3 && /^ {0,3}$/.test(content.slice(lineStart, opening.index));
160 if (opening[0][0] === "~" && !fenced) continue;
161 let closingIndex = -1;
162 for (let candidate = index + 1; candidate < delimiters.length; candidate += 1) {
163 const closing = delimiters[candidate]!;
164 if (!fenced && closing[0] === opening[0]) {
165 closingIndex = candidate;
166 break;
167 }
168 if (!fenced || closing[0][0] !== opening[0][0] || closing[0].length < opening[0].length)
169 continue;
170 const start = content.lastIndexOf("\n", closing.index - 1) + 1;
171 const nextLine = content.indexOf("\n", closing.index);
172 const end = nextLine === -1 ? content.length : nextLine;
173 if (
174 /^ {0,3}$/.test(content.slice(start, closing.index)) &&
175 /^\s*$/.test(content.slice(closing.index + closing[0].length, end))
176 ) {
177 closingIndex = candidate;
178 break;
179 }
180 }
181 if (closingIndex === -1) {
182 if (!fenced) continue;
183 // An unclosed fence runs to the end of the content, so no later opener matters.
184 codeRanges.push({ start: opening.index, end: content.length });
185 break;
186 }
187 const closing = delimiters[closingIndex]!;
188 codeRanges.push({ start: opening.index, end: closing.index + closing[0].length });
189 index = closingIndex;
190 }
191 return tags.filter(
192 (tag) => !codeRanges.some((range) => tag.index >= range.start && tag.index < range.end),
193 );
195​
196/**
197 * Called only for parsed HTML nodes, so Markdown code examples keep their literal tags.
198 * `anchors` is shared across sibling inline HTML nodes because each of those carries a single tag.
199 */
200export function markdownHtmlContent(
201 content: string,
202 options: { readonly anchors?: AnchorState; readonly inTableCell?: boolean } = {},
203): string {
204 const tags = markdownHtmlTags(content);
205 const anchors =
206 options.anchors ??
207 anchorMarkdown(tags.map((tag) => tag[0]).filter((tag) => ANCHOR_TAG.test(tag)));
208 let result = "";
209 let end = 0;
210 for (const match of tags) {
211 const text = content.slice(end, match.index);
212 result += anchors.open > 0 ? escapeLinkLabel(text) : text;
213 const replacement = htmlTagMarkdown(match[0], anchors, options);
214 if (replacement === "[" && bangBefore(result, result.length))
215 result = `${result.slice(0, -1)}\\!`;
216 result +=
217 anchors.open > 0 && /[\s[]/.test(result.at(-1) ?? "")
218 ? replacement.replace(/^ /, "")
219 : replacement;
220 end = match.index + match[0].length;
221 }
222 const text = content.slice(end);
223 return result + (anchors.open > 0 ? escapeLinkLabel(text) : text);
225​
226function htmlTagMarkdown(
227 tag: string,
228 anchors: AnchorState,
229 options: { readonly inTableCell?: boolean },
230): string {
231 if (tag.startsWith("<!--")) return "";
232 if (ANCHOR_TAG.test(tag)) {
233 const replacement = anchors.pending.shift() ?? "";
234 if (replacement === "[") anchors.open += 1;
235 else if (replacement) anchors.open -= 1;
236 return replacement;
237 }
238 if (/^<img\b/i.test(tag)) {
239 const src = attribute(tag, "src");
240 if (!src) return "";
241 const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&");
242 return `![${alt}](${markdownDestination(src)})`;
243 }
244 // A raw newline would end the table row; both parsers decode this reference to one inside the cell.
245 const cellBreak = "&#10;";
246 // A blank line inside an open link label would end the paragraph before its "]".
247 const blockBreak = anchors.open > 0 ? " " : options.inTableCell ? cellBreak : "\n\n";
248 if (/^<summary\b/i.test(tag)) return `${blockBreak}**`;
249 if (/^<\/summary\s*>/i.test(tag)) return `**${blockBreak}`;
250 if (/^<br\b/i.test(tag)) return options.inTableCell ? cellBreak : " \n";
251 if (/^<\/?(?:p|div|details)\b/i.test(tag)) return blockBreak;
252 return "";
254​
255export function markdownWithHtml(markdown: string): string {
256 if (!/<(?:!--|\/?[a-z])/i.test(markdown)) return markdown;
257 const edits: Array<{ start: number; end: number; content: string }> = [];
258 const visit = (node: MarkdownNode, inTableCell: boolean, inLink: boolean) => {
259 if (!("children" in node)) return;
260 inTableCell ||= node.type === "tableCell";
261 const children: readonly MarkdownNode[] = node.children;
262 // Inline HTML arrives one tag per node, so anchors pair across phrasing siblings.
263 const anchors =
264 node.type === "root" || node.type === "blockquote" || node.type === "listItem"
265 ? undefined
266 : anchorMarkdown(
267 children.flatMap((child) =>
268 child.type === "html"
269 ? markdownHtmlTags(child.value)
270 .map((tag) => tag[0])
271 .filter((tag) => ANCHOR_TAG.test(tag))
272 : [],
273 ),
274 );
275 for (const child of children) {
276 const start = child.position?.start.offset;
277 const end = child.position?.end.offset;
278 const linkLabel = inLink || (anchors?.open ?? 0) > 0;
279 if (child.type === "text") {
280 if (linkLabel && start !== undefined && end !== undefined) {
281 const content = escapeLinkLabel(markdown.slice(start, end));
282 if (content !== markdown.slice(start, end)) edits.push({ start, end, content });
283 }
284 continue;
285 }
286 if (child.type !== "html") {
287 visit(child, inTableCell, linkLabel);
288 continue;
289 }
290 const content = markdownHtmlContent(child.value, { anchors, inTableCell });
291 if (start === undefined || end === undefined) continue;
292 // Text before an outermost link is never edited, so this edit cannot overlap another.
293 if (content.startsWith("[") && !linkLabel && bangBefore(markdown, start))
294 edits.push({ start: start - 1, end: start, content: "\\!" });
295 edits.push({ start, end, content });
296 }
297 };
298 visit(parser.parse(markdown), false, false);
299 return applyMarkdownEdits(markdown, edits);
301​
302/** Reference definitions as authored, one line each, so a Windows destination keeps its backslashes. */
303export function markdownReferenceDefinitions(markdown: string): string[] {
304 if (!markdown.includes("]:")) return [];
305 // Flattened as the renderer does it: a raw HTML block hides the definitions inside it.
306 const flattened = markdownWithHtml(markdown);
307 const definitions: string[] = [];
308 const visit = (node: MarkdownNode, quotes: number) => {
309 if (node.type === "definition") {
310 // A wrapped definition drops its indent and the enclosing quotes' markers, not a literal ">".
311 const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "g");
312 definitions.push(
313 flattened.slice(node.position?.start.offset, node.position?.end.offset).replace(wrap, " "),
314 );
315 }
316 if (!("children" in node)) return;
317 for (const child of node.children) visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
318 };
319 visit(parser.parse(flattened), 0);
320 return definitions;
322​
323/**
324 * A reply split into folds and cards renders each fragment as its own document, so each one
325 * carries the reply's definitions. The first definition of a label wins, so the fragment's own
326 * lead: the renderer then prefers them by its own label matching, with none reimplemented here.
327 */
328export function withReferenceDefinitions(
329 fragment: string,
330 replyDefinitions: ReadonlyArray<string>,
331): string {
332 if (replyDefinitions.length === 0 || !fragment.includes("[")) return fragment;
333 const definitions = new Set([...markdownReferenceDefinitions(fragment), ...replyDefinitions]);
334 return `${[...definitions].join("\n")}\n\n${fragment}`;
336​
337// Start only at the beginning of a backtick run to avoid retrying every suffix.
338const INLINE_CODE_SPAN = /(?<!`)`+([^`\r\n]+)`+/g;
339​
340// The native regex stops at whitespace; the shared classifier decides paths with spaces.
341function isInlineCodeFileLink(code: string, fileLink: RegExp): boolean {
342 return fileLink.test(code) || (/\s/.test(code) && inlineCodeFilePathCandidate(code) !== null);
344​
345export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {
346 return transformNativeMarkdown(markdown, fileLink, false);
348​
349function transformNativeMarkdown(
350 markdown: string,
351 fileLink: RegExp | undefined,
352 tableBreaks: boolean,
353): string {
354 const breakTables = tableBreaks && mayHaveTableUnderText(markdown);
355 let linkFiles = false;
356 if (fileLink) {
357 for (const [, code] of markdown.matchAll(INLINE_CODE_SPAN)) {
358 if (isInlineCodeFileLink(code!.trim(), fileLink)) {
359 linkFiles = true;
360 break;
361 }
362 }
363 }
364 const linkProseFiles = fileLink !== undefined && absoluteFilePathMatches(markdown).length > 0;
365 if (!linkFiles && !linkProseFiles && !breakTables) return markdown;
366 const edits: MarkdownEdit[] = [];
367 const fileEdits: MarkdownEdit[] = [];
368 let rewritesPipe = false;
369 const visit = (node: MarkdownNode) => {
370 if (linkFiles && node.type === "inlineCode") {
371 const start = node.position?.start.offset;
372 const end = node.position?.end.offset;
373 const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");
374 if (
375 start !== undefined &&
376 end !== undefined &&
377 fileLink !== undefined &&
378 isInlineCodeFileLink(node.value, fileLink) &&
379 parseMarkdownFileLink(node.value) !== null &&
380 !/[<>]/.test(node.value)
381 ) {
382 const edit = {
383 start,
384 end,
385 content: `[${escaped}](<${escaped}>)`,
386 };
387 edits.push(edit);
388 fileEdits.push(edit);
389 if (node.value.includes("|")) rewritesPipe = true;
390 }
391 } else if (
392 linkProseFiles &&
393 node.type === "text" &&
394 node.position?.start.offset !== undefined
395 ) {
396 const start = node.position.start.offset;
397 const raw = markdown.slice(start, node.position.end.offset);
398 for (const { index, path } of absoluteFilePathMatches(raw)) {
399 // Source offsets stay valid for paths whose own text needs no Markdown decoding.
400 if (raw !== node.value && /[\\&]/.test(path)) continue;
401 const escaped = path.replace(/[\\[\]&]/g, "\\$&");
402 const edit = {
403 start: start + index,
404 end: start + index + path.length,
405 content: `[${escaped}](<${escaped}>)`,
406 };
407 edits.push(edit);
408 fileEdits.push(edit);
409 }
410 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
411 node.children.forEach((child, index) => {
412 const previous = node.children[index - 1];
413 const start = child.position?.start;
414 if (
415 breakTables &&
416 child.type === "table" &&
417 previous?.type === "paragraph" &&
418 start?.offset !== undefined &&
419 previous.position?.end.line === start.line - 1
420 ) {
421 let lineStart = start.offset;
422 while (lineStart > 0 && !/[\r\n]/.test(markdown[lineStart - 1]!)) lineStart -= 1;
423 // Replace only the container prefix, leaving cell edits disjoint from the table break.
424 const [, header = "", , ending = "\n", markers = ""] =
425 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? [];
426 edits.push({
427 start: lineStart,
428 end: lineStart + header.length,
429 content: `${markers.trimEnd()}${ending}${markers}`,
430 });
431 }
432 visit(child);
433 });
434 };
435 visit(parser.parse(markdown));
436 // Rewritten pipes can change table structure, so preserve the original pass ordering.
437 if (breakTables && rewritesPipe)
438 return markdownWithTableBreaks(applyMarkdownEdits(markdown, fileEdits));
439 return applyMarkdownEdits(markdown, edits);
441​
442// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
443function isTableDelimiterRow(line: string): boolean {
444 if (!line.includes("-")) return false;
445 const row = line.replace(/^[ \t>]+/, "").trim();
446 return row
447 .replace(/^\||\|$/g, "")
448 .split("|")
449 .every((cell) => /^:?-+:?$/.test(cell.trim()));
451​
452function mayHaveTableUnderText(markdown: string): boolean {
453 if (!markdown.includes("|")) return false;
454 const lines = markdown.split(/\r\n|\r|\n/);
455 for (let index = 2; index < lines.length; index += 1) {
456 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
457 }
458 return false;
460​
461/** md4c starts tables only at paragraph starts; insert breaks to match GFM. */
462export function markdownWithTableBreaks(markdown: string): string {
463 return transformNativeMarkdown(markdown, undefined, true);
465​
466// `>` covers a destination continued on a blockquote line.
467const WINDOWS_DESTINATION = /\](?:\(|:)[\s>]*<?(?:[A-Za-z]:[\\/]|\\\\)/;
468​
469interface DestinationToken {
470 readonly start: { readonly offset: number };
471 readonly end: { readonly offset: number };
473​
474/**
475 * Markdown reads `C:\work\.t3` as `C:\work.t3`. Web keeps authored Windows destinations
476 * literally (see `remarkKeepWindowsPaths` in shared), so escape their backslashes to give
477 * both parsers here the same path. `\&` stays an escape, as `markdownWithHtml` emits it.
478 * Expects authored Markdown: already escaped output would be escaped twice.
479 */
480function markdownWithWindowsPathDestinations(markdown: string): string {
481 // Skips the extra parse for the common message that has no Windows destination.
482 if (!WINDOWS_DESTINATION.test(markdown)) return markdown;
483 const edits: MarkdownEdit[] = [];
484 function record(
485 this: { resume(): string; sliceSerialize(token: DestinationToken): string },
486 token: DestinationToken,
487 ) {
488 this.resume();
489 const authored = this.sliceSerialize(token);
490 if (!isWindowsAbsolutePath(authored) || !authored.includes("\\") || /[<>]/.test(authored))
491 return;
492 const start = token.start.offset;
493 const end = token.end.offset;
494 const escaped = authored.replace(/\\(?!&)/g, "\\\\");
495 // A bare destination ends at an unescaped `)`, so wrap it to keep `\)` inside.
496 const angled = markdown[start - 1] === "<";
497 edits.push({ start, end, content: angled ? escaped : `<${escaped}>` });
498 }
499 unified()
500 .use(remarkParse)
501 .use(remarkGfm)
502 .use(function (this: Processor) {
503 (this.data().fromMarkdownExtensions ??= []).push({
504 exit: { resourceDestinationString: record, definitionDestinationString: record },
505 });
506 })
507 .parse(markdown);
508 return applyMarkdownEdits(markdown, edits);
510​
511// HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first.
512export function markdownForNativeParsing(markdown: string): string {
513 return markdownWithWindowsPathDestinations(markdownWithHtml(markdown));
515​
516export function parseMarkdownDocument(markdown: string): Root {
517 return parser.parse(markdownForNativeParsing(markdown));
519​
520export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string {
521 return transformNativeMarkdown(markdownForNativeParsing(markdown), fileLink, true);
523​
524/** Native media slots only cover standalone images; nested file embeds must become links. */
525export function markdownWithFileEmbeds(
526 markdown: string,
527 label: (href: string, standalone: boolean) => string | null,
528): { markdown: string; fileHrefs: ReadonlySet<string> } {
529 const fileHrefs = new Set<string>();
530 if (!markdown.includes("![")) return { markdown, fileHrefs };
531 const root = parser.parse(markdown);
532 const topLevelBlocks = new Set<MarkdownNode>(root.children);
533 const definitions = new Map<string, string>();
534 const collect = (node: MarkdownNode) => {
535 if (node.type === "definition") {
536 const identifier = node.identifier.toUpperCase();
537 if (!definitions.has(identifier)) definitions.set(identifier, node.url);
538 }
539 if ("children" in node) node.children.forEach(collect);
540 };
541 collect(root);
542 const edits: Array<{ start: number; end: number; content: string }> = [];
543 const visit = (node: MarkdownNode, standalone = false, insideLink = false) => {
544 if (node.type === "image" || node.type === "imageReference") {
545 const href =
546 node.type === "image" ? node.url : definitions.get(node.identifier.toUpperCase());
547 const name = href === undefined ? null : label(href, standalone);
548 const start = node.position?.start.offset;
549 const end = node.position?.end.offset;
550 if (href !== undefined && name !== null && start !== undefined && end !== undefined) {
551 const text = name.replace(/[\\[\]`*_~|&<>]/g, "\\$&");
552 const url = href.replace(/[\\&]/g, "\\$&").replace(/</g, "%3C").replace(/>/g, "%3E");
553 edits.push({ start, end, content: insideLink ? text : `[${text}](<${url}>)` });
554 fileHrefs.add(href);
555 }
556 }
557 if ("children" in node)
558 node.children.forEach((child) =>
559 visit(
560 child,
561 node.type === "paragraph" && node.children.length === 1 && topLevelBlocks.has(node),
562 insideLink || node.type === "link" || node.type === "linkReference",
563 ),
564 );
565 };
566 visit(root);
567 const parts: string[] = [];
568 let offset = 0;
569 for (const edit of edits) {
570 parts.push(markdown.slice(offset, edit.start), edit.content);
571 offset = edit.end;
572 }
573 parts.push(markdown.slice(offset));
574 return { markdown: parts.join(""), fileHrefs };
576​
577const DIRECTION_MARK = { ltr: "‎", rtl: "‏" } as const;
578​
579function proseText(node: MarkdownNode): string {
580 if (node.type === "text") return node.value;
581 if (node.type === "inlineCode" || node.type === "code") return " ";
582 if (!("children" in node)) return "";
583 const text = node.children.map(proseText).join("");
584 return node.type === "paragraph" || node.type === "heading" || node.type === "tableCell"
585 ? ` ${text} `
586 : text;
588​
589// The native renderer scans inline code too when it picks a paragraph's direction.
590function renderedText(node: MarkdownNode): string {
591 if (node.type === "text" || node.type === "inlineCode") return node.value;
592 if (!("children" in node)) return "";
593 return node.children.map(renderedText).join("");
595​
596// A mark inside `[label]` or `<url>` would break the reference or autolink.
597function firstLeafOffset(node: MarkdownNode): number | undefined {
598 if (
599 !("children" in node) ||
600 node.children.length === 0 ||
601 node.type === "link" ||
602 node.type === "linkReference"
603 ) {
604 return node.position?.start.offset;
605 }
606 return firstLeafOffset(node.children[0]!);
608​
609/**
610 * The native renderer gives each paragraph the direction of its first letter, so an Arabic
611 * line that opens with an English name renders left to right. Like the web's
612 * `rehypeTextDirection`, each top-level block follows the majority of its words, and a
613 * paragraph whose first letter disagrees gets a direction mark that the renderer reads first.
614 */
615export function markdownWithTextDirection(markdown: string): string {
616 if (!hasRightToLeftLetter(markdown)) return markdown;
617 const edits: MarkdownEdit[] = [];
618 for (const block of parser.parse(markdown).children) {
619 if (block.type === "code" || block.type === "html") continue;
620 const direction = textDirection(proseText(block));
621 if (!direction) continue;
622 const mark = (node: MarkdownNode) => {
623 if (node.type === "paragraph" || node.type === "heading" || node.type === "tableCell") {
624 const offset = firstLeafOffset(node);
625 const first = renderedText(node).match(/\p{L}/u)?.[0];
626 if (offset !== undefined && first && textDirection(first) !== direction) {
627 edits.push({ start: offset, end: offset, content: DIRECTION_MARK[direction] });
628 }
629 return;
630 }
631 if ("children" in node) node.children.forEach(mark);
632 };
633 mark(block);
634 }
635 return applyMarkdownEdits(markdown, edits);