Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(editor): add persistent font size controls (#894)

Call Whitefc514fe2b869
diff --git a/ui/src/components/workbench/AppsEditorPage.tsx b/ui/src/components/workbench/AppsEditorPage.tsx
index 7d9b0fb67..8a66f729e 100644
--- a/ui/src/components/workbench/AppsEditorPage.tsx
+++ b/ui/src/components/workbench/AppsEditorPage.tsx
@@ -6,6 +6,7 @@ import { CodeXml, FolderOpen } from 'lucide-react';
import { Button } from '../ui/button';
import { useUnsavedChanges } from '../../context/useUnsavedChanges';
import { FileEditorPane } from './FileEditorPane';
+import { EditorFontSizePopover } from './EditorFontSizePopover';
// The Editor app as a full-page route (sibling of /apps/files and /apps/terminal). On desktop it
// mounts the same full Editor IDE the Dock window uses; on phones — where there is no window layer —
@@ -141,6 +142,7 @@ const MobileEditor: React.FC<{
filename={file.filename}
mtime={file.mtime}
onOpenFile={openAnother}
+ headerActions={<EditorFontSizePopover trigger="mobile" />}
onDirtyChange={onDirtyChange}
/>
) : (
diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsx
index 1f89e828f..57120af6b 100644
--- a/ui/src/components/workbench/EditorApp.tsx
+++ b/ui/src/components/workbench/EditorApp.tsx
@@ -7,11 +7,13 @@ import { useWindowCloseGuard, useWindowManager, useWindowState } from '../../con
import { MAX_RESTORED_TABS, WINDOW_RESTORE_PARAM } from '../../lib/workbenchPersistence';
import { FilesApiError, contentUrl, downloadFile, fileMeta, joinPath, parentDir, writeFile, type FsEntry } from '../../lib/filesApi';
import { isEditableFile, isEditableMeta, previewOverlayKind, previewRenderKind } from '../../lib/filePreview';
+import { adjustEditorFontSize, resetEditorFontSize } from '../../lib/editorFontSize';
import { forgetRecentFile, loadEditorRecents, recentPathLabel, rememberRecentFile, rememberRecentFolder, removeRecentFile, type EditorRecents, type RecentFile } from '../../lib/editorRecents';
import { FileTree } from './FileTree';
import { FilePreview } from '../ui/file-preview';
import { FilePicker, type FilePickerMode } from './FilePicker';
import { EditorSearchView } from './EditorSearchView';
+import { EditorFontSizePopover } from './EditorFontSizePopover';
const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ default: m.FileEditorPane })));
@@ -75,6 +77,21 @@ type RecentOpenResult = 'opened' | 'gone' | 'unavailable';
// file's real values immediately, without waiting for its cursor to move.
type PaneStatus = { line: number; col: number; insertSpaces: boolean; tabSize: number };
+const IS_APPLE =
+ typeof navigator !== 'undefined' &&
+ /Mac|iP(hone|ad|od)/i.test(navigator.platform || navigator.userAgent || '');
+
+type FontZoom = 'in' | 'out' | 'reset';
+function fontZoomIntent(e: KeyboardEvent): FontZoom | null {
+ if (e.altKey) return null;
+ const modifier = IS_APPLE ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;
+ if (!modifier) return null;
+ if (e.key === '+' || e.key === '=') return 'in';
+ if (e.key === '-') return 'out';
+ if (e.key === '0') return 'reset';
+ return null;
+}
+
// Human language label for the status bar (design dnYPx shows e.g. "TypeScript React").
const LANGUAGE_LABEL: Record<string, string> = {
ts: 'TypeScript',
@@ -159,6 +176,7 @@ export const EditorApp: React.FC<{
// would clobber the stored tabs). Cleared as the restored tabs become live — see the mount effect.
const restorePendingRef = useRef(false);
const treeRefreshSeq = useRef(0);
+ const rootRef = useRef<HTMLDivElement | null>(null);
// Latest tabs + dirty for async callbacks (reloadTabs) so a reload landing after an in-flight
// replace never acts on a stale snapshot and clobbers a buffer the user just edited.
const dirtyRef = useRef(dirty);
@@ -564,6 +582,30 @@ export const EditorApp: React.FC<{
return () => window.removeEventListener('keydown', onKey, true);
}, [windowId, openFolder, newFile, picker, wm.focusedId]);
+ // Claim browser-style zoom only for the focused Editor surface. A window additionally checks real
+ // DOM focus so an Editor left open while the user works in the sidebar doesn't steal browser zoom.
+ // The route stays inactive while a floating window is on top. Capture prevents Monaco's session-only
+ // font zoom from also handling the key.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ const focusedWindow = document.activeElement instanceof Element
+ ? document.activeElement.closest('[data-window-id]')?.getAttribute('data-window-id')
+ : null;
+ const foreground = windowId
+ ? wm.focusedId === windowId && focusedWindow === windowId
+ : wm.focusedId === null && !!rootRef.current?.contains(document.activeElement);
+ if (!foreground) return;
+ const zoom = fontZoomIntent(e);
+ if (!zoom) return;
+ e.preventDefault();
+ e.stopPropagation();
+ if (zoom === 'reset') resetEditorFontSize();
+ else adjustEditorFontSize(zoom === 'in' ? 1 : -1);
+ };
+ window.addEventListener('keydown', onKey, true);
+ return () => window.removeEventListener('keydown', onKey, true);
+ }, [windowId, wm.focusedId]);
+
// The left panel collapses (toggled by the active activity-bar icon) and resizes (drag its right
// border). Width persists for the window's lifetime (state, not navigation).
const [explorerCollapsed, setExplorerCollapsed] = useState(false);
@@ -600,11 +642,9 @@ export const EditorApp: React.FC<{
const activeStatus = active ? status[active] : undefined;
return (
- <div className="relative flex h-full min-h-0 w-full flex-col bg-surface">
+ <div ref={rootRef} className="relative flex h-full min-h-0 w-full flex-col bg-surface">
<div className="flex min-h-0 flex-1">
- {/* Activity bar — Files / Search switch the left panel. Dead placeholder icons (Git / Bug /
- Blocks / Settings) were removed as honest chrome; a real Git view slots back into this
- column when Git integration lands (out of scope here). */}
+ {/* Activity bar — Files / Search switch the left panel; Settings owns persisted editor prefs. */}
<div className="flex w-12 shrink-0 flex-col items-center justify-between border-r border-border bg-surface-3 py-3">
<div className="flex flex-col items-center gap-[18px]">
{([
@@ -638,8 +678,7 @@ export const EditorApp: React.FC<{
</button>
))}
</div>
- {/* Bottom slot (Settings / SCM status) intentionally empty until wired — the column keeps
- its two-slot layout so a future control can slot back in here. */}
+ <EditorFontSizePopover trigger="activity" />
</div>
{/* Left panel — Explorer (Files view) or the cross-file Search view. Collapses via the
diff --git a/ui/src/components/workbench/EditorFontSizePopover.tsx b/ui/src/components/workbench/EditorFontSizePopover.tsx
new file mode 100644
index 000000000..b576e0430
--- /dev/null
+++ b/ui/src/components/workbench/EditorFontSizePopover.tsx
@@ -0,0 +1,114 @@
+import { useSyncExternalStore } from 'react';
+import { RotateCcw, Settings } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ EDITOR_FONT_DEFAULT,
+ EDITOR_FONT_MAX,
+ EDITOR_FONT_MIN,
+ adjustEditorFontSize,
+ getEditorFontSize,
+ resetEditorFontSize,
+ subscribeEditorFontSize,
+} from '../../lib/editorFontSize';
+import { Button } from '../ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
+
+export const EditorFontSizePopover: React.FC<{ trigger: 'activity' | 'mobile' }> = ({ trigger }) => {
+ const { t } = useTranslation();
+ const size = useSyncExternalStore(
+ subscribeEditorFontSize,
+ getEditorFontSize,
+ () => EDITOR_FONT_DEFAULT,
+ );
+ const settingsLabel = t('apps.editor.settings');
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ {trigger === 'activity' ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-8 w-12 rounded-none text-muted hover:bg-foreground/[0.06] hover:text-foreground"
+ aria-label={settingsLabel}
+ >
+ <Settings className="size-5" />
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-7 shrink-0 text-muted"
+ aria-label={settingsLabel}
+ >
+ <span aria-hidden className="text-[12px] font-semibold">Aa</span>
+ </Button>
+ )}
+ </PopoverTrigger>
+ <PopoverContent
+ data-theme={trigger === 'activity' ? 'dark' : undefined}
+ side={trigger === 'activity' ? 'right' : 'bottom'}
+ align="end"
+ sideOffset={8}
+ className="w-60 p-2.5"
+ >
+ <div className="mb-2 text-[12px] font-semibold text-foreground">{settingsLabel}</div>
+ {/* Each editor setting owns one row so word wrap and future preferences can extend this list. */}
+ <ul aria-label={settingsLabel} className="divide-y divide-border">
+ <li className="flex items-center justify-between gap-3 py-1">
+ <span className="text-[12px] text-muted">{t('apps.editor.fontSize')}</span>
+ <div
+ role="group"
+ aria-label={t('apps.editor.fontSize')}
+ className="flex h-8 shrink-0 items-center overflow-hidden rounded-md border border-border"
+ >
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-8 rounded-none border-r border-border px-0 text-[11px]"
+ aria-label={t('apps.editor.decreaseFontSize')}
+ disabled={size <= EDITOR_FONT_MIN}
+ onClick={() => adjustEditorFontSize(-1)}
+ >
+ <span aria-hidden>A−</span>
+ </Button>
+ <output
+ aria-label={t('apps.editor.currentFontSize', { size })}
+ aria-live="polite"
+ className="w-8 text-center font-mono text-[12px] tabular-nums text-foreground"
+ >
+ {size}
+ </output>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-8 rounded-none border-l border-border px-0 text-[11px]"
+ aria-label={t('apps.editor.increaseFontSize')}
+ disabled={size >= EDITOR_FONT_MAX}
+ onClick={() => adjustEditorFontSize(1)}
+ >
+ <span aria-hidden>A+</span>
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-8 rounded-none border-l border-border px-0 text-muted"
+ aria-label={t('apps.editor.resetFontSize')}
+ disabled={size === EDITOR_FONT_DEFAULT}
+ onClick={resetEditorFontSize}
+ >
+ <RotateCcw className="size-3.5" />
+ </Button>
+ </div>
+ </li>
+ </ul>
+ </PopoverContent>
+ </Popover>
+ );
+};
diff --git a/ui/src/components/workbench/FileEditorPane.tsx b/ui/src/components/workbench/FileEditorPane.tsx
index 41340ce18..89d076dec 100644
--- a/ui/src/components/workbench/FileEditorPane.tsx
+++ b/ui/src/components/workbench/FileEditorPane.tsx
@@ -95,6 +95,8 @@ export const FileEditorPane: React.FC<{
* no header.
*/
onOpenFile?: () => void;
+ /** Optional controls appended to the standalone pane header (the mobile editor uses font size). */
+ headerActions?: React.ReactNode;
/** Report dirty state up (used by the Editor IDE to aggregate one close guard over its tabs). */
onDirtyChange?: (dirty: boolean) => void;
/**
@@ -121,7 +123,7 @@ export const FileEditorPane: React.FC<{
* window-level ⌘S itself — scoped by this flag so only the foreground tab saves.
*/
saveHotkey?: boolean;
-}> = ({ path, filename, mtime, readOnly = false, onPopOut, windowId, onOpenFile, onDirtyChange, chromeless = false, onCursor, onSaveAs, reveal, reloadNonce, saveHotkey = false }) => {
+}> = ({ path, filename, mtime, readOnly = false, onPopOut, windowId, onOpenFile, headerActions, onDirtyChange, chromeless = false, onCursor, onSaveAs, reveal, reloadNonce, saveHotkey = false }) => {
const { t } = useTranslation();
const { resolvedTheme } = useTheme();
const [text, setText] = useState<string | null>(null);
@@ -411,6 +413,7 @@ export const FileEditorPane: React.FC<{
<PanelRightOpen className="size-3.5" />
</Button>
)}
+ {headerActions}
{!readOnly && (
<Button
type="button"
diff --git a/ui/src/components/workbench/MonacoEditor.tsx b/ui/src/components/workbench/MonacoEditor.tsx
index f9d62a444..07ce58cd1 100644
--- a/ui/src/components/workbench/MonacoEditor.tsx
+++ b/ui/src/components/workbench/MonacoEditor.tsx
@@ -2,7 +2,12 @@ import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { ClipboardCopy, TextSelect } from 'lucide-react';
import * as monaco from 'monaco-editor';
-import { DiffEditor, Editor, loader, type OnChange, type OnMount } from '@monaco-editor/react';
+import { DiffEditor, Editor, loader, type DiffOnMount, type OnChange, type OnMount } from '@monaco-editor/react';
+
+import {
+ getEditorFontSize,
+ subscribeEditorFontSize,
+} from '../../lib/editorFontSize';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
@@ -150,8 +155,14 @@ export default function MonacoEditor({ value, language, path, readOnly, dark = t
revealRef.current = reveal;
});
+ useEffect(
+ () => subscribeEditorFontSize((fontSize) => editorRef.current?.updateOptions({ fontSize })),
+ [],
+ );
+
const handleMount: OnMount = (editor) => {
editorRef.current = editor;
+ editor.updateOptions({ fontSize: getEditorFontSize() });
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => onSaveRef.current?.());
// Report the initial cursor + detected indentation, then keep both live: the cursor on every
// move, and indentation whenever Monaco (re)detects it (detectIndentation resolves the model's
@@ -226,7 +237,7 @@ export default function MonacoEditor({ value, language, path, readOnly, dark = t
}
options={{
readOnly,
- fontSize: 13,
+ fontSize: getEditorFontSize(),
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
minimap: { enabled: false },
scrollBeyondLastLine: false,
@@ -304,6 +315,15 @@ export interface MonacoDiffEditorProps {
// this is a comparison, not a merge surface; the conflict is resolved via Reload / Overwrite instead.
export function MonacoDiffEditor({ original, modified, language, dark = true }: MonacoDiffEditorProps) {
const { t } = useTranslation();
+ const editorRef = useRef<monaco.editor.IStandaloneDiffEditor | null>(null);
+ useEffect(
+ () => subscribeEditorFontSize((fontSize) => editorRef.current?.updateOptions({ fontSize })),
+ [],
+ );
+ const handleMount: DiffOnMount = (editor) => {
+ editorRef.current = editor;
+ editor.updateOptions({ fontSize: getEditorFontSize() });
+ };
return (
<DiffEditor
theme={dark ? 'avibe-dark' : 'light'}
@@ -311,6 +331,7 @@ export function MonacoDiffEditor({ original, modified, language, dark = true }:
original={original}
modified={modified}
beforeMount={setupMonaco}
+ onMount={handleMount}
loading={
<div className="grid h-full w-full place-items-center bg-surface-2 text-[12px] text-muted">
{t('common.loading')}
@@ -322,7 +343,7 @@ export function MonacoDiffEditor({ original, modified, language, dark = true }:
// Side-by-side per the design; Monaco auto-collapses to inline when the pane is too narrow
// (its default useInlineViewWhenSpaceIsLimited), so the mobile single-file page stays legible.
renderSideBySide: true,
- fontSize: 13,
+ fontSize: getEditorFontSize(),
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
minimap: { enabled: false },
scrollBeyondLastLine: false,
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 1ad06a71f..80bbda114 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -648,6 +648,12 @@
"lineCol": "Ln {{line}}, Col {{col}}",
"spaces": "Spaces: {{n}}",
"tabSize": "Tab Size: {{n}}",
+ "settings": "Editor settings",
+ "fontSize": "Font size",
+ "decreaseFontSize": "Decrease font size",
+ "increaseFontSize": "Increase font size",
+ "resetFontSize": "Reset font size",
+ "currentFontSize": "Current font size: {{size}}",
"plainText": "Plain Text",
"source": "Source",
"preview": "Preview",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c6b3cef8b..cff74093f 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -648,6 +648,12 @@
"lineCol": "行 {{line}},列 {{col}}",
"spaces": "空格:{{n}}",
"tabSize": "制表符宽度:{{n}}",
+ "settings": "编辑器设置",
+ "fontSize": "字体大小",
+ "decreaseFontSize": "减小字体",
+ "increaseFontSize": "增大字体",
+ "resetFontSize": "重置字体大小",
+ "currentFontSize": "当前字体大小:{{size}}",
"plainText": "纯文本",
"source": "源码",
"preview": "预览",
diff --git a/ui/src/lib/editorFontSize.ts b/ui/src/lib/editorFontSize.ts
new file mode 100644
index 000000000..1a5f15c94
--- /dev/null
+++ b/ui/src/lib/editorFontSize.ts
@@ -0,0 +1,18 @@
+import { createFontSizeStore } from './fontSizeStore';
+
+const STORAGE_KEY = 'avibe.editor.fontSize.v1';
+
+export const EDITOR_FONT_MIN = 9;
+export const EDITOR_FONT_MAX = 24;
+export const EDITOR_FONT_DEFAULT = 13;
+
+const editorFontSize = createFontSizeStore(STORAGE_KEY, {
+ min: EDITOR_FONT_MIN,
+ max: EDITOR_FONT_MAX,
+ default: EDITOR_FONT_DEFAULT,
+});
+
+export const getEditorFontSize = editorFontSize.get;
+export const adjustEditorFontSize = editorFontSize.adjust;
+export const resetEditorFontSize = editorFontSize.reset;
+export const subscribeEditorFontSize = editorFontSize.subscribe;
diff --git a/ui/src/lib/fontSizeStore.ts b/ui/src/lib/fontSizeStore.ts
new file mode 100644
index 000000000..5efcd8158
--- /dev/null
+++ b/ui/src/lib/fontSizeStore.ts
@@ -0,0 +1,67 @@
+export interface FontSizeStoreOptions {
+ min: number;
+ max: number;
+ default: number;
+}
+
+export interface FontSizeStore {
+ get: () => number;
+ adjust: (delta: number) => void;
+ reset: () => void;
+ subscribe: (listener: (size: number) => void) => () => void;
+ /** Test-only: restore the default and detach subscribers without touching persisted state. */
+ _reset: () => void;
+}
+
+// Small shared preference store for UI surfaces that mount independently but must follow one
+// persisted font size. Browser storage is best-effort so imports and updates remain safe in tests,
+// SSR-like environments, and privacy modes where localStorage is unavailable.
+export function createFontSizeStore(
+ storageKey: string,
+ { min, max, default: defaultSize }: FontSizeStoreOptions,
+): FontSizeStore {
+ const clamp = (n: number): number => Math.min(max, Math.max(min, Math.round(n)));
+
+ const read = (): number => {
+ try {
+ if (typeof window === 'undefined') return defaultSize;
+ const raw = window.localStorage.getItem(storageKey);
+ if (raw == null || raw === '') return defaultSize;
+ const n = Number(raw);
+ return Number.isFinite(n) ? clamp(n) : defaultSize;
+ } catch {
+ return defaultSize;
+ }
+ };
+
+ let current = read();
+ const listeners = new Set<(size: number) => void>();
+
+ const set = (size: number): void => {
+ const next = clamp(size);
+ if (next === current) return;
+ current = next;
+ try {
+ if (typeof window !== 'undefined') window.localStorage.setItem(storageKey, String(next));
+ } catch {
+ // Keep the in-memory preference when persistence is blocked.
+ }
+ for (const listener of listeners) listener(next);
+ };
+
+ return {
+ get: () => current,
+ adjust: (delta) => set(current + delta),
+ reset: () => set(defaultSize),
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ _reset: () => {
+ current = defaultSize;
+ listeners.clear();
+ },
+ };
+}
diff --git a/ui/src/lib/terminalFontSize.test.ts b/ui/src/lib/terminalFontSize.test.ts
index 20c8c4d6b..d85ebaf02 100644
--- a/ui/src/lib/terminalFontSize.test.ts
+++ b/ui/src/lib/terminalFontSize.test.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createFontSizeStore } from './fontSizeStore';
import {
TERMINAL_FONT_DEFAULT,
TERMINAL_FONT_MAX,
@@ -11,7 +12,49 @@ import {
_resetTerminalFontSize,
} from './terminalFontSize';
-afterEach(() => _resetTerminalFontSize());
+afterEach(() => {
+ _resetTerminalFontSize();
+ vi.unstubAllGlobals();
+});
+
+describe('font size store factory', () => {
+ it('uses each instance config and storage key', () => {
+ const stored = new Map([['test.font.v2', '18.6']]);
+ const localStorage = {
+ getItem: vi.fn((key: string) => stored.get(key) ?? null),
+ setItem: vi.fn((key: string, value: string) => stored.set(key, value)),
+ };
+ vi.stubGlobal('window', { localStorage });
+
+ const store = createFontSizeStore('test.font.v2', { min: 10, max: 20, default: 12 });
+ expect(store.get()).toBe(19);
+
+ store.adjust(100);
+ expect(store.get()).toBe(20);
+ expect(localStorage.setItem).toHaveBeenLastCalledWith('test.font.v2', '20');
+ expect(createFontSizeStore('test.font.v2', { min: 10, max: 20, default: 12 }).get()).toBe(20);
+ });
+
+ it('keeps updates and subscriptions working when storage is unavailable', () => {
+ vi.stubGlobal('window', {
+ localStorage: {
+ getItem: () => {
+ throw new Error('blocked');
+ },
+ setItem: () => {
+ throw new Error('blocked');
+ },
+ },
+ });
+ const store = createFontSizeStore('test.blocked.v1', { min: 9, max: 24, default: 13 });
+ const listener = vi.fn();
+ store.subscribe(listener);
+
+ store.adjust(1);
+ expect(store.get()).toBe(14);
+ expect(listener).toHaveBeenCalledWith(14);
+ });
+});
describe('terminal font size preference', () => {
it('starts at the default size', () => {
diff --git a/ui/src/lib/terminalFontSize.ts b/ui/src/lib/terminalFontSize.ts
index bccd1e2d5..1a7d1dc4c 100644
--- a/ui/src/lib/terminalFontSize.ts
+++ b/ui/src/lib/terminalFontSize.ts
@@ -1,76 +1,19 @@
-// Global terminal font-size preference.
-//
-// One value shared by every open terminal — the /apps/terminal route, every
-// windowed terminal, and every tab within them — so a zoom applies everywhere at
-// once instead of per-instance. Persisted to localStorage under a versioned key so
-// the choice survives reloads and new tabs open at the same size.
-//
-// Kept as a tiny module-level store with a subscriber set (mirrors terminalSlots.ts)
-// because terminals don't share a common React parent: the route terminal and each
-// windowed terminal mount independently, so a change from one must reach the others
-// through a shared store, not props. All window/localStorage access is guarded so the
-// module is safe to import in a non-DOM (test) environment.
+import { createFontSizeStore } from './fontSizeStore';
+
const STORAGE_KEY = 'avibe.terminal.fontSize.v1';
export const TERMINAL_FONT_MIN = 9;
export const TERMINAL_FONT_MAX = 24;
export const TERMINAL_FONT_DEFAULT = 13;
-const clamp = (n: number): number =>
- Math.min(TERMINAL_FONT_MAX, Math.max(TERMINAL_FONT_MIN, Math.round(n)));
-
-function read(): number {
- try {
- if (typeof window === 'undefined') return TERMINAL_FONT_DEFAULT;
- const raw = window.localStorage.getItem(STORAGE_KEY);
- if (raw == null || raw === '') return TERMINAL_FONT_DEFAULT;
- const n = Number(raw);
- return Number.isFinite(n) ? clamp(n) : TERMINAL_FONT_DEFAULT;
- } catch {
- // Storage blocked (private mode, disabled cookies) — fall back to the default.
- return TERMINAL_FONT_DEFAULT;
- }
-}
-
-let current = read();
-const listeners = new Set<(size: number) => void>();
-
-export function getTerminalFontSize(): number {
- return current;
-}
-
-function set(size: number): void {
- const next = clamp(size);
- if (next === current) return; // already there (e.g. ⌘+ at the max) — no refit, no churn
- current = next;
- try {
- if (typeof window !== 'undefined') window.localStorage.setItem(STORAGE_KEY, String(next));
- } catch {
- // Persistence is best-effort; keep the in-memory value even if the write fails.
- }
- for (const listener of listeners) listener(next);
-}
-
-/** Nudge the shared size by `delta` steps (clamped to [MIN, MAX]); notifies every terminal. */
-export function adjustTerminalFontSize(delta: number): void {
- set(current + delta);
-}
-
-/** Restore the default size (⌘0). */
-export function resetTerminalFontSize(): void {
- set(TERMINAL_FONT_DEFAULT);
-}
-
-/** Subscribe to size changes; returns an unsubscribe fn. Does not fire on subscribe. */
-export function subscribeTerminalFontSize(listener: (size: number) => void): () => void {
- listeners.add(listener);
- return () => {
- listeners.delete(listener);
- };
-}
-
-// Test-only: reset the shared preference between cases.
-export function _resetTerminalFontSize(): void {
- current = TERMINAL_FONT_DEFAULT;
- listeners.clear();
-}
+const terminalFontSize = createFontSizeStore(STORAGE_KEY, {
+ min: TERMINAL_FONT_MIN,
+ max: TERMINAL_FONT_MAX,
+ default: TERMINAL_FONT_DEFAULT,
+});
+
+export const getTerminalFontSize = terminalFontSize.get;
+export const adjustTerminalFontSize = terminalFontSize.adjust;
+export const resetTerminalFontSize = terminalFontSize.reset;
+export const subscribeTerminalFontSize = terminalFontSize.subscribe;
+export const _resetTerminalFontSize = terminalFontSize._reset;