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

ThemeImportDialog.tsx

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