The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Children, isValidElement, type ReactNode } from "react"; |
| 2 | import type { ExtraProps as ReactMarkdownExtraProps } from "react-markdown"; |
| 3 | |
| 4 | import type { DiffThemeName } from "../../lib/diffRendering"; |
| 5 | |
| 6 | const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/; |
| 7 | |
| 8 | export function extractFenceLanguage(className: string | undefined): string { |
| 9 | const match = className?.match(CODE_FENCE_LANGUAGE_REGEX); |
| 10 | return highlighterLanguageOf(match?.[1] ?? "text"); |
| 11 | } |
| 12 | |
| 13 | export 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 | |
| 18 | const FENCE_TITLE_ATTR_REGEX = /(?:^|\s)(?:title|file(?:name)?)=(?:"([^"]+)"|'([^']+)'|(\S+))/i; |
| 19 | const FENCE_FILENAME_TOKEN_REGEX = /^[\w@][\w@./-]*\.[A-Za-z0-9]+$/; |
| 20 | |
| 21 | export 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 | |
| 29 | export 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 | |
| 47 | export function isClosedCodeFence( |
| 48 | node: ReactMarkdownExtraProps["node"], |
| 49 | text: string, |
| 50 | code: string, |
| 51 | ): boolean { |
| 52 | const start = node?.position?.start.offset; |
| 53 | const end = node?.position?.end.offset; |
| 54 | if (start === undefined || end === undefined) return false; |
| 55 | const source = text.slice(start, end); |
| 56 | const opening = /^(?:`{3,}|~{3,})/.exec(source)?.[0]; |
| 57 | // One class for the blockquote prefix: nested quantifiers here backtrack |
| 58 | // exponentially on code lines that start with many `> ` markers. |
| 59 | const closing = /(?:^|\n)[ \t>]*(`{3,}|~{3,})[ \t\r]*$/.exec(source)?.[1]; |
| 60 | return ( |
| 61 | opening !== undefined && |
| 62 | closing !== undefined && |
| 63 | opening[0] === closing[0] && |
| 64 | closing.length >= opening.length && |
| 65 | // Only a real closer is omitted from parsed code. A CRLF stream cut after |
| 66 | // CR must not count as an extra source line. |
| 67 | source.replace(/\r$/, "").split(/\r\n|\r|\n/).length > code.split(/\r\n|\r|\n/).length |
| 68 | ); |
| 69 | } |
| 70 | |
| 71 | export function nodeToPlainText(node: ReactNode): string { |
| 72 | if (typeof node === "string" || typeof node === "number") { |
| 73 | return String(node); |
| 74 | } |
| 75 | if (Array.isArray(node)) { |
| 76 | return node.map((child) => nodeToPlainText(child)).join(""); |
| 77 | } |
| 78 | if (isValidElement<{ children?: ReactNode }>(node)) { |
| 79 | return nodeToPlainText(node.props.children); |
| 80 | } |
| 81 | return ""; |
| 82 | } |
| 83 | |
| 84 | export function extractCodeBlock( |
| 85 | children: ReactNode, |
| 86 | ): { className: string | undefined; code: string } | null { |
| 87 | const childNodes = Children.toArray(children); |
| 88 | if (childNodes.length !== 1) { |
| 89 | return null; |
| 90 | } |
| 91 | |
| 92 | const onlyChild = childNodes[0]; |
| 93 | if ( |
| 94 | !isValidElement<{ className?: string; children?: ReactNode; node?: { tagName?: string } }>( |
| 95 | onlyChild, |
| 96 | ) |
| 97 | ) { |
| 98 | return null; |
| 99 | } |
| 100 | // With a custom `code` component the child's type is that component, not |
| 101 | // the "code" tag — the hast node react-markdown attaches still names it. |
| 102 | if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") { |
| 103 | return null; |
| 104 | } |
| 105 | |
| 106 | return { |
| 107 | className: onlyChild.props.className, |
| 108 | code: nodeToPlainText(onlyChild.props.children), |
| 109 | }; |
| 110 | } |
| 111 | |
| 112 | // The key holds the code itself: a hash would let two different blocks share |
| 113 | // highlighted HTML. The length prefix keeps a language with ":" unambiguous. |
| 114 | export function createHighlightCacheKey( |
| 115 | code: string, |
| 116 | language: string, |
| 117 | themeName: DiffThemeName, |
| 118 | ): string { |
| 119 | return `${language.length}:${language}:${themeName}:${code}`; |
| 120 | } |
| 121 | |
| 122 | /** Approximate UTF-16 bytes for a cache entry, counting its key, which holds the code. */ |
| 123 | export function estimateHighlightedSize(html: string, cacheKey: string): number { |
| 124 | return (cacheKey.length + html.length) * 2; |
| 125 | } |