|
| 1 | +import * as React from 'react' |
| 2 | +import { twMerge } from 'tailwind-merge' |
| 3 | +import { useToast } from '~/components/ToastProvider' |
| 4 | +import { Copy } from 'lucide-react' |
| 5 | +import type { Mermaid } from 'mermaid' |
| 6 | +import { transformerNotationDiff } from '@shikijs/transformers' |
| 7 | +import { createHighlighter, type HighlighterGeneric } from 'shiki' |
| 8 | +import { Button } from '../Button' |
| 9 | + |
| 10 | +// Language aliases mapping |
| 11 | +const LANG_ALIASES: Record<string, string> = { |
| 12 | + ts: 'typescript', |
| 13 | + js: 'javascript', |
| 14 | + sh: 'bash', |
| 15 | + shell: 'bash', |
| 16 | + console: 'bash', |
| 17 | + zsh: 'bash', |
| 18 | + md: 'markdown', |
| 19 | + txt: 'plaintext', |
| 20 | + text: 'plaintext', |
| 21 | +} |
| 22 | + |
| 23 | +// Lazy highlighter singleton |
| 24 | +let highlighterPromise: Promise<HighlighterGeneric<any, any>> | null = null |
| 25 | +let mermaidInstance: Mermaid | null = null |
| 26 | +const genSvgMap = new Map<string, string>() |
| 27 | + |
| 28 | +async function getHighlighter(language: string) { |
| 29 | + if (!highlighterPromise) { |
| 30 | + highlighterPromise = createHighlighter({ |
| 31 | + themes: ['github-light', 'vitesse-dark'], |
| 32 | + langs: [ |
| 33 | + 'typescript', |
| 34 | + 'javascript', |
| 35 | + 'tsx', |
| 36 | + 'jsx', |
| 37 | + 'bash', |
| 38 | + 'json', |
| 39 | + 'html', |
| 40 | + 'css', |
| 41 | + 'markdown', |
| 42 | + 'plaintext', |
| 43 | + ], |
| 44 | + }) |
| 45 | + } |
| 46 | + |
| 47 | + const highlighter = await highlighterPromise |
| 48 | + const normalizedLang = LANG_ALIASES[language] || language |
| 49 | + const langToLoad = normalizedLang === 'mermaid' ? 'plaintext' : normalizedLang |
| 50 | + |
| 51 | + // Load language if not already loaded |
| 52 | + if (!highlighter.getLoadedLanguages().includes(langToLoad as any)) { |
| 53 | + try { |
| 54 | + await highlighter.loadLanguage(langToLoad as any) |
| 55 | + } catch { |
| 56 | + console.warn(`Shiki: Language "${langToLoad}" not found, using plaintext`) |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return highlighter |
| 61 | +} |
| 62 | + |
| 63 | +// Lazy load mermaid only when needed |
| 64 | +async function getMermaid(): Promise<Mermaid> { |
| 65 | + if (!mermaidInstance) { |
| 66 | + const { default: mermaid } = await import('mermaid') |
| 67 | + mermaid.initialize({ startOnLoad: false, securityLevel: 'loose' }) |
| 68 | + mermaidInstance = mermaid |
| 69 | + } |
| 70 | + return mermaidInstance |
| 71 | +} |
| 72 | + |
| 73 | +function extractPreAttributes(html: string): { |
| 74 | + class: string | null |
| 75 | + style: string | null |
| 76 | +} { |
| 77 | + const match = html.match(/<pre\b([^>]*)>/i) |
| 78 | + if (!match) { |
| 79 | + return { class: null, style: null } |
| 80 | + } |
| 81 | + |
| 82 | + const attributes = match[1] |
| 83 | + |
| 84 | + const classMatch = attributes.match(/\bclass\s*=\s*["']([^"']*)["']/i) |
| 85 | + const styleMatch = attributes.match(/\bstyle\s*=\s*["']([^"']*)["']/i) |
| 86 | + |
| 87 | + return { |
| 88 | + class: classMatch ? classMatch[1] : null, |
| 89 | + style: styleMatch ? styleMatch[1] : null, |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +export function CodeBlock({ |
| 94 | + isEmbedded, |
| 95 | + showTypeCopyButton = true, |
| 96 | + ...props |
| 97 | +}: React.HTMLProps<HTMLPreElement> & { |
| 98 | + isEmbedded?: boolean |
| 99 | + showTypeCopyButton?: boolean |
| 100 | +}) { |
| 101 | + // Extract title from data-code-title attribute, handling both camelCase and kebab-case |
| 102 | + const rawTitle = ((props as any)?.dataCodeTitle || |
| 103 | + (props as any)?.['data-code-title']) as string | undefined |
| 104 | + |
| 105 | + // Filter out "undefined" strings, null, and empty strings |
| 106 | + const title = |
| 107 | + rawTitle && rawTitle !== 'undefined' && rawTitle.trim().length > 0 |
| 108 | + ? rawTitle.trim() |
| 109 | + : undefined |
| 110 | + |
| 111 | + const childElement = props.children as |
| 112 | + | undefined |
| 113 | + | { props?: { className?: string; children?: string } } |
| 114 | + let lang = childElement?.props?.className?.replace('language-', '') |
| 115 | + |
| 116 | + if (lang === 'diff') { |
| 117 | + lang = 'plaintext' |
| 118 | + } |
| 119 | + |
| 120 | + const children = props.children as |
| 121 | + | undefined |
| 122 | + | { |
| 123 | + props: { |
| 124 | + children: string |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + const [copied, setCopied] = React.useState(false) |
| 129 | + const ref = React.useRef<any>(null) |
| 130 | + const { notify } = useToast() |
| 131 | + |
| 132 | + const code = children?.props.children |
| 133 | + |
| 134 | + const [codeElement, setCodeElement] = React.useState( |
| 135 | + <pre ref={ref} className={`shiki h-full github-light dark:vitesse-dark`}> |
| 136 | + <code>{lang === 'mermaid' ? <svg /> : code}</code> |
| 137 | + </pre>, |
| 138 | + ) |
| 139 | + |
| 140 | + React[ |
| 141 | + typeof document !== 'undefined' ? 'useLayoutEffect' : 'useEffect' |
| 142 | + ](() => { |
| 143 | + ;(async () => { |
| 144 | + const themes = ['github-light', 'vitesse-dark'] |
| 145 | + const langStr = lang || 'plaintext' |
| 146 | + const normalizedLang = LANG_ALIASES[langStr] || langStr |
| 147 | + const effectiveLang = |
| 148 | + normalizedLang === 'mermaid' ? 'plaintext' : normalizedLang |
| 149 | + |
| 150 | + const highlighter = await getHighlighter(langStr) |
| 151 | + // Trim trailing newlines to prevent empty lines at end of code block |
| 152 | + const trimmedCode = (code || '').trimEnd() |
| 153 | + |
| 154 | + const htmls = await Promise.all( |
| 155 | + themes.map(async (theme) => { |
| 156 | + const output = highlighter.codeToHtml(trimmedCode, { |
| 157 | + lang: effectiveLang, |
| 158 | + theme, |
| 159 | + transformers: [transformerNotationDiff()], |
| 160 | + }) |
| 161 | + |
| 162 | + if (lang === 'mermaid') { |
| 163 | + const preAttributes = extractPreAttributes(output) |
| 164 | + let svgHtml = genSvgMap.get(trimmedCode) |
| 165 | + if (!svgHtml) { |
| 166 | + const mermaid = await getMermaid() |
| 167 | + const { svg } = await mermaid.render('foo', trimmedCode) |
| 168 | + genSvgMap.set(trimmedCode, svg) |
| 169 | + svgHtml = svg |
| 170 | + } |
| 171 | + return `<div class='${preAttributes.class} py-4 bg-neutral-50'>${svgHtml}</div>` |
| 172 | + } |
| 173 | + |
| 174 | + return output |
| 175 | + }), |
| 176 | + ) |
| 177 | + |
| 178 | + setCodeElement( |
| 179 | + <div |
| 180 | + className={twMerge( |
| 181 | + isEmbedded ? 'h-full [&>pre]:h-full [&>pre]:rounded-none' : '', |
| 182 | + )} |
| 183 | + dangerouslySetInnerHTML={{ __html: htmls.join('') }} |
| 184 | + ref={ref} |
| 185 | + />, |
| 186 | + ) |
| 187 | + })() |
| 188 | + }, [code, lang]) |
| 189 | + |
| 190 | + return ( |
| 191 | + <div |
| 192 | + className={twMerge( |
| 193 | + 'codeblock w-full max-w-full relative not-prose border border-gray-500/20 rounded-md [&_pre]:rounded-md', |
| 194 | + props.className, |
| 195 | + )} |
| 196 | + style={props.style} |
| 197 | + > |
| 198 | + {(title || showTypeCopyButton) && ( |
| 199 | + <div className="flex items-center justify-between px-4 py-2 bg-gray-50 dark:bg-gray-900"> |
| 200 | + <div className="text-xs text-gray-700 dark:text-gray-300"> |
| 201 | + {title || (lang?.toLowerCase() === 'bash' ? 'sh' : (lang ?? ''))} |
| 202 | + </div> |
| 203 | + |
| 204 | + <Button |
| 205 | + className={twMerge('border-0 rounded-md transition-opacity')} |
| 206 | + onClick={() => { |
| 207 | + let copyContent = |
| 208 | + typeof ref.current?.innerText === 'string' |
| 209 | + ? ref.current.innerText |
| 210 | + : '' |
| 211 | + |
| 212 | + if (copyContent.endsWith('\n')) { |
| 213 | + copyContent = copyContent.slice(0, -1) |
| 214 | + } |
| 215 | + |
| 216 | + navigator.clipboard.writeText(copyContent) |
| 217 | + setCopied(true) |
| 218 | + setTimeout(() => setCopied(false), 2000) |
| 219 | + notify( |
| 220 | + <div className="flex flex-col"> |
| 221 | + <span className="font-medium">Copied code</span> |
| 222 | + <span className="text-gray-500 dark:text-gray-400 text-xs"> |
| 223 | + Code block copied to clipboard |
| 224 | + </span> |
| 225 | + </div>, |
| 226 | + ) |
| 227 | + }} |
| 228 | + aria-label="Copy code to clipboard" |
| 229 | + > |
| 230 | + {copied ? ( |
| 231 | + <span className="text-xs">Copied!</span> |
| 232 | + ) : ( |
| 233 | + <Copy className="w-4 h-4" /> |
| 234 | + )} |
| 235 | + </Button> |
| 236 | + </div> |
| 237 | + )} |
| 238 | + {codeElement} |
| 239 | + </div> |
| 240 | + ) |
| 241 | +} |
0 commit comments