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

ThemeImportDialog.tsx

527 lines18.3 KB

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