This repository was archived by the owner on Mar 24, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcode-block.tsx
More file actions
203 lines (183 loc) · 5.8 KB
/
code-block.tsx
File metadata and controls
203 lines (183 loc) · 5.8 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
'use client';
import React, { useState, useEffect, useMemo } from 'react';
import { IconCheck, IconCopy } from '@tabler/icons-react';
type CodeBlockProps = {
language: string;
filename: string;
highlightLines?: number[];
} & (
| {
code: string;
tabs?: never;
}
| {
code?: never;
tabs: Array<{
name: string;
code: string;
language?: string;
highlightLines?: number[];
}>;
}
);
export const CodeBlock = ({
language,
filename,
code,
highlightLines = [],
tabs = [],
}: CodeBlockProps) => {
const [copied, setCopied] = useState(false);
const [activeTab, setActiveTab] = useState(0);
const [highlightedCode, setHighlightedCode] = useState<string>('');
const [error, setError] = useState<string | null>(null);
const tabsExist = tabs.length > 0;
const copyToClipboard = async () => {
const textToCopy = tabsExist ? tabs[activeTab].code : code;
if (textToCopy) {
await navigator.clipboard.writeText(textToCopy);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
};
const activeCode = useMemo(
() => (tabsExist ? tabs[activeTab].code : code),
[tabsExist, tabs, activeTab, code]
);
const activeLanguage = useMemo(
() => (tabsExist ? tabs[activeTab].language || language : language),
[tabsExist, tabs, activeTab, language]
);
const activeHighlightLines = useMemo(
() => (tabsExist ? tabs[activeTab].highlightLines || [] : highlightLines),
[tabsExist, tabs, activeTab, highlightLines]
);
useEffect(() => {
// Simple syntax highlighting function that doesn't rely on external libraries
const highlightCode = () => {
if (!activeCode) {
setHighlightedCode('<pre><code>No code content available</code></pre>');
return;
}
try {
// Create a simple highlighted HTML with line numbers
const lines = activeCode.split('\n');
let html = '<pre class="shiki"><code>';
lines.forEach((line, index) => {
const lineNumber = index + 1;
const isHighlighted = activeHighlightLines.includes(lineNumber);
const lineClass = isHighlighted ? 'line highlighted-line' : 'line';
// Escape HTML characters
const escapedLine = line
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
html += `<span class="${lineClass}">${escapedLine}</span>`;
});
html += '</code></pre>';
setHighlightedCode(html);
setError(null);
} catch (err) {
// Safe error logging without accessing err.stack
console.error(
'Failed to highlight code:',
err instanceof Error ? err.message : 'Unknown error'
);
setError('Failed to highlight code. Displaying plain text instead.');
// Fallback to plain text with safe HTML escaping
try {
const escapedCode = activeCode
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
setHighlightedCode(`<pre><code>${escapedCode}</code></pre>`);
} catch (escapeErr) {
// If even the escaping fails, use a very simple fallback
setHighlightedCode(`<pre><code>Code rendering failed</code></pre>`);
setError(
escapeErr instanceof Error
? escapeErr.message
: 'Unknown error during code highlighting'
);
}
}
};
highlightCode();
}, [activeCode, activeLanguage, activeHighlightLines]);
return (
<div className="relative w-full rounded-lg bg-slate-900 p-4 font-mono text-sm">
<div className="flex flex-col gap-2">
{tabsExist && (
<div className="flex overflow-x-auto">
{tabs.map((tab, index) => (
<button
key={index}
onClick={() => setActiveTab(index)}
className={`px-3 !py-2 text-xs transition-colors font-sans ${
activeTab === index
? 'text-white'
: 'text-zinc-400 hover:text-zinc-200'
}`}
>
{tab.name}
</button>
))}
</div>
)}
{filename && (
<div className="flex justify-between items-center py-2">
<div className="text-xs text-zinc-400">{filename}</div>
<button
onClick={copyToClipboard}
className="flex items-center gap-1 text-xs text-zinc-400 hover:text-zinc-200 transition-colors font-sans"
>
{copied ? <IconCheck size={14} /> : <IconCopy size={14} />}
</button>
</div>
)}
</div>
{error ? (
<div className="py-4 text-red-400">{error}</div>
) : (
<div
className="shiki-container"
dangerouslySetInnerHTML={{ __html: highlightedCode }}
style={{
fontSize: '0.875rem',
}}
/>
)}
<style jsx global>{`
.shiki-container {
background: transparent;
margin: 0;
padding: 0;
overflow-x: auto;
}
.shiki-container pre {
margin: 0;
padding: 0;
}
.shiki-container .line {
display: block;
width: 100%;
}
.shiki-container .highlighted-line {
background-color: rgba(255, 255, 255, 0.1);
}
.shiki-container code {
counter-reset: line;
}
.shiki-container .line::before {
counter-increment: line;
content: counter(line);
display: inline-block;
width: 1.5rem;
margin-right: 1rem;
text-align: right;
color: rgba(115, 138, 148, 0.4);
}
`}</style>
</div>
);
};