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