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

main
tsx 575 lines 18.8 KB
Raw
1 import type { ReactNode } from "react";
2 import { useEffect, useEffectEvent, useRef, useState } from "react";
3 import {
4 DEFAULT_UNIFIED_SETTINGS,
5 MAX_CODE_FONT_SIZE,
6 MAX_INTERFACE_FONT_SIZE,
7 MAX_PROMPT_FONT_SIZE,
8 MAX_TERMINAL_FONT_SIZE,
9 MIN_CODE_FONT_SIZE,
10 MIN_INTERFACE_FONT_SIZE,
11 MIN_PROMPT_FONT_SIZE,
12 MIN_TERMINAL_FONT_SIZE,
13 } from "@t3tools/contracts/settings";
14 import * as Schema from "effect/Schema";
15 import { useGT } from "gt-react";
16 import { useLocalStorage } from "../../hooks/useLocalStorage";
17 import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
18 import { isMacPlatform } from "../../lib/utils";
19 import { Input } from "../ui/input";
20 import {
21 DEFAULT_CODE_FONT_STACK,
22 DEFAULT_SANS_FONT_STACK,
23 isFontFamilyAvailable,
24 isMonospaceFamily,
25 resolveDefaultFamilyLabel,
26 resolveTerminalFontPreference,
27 resolveTerminalFontSizePreference,
28 TYPOGRAPHY_ADVANCED_STORAGE_KEY,
29 } from "../../appearanceFonts";
30 import { AdvancedSettings } from "./AdvancedSettings";
31 import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews";
32 import { discoverInstalledFonts, FontFamilyPicker, useFontEnumeration } from "./FontFamilyPicker";
33 import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
34 import { Switch } from "../ui/switch";
35 import {
36 SettingResetButton,
37 SettingsRow,
38 SettingsSection,
39 useSettingsSearchTargetId,
40 } from "./settingsLayout";
41 import {
42 isAdvancedTypographyTarget,
43 revealSettingsSearchTarget,
44 useSearchableSetting,
45 } from "./settingsSearch";
46
47 let fontDefaultFamilies: { readonly sans: string | null; readonly code: string | null } | undefined;
48
49 function resolveFontDefaultFamilies() {
50 if (fontDefaultFamilies !== undefined) return fontDefaultFamilies;
51 const families = {
52 sans: resolveDefaultFamilyLabel(DEFAULT_SANS_FONT_STACK) ?? null,
53 code: resolveDefaultFamilyLabel(DEFAULT_CODE_FONT_STACK) ?? null,
54 };
55 if (document.fonts.status === "loaded") fontDefaultFamilies = families;
56 return families;
57 }
58
59 function useFontDefaultFamilies() {
60 const gt = useGT();
61 const settings = useScopedSettings();
62 const [defaults] = useState(resolveFontDefaultFamilies);
63 const sans = defaults.sans ?? gt("System default");
64 return {
65 sans,
66 code: defaults.code ?? gt("System monospace"),
67 interfaceFamily: settings.fontFamilySans.trim() || sans,
68 };
69 }
70
71 function InterfaceFontRow({ preview }: { preview?: ReactNode }) {
72 const gt = useGT();
73 const searchableSetting = useSearchableSetting();
74 const settings = useScopedSettings();
75 const updateSettings = useUpdateScopedSettings();
76 const defaults = useFontDefaultFamilies();
77 return (
78 <FontFamilySettingsRow
79 {...searchableSetting("interface-font")}
80 resetLabel={gt("Reset interface font to default")}
81 description={gt("Everything outside code blocks and the terminal.")}
82 defaultFamily={defaults.sans}
83 defaultValue={DEFAULT_UNIFIED_SETTINGS.fontFamilySans}
84 value={settings.fontFamilySans}
85 onValueChange={(fontFamilySans) => updateSettings({ fontFamilySans })}
86 onReset={() =>
87 updateSettings({
88 fontFamilySans: DEFAULT_UNIFIED_SETTINGS.fontFamilySans,
89 fontSizeInterface: DEFAULT_UNIFIED_SETTINGS.fontSizeInterface,
90 })
91 }
92 size={{
93 label: gt("Interface font size"),
94 min: MIN_INTERFACE_FONT_SIZE,
95 max: MAX_INTERFACE_FONT_SIZE,
96 value: settings.fontSizeInterface,
97 defaultValue: DEFAULT_UNIFIED_SETTINGS.fontSizeInterface,
98 onChange: (fontSizeInterface) => updateSettings({ fontSizeInterface }),
99 }}
100 {...(preview !== undefined ? { preview } : {})}
101 />
102 );
103 }
104
105 function PromptFontRow() {
106 const gt = useGT();
107 const searchableSetting = useSearchableSetting();
108 const settings = useScopedSettings();
109 const updateSettings = useUpdateScopedSettings();
110 const defaults = useFontDefaultFamilies();
111 return (
112 <FontFamilySettingsRow
113 {...searchableSetting("prompt-font")}
114 resetLabel={gt("Reset prompt font to default")}
115 description={gt("Only the box you write prompts in. Mono works well here.")}
116 defaultFamily={defaults.interfaceFamily}
117 defaultValue={DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer}
118 value={settings.fontFamilyComposer}
119 onValueChange={(fontFamilyComposer) => updateSettings({ fontFamilyComposer })}
120 onReset={() =>
121 updateSettings({
122 fontFamilyComposer: DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer,
123 fontSizePrompt: DEFAULT_UNIFIED_SETTINGS.fontSizePrompt,
124 })
125 }
126 size={{
127 label: gt("Prompt font size"),
128 min: MIN_PROMPT_FONT_SIZE,
129 max: MAX_PROMPT_FONT_SIZE,
130 value: settings.fontSizePrompt,
131 defaultValue: DEFAULT_UNIFIED_SETTINGS.fontSizePrompt,
132 onChange: (fontSizePrompt) => updateSettings({ fontSizePrompt }),
133 }}
134 preview={<PromptFontPreview />}
135 />
136 );
137 }
138
139 function CodeFontRow({
140 title,
141 resetLabel,
142 description,
143 preview,
144 }: {
145 title?: string;
146 resetLabel?: string;
147 description?: string;
148 preview?: ReactNode;
149 }) {
150 const gt = useGT();
151 const searchableSetting = useSearchableSetting();
152 const settings = useScopedSettings();
153 const updateSettings = useUpdateScopedSettings();
154 const defaults = useFontDefaultFamilies();
155 return (
156 <FontFamilySettingsRow
157 {...searchableSetting("code-font")}
158 {...(title !== undefined ? { title } : {})}
159 resetLabel={resetLabel ?? gt("Reset code font to default")}
160 description={description ?? gt("Code blocks, diffs, and file previews.")}
161 defaultFamily={defaults.code}
162 defaultValue={DEFAULT_UNIFIED_SETTINGS.fontFamilyCode}
163 value={settings.fontFamilyCode}
164 onValueChange={(fontFamilyCode) => updateSettings({ fontFamilyCode })}
165 onReset={() =>
166 updateSettings({
167 fontFamilyCode: DEFAULT_UNIFIED_SETTINGS.fontFamilyCode,
168 fontSizeCode: DEFAULT_UNIFIED_SETTINGS.fontSizeCode,
169 })
170 }
171 requireMonospace
172 size={{
173 label: gt("Code font size"),
174 min: MIN_CODE_FONT_SIZE,
175 max: MAX_CODE_FONT_SIZE,
176 value: settings.fontSizeCode,
177 defaultValue: DEFAULT_UNIFIED_SETTINGS.fontSizeCode,
178 onChange: (fontSizeCode) => updateSettings({ fontSizeCode }),
179 }}
180 preview={preview ?? <CodeFontPreview />}
181 />
182 );
183 }
184
185 function TerminalFontRow() {
186 const gt = useGT();
187 const searchableSetting = useSearchableSetting();
188 const settings = useScopedSettings();
189 const updateSettings = useUpdateScopedSettings();
190 const defaults = useFontDefaultFamilies();
191 return (
192 <FontFamilySettingsRow
193 {...searchableSetting("terminal-font")}
194 resetLabel={gt("Reset terminal font to default")}
195 description={gt("Terminal output, independent from code blocks and diffs.")}
196 defaultFamily={defaults.code}
197 defaultValue={DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal}
198 value={settings.fontFamilyTerminal}
199 onValueChange={(fontFamilyTerminal) => updateSettings({ fontFamilyTerminal })}
200 onReset={() =>
201 updateSettings({
202 fontFamilyTerminal: DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal,
203 fontSizeTerminal: DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal,
204 })
205 }
206 requireMonospace
207 size={{
208 label: gt("Terminal font size"),
209 min: MIN_TERMINAL_FONT_SIZE,
210 max: MAX_TERMINAL_FONT_SIZE,
211 value: settings.fontSizeTerminal,
212 defaultValue: DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal,
213 onChange: (fontSizeTerminal) => updateSettings({ fontSizeTerminal }),
214 }}
215 preview={
216 <TerminalFontPreview
217 family={resolveTerminalFontPreference({
218 advanced: true,
219 code: settings.fontFamilyCode,
220 terminal: settings.fontFamilyTerminal,
221 })}
222 size={settings.fontSizeTerminal}
223 />
224 }
225 />
226 );
227 }
228
229 function FontSmoothingRow() {
230 const gt = useGT();
231 const searchableSetting = useSearchableSetting();
232 const settings = useScopedSettings();
233 const updateSettings = useUpdateScopedSettings();
234 if (!isMacPlatform(navigator.platform)) return null;
235 return (
236 <SettingsRow
237 {...searchableSetting("font-smoothing")}
238 description={gt("Use thinner grayscale text smoothing instead of the macOS default.")}
239 resetAction={
240 settings.fontSmoothing !== DEFAULT_UNIFIED_SETTINGS.fontSmoothing ? (
241 <SettingResetButton
242 ariaLabel={gt("Reset font smoothing to default")}
243 onClick={() =>
244 updateSettings({ fontSmoothing: DEFAULT_UNIFIED_SETTINGS.fontSmoothing })
245 }
246 />
247 ) : null
248 }
249 control={
250 <Switch
251 checked={settings.fontSmoothing}
252 onCheckedChange={(checked) => updateSettings({ fontSmoothing: Boolean(checked) })}
253 aria-label={gt("Font smoothing")}
254 />
255 }
256 />
257 );
258 }
259
260 function WordWrapRow() {
261 const gt = useGT();
262 const searchableSetting = useSearchableSetting();
263 const settings = useScopedSettings();
264 const updateSettings = useUpdateScopedSettings();
265 return (
266 <SettingsRow
267 {...searchableSetting("word-wrap")}
268 description={gt("Wrap long lines in code blocks, diffs, and file previews by default.")}
269 resetAction={
270 settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? (
271 <SettingResetButton
272 ariaLabel={gt("Reset word wrapping to default")}
273 onClick={() => updateSettings({ wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap })}
274 />
275 ) : null
276 }
277 control={
278 <Switch
279 checked={settings.wordWrap}
280 onCheckedChange={(checked) => updateSettings({ wordWrap: Boolean(checked) })}
281 aria-label={gt("Wrap code, diffs, and file previews by default")}
282 />
283 }
284 />
285 );
286 }
287
288 function FontSettingsGroup() {
289 return (
290 <>
291 <InterfaceFontRow />
292 <PromptFontRow />
293 <CodeFontRow />
294 <TerminalFontRow />
295 </>
296 );
297 }
298
299 function SeparateFontsRow({
300 checked,
301 onCheckedChange,
302 }: {
303 readonly checked: boolean;
304 readonly onCheckedChange: (checked: boolean) => void;
305 }) {
306 const gt = useGT();
307 const searchableSetting = useSearchableSetting();
308 return (
309 <SettingsRow
310 {...searchableSetting("separate-fonts")}
311 description={gt(
312 "Set the prompt, code, and terminal fonts separately instead of one monospace font.",
313 )}
314 control={
315 <Switch
316 checked={checked}
317 onCheckedChange={(next) => onCheckedChange(Boolean(next))}
318 aria-label={gt("Separate fonts")}
319 />
320 }
321 />
322 );
323 }
324
325 function SimpleFontRows() {
326 const gt = useGT();
327 const settings = useScopedSettings();
328 return (
329 <>
330 <InterfaceFontRow preview={<PromptFontPreview />} />
331 <CodeFontRow
332 title={gt("Monospace font")}
333 resetLabel={gt("Reset monospace font to default")}
334 description={gt("Code blocks, diffs, file previews, and the terminal.")}
335 preview={
336 <>
337 <CodeFontPreview />
338 <TerminalFontPreview
339 family={resolveTerminalFontPreference({
340 advanced: false,
341 code: settings.fontFamilyCode,
342 terminal: settings.fontFamilyTerminal,
343 })}
344 size={resolveTerminalFontSizePreference({
345 advanced: false,
346 code: settings.fontSizeCode,
347 terminal: settings.fontSizeTerminal,
348 })}
349 />
350 </>
351 }
352 />
353 </>
354 );
355 }
356
357 export function TypographySection() {
358 const gt = useGT();
359 const searchableSetting = useSearchableSetting();
360 const [advanced, setAdvanced] = useLocalStorage(
361 TYPOGRAPHY_ADVANCED_STORAGE_KEY,
362 false,
363 Schema.Boolean,
364 );
365 // A deep link or history step must persist the flag too: the terminal reads it, so advanced
366 // rows without it would make terminal font edits do nothing. The rows follow the target
367 // directly so its row mounts in the first commit; the target clears once handled.
368 const searchTargetId = useSettingsSearchTargetId();
369 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the advanced typography flag to localStorage when a search target needs it
370 useEffect(() => {
371 if (searchTargetId !== null) revealSettingsSearchTarget(searchTargetId);
372 }, [searchTargetId]);
373 const showAdvanced =
374 advanced || (searchTargetId !== null && isAdvancedTypographyTarget(searchTargetId));
375 return (
376 <SettingsSection id="typography" title={gt("Typography")}>
377 {showAdvanced ? <FontSettingsGroup /> : <SimpleFontRows />}
378 <WordWrapRow />
379 <AdvancedSettings
380 targetIds={[searchableSetting("separate-fonts").id, searchableSetting("font-smoothing").id]}
381 >
382 <SeparateFontsRow checked={showAdvanced} onCheckedChange={setAdvanced} />
383 <FontSmoothingRow />
384 </AdvancedSettings>
385 </SettingsSection>
386 );
387 }
388
389 function FontFamilySettingsRow({
390 id,
391 title,
392 resetLabel,
393 description,
394 defaultFamily,
395 defaultValue,
396 preview,
397 value,
398 onValueChange,
399 onReset,
400 requireMonospace = false,
401 size,
402 }: {
403 id?: string;
404 title: string;
405 resetLabel: string;
406 description: string;
407 defaultFamily: string;
408 defaultValue: string;
409 preview?: ReactNode;
410 value: string;
411 onValueChange: (value: string) => void;
412 onReset: () => void;
413 requireMonospace?: boolean;
414 size: {
415 label: string;
416 min: number;
417 max: number;
418 value: number;
419 defaultValue: number;
420 onChange: (v: number) => void;
421 };
422 }) {
423 const gt = useGT();
424 const trimmed = value.trim();
425 const [draft, setDraft] = useState(value);
426 const [draftSettled, setDraftSettled] = useState(true);
427 // Each pending commit remembers the value it was typed against, so one that outlives
428 // an external change (hydration, reset, picker selection) drops its stale draft.
429 const commitTimerRef = useRef<{ readonly id: number; readonly value: string } | null>(null);
430 const cancelPendingCommit = () => {
431 if (commitTimerRef.current !== null) window.clearTimeout(commitTimerRef.current.id);
432 commitTimerRef.current = null;
433 };
434 // Bumped on every external value change, so a pending commit typed before one never lands,
435 // even if the value has since changed back to what it was typed against.
436 const [adopted, setAdopted] = useState({ value, generation: 0 });
437 if (adopted.value !== value) {
438 setAdopted({ value, generation: adopted.generation + 1 });
439 setDraft(value);
440 setDraftSettled(true);
441 }
442 const readAdoptedGeneration = useEffectEvent(() => adopted.generation);
443 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the pending commit timer on unmount
444 useEffect(
445 () => () => {
446 if (commitTimerRef.current !== null) window.clearTimeout(commitTimerRef.current.id);
447 },
448 [],
449 );
450 const acceptsFamily = (candidate: string) =>
451 isFontFamilyAvailable(candidate) && (!requireMonospace || isMonospaceFamily(candidate));
452 const commitDraft = (next: string) => {
453 setDraftSettled(true);
454 if (next.trim().length === 0 || acceptsFamily(next)) {
455 onValueChange(next);
456 }
457 };
458 const flushDraft = () => {
459 const pending = commitTimerRef.current;
460 cancelPendingCommit();
461 if (pending !== null && pending.value === value) commitDraft(draft);
462 };
463 const draftTrimmed = draft.trim();
464 const draftPending = draftSettled && draftTrimmed.length > 0 && draftTrimmed !== trimmed;
465 const resetToDefault = () => {
466 cancelPendingCommit();
467 setDraft(defaultValue);
468 setDraftSettled(true);
469 onReset();
470 };
471 const resetAction =
472 value !== defaultValue || size.value !== size.defaultValue ? (
473 <SettingResetButton ariaLabel={resetLabel} onClick={resetToDefault} />
474 ) : null;
475 const fontEnumeration = useFontEnumeration();
476 const [inputFocused, setInputFocused] = useState(false);
477 const familyControl =
478 fontEnumeration.status === "granted" ? (
479 <FontFamilyPicker
480 ariaLabel={gt("{title} family", { title })}
481 defaultFamily={defaultFamily}
482 selectedFamily={trimmed}
483 requireMonospace={requireMonospace}
484 initialOpen={inputFocused}
485 onSelect={onValueChange}
486 />
487 ) : (
488 <Input
489 size="sm"
490 aria-label={gt("{title} family", { title })}
491 aria-invalid={draftPending || undefined}
492 autoCapitalize="off"
493 autoComplete="off"
494 className="min-w-0 flex-1"
495 maxLength={200}
496 onFocus={() => {
497 setInputFocused(true);
498 discoverInstalledFonts();
499 }}
500 onBlur={() => {
501 setInputFocused(false);
502 flushDraft();
503 }}
504 onChange={(event) => {
505 const next = event.currentTarget.value;
506 setDraft(next);
507 setDraftSettled(false);
508 cancelPendingCommit();
509 const typedAgainst = value;
510 const typedInGeneration = adopted.generation;
511 commitTimerRef.current = {
512 id: window.setTimeout(() => {
513 commitTimerRef.current = null;
514 if (readAdoptedGeneration() === typedInGeneration) commitDraft(next);
515 }, 400),
516 value: typedAgainst,
517 };
518 }}
519 onKeyDown={(event) => {
520 if (event.key === "Enter") flushDraft();
521 if (event.key === "Escape") {
522 // Discard uncommitted typing without closing the settings page,
523 // which is what an unhandled Escape does.
524 event.preventDefault();
525 event.stopPropagation();
526 cancelPendingCommit();
527 setDraft(value);
528 setDraftSettled(true);
529 }
530 }}
531 placeholder={defaultFamily}
532 spellCheck={false}
533 value={draft}
534 />
535 );
536 const control = (
537 <div className="flex w-full flex-wrap items-center gap-2 sm:w-auto @min-[32rem]/settings-row:flex-nowrap">
538 <div className="min-w-36 flex-1 sm:w-44 sm:flex-none">{familyControl}</div>
539 <Select
540 value={String(size.value)}
541 onValueChange={(next) => {
542 if (typeof next !== "string") return;
543 const parsed = Number(next);
544 if (Number.isInteger(parsed) && parsed >= size.min && parsed <= size.max) {
545 size.onChange(parsed);
546 }
547 }}
548 >
549 <SelectTrigger size="sm" className="w-22 shrink-0" aria-label={size.label}>
550 <SelectValue>{size.value} px</SelectValue>
551 </SelectTrigger>
552 <SelectPopup align="end" alignItemWithTrigger={false}>
553 {Array.from({ length: size.max - size.min + 1 }, (_, index) => size.min + index).map(
554 (px) => (
555 <SelectItem hideIndicator key={px} value={String(px)}>
556 {px} px
557 </SelectItem>
558 ),
559 )}
560 </SelectPopup>
561 </Select>
562 </div>
563 );
564 return (
565 <SettingsRow
566 {...(id !== undefined ? { id } : {})}
567 title={title}
568 description={description}
569 resetAction={resetAction}
570 control={control}
571 >
572 {preview}
573 </SettingsRow>
574 );
575 }