MCPcopy Create free account
hub / github.com/Ali-Hussein-dev/formcn / CodeBlockCode

Function CodeBlockCode

src/components/ui/code-block.tsx:33–100  ·  view source on GitHub ↗
({
	code,
	language = 'tsx',
	className,
	...props
}: CodeBlockCodeProps)

Source from the content-addressed store, hash-verified

31} & React.HTMLProps<HTMLDivElement>
32
33function CodeBlockCode({
34 code,
35 language = 'tsx',
36 className,
37 ...props
38}: CodeBlockCodeProps) {
39 const [highlightedHtml, setHighlightedHtml] = useState<string | null>(null)
40 const [theme, setTheme] = useState<'dark' | 'light'>('dark')
41
42 useEffect(() => {
43 if (typeof document === 'undefined') return
44
45 const updateTheme = () => {
46 const isDark = document.documentElement.classList.contains('dark')
47 setTheme(isDark ? 'dark' : 'light')
48 }
49
50 // Initial theme
51 updateTheme()
52
53 // Watch for theme changes
54 const observer = new MutationObserver(updateTheme)
55 observer.observe(document.documentElement, {
56 attributes: true,
57 attributeFilter: ['class'],
58 })
59
60 return () => observer.disconnect()
61 }, [])
62
63 useEffect(() => {
64 async function highlight() {
65 if (!code) {
66 setHighlightedHtml('<pre><code></code></pre>')
67 return
68 }
69
70 // Dynamically import shiki only on client-side to avoid SSR bundling all language grammars
71 const { codeToHtml } = await import('shiki')
72 const html = await codeToHtml(code, {
73 lang: language,
74 theme: theme === 'light' ? 'github-light' : 'vesper',
75 })
76 setHighlightedHtml(html)
77 }
78 highlight()
79 }, [code, language, theme])
80
81 const classNames = cn(
82 'w-full text-[13px] [&>pre]:px-4 [&>pre]:py-4 dark:[&>pre]:bg-accent! focus:outline-none focus-visible:outline-none [&>pre]:text-wrap',
83 className,
84 )
85
86 // SSR fallback: render plain code if not hydrated yet
87 return highlightedHtml ? (
88 <div
89 className={classNames}
90 dangerouslySetInnerHTML={{ __html: highlightedHtml }}

Callers

nothing calls this directly

Calls 3

cnFunction · 0.90
highlightFunction · 0.85
updateThemeFunction · 0.70

Tested by

no test coverage detected