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

ThemeImportDialog.tsx

549 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 if (failures.length > 0) {
288 setError(failures.join("; "));
289 } else if (conflicting.length > 0) {
290 setConflicts(conflicting);
291 } else if (installed.length > 0) {
292 onClose();
293 }
294 };
295​
296 const readThemeFiles = (files: ReadonlyArray<ImportableThemeFile>) => {
297 if (files.length === 0) return;
298 if (files.length === 1) void readThemeFile(files[0]!);
299 else void readThemeBatch(files);
300 };
301​
302 const openFilePicker = () => {
303 const bridge = window.desktopBridge;
304 if (bridge?.pickThemeFiles) {
305 void bridge.pickThemeFiles().then((picked) => {
306 if (!picked || picked.length === 0) return;
307 readThemeFiles(
308 picked.map((file) => ({
309 name: file.name,
310 size: file.size,
311 text: () => Promise.resolve(file.text),
312 })),
313 );
314 });
315 return;
316 }
317 fileInputRef.current?.click();
318 };
319​
320 const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
321 const files = [...(event.currentTarget.files ?? [])];
322 event.currentTarget.value = "";
323 readThemeFiles(files);
324 };
325​
326 const handleDrop = (event: DragEvent<HTMLDivElement>) => {
327 event.preventDefault();
328 setIsDropTarget(false);
329 readThemeFiles([...event.dataTransfer.files]);
330 };
331​
332 const versionedCopy = (
333 theme: ThemeDefinition,
334 preferredName?: string | null,
335 ): ThemeDefinition => {
336 if (preferredName && preferredName.toLowerCase() !== theme.label.toLowerCase()) {
337 const candidate = parseThemeFile({
338 version: THEME_FILE_VERSION,
339 name: preferredName.slice(0, 48),
340 appearance: theme.appearance,
341 colors: theme.colors,
342 ...(theme.variants ? { variants: theme.variants } : {}),
343 ...(theme.managed ? { managed: true } : {}),
344 });
345 if (!getCustomThemes().some((existing) => existing.id === candidate.id)) return candidate;
346 }
347 for (let copy = 1; copy < 100; copy += 1) {
348 const candidate = parseThemeFile({
349 version: THEME_FILE_VERSION,
350 name: `${theme.label.slice(0, 48 - ` (${copy})`.length)} (${copy})`,
351 appearance: theme.appearance,
352 colors: theme.colors,
353 ...(theme.variants ? { variants: theme.variants } : {}),
354 ...(theme.managed ? { managed: true } : {}),
355 });
356 if (getCustomThemes().some((existing) => existing.id === candidate.id)) continue;
357 return candidate;
358 }
359 throw new Error(`Too many copies of "${theme.label}".`);
360 };
361​
362 const resolveConflicts = (mode: "update" | "copy") => {
363 if (!conflicts) return;
364 const resolved: ThemeDefinition[] = [];
365 const failures: string[] = [];
366 const preferredName =
367 conflicts.length === 1 && fileName
368 ? humanizeThemeName(fileName.replace(/\.[^.]+$/, ""))
369 : null;
370 for (const theme of conflicts) {
371 try {
372 const existingTheme =
373 mode === "update"
374 ? getCustomThemes().find((candidate) => candidate.id === theme.id)
375 : undefined;
376 const themeToUpdate = existingTheme?.collection
377 ? { ...theme, collection: existingTheme.collection }
378 : theme;
379 resolved.push(
380 mode === "update"
381 ? updateCustomTheme(themeToUpdate)
382 : installCustomTheme(versionedCopy(theme, preferredName)),
383 );
384 } catch (cause) {
385 failures.push(`${theme.label}: ${cause instanceof Error ? cause.message : "failed"}`);
386 }
387 }
388 if (resolved.length > 0) onImportedMany(resolved, { updated: mode === "update" });
389 setConflicts(null);
390 if (failures.length > 0) setError(failures.join("; "));
391 else onClose();
392 };
393​
394 const handleSubmit = () => {
395 const oversized = describeOversizedThemeFile(json.length);
396 if (oversized) {
397 setError(oversized);
398 return;
399 }
400 try {
401 const parsed: unknown = JSON.parse(json);
402 const theme = isVsCodeThemeFile(parsed)
403 ? parseVsCodeThemeFile(parsed)
404 : parseThemeFile(parsed);
405 if (getCustomThemes().some((existing) => existing.id === theme.id)) {
406 setError(null);
407 setConflicts([theme]);
408 return;
409 }
410 const installedTheme = installCustomTheme(theme);
411 if (!onImported(installedTheme)) {
412 try {
413 removeCustomTheme(installedTheme.id);
414 } catch {}
415 setError("Theme added, but it could not be selected. Try again.");
416 return;
417 }
418 onClose();
419 } catch (cause) {
420 setError(cause instanceof Error ? cause.message : "That theme file is invalid.");
421 }
422 };
423​
424 return (
425 <DialogPanel>
426 <ThemeSearchSection
427 onInstalled={(themes, context) => {
428 onImportedMany(themes, context);
429 onClose();
430 }}
431 signal={signal}
432 />
433​
434 <div className="flex items-center gap-3" aria-hidden>
435 <div className="h-px flex-1 bg-border" />
436 <span className="text-muted-foreground text-2xs uppercase tracking-wider">
437 or import a file
438 </span>
439 <div className="h-px flex-1 bg-border" />
440 </div>
441​
442 {(() => {
443 const dropHandlers = {
444 onDragEnter: (event: DragEvent<HTMLDivElement>) => {
445 event.preventDefault();
446 setIsDropTarget(true);
447 },
448 onDragOver: (event: DragEvent<HTMLDivElement>) => {
449 event.preventDefault();
450 setIsDropTarget(true);
451 },
452 onDragLeave: (event: DragEvent<HTMLDivElement>) => {
453 if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
454 setIsDropTarget(false);
455 },
456 onDrop: handleDrop,
457 };
458 const fileInput = (
459 <input
460 ref={fileInputRef}
461 accept=".json,application/json"
462 className="sr-only"
463 onChange={handleFileChange}
464 multiple
465 type="file"
466 />
467 );
468 const chooseButton = (label = "Choose files") => (
469 <Button disabled={isReading} size="sm" variant="outline" onClick={openFilePicker}>
470 <DownloadIcon />
471 {isReading ? "Reading…" : label}
472 </Button>
473 );
474 const editorSection = () => (
475 <div className="space-y-2">
476 <div className="flex items-baseline justify-between gap-3">
477 <label className="text-sm font-medium" htmlFor="theme-json-editor">
478 Theme JSON
479 </label>
480 </div>
481 <ThemeJsonEditor id="theme-json-editor" onChange={setJson} value={json} />
482 </div>
483 );
484 if (conflicts) {
485 return (
486 <div className="space-y-3">
487 <div className="rounded-xl border border-border/70 bg-muted/20 p-3">
488 <p className="text-sm font-medium">Already installed</p>
489 <p className="mt-1 text-xs text-muted-foreground">
490 {conflicts.map((theme) => theme.label).join(", ")}
491 </p>
492 </div>
493 <div className="flex flex-wrap items-center gap-2">
494 <Button size="sm" onClick={() => resolveConflicts("update")}>
495 Update existing
496 </Button>
497 <Button size="sm" variant="outline" onClick={() => resolveConflicts("copy")}>
498 Keep both
499 </Button>
500 <Button size="sm" variant="ghost" onClick={() => setConflicts(null)}>
501 Back
502 </Button>
503 <Button size="sm" variant="ghost" onClick={() => onClose()}>
504 Cancel
505 </Button>
506 </div>
507 </div>
508 );
509 }
510 return (
511 <div className="space-y-4">
512 <div
513 className={cn(
514 "flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed px-3 py-3 transition-colors",
515 isDropTarget ? "border-ring bg-accent/20" : "border-border/80 bg-muted/20",
516 )}
517 {...dropHandlers}
518 >
519 <div className="min-w-0">
520 <p className="text-sm font-medium">Theme file</p>
521 <p className="truncate text-xs text-muted-foreground">
522 {fileName ?? "Drop T3 Code or VS Code .json files"}
523 </p>
524 </div>
525 {chooseButton()}
526 {fileInput}
527 </div>
528 {editorSection()}
529 <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
530 <Button variant="ghost" onClick={() => onClose()}>
531 Cancel
532 </Button>
533 <Button disabled={!json.trim() || isReading} onClick={handleSubmit}>
534 <PlusIcon />
535 Add theme
536 </Button>
537 </div>
538 </div>
539 );
540 })()}
541​
542 {error ? (
543 <Alert aria-live="polite" variant="error">
544 {error}
545 </Alert>
546 ) : null}
547 </DialogPanel>
548 );