-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathCodeViewer.tsx
More file actions
265 lines (243 loc) · 9.1 KB
/
CodeViewer.tsx
File metadata and controls
265 lines (243 loc) · 9.1 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { useState } from 'react';
import { Copy, Check, FileCode, Download, Maximize2, X } from 'lucide-react';
interface CodeViewerProps {
code: string;
fileName?: string;
language?: string;
}
export function CodeViewer({ code, fileName, language }: CodeViewerProps) {
const [copied, setCopied] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
// Determine language from file extension
const getLanguageFromFileName = (filename?: string): string => {
if (!filename) return 'text';
const extension = filename.split('.').pop()?.toLowerCase();
const languageMap: Record<string, string> = {
'js': 'javascript',
'jsx': 'javascript',
'ts': 'typescript',
'tsx': 'typescript',
'py': 'python',
'rb': 'ruby',
'go': 'go',
'rs': 'rust',
'java': 'java',
'cpp': 'cpp',
'c': 'c',
'h': 'c',
'hpp': 'cpp',
'cs': 'csharp',
'php': 'php',
'swift': 'swift',
'kt': 'kotlin',
'scala': 'scala',
'r': 'r',
'sh': 'bash',
'bash': 'bash',
'zsh': 'bash',
'fish': 'bash',
'ps1': 'powershell',
'sql': 'sql',
'html': 'html',
'htm': 'html',
'xml': 'xml',
'css': 'css',
'scss': 'scss',
'sass': 'sass',
'less': 'less',
'json': 'json',
'yaml': 'yaml',
'yml': 'yaml',
'toml': 'toml',
'md': 'markdown',
'mdx': 'markdown',
'tex': 'latex',
'dockerfile': 'dockerfile',
'makefile': 'makefile',
'cmake': 'cmake',
'gradle': 'gradle',
'maven': 'xml',
'vim': 'vim',
'lua': 'lua',
'dart': 'dart',
'elixir': 'elixir',
'elm': 'elm',
'erlang': 'erlang',
'haskell': 'haskell',
'julia': 'julia',
'nim': 'nim',
'perl': 'perl',
'ocaml': 'ocaml',
'clj': 'clojure',
'cljs': 'clojure',
'cljc': 'clojure'
};
return languageMap[extension || ''] || 'text';
};
const detectedLanguage = language || getLanguageFromFileName(fileName);
// Single-pass syntax highlighting to avoid corrupting HTML class attributes
const highlightCode = (code: string): string => {
// Escape HTML helper
const escapeHtml = (str: string) => str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
// Define token patterns with priorities (first match wins)
// Order matters: strings and comments first to avoid highlighting inside them
const tokenPatterns = [
{ regex: /"(?:[^"\\]|\\.)*"/, className: 'text-green-400' }, // double-quoted strings
{ regex: /'(?:[^'\\]|\\.)*'/, className: 'text-green-400' }, // single-quoted strings
{ regex: /`(?:[^`\\]|\\.)*`/, className: 'text-green-400' }, // backtick strings
{ regex: /\/\/.*$/, className: 'text-gray-500 italic' }, // single-line comments
{ regex: /\/\*[\s\S]*?\*\//, className: 'text-gray-500 italic' }, // multi-line comments
{ regex: /#.*$/, className: 'text-gray-500 italic' }, // hash comments
{ regex: /\b(function|const|let|var|if|else|for|while|return|class|import|export|from|async|await|def|elif|except|finally|lambda|with|as|raise|del|global|nonlocal|assert|break|continue|try|catch|throw|new|this|super|extends|implements|interface|abstract|static|public|private|protected|void|int|string|boolean|float|double|char|long|short|byte|enum|struct|typedef|union|namespace|using|package|goto|switch|case|default|fn|pub|mod|use|mut|match|loop|impl|trait|where|type|readonly|override)\b/, className: 'text-blue-400' }, // keywords
{ regex: /\b(true|false|null|undefined|nil|None|True|False|NULL)\b/, className: 'text-orange-400' }, // literals
{ regex: /\b\d+\.?\d*\b/, className: 'text-purple-400' }, // numbers
{ regex: /\b[A-Z][a-zA-Z0-9]*\b/, className: 'text-cyan-400' }, // PascalCase (types/classes)
];
// Build a combined regex that matches any token
const combinedPattern = new RegExp(
tokenPatterns.map(p => `(${p.regex.source})`).join('|'),
'gm'
);
let result = '';
let lastIndex = 0;
// Single pass through the string
for (const match of code.matchAll(combinedPattern)) {
// Add non-matched text before this match (escaped)
if (match.index! > lastIndex) {
result += escapeHtml(code.slice(lastIndex, match.index));
}
// Find which pattern matched (first non-undefined capture group)
const matchedText = match[0];
let className = '';
for (let i = 0; i < tokenPatterns.length; i++) {
if (match[i + 1] !== undefined) {
className = tokenPatterns[i].className;
break;
}
}
// Add the highlighted token (escape the matched text too)
result += `<span class="${className}">${escapeHtml(matchedText)}</span>`;
lastIndex = match.index! + matchedText.length;
}
// Add remaining text after last match
if (lastIndex < code.length) {
result += escapeHtml(code.slice(lastIndex));
}
return result;
};
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(code);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
}
};
const handleDownload = () => {
const blob = new Blob([code], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName || 'code.txt';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
const lines = code.split('\n');
const lineCount = lines.length;
const CodeDisplay = ({ inModal = false }: { inModal?: boolean }) => (
<div className={`rounded-lg border border-gray-700 bg-gray-900 overflow-hidden ${inModal ? '' : 'max-h-[600px]'}`}>
{/* Header */}
<div className="px-4 py-2 bg-gray-800 border-b border-gray-700 flex items-center justify-between">
<div className="flex items-center space-x-3">
<FileCode className="w-4 h-4 text-blue-400" />
<span className="text-sm text-gray-300 font-mono">
{fileName || 'Untitled'}
</span>
<span className="text-xs text-gray-500 bg-gray-700 px-2 py-1 rounded">
{detectedLanguage}
</span>
<span className="text-xs text-gray-500">
{lineCount} lines
</span>
</div>
<div className="flex items-center space-x-2">
<button
onClick={handleDownload}
className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors"
title="Download file"
>
<Download className="w-4 h-4" />
</button>
{!inModal && (
<button
onClick={() => setIsFullscreen(true)}
className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors"
title="View fullscreen"
>
<Maximize2 className="w-4 h-4" />
</button>
)}
<button
onClick={handleCopy}
className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors"
title="Copy code"
>
{copied ? (
<Check className="w-4 h-4 text-green-400" />
) : (
<Copy className="w-4 h-4" />
)}
</button>
</div>
</div>
{/* Code content */}
<div className={`overflow-auto ${inModal ? 'max-h-[80vh]' : 'max-h-[500px]'}`}>
<table className="w-full text-sm font-mono">
<tbody>
{lines.map((line, idx) => (
<tr key={idx} className="hover:bg-gray-800/50">
<td className="px-4 py-0.5 text-right text-gray-500 select-none w-12 align-top">
{idx + 1}
</td>
<td className="px-4 py-0.5 whitespace-pre text-gray-300">
<span dangerouslySetInnerHTML={{ __html: highlightCode(line) }} />
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
return (
<>
<CodeDisplay />
{/* Fullscreen Modal */}
{isFullscreen && (
<div
className="fixed inset-0 z-50 bg-black bg-opacity-90 flex items-center justify-center p-4"
onClick={() => setIsFullscreen(false)}
>
<div className="relative max-w-[90vw] w-full max-h-[90vh]" onClick={(e) => e.stopPropagation()}>
<button
onClick={() => setIsFullscreen(false)}
className="absolute -top-10 right-0 p-2 text-white hover:text-gray-300 transition-colors"
title="Close"
>
<X className="w-6 h-6" />
</button>
<CodeDisplay inModal />
</div>
</div>
)}
</>
);
}