A code-block component from Aceternity UI.
From Aceternity UI
1"use client";
2import React from "react";
3import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
4import { atomDark } from "react-syntax-highlighter/dist/cjs/styles/prism";
5import { IconCheck, IconCopy } from "@tabler/icons-react";
6
7type CodeBlockProps = {
8 language: string;
9 filename: string;
10 highlightLines?: number[];
11} & (
12 | {
13 code: string;
14 tabs?: never;
15 }
16 | {
17 code?: never;
18 tabs: Array<{
19 name: string;
20 code: string;
21 language?: string;
22 highlightLines?: number[];
23 }>;
24 }
25);
26
27export const CodeBlock = ({
28 language,
29 filename,
30 code,
31 highlightLines = [],
32 tabs = [],
33}: CodeBlockProps) => {
34 const [copied, setCopied] = React.useState(false);
35 const [activeTab, setActiveTab] = React.useState(0);
36
37 const tabsExist = tabs.length > 0;
38
39 const copyToClipboard = async () => {
40 const textToCopy = tabsExist ? tabs[activeTab].code : code;
41 if (textToCopy) {
42 await navigator.clipboard.writeText(textToCopy);
43 setCopied(true);
44 setTimeout(() => setCopied(false), 2000);
45 }
46 };
47
48 const activeCode = tabsExist ? tabs[activeTab].code : code;
49 const activeLanguage = tabsExist
50 ? tabs[activeTab].language || language
51 : language;
52 const activeHighlightLines = tabsExist
53 ? tabs[activeTab].highlightLines || []
54 : highlightLines;
55
56 return (
57 <div className="relative w-full rounded-lg bg-slate-900 p-4 font-mono text-sm">
58 <div className="flex flex-col gap-2">
59 {tabsExist && (
60 <div className="flex overflow-x-auto">
61 {tabs.map((tab, index) => (
62 <button
63 key={index}
64 onClick={() => setActiveTab(index)}
65 className={`px-3 !py-2 text-xs transition-colors font-sans ${
66 activeTab === index
67 ? "text-white"
68 : "text-zinc-400 hover:text-zinc-200"
69 }`}
70 >
71 {tab.name}
72 </button>
73 ))}
74 </div>
75 )}
76 {!tabsExist && filename && (
77 <div className="flex justify-between items-center py-2">
78 <div className="text-xs text-zinc-400">{filename}</div>
79 <button
80 onClick={copyToClipboard}
81 className="flex items-center gap-1 text-xs text-zinc-400 hover:text-zinc-200 transition-colors font-sans"
82 >
83 {copied ? <IconCheck size={14} /> : <IconCopy size={14} />}
84 </button>
85 </div>
86 )}
87 </div>
88 <SyntaxHighlighter
89 language={activeLanguage}
90 style={atomDark}
91 customStyle={{
92 margin: 0,
93 padding: 0,
94 background: "transparent",
95 fontSize: "0.875rem", // text-sm equivalent
96 }}
97 wrapLines={true}
98 showLineNumbers={true}
99 lineProps={(lineNumber) => ({
100 style: {
101 backgroundColor: activeHighlightLines.includes(lineNumber)
102 ? "rgba(255,255,255,0.1)"
103 : "transparent",
104 display: "block",
105 width: "100%",
106 },
107 })}
108 PreTag="div"
109 >
110 {String(activeCode)}
111 </SyntaxHighlighter>
112 </div>
113 );
114};
115