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