1 "use client"
2 import { Highlight, Prism, themes } from "prism-react-renderer"
3 import * as React from "react"
4 ;(typeof global !== "undefined" ? global : window).Prism = Prism
5
6 // @ts-ignore
7 import("prismjs/components/prism-json")
8
9 import { Copy } from "@/components/copy"
10 import { clx } from "@/utils/clx"
11
12 export type CodeSnippet = {
13 /**
14 * The label of the code snippet's tab.
15 */
16 label: string
17 /**
18 * The language of the code snippet. For example, `tsx`.
19 */
20 language: string
21 /**
22 * The code snippet.
23 */
24 code: string
25 /**
26 * Whether to hide the line numbers shown as the side of the code snippet.
27 */
28 hideLineNumbers?: boolean
29 /**
30 * Whether to hide the copy button.
31 */
32 hideCopy?: boolean
33 }
34
35 type CodeBlockState = {
36 snippets: CodeSnippet[]
37 active: CodeSnippet
38 setActive: (active: CodeSnippet) => void
39 } | null
40
41 const CodeBlockContext = React.createContext<CodeBlockState>(null)
42
43 const useCodeBlockContext = () => {
44 const context = React.useContext(CodeBlockContext)
45
46 if (context === null)
47 throw new Error(
48 "useCodeBlockContext can only be used within a CodeBlockContext"
49 )
50
51 return context
52 }
53
54 type RootProps = {
55 snippets: CodeSnippet[]
56 }
57
58 /**
59 * This component is based on the `div` element and supports all of its props
60 */
61 const Root = ({
62 /**
63 * The code snippets.
64 */
65 snippets,
66 className,
67 children,
68 ...props
69 }: React.HTMLAttributes<HTMLDivElement> & RootProps) => {
70 const [active, setActive] = React.useState(snippets[0])
71
72 return (
73 <CodeBlockContext.Provider value={{ snippets, active, setActive }}>
74 <div
75 className={clx(
76 "bg-ui-contrast-bg-base shadow-elevation-code-block flex flex-col overflow-hidden rounded-xl",
77 className
78 )}
79 {...props}
80 >
81 {children}
82 </div>
83 </CodeBlockContext.Provider>
84 )
85 }
86 Root.displayName = "CodeBlock"
87
88 type HeaderProps = {
89 hideLabels?: boolean
90 }
91
92 /**
93 * This component is based on the `div` element and supports all of its props
94 */
95 const HeaderComponent = ({
96 children,
97 className,
98 /**
99 * Whether to hide the code snippets' labels.
100 */
101 hideLabels = false,
102 ...props
103 }: React.HTMLAttributes<HTMLDivElement> & HeaderProps) => {
104 const { snippets, active, setActive } = useCodeBlockContext()
105
106 const tabRefs = React.useRef<Array<HTMLSpanElement | null>>([])
107 const tabIndicatorRef = React.useRef<HTMLDivElement | null>(null)
108
109 React.useEffect(() => {
110 const activeTabRef = tabRefs.current.find(
111 (ref) => ref?.dataset.label === active.label
112 )
113
114 if (activeTabRef && tabIndicatorRef.current) {
115 const activeTabIndex = tabRefs.current.indexOf(activeTabRef)
116
117 const prevTabRef =
118 activeTabIndex > 0 ? tabRefs.current[activeTabIndex - 1] : null
119
120 tabIndicatorRef.current.style.width = `${activeTabRef.offsetWidth}px`
121 tabIndicatorRef.current.style.left = prevTabRef
122 ? `${
123 tabRefs.current
124 .slice(0, activeTabIndex)
125 .reduce((total, tab) => total + (tab?.offsetWidth || 0) + 12, 0) +
126 15
127 }px`
128 : "15px"
129 }
130 }, [active])
131
132 return (
133 <div>
134 <div
135 className={clx("flex items-start px-4 pt-2.5", className)}
136 {...props}
137 >
138 {!hideLabels &&
139 snippets.map((snippet, idx) => (
140 <div
141 className={clx(
142 "text-ui-contrast-fg-secondary txt-compact-small-plus transition-fg relative cursor-pointer pb-[9px] pr-3",
143 {
144 "text-ui-contrast-fg-primary cursor-default":
145 active.label === snippet.label,
146 }
147 )}
148 key={snippet.label}
149 onClick={() => setActive(snippet)}
150 >
151 <span
152 ref={(ref) => {
153 tabRefs.current[idx] = ref
154 return undefined
155 }}
156 data-label={snippet.label}
157 >
158 {snippet.label}
159 </span>
160 </div>
161 ))}
162 {children}
163 </div>
164 <div className="w-full px-0.5">
165 <div className="bg-ui-contrast-border-top relative h-px w-full">
166 <div
167 ref={tabIndicatorRef}
168 className={clx(
169 "absolute bottom-0 transition-all motion-reduce:transition-none",
170 "duration-150 ease-linear"
171 )}
172 >
173 <div className="bg-ui-contrast-fg-primary h-px rounded-full" />
174 </div>
175 </div>
176 </div>
177 </div>
178 )
179 }
180 HeaderComponent.displayName = "CodeBlock.Header"
181
182 /**
183 * This component is based on the `div` element and supports all of its props
184 */
185 const Meta = ({
186 className,
187 ...props
188 }: React.HTMLAttributes<HTMLDivElement>) => {
189 return (
190 <div
191 className={clx(
192 "txt-compact-small text-ui-contrast-fg-secondary ml-auto",
193 className
194 )}
195 {...props}
196 />
197 )
198 }
199 Meta.displayName = "CodeBlock.Header.Meta"
200
201 const Header = Object.assign(HeaderComponent, { Meta })
202
203 /**
204 * This component is based on the `div` element and supports all of its props
205 */
206 const Body = ({
207 className,
208 children,
209 ...props
210 }: React.HTMLAttributes<HTMLDivElement>) => {
211 const { active } = useCodeBlockContext()
212
213 const showToolbar = children || !active.hideCopy
214
215 return (
216 <div>
217 {showToolbar && (
218 <div className="border-ui-contrast-border-bot flex min-h-10 items-center gap-x-3 border-t px-4 py-2">
219 <div className="code-body text-ui-contrast-fg-secondary flex-1">
220 {children}
221 </div>
222 {!active.hideCopy && (
223 <Copy
224 content={active.code}
225 className="text-ui-contrast-fg-secondary"
226 />
227 )}
228 </div>
229 )}
230 <div className="flex h-full flex-col overflow-hidden px-[5px] pb-[5px]">
231 <div
232 className={clx(
233 "bg-ui-contrast-bg-subtle border-ui-contrast-border-bot relative h-full overflow-y-auto rounded-lg border p-4",
234 className
235 )}
236 {...props}
237 >
238 <div className="max-w-[90%]">
239 <Highlight
240 theme={{
241 ...themes.palenight,
242 plain: {
243 color: "rgba(249, 250, 251, 1)",
244 backgroundColor: "var(--contrast-fg-primary)",
245 },
246 styles: [
247 ...themes.palenight.styles,
248 {
249 types: ["keyword"],
250 style: {
251 fontStyle: "normal",
252 color: "rgb(187,160,255)",
253 },
254 },
255 {
256 types: ["punctuation", "operator"],
257 style: {
258 fontStyle: "normal",
259 color: "rgb(255,255,255)",
260 },
261 },
262 {
263 types: ["constant", "boolean"],
264 style: {
265 fontStyle: "normal",
266 color: "rgb(187,77,96)",
267 },
268 },
269 {
270 types: ["function"],
271 style: {
272 fontStyle: "normal",
273 color: "rgb(27,198,242)",
274 },
275 },
276 {
277 types: ["number"],
278 style: {
279 color: "rgb(247,208,25)",
280 },
281 },
282 {
283 types: ["property"],
284 style: {
285 color: "rgb(247,208,25)",
286 },
287 },
288 {
289 types: ["maybe-class-name"],
290 style: {
291 color: "rgb(255,203,107)",
292 },
293 },
294 {
295 types: ["string"],
296 style: {
297 color: "rgb(73,209,110)",
298 },
299 },
300 {
301 types: ["comment"],
302 style: {
303 color: "var(--contrast-fg-secondary)",
304 fontStyle: "normal",
305 },
306 },
307 ],
308 }}
309 code={active.code}
310 language={active.language}
311 >
312 {({ style, tokens, getLineProps, getTokenProps }) => (
313 <pre
314 className={clx(
315 "code-body whitespace-pre-wrap bg-transparent",
316 {
317 "grid grid-cols-[auto,1fr] gap-x-4":
318 !active.hideLineNumbers,
319 }
320 )}
321 style={{
322 ...style,
323 background: "transparent",
324 }}
325 >
326 {!active.hideLineNumbers && (
327 <div
328 role="presentation"
329 className="flex flex-col text-right"
330 >
331 {tokens.map((_, i) => (
332 <span
333 key={i}
334 className="text-ui-contrast-fg-secondary tabular-nums"
335 >
336 {i + 1}
337 </span>
338 ))}
339 </div>
340 )}
341 <div>
342 {tokens.map((line, i) => (
343 <div key={i} {...getLineProps({ line })}>
344 {line.map((token, key) => (
345 <span key={key} {...getTokenProps({ token })} />
346 ))}
347 </div>
348 ))}
349 </div>
350 </pre>
351 )}
352 </Highlight>
353 </div>
354 </div>
355 </div>
356 </div>
357 )
358 }
359 Body.displayName = "CodeBlock.Body"
360
361 const CodeBlock = Object.assign(Root, { Body, Header, Meta })
362
363 export { CodeBlock }