@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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