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

ThemeImportDialog.tsx

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