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

TypographySettings.tsx

522 lines16.6 KB

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