Open History to see the last commit
1import { Children, isValidElement, type ReactNode } from "react";
2import type { ExtraProps as ReactMarkdownExtraProps } from "react-markdown";
3
4import { fnv1a32, type DiffThemeName } from "../../lib/diffRendering";
5
6const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
7
8export function extractFenceLanguage(className: string | undefined): string {
9 const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
10 const raw = match?.[1] ?? "text";
11 // Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
12 return raw === "gitignore" ? "ini" : raw;
13}
14
15const FENCE_TITLE_ATTR_REGEX = /(?:^|\s)(?:title|file(?:name)?)=(?:"([^"]+)"|'([^']+)'|(\S+))/i;
16const FENCE_FILENAME_TOKEN_REGEX = /^[\w@][\w@./-]*\.[A-Za-z0-9]+$/;
17
18export function extractFenceTitle(meta: string | undefined): string | null {
19 if (!meta) return null;
20 const attrMatch = FENCE_TITLE_ATTR_REGEX.exec(meta);
21 const attrTitle = attrMatch?.[1] ?? attrMatch?.[2] ?? attrMatch?.[3];
22 if (attrTitle) return attrTitle;
23 return meta.split(/\s+/).find((candidate) => FENCE_FILENAME_TOKEN_REGEX.test(candidate)) ?? null;
24}
25
26export function extractPreCodeMeta(node: unknown): string | undefined {
27 const children = (
28 node as
29 | {
30 children?: Array<{
31 type?: string;
32 tagName?: string;
33 data?: { meta?: unknown };
34 properties?: { dataCodeMeta?: unknown };
35 }>;
36 }
37 | undefined
38 )?.children;
39 const codeNode = children?.find((child) => child?.type === "element" && child.tagName === "code");
40 const meta = codeNode?.properties?.dataCodeMeta ?? codeNode?.data?.meta;
41 return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined;
42}
43
44export function isClosedCodeFence(
45 node: ReactMarkdownExtraProps["node"],
46 text: string,
47 code: string,
48): boolean {
49 const start = node?.position?.start.offset;
50 const end = node?.position?.end.offset;
51 if (start === undefined || end === undefined) return false;
52 const source = text.slice(start, end);
53 const opening = /^(?:`{3,}|~{3,})/.exec(source)?.[0];
54 // One class for the blockquote prefix: nested quantifiers here backtrack
55 // exponentially on code lines that start with many `> ` markers.
56 const closing = /(?:^|\n)[ \t>]*(`{3,}|~{3,})[ \t\r]*$/.exec(source)?.[1];
57 return (
58 opening !== undefined &&
59 closing !== undefined &&
60 opening[0] === closing[0] &&
61 closing.length >= opening.length &&
62 // Only a real closer is omitted from parsed code. A CRLF stream cut after
63 // CR must not count as an extra source line.
64 source.replace(/\r$/, "").split(/\r\n|\r|\n/).length > code.split(/\r\n|\r|\n/).length
65 );
66}
67
68export function nodeToPlainText(node: ReactNode): string {
69 if (typeof node === "string" || typeof node === "number") {
70 return String(node);
71 }
72 if (Array.isArray(node)) {
73 return node.map((child) => nodeToPlainText(child)).join("");
74 }
75 if (isValidElement<{ children?: ReactNode }>(node)) {
76 return nodeToPlainText(node.props.children);
77 }
78 return "";
79}
80
81export function extractCodeBlock(
82 children: ReactNode,
83): { className: string | undefined; code: string } | null {
84 const childNodes = Children.toArray(children);
85 if (childNodes.length !== 1) {
86 return null;
87 }
88
89 const onlyChild = childNodes[0];
90 if (
91 !isValidElement<{ className?: string; children?: ReactNode; node?: { tagName?: string } }>(
92 onlyChild,
93 )
94 ) {
95 return null;
96 }
97 // With a custom `code` component the child's type is that component, not
98 // the "code" tag — the hast node react-markdown attaches still names it.
99 if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") {
100 return null;
101 }
102
103 return {
104 className: onlyChild.props.className,
105 code: nodeToPlainText(onlyChild.props.children),
106 };
107}
108
109export function createHighlightCacheKey(
110 code: string,
111 language: string,
112 themeName: DiffThemeName,
113): string {
114 return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
115}
116
117export function estimateHighlightedSize(html: string, code: string): number {
118 return Math.max(html.length * 2, code.length * 3);
119}