Open History to see the last commit
1import { DownloadIcon, PlusIcon } from "lucide-react";
2import type { ChangeEvent, DragEvent, UIEvent } from "react";
3import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4import { cn } from "../../lib/utils";
5import {
6 getCustomThemes,
7 installCustomTheme,
8 parseThemeFile,
9 removeCustomTheme,
10 THEME_FILE_VERSION,
11 updateCustomTheme,
12 type ThemeDefinition,
13} from "../../themePalette";
14import {
15 humanizeThemeName,
16 isVsCodeThemeFile,
17 pairVsCodeThemes,
18 parseVsCodeThemeFile,
19 resolveThemeLabelCollisions,
20} from "../../vscodeThemeImport";
21import { Alert } from "../ui/alert";
22import { Button } from "../ui/button";
23import {
24 Dialog,
25 DialogFooter,
26 DialogHeader,
27 DialogPanel,
28 DialogPopup,
29 DialogTitle,
30} from "../ui/dialog";
31
32/**
33 * A full theme export is a few KB, so anything past this is not a theme file.
34 * The guard runs on the size before the bytes are ever read: a large file
35 * would otherwise be pulled into memory, highlighted, and rendered, which
36 * locks the UI for as long as that takes.
37 */
38export const MAX_THEME_FILE_BYTES = 256 * 1024;
39
40/** Highlighting rebuilds the whole markup on every keystroke, so oversized
41 * pastes fall back to plain text instead of freezing the editor. */
42const MAX_HIGHLIGHTED_JSON_LENGTH = 20_000;
43
44function formatByteSize(bytes: number): string {
45 if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
46 if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
47 return `${bytes} bytes`;
48}
49
50/** Returns the error to show for a file too large to be a theme, else null. */
51export function describeOversizedThemeFile(bytes: number): string | null {
52 if (bytes <= MAX_THEME_FILE_BYTES) return null;
53 return `That file is ${formatByteSize(bytes)}. Theme files are only a few KB, so this one was not read (limit ${formatByteSize(MAX_THEME_FILE_BYTES)}).`;
54}
55
56function escapeJsonHtml(value: string): string {
57 return value.replace(
58 /[&<>"']/g,
59 (character) =>
60 ({
61 "&": "&",
62 "<": "<",
63 ">": ">",
64 '"': """,
65 "'": "'",
66 })[character] ?? character,
67 );
68}
69
70function highlightJson(value: string): string {
71 const tokenPattern =
72 /"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g;
73 let highlighted = "";
74 let cursor = 0;
75
76 for (const match of value.matchAll(tokenPattern)) {
77 const token = match[0];
78 const index = match.index ?? 0;
79 highlighted += escapeJsonHtml(value.slice(cursor, index));
80
81 let tokenClass = "theme-json-number";
82 if (token.startsWith('"')) {
83 tokenClass = /^\s*:/.test(value.slice(index + token.length))
84 ? "theme-json-key"
85 : "theme-json-string";
86 } else if (token === "true" || token === "false" || token === "null") {
87 tokenClass = "theme-json-constant";
88 }
89 highlighted += `<span class="${tokenClass}">${escapeJsonHtml(token)}</span>`;
90 cursor = index + token.length;
91 }
92
93 return highlighted + escapeJsonHtml(value.slice(cursor));
94}
95
96function ThemeJsonEditor({
97 id,
98 value,
99 onChange,
100}: {
101 id: string;
102 value: string;
103 onChange: (value: string) => void;
104}) {
105 const highlightRef = useRef<HTMLPreElement>(null);
106 const isPlainText = value.length > MAX_HIGHLIGHTED_JSON_LENGTH;
107 const highlightedJson = useMemo(
108 () => (value.length > MAX_HIGHLIGHTED_JSON_LENGTH ? "" : highlightJson(value)),
109 [value],
110 );
111
112 const syncScroll = useCallback((event: UIEvent<HTMLTextAreaElement>) => {
113 const highlightElement = highlightRef.current;
114 if (!highlightElement) return;
115 highlightElement.scrollTop = event.currentTarget.scrollTop;
116 highlightElement.scrollLeft = event.currentTarget.scrollLeft;
117 }, []);
118
119 return (
120 <div className="relative overflow-hidden rounded-xl border border-input bg-background shadow-xs/5 focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/24">
121 {isPlainText ? null : (
122 <pre
123 ref={highlightRef}
124 aria-hidden
125 className="pointer-events-none absolute inset-0 m-0 overflow-hidden whitespace-pre-wrap break-words p-3 font-mono text-[12px] leading-5 text-foreground"
126 >
127 <code dangerouslySetInnerHTML={{ __html: highlightedJson }} />
128 </pre>
129 )}
130 <textarea
131 aria-label="Theme JSON"
132 className={cn(
133 "relative z-10 block min-h-72 w-full resize-y overflow-auto bg-transparent p-3 font-mono text-[12px] leading-5 caret-foreground outline-none placeholder:text-muted-foreground selection:bg-accent/30",
134 isPlainText ? "text-foreground" : "text-transparent selection:text-transparent",
135 )}
136 id={id}
137 onChange={(event) => onChange(event.currentTarget.value)}
138 onScroll={syncScroll}
139 placeholder={
140 '{\n "version": 1,\n "name": "Aurora",\n "appearance": "light",\n "colors": { ... }\n}'
141 }
142 spellCheck={false}
143 value={value}
144 />
145 </div>
146 );
147}
148
149/** What the import pipeline needs from a file; DOM File satisfies it. */
150type ImportableThemeFile = { name: string; size: number; text: () => Promise<string> };
151
152export function ThemeImportDialog({
153 open,
154 onOpenChange,
155 onImported,
156 onImportedMany,
157}: {
158 open: boolean;
159 onOpenChange: (open: boolean) => void;
160 onImported: (theme: ThemeDefinition) => boolean;
161 /** Batch imports install without activating; the caller reports them. */
162 onImportedMany: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
163}) {
164 const fileInputRef = useRef<HTMLInputElement>(null);
165 const [json, setJson] = useState("");
166 const [fileName, setFileName] = useState<string | null>(null);
167 const [error, setError] = useState<string | null>(null);
168 const [isReading, setIsReading] = useState(false);
169 const [isDropTarget, setIsDropTarget] = useState(false);
170 // Imports whose id is already installed wait here for an update-or-copy
171 // decision instead of failing.
172 const [conflicts, setConflicts] = useState<ReadonlyArray<ThemeDefinition> | null>(null);
173 const importRequestRef = useRef(0);
174
175 useEffect(() => {
176 importRequestRef.current += 1;
177 // Reset on close too: a dialog dismissed mid-drag would otherwise reopen
178 // still wearing the drop highlight.
179 setIsDropTarget(false);
180 if (!open) return;
181 setJson("");
182 setFileName(null);
183 setError(null);
184 setIsReading(false);
185 setConflicts(null);
186 }, [open]);
187
188 const readThemeFile = useCallback(async (file: ImportableThemeFile) => {
189 // Check the size first: reading a large file is what locks the UI, so it
190 // never gets read at all.
191 const oversized = describeOversizedThemeFile(file.size);
192 if (oversized) {
193 setError(oversized);
194 return;
195 }
196
197 const requestId = ++importRequestRef.current;
198 setIsReading(true);
199 try {
200 const fileText = await file.text();
201 if (requestId !== importRequestRef.current) return;
202 setJson(fileText);
203 setFileName(file.name);
204 setError(null);
205 } catch {
206 if (requestId !== importRequestRef.current) return;
207 setError("Could not read that file. Paste the JSON below instead.");
208 } finally {
209 if (requestId === importRequestRef.current) setIsReading(false);
210 }
211 }, []);
212
213 // Several files at once import as a batch: VS Code families pair their
214 // light and dark variants, everything installs without activating, and the
215 // single-file flow keeps filling the editor for review.
216 const readThemeBatch = useCallback(
217 async (files: ReadonlyArray<ImportableThemeFile>) => {
218 const requestId = ++importRequestRef.current;
219 setIsReading(true);
220 const failures: string[] = [];
221 const parsed: Array<{ theme: ThemeDefinition; sourceName: string }> = [];
222 try {
223 for (const file of files) {
224 const oversized = describeOversizedThemeFile(file.size);
225 if (oversized) {
226 failures.push(`${file.name}: too large`);
227 continue;
228 }
229 try {
230 const value: unknown = JSON.parse(await file.text());
231 parsed.push({
232 sourceName: file.name,
233 theme: isVsCodeThemeFile(value) ? parseVsCodeThemeFile(value) : parseThemeFile(value),
234 });
235 } catch (cause) {
236 failures.push(
237 `${file.name}: ${cause instanceof Error ? cause.message : "not a theme file"}`,
238 );
239 }
240 }
241 if (requestId !== importRequestRef.current) return;
242 const installed: ThemeDefinition[] = [];
243 const conflicting: ThemeDefinition[] = [];
244 for (const theme of pairVsCodeThemes(resolveThemeLabelCollisions(parsed))) {
245 if (getCustomThemes().some((existing) => existing.id === theme.id)) {
246 conflicting.push(theme);
247 continue;
248 }
249 try {
250 installed.push(installCustomTheme(theme));
251 } catch (cause) {
252 failures.push(
253 `${theme.label}: ${cause instanceof Error ? cause.message : "could not install"}`,
254 );
255 }
256 }
257 if (installed.length > 0) onImportedMany(installed, { updated: false });
258 if (failures.length > 0) {
259 setError(failures.join(" — "));
260 } else if (conflicting.length > 0) {
261 setConflicts(conflicting);
262 } else if (installed.length > 0) {
263 onOpenChange(false);
264 }
265 } finally {
266 if (requestId === importRequestRef.current) setIsReading(false);
267 }
268 },
269 [onImportedMany, onOpenChange],
270 );
271
272 const readThemeFiles = useCallback(
273 (files: ReadonlyArray<ImportableThemeFile>) => {
274 if (files.length === 0) return;
275 if (files.length === 1) void readThemeFile(files[0]!);
276 else void readThemeBatch(files);
277 },
278 [readThemeBatch, readThemeFile],
279 );
280
281 // On desktop the native picker opens in ~/.vscode/extensions (when it
282 // exists) and reads the files in the main process; the browser input is
283 // the fallback everywhere else.
284 const openFilePicker = useCallback(() => {
285 const bridge = window.desktopBridge;
286 if (bridge?.pickThemeFiles) {
287 void bridge.pickThemeFiles().then((picked) => {
288 if (!picked || picked.length === 0) return;
289 readThemeFiles(
290 picked.map((file) => ({
291 name: file.name,
292 size: file.size,
293 text: () => Promise.resolve(file.text),
294 })),
295 );
296 });
297 return;
298 }
299 fileInputRef.current?.click();
300 }, [readThemeFiles]);
301
302 const handleFileChange = useCallback(
303 (event: ChangeEvent<HTMLInputElement>) => {
304 const files = [...(event.currentTarget.files ?? [])];
305 event.currentTarget.value = "";
306 readThemeFiles(files);
307 },
308 [readThemeFiles],
309 );
310
311 const handleDrop = useCallback(
312 (event: DragEvent<HTMLDivElement>) => {
313 event.preventDefault();
314 setIsDropTarget(false);
315 readThemeFiles([...event.dataTransfer.files]);
316 },
317 [readThemeFiles],
318 );
319
320 /** Copy of an already-installed theme under the source file's name when
321 * that differs (Dracula Soft), else the next free "Name (1)". */
322 const versionedCopy = (
323 theme: ThemeDefinition,
324 preferredName?: string | null,
325 ): ThemeDefinition => {
326 if (preferredName && preferredName.toLowerCase() !== theme.label.toLowerCase()) {
327 const candidate = parseThemeFile({
328 version: THEME_FILE_VERSION,
329 name: preferredName.slice(0, 48),
330 appearance: theme.appearance,
331 colors: theme.colors,
332 ...(theme.variants ? { variants: theme.variants } : {}),
333 ...(theme.managed ? { managed: true } : {}),
334 });
335 if (!getCustomThemes().some((existing) => existing.id === candidate.id)) return candidate;
336 }
337 for (let copy = 1; copy < 100; copy += 1) {
338 const candidate = parseThemeFile({
339 version: THEME_FILE_VERSION,
340 name: `${theme.label.slice(0, 48 - ` (${copy})`.length)} (${copy})`,
341 appearance: theme.appearance,
342 colors: theme.colors,
343 ...(theme.variants ? { variants: theme.variants } : {}),
344 ...(theme.managed ? { managed: true } : {}),
345 });
346 if (getCustomThemes().some((existing) => existing.id === candidate.id)) continue;
347 return candidate;
348 }
349 throw new Error(`Too many copies of "${theme.label}".`);
350 };
351
352 const resolveConflicts = useCallback(
353 (mode: "update" | "copy") => {
354 if (!conflicts) return;
355 const resolved: ThemeDefinition[] = [];
356 const failures: string[] = [];
357 const preferredName =
358 conflicts.length === 1 && fileName
359 ? humanizeThemeName(fileName.replace(/\.[^.]+$/, ""))
360 : null;
361 for (const theme of conflicts) {
362 try {
363 resolved.push(
364 mode === "update"
365 ? updateCustomTheme(theme)
366 : installCustomTheme(versionedCopy(theme, preferredName)),
367 );
368 } catch (cause) {
369 failures.push(`${theme.label}: ${cause instanceof Error ? cause.message : "failed"}`);
370 }
371 }
372 if (resolved.length > 0) onImportedMany(resolved, { updated: mode === "update" });
373 setConflicts(null);
374 if (failures.length > 0) setError(failures.join(" — "));
375 else onOpenChange(false);
376 },
377 [conflicts, fileName, onImportedMany, onOpenChange],
378 );
379
380 const handleSubmit = useCallback(() => {
381 // Pasted text bypasses the file guard, so the same limit applies here.
382 const oversized = describeOversizedThemeFile(json.length);
383 if (oversized) {
384 setError(oversized);
385 return;
386 }
387 try {
388 const parsed: unknown = JSON.parse(json);
389 // VS Code themes are converted on the way in; anything else has to be
390 // one of our own files.
391 const theme = isVsCodeThemeFile(parsed)
392 ? parseVsCodeThemeFile(parsed)
393 : parseThemeFile(parsed);
394 if (getCustomThemes().some((existing) => existing.id === theme.id)) {
395 setError(null);
396 setConflicts([theme]);
397 return;
398 }
399 const installedTheme = installCustomTheme(theme);
400 if (!onImported(installedTheme)) {
401 // Roll the install back so a retry can run it again instead of
402 // failing on the already-taken theme id.
403 try {
404 removeCustomTheme(installedTheme.id);
405 } catch {
406 // Storage is failing wholesale; the error below covers it.
407 }
408 setError("Theme added, but it could not be selected. Try again.");
409 return;
410 }
411 onOpenChange(false);
412 } catch (cause) {
413 setError(cause instanceof Error ? cause.message : "That theme file is invalid.");
414 }
415 }, [json, onImported, onOpenChange]);
416
417 return (
418 <Dialog
419 open={open}
420 onOpenChange={(nextOpen) => {
421 if (!nextOpen) setError(null);
422 onOpenChange(nextOpen);
423 }}
424 >
425 <DialogPopup className="max-w-3xl overflow-hidden">
426 <DialogHeader>
427 <DialogTitle>Add a theme</DialogTitle>
428 </DialogHeader>
429 <DialogPanel className="space-y-4">
430 {(() => {
431 const dropHandlers = {
432 onDragEnter: (event: DragEvent<HTMLDivElement>) => {
433 event.preventDefault();
434 setIsDropTarget(true);
435 },
436 onDragOver: (event: DragEvent<HTMLDivElement>) => {
437 event.preventDefault();
438 setIsDropTarget(true);
439 },
440 onDragLeave: (event: DragEvent<HTMLDivElement>) => {
441 // Ignore moves between children of the drop zone.
442 if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
443 setIsDropTarget(false);
444 },
445 onDrop: handleDrop,
446 };
447 const fileInput = (
448 <input
449 ref={fileInputRef}
450 accept=".json,application/json"
451 className="sr-only"
452 onChange={handleFileChange}
453 multiple
454 type="file"
455 />
456 );
457 const chooseButton = (label = "Choose files") => (
458 <Button disabled={isReading} size="sm" variant="outline" onClick={openFilePicker}>
459 <DownloadIcon />
460 {isReading ? "Reading…" : label}
461 </Button>
462 );
463 const editorSection = () => (
464 <div className="space-y-2">
465 <div className="flex items-baseline justify-between gap-3">
466 <label className="text-sm font-medium" htmlFor="theme-json-editor">
467 Theme JSON
468 </label>
469 </div>
470 <ThemeJsonEditor id="theme-json-editor" onChange={setJson} value={json} />
471 </div>
472 );
473 if (conflicts) {
474 return (
475 <div className="space-y-3">
476 <div className="rounded-xl border border-border/70 bg-muted/20 p-3">
477 <p className="text-sm font-medium">Already installed</p>
478 <p className="mt-1 text-xs text-muted-foreground">
479 {conflicts.map((theme) => theme.label).join(", ")}
480 </p>
481 </div>
482 <div className="flex flex-wrap items-center gap-2">
483 <Button size="sm" onClick={() => resolveConflicts("update")}>
484 Update existing
485 </Button>
486 <Button size="sm" variant="outline" onClick={() => resolveConflicts("copy")}>
487 Keep both
488 </Button>
489 <Button size="sm" variant="ghost" onClick={() => setConflicts(null)}>
490 Back
491 </Button>
492 </div>
493 </div>
494 );
495 }
496 return (
497 <div className="space-y-4">
498 <div
499 className={cn(
500 "flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed px-3 py-3 transition-colors",
501 isDropTarget ? "border-ring bg-accent/20" : "border-border/80 bg-muted/20",
502 )}
503 {...dropHandlers}
504 >
505 <div className="min-w-0">
506 <p className="text-sm font-medium">Theme file</p>
507 <p className="truncate text-xs text-muted-foreground">
508 {fileName ?? "Drop T3 Code or VS Code .json files"}
509 </p>
510 </div>
511 {chooseButton()}
512 {fileInput}
513 </div>
514 {editorSection()}
515 </div>
516 );
517 })()}
518
519 {error ? (
520 <Alert aria-live="polite" variant="error">
521 {error}
522 </Alert>
523 ) : null}
524 </DialogPanel>
525 <DialogFooter>
526 <Button variant="ghost" onClick={() => onOpenChange(false)}>
527 Cancel
528 </Button>
529 <Button disabled={!json.trim() || isReading} onClick={handleSubmit}>
530 <PlusIcon />
531 Add theme
532 </Button>
533 </DialogFooter>
534 </DialogPopup>
535 </Dialog>
536 );
537}