1"use client";
2
3import { useControllableState } from "@radix-ui/react-use-controllable-state";
4import {
5 transformerNotationDiff,
6 transformerNotationErrorLevel,
7 transformerNotationFocus,
8 transformerNotationHighlight,
9 transformerNotationWordHighlight,
10} from "@shikijs/transformers";
11import { CheckIcon, CopyIcon } from "lucide-react";
12import type {
13 ComponentProps,
14 HTMLAttributes,
15 ReactElement,
16 ReactNode,
17} from "react";
18import {
19 cloneElement,
20 createContext,
21 useContext,
22 useEffect,
23 useState,
24} from "react";
25import type { IconType } from "react-icons";
26import {
27 SiAstro,
28 SiBiome,
29 SiBower,
30 SiBun,
31 SiC,
32 SiCircleci,
33 SiCoffeescript,
34 SiCplusplus,
35 SiCss3,
36 SiCssmodules,
37 SiDart,
38 SiDocker,
39 SiDocusaurus,
40 SiDotenv,
41 SiEditorconfig,
42 SiEslint,
43 SiGatsby,
44 SiGitignoredotio,
45 SiGnubash,
46 SiGo,
47 SiGraphql,
48 SiGrunt,
49 SiGulp,
50 SiHandlebarsdotjs,
51 SiHtml5,
52 SiJavascript,
53 SiJest,
54 SiJson,
55 SiLess,
56 SiMarkdown,
57 SiMdx,
58 SiMintlify,
59 SiMocha,
60 SiMysql,
61 SiNextdotjs,
62 SiPerl,
63 SiPhp,
64 SiPostcss,
65 SiPrettier,
66 SiPrisma,
67 SiPug,
68 SiPython,
69 SiR,
70 SiReact,
71 SiReadme,
72 SiRedis,
73 SiRemix,
74 SiRive,
75 SiRollupdotjs,
76 SiRuby,
77 SiSanity,
78 SiSass,
79 SiScala,
80 SiSentry,
81 SiShadcnui,
82 SiStorybook,
83 SiStylelint,
84 SiSublimetext,
85 SiSvelte,
86 SiSvg,
87 SiSwift,
88 SiTailwindcss,
89 SiToml,
90 SiTypescript,
91 SiVercel,
92 SiVite,
93 SiVuedotjs,
94 SiWebassembly,
95} from "react-icons/si";
96import {
97 type BundledLanguage,
98 type CodeOptionsMultipleThemes,
99 codeToHtml,
100} from "shiki";
101import { Button } from "@/components/ui/button";
102import {
103 Select,
104 SelectContent,
105 SelectItem,
106 SelectTrigger,
107 SelectValue,
108} from "@/components/ui/select";
109import { cn } from "@/lib/utils";
110
111export type { BundledLanguage } from "shiki";
112
113const filenameIconMap = {
114 ".env": SiDotenv,
115 "*.astro": SiAstro,
116 "biome.json": SiBiome,
117 ".bowerrc": SiBower,
118 "bun.lockb": SiBun,
119 "*.c": SiC,
120 "*.cpp": SiCplusplus,
121 ".circleci/config.yml": SiCircleci,
122 "*.coffee": SiCoffeescript,
123 "*.module.css": SiCssmodules,
124 "*.css": SiCss3,
125 "*.dart": SiDart,
126 Dockerfile: SiDocker,
127 "docusaurus.config.js": SiDocusaurus,
128 ".editorconfig": SiEditorconfig,
129 ".eslintrc": SiEslint,
130 "eslint.config.*": SiEslint,
131 "gatsby-config.*": SiGatsby,
132 ".gitignore": SiGitignoredotio,
133 "*.go": SiGo,
134 "*.graphql": SiGraphql,
135 "*.sh": SiGnubash,
136 "Gruntfile.*": SiGrunt,
137 "gulpfile.*": SiGulp,
138 "*.hbs": SiHandlebarsdotjs,
139 "*.html": SiHtml5,
140 "*.js": SiJavascript,
141 "*.json": SiJson,
142 "*.test.js": SiJest,
143 "*.less": SiLess,
144 "*.md": SiMarkdown,
145 "*.mdx": SiMdx,
146 "mintlify.json": SiMintlify,
147 "mocha.opts": SiMocha,
148 "*.mustache": SiHandlebarsdotjs,
149 "*.sql": SiMysql,
150 "next.config.*": SiNextdotjs,
151 "*.pl": SiPerl,
152 "*.php": SiPhp,
153 "postcss.config.*": SiPostcss,
154 "prettier.config.*": SiPrettier,
155 "*.prisma": SiPrisma,
156 "*.pug": SiPug,
157 "*.py": SiPython,
158 "*.r": SiR,
159 "*.rb": SiRuby,
160 "*.jsx": SiReact,
161 "*.tsx": SiReact,
162 "readme.md": SiReadme,
163 "*.rdb": SiRedis,
164 "remix.config.*": SiRemix,
165 "*.riv": SiRive,
166 "rollup.config.*": SiRollupdotjs,
167 "sanity.config.*": SiSanity,
168 "*.sass": SiSass,
169 "*.scss": SiSass,
170 "*.sc": SiScala,
171 "*.scala": SiScala,
172 "sentry.client.config.*": SiSentry,
173 "components.json": SiShadcnui,
174 "storybook.config.*": SiStorybook,
175 "stylelint.config.*": SiStylelint,
176 ".sublime-settings": SiSublimetext,
177 "*.svelte": SiSvelte,
178 "*.svg": SiSvg,
179 "*.swift": SiSwift,
180 "tailwind.config.*": SiTailwindcss,
181 "*.toml": SiToml,
182 "*.ts": SiTypescript,
183 "vercel.json": SiVercel,
184 "vite.config.*": SiVite,
185 "*.vue": SiVuedotjs,
186 "*.wasm": SiWebassembly,
187};
188
189const lineNumberClassNames = cn(
190 "[&_code]:[counter-reset:line]",
191 "[&_code]:[counter-increment:line_0]",
192 "[&_.line]:before:content-[counter(line)]",
193 "[&_.line]:before:inline-block",
194 "[&_.line]:before:[counter-increment:line]",
195 "[&_.line]:before:w-4",
196 "[&_.line]:before:mr-4",
197 "[&_.line]:before:text-[13px]",
198 "[&_.line]:before:text-right",
199 "[&_.line]:before:text-muted-foreground/50",
200 "[&_.line]:before:font-mono",
201 "[&_.line]:before:select-none"
202);
203
204const darkModeClassNames = cn(
205 "dark:[&_.shiki]:!text-[var(--shiki-dark)]",
206 // "dark:[&_.shiki]:!bg-[var(--shiki-dark-bg)]",
207 "dark:[&_.shiki]:![font-style:var(--shiki-dark-font-style)]",
208 "dark:[&_.shiki]:![font-weight:var(--shiki-dark-font-weight)]",
209 "dark:[&_.shiki]:![text-decoration:var(--shiki-dark-text-decoration)]",
210 "dark:[&_.shiki_span]:!text-[var(--shiki-dark)]",
211 "dark:[&_.shiki_span]:![font-style:var(--shiki-dark-font-style)]",
212 "dark:[&_.shiki_span]:![font-weight:var(--shiki-dark-font-weight)]",
213 "dark:[&_.shiki_span]:![text-decoration:var(--shiki-dark-text-decoration)]"
214);
215
216const lineHighlightClassNames = cn(
217 "[&_.line.highlighted]:bg-blue-50",
218 "[&_.line.highlighted]:after:bg-blue-500",
219 "[&_.line.highlighted]:after:absolute",
220 "[&_.line.highlighted]:after:left-0",
221 "[&_.line.highlighted]:after:top-0",
222 "[&_.line.highlighted]:after:bottom-0",
223 "[&_.line.highlighted]:after:w-0.5",
224 "dark:[&_.line.highlighted]:!bg-blue-500/10"
225);
226
227const lineDiffClassNames = cn(
228 "[&_.line.diff]:after:absolute",
229 "[&_.line.diff]:after:left-0",
230 "[&_.line.diff]:after:top-0",
231 "[&_.line.diff]:after:bottom-0",
232 "[&_.line.diff]:after:w-0.5",
233 "[&_.line.diff.add]:bg-emerald-50",
234 "[&_.line.diff.add]:after:bg-emerald-500",
235 "[&_.line.diff.remove]:bg-rose-50",
236 "[&_.line.diff.remove]:after:bg-rose-500",
237 "dark:[&_.line.diff.add]:!bg-emerald-500/10",
238 "dark:[&_.line.diff.remove]:!bg-rose-500/10"
239);
240
241const lineFocusedClassNames = cn(
242 "[&_code:has(.focused)_.line]:blur-[2px]",
243 "[&_code:has(.focused)_.line.focused]:blur-none"
244);
245
246const wordHighlightClassNames = cn(
247 "[&_.highlighted-word]:bg-blue-50",
248 "dark:[&_.highlighted-word]:!bg-blue-500/10"
249);
250
251const codeBlockClassName = cn(
252 "mt-0 bg-background text-sm",
253 "[&_pre]:py-4",
254 // "[&_.shiki]:!bg-[var(--shiki-bg)]",
255 "[&_.shiki]:!bg-transparent",
256 "[&_code]:w-full",
257 "[&_code]:grid",
258 "[&_code]:overflow-x-auto",
259 "[&_code]:bg-transparent",
260 "[&_.line]:px-4",
261 "[&_.line]:w-full",
262 "[&_.line]:relative"
263);
264
265const highlight = (
266 html: string,
267 language?: BundledLanguage,
268 themes?: CodeOptionsMultipleThemes["themes"]
269) =>
270 codeToHtml(html, {
271 lang: language ?? "typescript",
272 themes: themes ?? {
273 light: "github-light",
274 dark: "github-dark-default",
275 },
276 transformers: [
277 transformerNotationDiff({
278 matchAlgorithm: "v3",
279 }),
280 transformerNotationHighlight({
281 matchAlgorithm: "v3",
282 }),
283 transformerNotationWordHighlight({
284 matchAlgorithm: "v3",
285 }),
286 transformerNotationFocus({
287 matchAlgorithm: "v3",
288 }),
289 transformerNotationErrorLevel({
290 matchAlgorithm: "v3",
291 }),
292 ],
293 });
294
295type CodeBlockData = {
296 language: string;
297 filename: string;
298 code: string;
299};
300
301type CodeBlockContextType = {
302 value: string | undefined;
303 onValueChange: ((value: string) => void) | undefined;
304 data: CodeBlockData[];
305};
306
307const CodeBlockContext = createContext<CodeBlockContextType>({
308 value: undefined,
309 onValueChange: undefined,
310 data: [],
311});
312
313export type CodeBlockProps = HTMLAttributes<HTMLDivElement> & {
314 defaultValue?: string;
315 value?: string;
316 onValueChange?: (value: string) => void;
317 data: CodeBlockData[];
318};
319
320export const CodeBlock = ({
321 value: controlledValue,
322 onValueChange: controlledOnValueChange,
323 defaultValue,
324 className,
325 data,
326 ...props
327}: CodeBlockProps) => {
328 const [value, onValueChange] = useControllableState({
329 defaultProp: defaultValue ?? "",
330 prop: controlledValue,
331 onChange: controlledOnValueChange,
332 });
333
334 return (
335 <CodeBlockContext.Provider value={{ value, onValueChange, data }}>
336 <div
337 className={cn("size-full overflow-hidden rounded-md border", className)}
338 {...props}
339 />
340 </CodeBlockContext.Provider>
341 );
342};
343
344export type CodeBlockHeaderProps = HTMLAttributes<HTMLDivElement>;
345
346export const CodeBlockHeader = ({
347 className,
348 ...props
349}: CodeBlockHeaderProps) => (
350 <div
351 className={cn(
352 "flex flex-row items-center border-b bg-secondary p-1",
353 className
354 )}
355 {...props}
356 />
357);
358
359export type CodeBlockFilesProps = Omit<
360 HTMLAttributes<HTMLDivElement>,
361 "children"
362> & {
363 children: (item: CodeBlockData) => ReactNode;
364};
365
366export const CodeBlockFiles = ({
367 className,
368 children,
369 ...props
370}: CodeBlockFilesProps) => {
371 const { data } = useContext(CodeBlockContext);
372
373 return (
374 <div
375 className={cn("flex grow flex-row items-center gap-2", className)}
376 {...props}
377 >
378 {data.map(children)}
379 </div>
380 );
381};
382
383export type CodeBlockFilenameProps = HTMLAttributes<HTMLDivElement> & {
384 icon?: IconType;
385 value?: string;
386};
387
388export const CodeBlockFilename = ({
389 className,
390 icon,
391 value,
392 children,
393 ...props
394}: CodeBlockFilenameProps) => {
395 const { value: activeValue } = useContext(CodeBlockContext);
396 const defaultIcon = Object.entries(filenameIconMap).find(([pattern]) => {
397 const regex = new RegExp(
398 `^${pattern.replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")}$`
399 );
400 return regex.test(children as string);
401 })?.[1];
402 const Icon = icon ?? defaultIcon;
403
404 if (value !== activeValue) {
405 return null;
406 }
407
408 return (
409 <div
410 className="flex items-center gap-2 bg-secondary px-4 py-1.5 text-muted-foreground text-xs"
411 {...props}
412 >
413 {Icon && <Icon className="h-4 w-4 shrink-0" />}
414 <span className="flex-1 truncate">{children}</span>
415 </div>
416 );
417};
418
419export type CodeBlockSelectProps = ComponentProps<typeof Select>;
420
421export const CodeBlockSelect = (props: CodeBlockSelectProps) => {
422 const { value, onValueChange } = useContext(CodeBlockContext);
423
424 return <Select onValueChange={onValueChange} value={value} {...props} />;
425};
426
427export type CodeBlockSelectTriggerProps = ComponentProps<typeof SelectTrigger>;
428
429export const CodeBlockSelectTrigger = ({
430 className,
431 ...props
432}: CodeBlockSelectTriggerProps) => (
433 <SelectTrigger
434 className={cn(
435 "w-fit border-none text-muted-foreground text-xs shadow-none",
436 className
437 )}
438 {...props}
439 />
440);
441
442export type CodeBlockSelectValueProps = ComponentProps<typeof SelectValue>;
443
444export const CodeBlockSelectValue = (props: CodeBlockSelectValueProps) => (
445 <SelectValue {...props} />
446);
447
448export type CodeBlockSelectContentProps = Omit<
449 ComponentProps<typeof SelectContent>,
450 "children"
451> & {
452 children: (item: CodeBlockData) => ReactNode;
453};
454
455export const CodeBlockSelectContent = ({
456 children,
457 ...props
458}: CodeBlockSelectContentProps) => {
459 const { data } = useContext(CodeBlockContext);
460
461 return <SelectContent {...props}>{data.map(children)}</SelectContent>;
462};
463
464export type CodeBlockSelectItemProps = ComponentProps<typeof SelectItem>;
465
466export const CodeBlockSelectItem = ({
467 className,
468 ...props
469}: CodeBlockSelectItemProps) => (
470 <SelectItem className={cn("text-sm", className)} {...props} />
471);
472
473export type CodeBlockCopyButtonProps = ComponentProps<typeof Button> & {
474 onCopy?: () => void;
475 onError?: (error: Error) => void;
476 timeout?: number;
477};
478
479export const CodeBlockCopyButton = ({
480 asChild,
481 onCopy,
482 onError,
483 timeout = 2000,
484 children,
485 className,
486 ...props
487}: CodeBlockCopyButtonProps) => {
488 const [isCopied, setIsCopied] = useState(false);
489 const { data, value } = useContext(CodeBlockContext);
490 const code = data.find((item) => item.language === value)?.code;
491
492 const copyToClipboard = () => {
493 if (
494 typeof window === "undefined" ||
495 !navigator.clipboard.writeText ||
496 !code
497 ) {
498 return;
499 }
500
501 navigator.clipboard.writeText(code).then(() => {
502 setIsCopied(true);
503 onCopy?.();
504
505 setTimeout(() => setIsCopied(false), timeout);
506 }, onError);
507 };
508
509 if (asChild) {
510 return cloneElement(children as ReactElement, {
511 // @ts-expect-error - we know this is a button
512 onClick: copyToClipboard,
513 });
514 }
515
516 const Icon = isCopied ? CheckIcon : CopyIcon;
517
518 return (
519 <Button
520 className={cn("shrink-0", className)}
521 onClick={copyToClipboard}
522 size="icon"
523 variant="ghost"
524 {...props}
525 >
526 {children ?? <Icon className="text-muted-foreground" size={14} />}
527 </Button>
528 );
529};
530
531type CodeBlockFallbackProps = HTMLAttributes<HTMLDivElement>;
532
533const CodeBlockFallback = ({ children, ...props }: CodeBlockFallbackProps) => (
534 <div {...props}>
535 <pre className="w-full">
536 <code>
537 {children
538 ?.toString()
539 .split("\n")
540 .map((line, i) => (
541 <span className="line" key={i}>
542 {line}
543 </span>
544 ))}
545 </code>
546 </pre>
547 </div>
548);
549
550export type CodeBlockBodyProps = Omit<
551 HTMLAttributes<HTMLDivElement>,
552 "children"
553> & {
554 children: (item: CodeBlockData) => ReactNode;
555};
556
557export const CodeBlockBody = ({ children, ...props }: CodeBlockBodyProps) => {
558 const { data } = useContext(CodeBlockContext);
559
560 return <div {...props}>{data.map(children)}</div>;
561};
562
563export type CodeBlockItemProps = HTMLAttributes<HTMLDivElement> & {
564 value: string;
565 lineNumbers?: boolean;
566};
567
568export const CodeBlockItem = ({
569 children,
570 lineNumbers = true,
571 className,
572 value,
573 ...props
574}: CodeBlockItemProps) => {
575 const { value: activeValue } = useContext(CodeBlockContext);
576
577 if (value !== activeValue) {
578 return null;
579 }
580
581 return (
582 <div
583 className={cn(
584 codeBlockClassName,
585 lineHighlightClassNames,
586 lineDiffClassNames,
587 lineFocusedClassNames,
588 wordHighlightClassNames,
589 darkModeClassNames,
590 lineNumbers && lineNumberClassNames,
591 className
592 )}
593 {...props}
594 >
595 {children}
596 </div>
597 );
598};
599
600export type CodeBlockContentProps = HTMLAttributes<HTMLDivElement> & {
601 themes?: CodeOptionsMultipleThemes["themes"];
602 language?: BundledLanguage;
603 syntaxHighlighting?: boolean;
604 children: string;
605};
606
607export const CodeBlockContent = ({
608 children,
609 themes,
610 language,
611 syntaxHighlighting = true,
612 ...props
613}: CodeBlockContentProps) => {
614 const [html, setHtml] = useState<string | null>(null);
615
616 useEffect(() => {
617 if (!syntaxHighlighting) {
618 return;
619 }
620
621 highlight(children as string, language, themes)
622 .then(setHtml)
623 // biome-ignore lint/suspicious/noConsole: "it's fine"
624 .catch(console.error);
625 }, [children, themes, syntaxHighlighting, language]);
626
627 if (!(syntaxHighlighting && html)) {
628 return <CodeBlockFallback>{children}</CodeBlockFallback>;
629 }
630
631 return (
632 <div
633 // biome-ignore lint/security/noDangerouslySetInnerHtml: "Kinda how Shiki works"
634 dangerouslySetInnerHTML={{ __html: html }}
635 {...props}
636 />
637 );
638};
639