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

ThemeImportDialog.tsx

582 lines19.4 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { DownloadIcon, PlusIcon } from "lucide-react";
3import type { ChangeEvent, DragEvent, UIEvent } from "react";
4import { settlePromise } from "@t3tools/client-runtime/state/runtime";
5import { useEffect, useRef, useState } from "react";
6import { formatBytes } from "../../lib/formatBytes";
7import { cn } from "../../lib/utils";
8import {
9 getCustomThemes,
10 installCustomTheme,
11 isReservedThemeId,
12 removeCustomTheme,
13 renameTheme,
14 themeIdFromName,
15 updateCustomTheme,
16 type ThemeDefinition,
17} from "../../themePalette";
18import {
19 humanizeThemeName,
20 numberedThemeName,
21 pairVsCodeThemes,
22 parseThemeImport,
23 resolveThemeLabelCollisions,
24 truncateThemeName,
25} from "../../vscodeThemeImport";
26import { Alert } from "../ui/alert";
27import { Button } from "../ui/button";
28import { Dialog, DialogHeader, DialogPanel, DialogPopup, DialogTitle } from "../ui/dialog";
29import { ThemeSearchSection } from "./ThemeSearchSection";
30import { msg, T, useGT } from "gt-react";
31import { m } from "../../i18n/messages";
32​
33/**
34 * The guard runs on the size before the bytes are ever read: a large file
35 * would otherwise be pulled into memory, highlighted, and rendered, which
36 * locks the UI for as long as that takes.
37 */
38const MAX_THEME_FILE_BYTES = 256 * 1024;
39​
40/** Highlighting rebuilds markup per keystroke; fall back to plain text for oversized pastes. */
41const MAX_HIGHLIGHTED_JSON_LENGTH = 20_000;
42​
43function describeOversizedThemeFile(bytes: number): string | null {
44 if (bytes <= MAX_THEME_FILE_BYTES) return null;
45 return m(
46 msg`That file is ${{ size: formatBytes(bytes) }}. Theme files are only a few KB, so this one was not read (limit ${{ limit: formatBytes(MAX_THEME_FILE_BYTES) }}).`,
47 );
49​
50function isThemeIdTaken(themeId: string): boolean {
51 return getCustomThemes().some((existing) => existing.id === themeId);
53​
54function escapeJsonHtml(value: string): string {
55 return value.replace(
56 /[&<>"']/g,
57 (character) =>
58 ({
59 "&": "&amp;",
60 "<": "&lt;",
61 ">": "&gt;",
62 '"': "&quot;",
63 "'": "&#39;",
64 })[character] ?? character,
65 );
67​
68function highlightJson(value: string): string {
69 const tokenPattern =
70 /"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g;
71 let highlighted = "";
72 let cursor = 0;
73​
74 for (const match of value.matchAll(tokenPattern)) {
75 const token = match[0];
76 const index = match.index ?? 0;
77 highlighted += escapeJsonHtml(value.slice(cursor, index));
78​
79 let tokenClass = "text-[var(--app-theme-secondary-foreground,var(--color-amber-600))]";
80 if (token.startsWith('"')) {
81 tokenClass = /^\s*:/.test(value.slice(index + token.length))
82 ? "text-[var(--app-theme-accent,var(--color-blue-600))]"
83 : "text-[var(--app-theme-message-action,var(--color-emerald-600))]";
84 } else if (token === "true" || token === "false" || token === "null") {
85 tokenClass = "text-[var(--app-theme-accent-surface-foreground,var(--color-violet-600))]";
86 }
87 highlighted += `<span class="${tokenClass}">${escapeJsonHtml(token)}</span>`;
88 cursor = index + token.length;
89 }
90​
91 return highlighted + escapeJsonHtml(value.slice(cursor));
93​
94function ThemeJsonEditor({
95 id,
96 value,
97 onChange,
98}: {
99 id: string;
100 value: string;
101 onChange: (value: string) => void;
102}) {
103 const gt = useGT();
104 const highlightRef = useRef<HTMLPreElement>(null);
105 const isPlainText = value.length > MAX_HIGHLIGHTED_JSON_LENGTH;
106 const highlightedJson = isPlainText ? "" : highlightJson(value);
107​
108 const syncScroll = (event: UIEvent<HTMLTextAreaElement>) => {
109 const highlightElement = highlightRef.current;
110 if (!highlightElement) return;
111 highlightElement.scrollTop = event.currentTarget.scrollTop;
112 highlightElement.scrollLeft = event.currentTarget.scrollLeft;
113 };
114​
115 return (
116 <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">
117 {isPlainText ? null : (
118 <pre
119 ref={highlightRef}
120 aria-hidden
121 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"
122 >
123 <code dangerouslySetInnerHTML={{ __html: highlightedJson }} />
124 </pre>
125 )}
126 <textarea
127 aria-label={gt`Theme JSON`}
128 className={cn(
129 "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",
130 isPlainText ? "text-foreground" : "text-transparent",
131 )}
132 id={id}
133 onChange={(event) => onChange(event.currentTarget.value)}
134 onScroll={syncScroll}
135 placeholder={
136 // oxlint-disable-next-line t3code/no-untranslated-copy -- example theme JSON
137 '{\n "version": 1,\n "name": "Aurora",\n "appearance": "light",\n "colors": { ... }\n}'
138 }
139 spellCheck={false}
140 value={value}
141 />
142 </div>
143 );
145​
146type ImportableThemeFile = { name: string; size: number; text: () => Promise<string> };
147​
148interface ThemeImportCallbacks {
149 onImported: (theme: ThemeDefinition) => boolean;
150 onImportedMany: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
152​
153export function ThemeImportDialog({
154 open,
155 onOpenChange,
156 onImported,
157 onImportedMany,
158}: ThemeImportCallbacks & {
159 open: boolean;
160 onOpenChange: (open: boolean) => void;
161}) {
162 // Each opening is a fresh session: its body remounts with clean state, and
163 // closing aborts every read, search, and install the session started.
164 const [session, setSession] = useState(() => ({
165 open,
166 id: 0,
167 controller: new AbortController(),
168 }));
169 if (session.open !== open) {
170 setSession(
171 open ? { open, id: session.id + 1, controller: new AbortController() } : { ...session, open },
172 );
173 }
174 const close = () => {
175 session.controller.abort();
176 onOpenChange(false);
177 };
178 // Leaving the page ends the session as closing does. The abort waits a microtask
179 // so StrictMode's replayed cleanup, undone by its replayed setup, keeps it alive.
180 const { controller } = session;
181 const mountedController = useRef<AbortController | null>(null);
182 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- unmounting must abort in-flight Open VSX installs
183 useEffect(() => {
184 mountedController.current = controller;
185 return () => {
186 mountedController.current = null;
187 queueMicrotask(() => {
188 if (mountedController.current !== controller) controller.abort();
189 });
190 };
191 }, [controller]);
192​
193 return (
194 <Dialog
195 open={open}
196 onOpenChange={(nextOpen) => {
197 if (nextOpen) onOpenChange(true);
198 else close();
199 }}
200 >
201 <DialogPopup className="max-w-3xl overflow-hidden">
202 <DialogHeader>
203 <DialogTitle>
204 <T>Add a theme</T>
205 </DialogTitle>
206 </DialogHeader>
207 <ThemeImportBody
208 key={session.id}
209 session={session.controller}
210 onClose={close}
211 onImported={onImported}
212 onImportedMany={onImportedMany}
213 />
214 </DialogPopup>
215 </Dialog>
216 );
218​
219function ThemeImportBody({
220 session,
221 onClose,
222 onImported,
223 onImportedMany,
224}: ThemeImportCallbacks & {
225 session: AbortController;
226 onClose: () => void;
227}) {
228 const gt = useGT();
229 const { signal } = session;
230 const fileInputRef = useRef<HTMLInputElement>(null);
231 const [json, setJson] = useState("");
232 const [fileName, setFileName] = useState<string | null>(null);
233 const [error, setError] = useState<string | null>(null);
234 const [isReading, setIsReading] = useState(false);
235 const [isDropTarget, setIsDropTarget] = useState(false);
236 const [conflicts, setConflicts] = useState<ReadonlyArray<ThemeDefinition> | null>(null);
237 const [conflictFileName, setConflictFileName] = useState<string | null>(null);
238 // A new file selection supersedes a pending import even if the selection is rejected.
239 const importRequestRef = useRef(0);
240 const isCurrentRequest = (requestId: number) =>
241 requestId === importRequestRef.current && !signal.aborted;
242​
243 const readThemeFile = async (file: ImportableThemeFile) => {
244 const requestId = ++importRequestRef.current;
245 const oversized = describeOversizedThemeFile(file.size);
246 if (oversized) {
247 setIsReading(false);
248 setError(oversized);
249 return;
250 }
251​
252 setIsReading(true);
253 const fileText = await settlePromise(() => file.text());
254 if (!isCurrentRequest(requestId)) return;
255 setIsReading(false);
256 if (fileText._tag === "Failure") {
257 setError(gt`Could not read that file. Paste the JSON below instead.`);
258 return;
259 }
260 setJson(fileText.value);
261 setFileName(file.name);
262 setError(null);
263 };
264​
265 const readThemeBatch = (files: ReadonlyArray<ImportableThemeFile>) => {
266 const requestId = ++importRequestRef.current;
267 setIsReading(true);
268 return installThemeBatch(files, requestId).finally(() => {
269 if (isCurrentRequest(requestId)) setIsReading(false);
270 });
271 };
272​
273 const installThemeBatch = async (
274 files: ReadonlyArray<ImportableThemeFile>,
275 requestId: number,
276 ) => {
277 const failures: string[] = [];
278 const parsed: Array<{ theme: ThemeDefinition; sourceName: string }> = [];
279 for (const file of files) {
280 const oversized = describeOversizedThemeFile(file.size);
281 if (oversized) {
282 failures.push(`${file.name}: ${oversized}`);
283 continue;
284 }
285 try {
286 parsed.push({
287 sourceName: file.name,
288 theme: parseThemeImport(await file.text()),
289 });
290 } catch (cause) {
291 failures.push(
292 `${file.name}: ${cause instanceof Error ? (thrownErrorMessage(cause, m) ?? cause.message) : gt`not a theme file`}`,
293 );
294 }
295 }
296 if (!isCurrentRequest(requestId)) return;
297 const installed: ThemeDefinition[] = [];
298 const conflicting: ThemeDefinition[] = [];
299 for (const theme of pairVsCodeThemes(resolveThemeLabelCollisions(parsed))) {
300 if (isThemeIdTaken(theme.id)) {
301 conflicting.push(theme);
302 continue;
303 }
304 try {
305 installed.push(installCustomTheme(theme));
306 } catch (cause) {
307 failures.push(
308 `${theme.label}: ${cause instanceof Error ? (thrownErrorMessage(cause, m) ?? cause.message) : gt`could not install`}`,
309 );
310 }
311 }
312 if (installed.length > 0) onImportedMany(installed, { updated: false });
313 setError(failures.length > 0 ? failures.join("; ") : null);
314 if (conflicting.length > 0) {
315 setConflictFileName(null);
316 setConflicts(conflicting);
317 } else if (installed.length > 0 && failures.length === 0) {
318 onClose();
319 }
320 };
321​
322 const readThemeFiles = (files: ReadonlyArray<ImportableThemeFile>) => {
323 if (files.length === 0) return;
324 if (files.length === 1) void readThemeFile(files[0]!);
325 else void readThemeBatch(files);
326 };
327​
328 const openFilePicker = () => {
329 const bridge = window.desktopBridge;
330 if (bridge) {
331 void bridge.pickThemeFiles().then((picked) => {
332 if (!picked || picked.length === 0) return;
333 readThemeFiles(
334 picked.map((file) => ({
335 name: file.name,
336 size: file.size,
337 text: () => Promise.resolve(file.text),
338 })),
339 );
340 });
341 return;
342 }
343 fileInputRef.current?.click();
344 };
345​
346 const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
347 const files = [...(event.currentTarget.files ?? [])];
348 event.currentTarget.value = "";
349 readThemeFiles(files);
350 };
351​
352 const handleDrop = (event: DragEvent<HTMLDivElement>) => {
353 event.preventDefault();
354 setIsDropTarget(false);
355 readThemeFiles([...event.dataTransfer.files]);
356 };
357​
358 const versionedCopy = (
359 theme: ThemeDefinition,
360 preferredName?: string | null,
361 ): ThemeDefinition => {
362 // renameTheme leaves the collection behind: updating a collection replaces every theme in it.
363 if (preferredName) {
364 const name = truncateThemeName(preferredName).trimEnd();
365 if (
366 name &&
367 name.toLowerCase() !== theme.label.toLowerCase() &&
368 !isReservedThemeId(themeIdFromName(name))
369 ) {
370 const candidate = renameTheme(theme, name);
371 if (!isThemeIdTaken(candidate.id)) return candidate;
372 }
373 }
374 for (let copy = 1; copy < 100; copy += 1) {
375 const candidate = renameTheme(theme, numberedThemeName(theme.label, ` (${copy})`));
376 if (!isThemeIdTaken(candidate.id)) return candidate;
377 }
378 throw new Error(m(msg`Too many copies of "${{ label: theme.label }}".`));
379 };
380​
381 const resolveConflicts = (mode: "update" | "copy") => {
382 if (!conflicts) return;
383 const resolved: ThemeDefinition[] = [];
384 const failures: string[] = [];
385 const preferredName =
386 conflicts.length === 1 && conflictFileName
387 ? humanizeThemeName(conflictFileName.replace(/\.[^.]+$/, ""))
388 : null;
389 for (const theme of conflicts) {
390 try {
391 const existingTheme =
392 mode === "update"
393 ? getCustomThemes().find((candidate) => candidate.id === theme.id)
394 : undefined;
395 const themeToUpdate = existingTheme?.collection
396 ? { ...theme, collection: existingTheme.collection }
397 : theme;
398 resolved.push(
399 mode === "update"
400 ? updateCustomTheme(themeToUpdate)
401 : installCustomTheme(versionedCopy(theme, preferredName)),
402 );
403 } catch (cause) {
404 failures.push(
405 `${theme.label}: ${cause instanceof Error ? (thrownErrorMessage(cause, m) ?? cause.message) : gt({ context: "theme import result" })`failed`}`,
406 );
407 }
408 }
409 if (resolved.length > 0) onImportedMany(resolved, { updated: mode === "update" });
410 setConflicts(null);
411 if (failures.length > 0) setError([error, ...failures].filter(Boolean).join("; "));
412 else if (!error) onClose();
413 };
414​
415 const handleJsonChange = (nextJson: string) => {
416 setJson(nextJson);
417 setError(null);
418 };
419​
420 const handleSubmit = () => {
421 const oversized = describeOversizedThemeFile(new TextEncoder().encode(json).byteLength);
422 if (oversized) {
423 setError(oversized);
424 return;
425 }
426 try {
427 const theme = parseThemeImport(json);
428 if (isThemeIdTaken(theme.id)) {
429 setError(null);
430 setConflictFileName(fileName);
431 setConflicts([theme]);
432 return;
433 }
434 const installedTheme = installCustomTheme(theme);
435 if (!onImported(installedTheme)) {
436 try {
437 removeCustomTheme(installedTheme.id);
438 } catch {}
439 setError(gt`Theme added, but it could not be selected. Try again.`);
440 return;
441 }
442 onClose();
443 } catch (cause) {
444 setError(
445 cause instanceof Error
446 ? (thrownErrorMessage(cause, m) ?? cause.message)
447 : gt`That theme file is invalid.`,
448 );
449 }
450 };
451​
452 return (
453 <DialogPanel>
454 <ThemeSearchSection
455 onInstalled={(themes, context) => {
456 onImportedMany(themes, context);
457 onClose();
458 }}
459 signal={signal}
460 />
461​
462 <div className="flex items-center gap-3" aria-hidden>
463 <div className="h-px flex-1 bg-border" />
464 <span className="text-muted-foreground text-2xs uppercase tracking-wider">
465 <T>or import a file</T>
466 </span>
467 <div className="h-px flex-1 bg-border" />
468 </div>
469​
470 {(() => {
471 const dropHandlers = {
472 onDragEnter: (event: DragEvent<HTMLDivElement>) => {
473 event.preventDefault();
474 setIsDropTarget(true);
475 },
476 onDragOver: (event: DragEvent<HTMLDivElement>) => {
477 event.preventDefault();
478 setIsDropTarget(true);
479 },
480 onDragLeave: (event: DragEvent<HTMLDivElement>) => {
481 if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
482 setIsDropTarget(false);
483 },
484 onDrop: handleDrop,
485 };
486 const fileInput = (
487 <input
488 ref={fileInputRef}
489 accept=".json,application/json"
490 className="sr-only"
491 onChange={handleFileChange}
492 multiple
493 type="file"
494 />
495 );
496 const chooseFiles = gt`Choose files`;
497 const chooseButton = (label = chooseFiles) => (
498 <Button disabled={isReading} size="sm" variant="outline" onClick={openFilePicker}>
499 <DownloadIcon />
500 {isReading ? gt`Reading…` : label}
501 </Button>
502 );
503 const editorSection = () => (
504 <div className="space-y-2">
505 <div className="flex items-baseline justify-between gap-3">
506 <label className="text-sm font-medium" htmlFor="theme-json-editor">
507 <T>Theme JSON</T>
508 </label>
509 </div>
510 <ThemeJsonEditor id="theme-json-editor" onChange={handleJsonChange} value={json} />
511 </div>
512 );
513 if (conflicts) {
514 return (
515 <div className="space-y-3">
516 <div className="rounded-xl border border-border/70 bg-muted/20 p-3">
517 <p className="text-sm font-medium">
518 <T>Already installed</T>
519 </p>
520 <p className="mt-1 text-xs text-muted-foreground">
521 {conflicts.map((theme) => theme.label).join(", ")}
522 </p>
523 </div>
524 <div className="flex flex-wrap items-center gap-2">
525 <Button size="sm" onClick={() => resolveConflicts("update")}>
526 <T>Update existing</T>
527 </Button>
528 <Button size="sm" variant="outline" onClick={() => resolveConflicts("copy")}>
529 <T>Keep both</T>
530 </Button>
531 <Button size="sm" variant="ghost" onClick={() => setConflicts(null)}>
532 <T>Back</T>
533 </Button>
534 <Button size="sm" variant="ghost" onClick={() => onClose()}>
535 <T>Cancel</T>
536 </Button>
537 </div>
538 </div>
539 );
540 }
541 return (
542 <div className="space-y-4">
543 <div
544 className={cn(
545 "flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed px-3 py-3 transition-colors",
546 isDropTarget ? "border-ring bg-accent/20" : "border-border/80 bg-muted/20",
547 )}
548 {...dropHandlers}
549 >
550 <div className="min-w-0">
551 <p className="text-sm font-medium">
552 <T>Theme file</T>
553 </p>
554 <p className="truncate text-xs text-muted-foreground">
555 {fileName ?? gt`Drop T3 Code or VS Code .json files`}
556 </p>
557 </div>
558 {chooseButton()}
559 {fileInput}
560 </div>
561 {editorSection()}
562 <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
563 <Button variant="ghost" onClick={() => onClose()}>
564 <T>Cancel</T>
565 </Button>
566 <Button disabled={!json.trim() || isReading} onClick={handleSubmit}>
567 <PlusIcon />
568 <T>Add theme</T>
569 </Button>
570 </div>
571 </div>
572 );
573 })()}
574​
575 {error ? (
576 <Alert aria-live="polite" variant="error">
577 {error}
578 </Alert>
579 ) : null}
580 </DialogPanel>
581 );