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