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