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