Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThemeImportDialog.tsx

561 lines19.8 KB

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