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