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