Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

refactor(ui): group feature state into hooks

Luis Ortiz844a4077d5b6
diff --git a/AGENTS.md b/AGENTS.md
index 41162be..944cff3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -755,6 +755,34 @@ a role and an accessible name and writes the same wording it writes for the exte
it has nothing but the action, and every step in the guide reads the same β€” which is what a
`screen`-sourced recording looks like.
+## Feature Hooks
+
+A cluster of `useState` that moves as one thing is a hook, not a pile of state in a component.
+`ExportPreviewModal` held fourteen, of which eleven were two jobs wearing one coat: `useGuideExport`
+owns the document preview and every download, `useVideoPreview` owns the encode, its progress, its
+container and the deferral past twenty-five steps. The modal keeps three β€” the options, the tab, and
+nothing else.
+
+The shape repeats wherever an async job meets a component: `data`, `loading`, `error`, `progress`
+spread across four `useState` and one long effect. `useGuideDescription`, `useSnapshots`,
+`useSettingsAutosave`, `useEditHistory` and `useTextStyle` are the same extraction, and
+`useAiSettings` and `useKeyCheck` were already it before the pattern had a name.
+
+What stays a `useState` is state one component owns and nothing else reads: a dialog's open flag, an
+input draft, a hover. Grouping those into a hook adds indirection and removes nothing. The test is
+whether the values change together and are read together, not how many there are.
+
+`useSettingsAutosave` is the odd one: it holds no settings at all. The fields stay in the view
+because each is bound to its own control; what the hook owns is the machinery around them β€” the
+snapshot, the diff, the debounce, the flush on unmount and the saved badge β€” which is the part that
+was subtle and the part nobody should have to read twice.
+
+`AnnotationEditor` resisted a bulk rewrite and is worth saying so: twenty-eight states, most of them
+genuinely interdependent canvas state. Undo/redo and the text style came out cleanly because both
+are self-contained; a regex pass across the rest broke the file's syntax and was reverted. The
+drawing gesture β€” `draft`, `cropDraft`, `grabbing`, `hovering`, `anchor` β€” is still a cluster, and
+still wants a careful hand rather than a script.
+
## Fullview Store
One Zustand store, four slices β€” `library`, `search`, `guide`, `editor` β€” merged in
diff --git a/packages/ui/src/fullview/components/VersionHistoryPanel.tsx b/packages/ui/src/fullview/components/VersionHistoryPanel.tsx
index de36848..39a7fcd 100644
--- a/packages/ui/src/fullview/components/VersionHistoryPanel.tsx
+++ b/packages/ui/src/fullview/components/VersionHistoryPanel.tsx
@@ -1,5 +1,4 @@
import { i18n } from '@mimik/core/env';
-import { getSnapshots, renameSnapshot, revertToSnapshot } from '@mimik/core/guides/service';
import { diffSnapshots, type SnapshotDiff, type SnapshotLike } from '@mimik/core/guides/snapshot-diff';
import { groupSnapshots } from '@mimik/core/guides/snapshot-groups';
import type { Snapshot } from '@mimik/core/guides/types';
@@ -11,11 +10,8 @@ import {
} from '@mimik/ui/components/ui/dropdown-menu';
import { formatDateTime } from '@mimik/ui/lib/utils';
import { ChevronRight, MoreVertical, RotateCcw, X } from 'lucide-react';
-import { useEffect, useMemo, useRef, useState } from 'react';
-
-function isQuotaError(e: unknown): boolean {
- return e instanceof Error && (e.name === 'QuotaExceededError' || e.name === 'DexieError2QuotaExceededError');
-}
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useSnapshots } from './use-snapshots';
function changeSummary(diff: SnapshotDiff): string {
const parts: string[] = [];
@@ -68,43 +64,19 @@ export default function VersionHistoryPanel({
onRestored,
onClose,
}: VersionHistoryPanelProps) {
- const [snapshots, setSnapshots] = useState<Snapshot[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [restoring, setRestoring] = useState(false);
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [namedOnly, setNamedOnly] = useState(false);
const [renamingId, setRenamingId] = useState<string | null>(null);
const [draft, setDraft] = useState('');
- const refreshRef = useRef(refreshKey);
const renamingRef = useRef<string | null>(null);
+ const clearRenaming = useCallback(() => {
+ renamingRef.current = null;
+ setRenamingId(null);
+ }, []);
+ const history = useSnapshots(guideId, refreshKey, clearRenaming);
+ const snapshots = history.list;
const inputRef = useRef<HTMLInputElement>(null);
- useEffect(() => {
- const silent = refreshRef.current !== refreshKey;
- refreshRef.current = refreshKey;
- let cancelled = false;
- if (!silent) {
- setLoading(true);
- setError(null);
- renamingRef.current = null;
- setRenamingId(null);
- }
- getSnapshots(guideId)
- .then((list) => {
- if (!cancelled) setSnapshots(list);
- })
- .catch(() => {
- if (!cancelled) setError(i18n.t('history.loadError'));
- })
- .finally(() => {
- if (!cancelled) setLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, [guideId, refreshKey]);
-
useEffect(() => {
if (renamingId) inputRef.current?.focus();
}, [renamingId]);
@@ -126,26 +98,13 @@ export default function VersionHistoryPanel({
const named = useMemo(() => snapshots.filter((s) => s.name), [snapshots]);
const handleRestore = async (snapshot: Snapshot) => {
- if (restoring) return;
- setRestoring(true);
- setError(null);
- try {
- const undo = await revertToSnapshot(snapshot.id);
- if (!undo) {
- setError(i18n.t('history.restoreError'));
- return;
- }
- setSnapshots(await getSnapshots(guideId));
+ const done = await history.restore(snapshot, () => {
setExpanded(new Set());
- renamingRef.current = null;
- setRenamingId(null);
+ clearRenaming();
onSelect(null);
onRestored();
- } catch (e) {
- setError(i18n.t(isQuotaError(e) ? 'history.storageFull' : 'history.restoreError'));
- } finally {
- setRestoring(false);
- }
+ });
+ if (!done) return;
};
const startRename = (snapshot: Snapshot) => {
@@ -166,12 +125,7 @@ export default function VersionHistoryPanel({
const trimmed = draft.trim();
const name = trimmed === '' ? undefined : trimmed;
if (name === snapshot.name) return;
- try {
- await renameSnapshot(snapshot.id, trimmed);
- setSnapshots((prev) => prev.map((s) => (s.id === snapshot.id ? { ...s, name } : s)));
- } catch {
- setError(i18n.t('history.renameError'));
- }
+ await history.rename(snapshot, name);
};
const toggle = (key: string) => {
@@ -236,7 +190,7 @@ export default function VersionHistoryPanel({
{active && (
<button
type="button"
- disabled={restoring}
+ disabled={history.restoring}
onClick={() => void handleRestore(snapshot)}
className="inline-flex items-center gap-1.5 mt-2 text-[11px] font-semibold text-accent disabled:opacity-50"
>
@@ -280,13 +234,13 @@ export default function VersionHistoryPanel({
<span className="text-[13px] font-semibold text-foreground">{i18n.t('history.title')}</span>
</div>
- {error && (
+ {history.error && (
<p role="alert" className="text-[11px] text-destructive py-2">
- {error}
+ {history.error}
</p>
)}
- {loading ? (
+ {history.loading ? (
<p className="text-[11px] text-muted-foreground py-2">{i18n.t('common.loading')}</p>
) : snapshots.length === 0 ? (
<p className="text-[11px] text-muted-foreground py-2">{i18n.t('history.empty')}</p>
diff --git a/packages/ui/src/fullview/components/use-snapshots.ts b/packages/ui/src/fullview/components/use-snapshots.ts
new file mode 100644
index 0000000..2bc2553
--- /dev/null
+++ b/packages/ui/src/fullview/components/use-snapshots.ts
@@ -0,0 +1,82 @@
+import { i18n } from '@mimik/core/env';
+import { getSnapshots, renameSnapshot, revertToSnapshot } from '@mimik/core/guides/service';
+import type { Snapshot } from '@mimik/core/guides/types';
+import { useEffect, useRef, useState } from 'react';
+
+function isQuotaError(e: unknown): boolean {
+ return e instanceof Error && (e.name === 'QuotaExceededError' || e.name === 'DexieError2QuotaExceededError');
+}
+
+export interface Snapshots {
+ list: Snapshot[];
+ loading: boolean;
+ error: string | null;
+ restoring: boolean;
+ clearError: () => void;
+ rename: (snapshot: Snapshot, name: string | undefined) => Promise<void>;
+ restore: (snapshot: Snapshot, onRestored: () => void) => Promise<boolean>;
+}
+
+export function useSnapshots(guideId: string, refreshKey: number, onReload: () => void): Snapshots {
+ const [list, setList] = useState<Snapshot[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [restoring, setRestoring] = useState(false);
+ const seen = useRef(refreshKey);
+
+ useEffect(() => {
+ const silent = seen.current !== refreshKey;
+ seen.current = refreshKey;
+ let cancelled = false;
+ if (!silent) {
+ setLoading(true);
+ setError(null);
+ onReload();
+ }
+ getSnapshots(guideId)
+ .then((next) => {
+ if (!cancelled) setList(next);
+ })
+ .catch(() => {
+ if (!cancelled) setError(i18n.t('history.loadError'));
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [guideId, refreshKey, onReload]);
+
+ const restore = async (snapshot: Snapshot, onRestored: () => void): Promise<boolean> => {
+ if (restoring) return false;
+ setRestoring(true);
+ setError(null);
+ try {
+ const undo = await revertToSnapshot(snapshot.id);
+ if (!undo) {
+ setError(i18n.t('history.restoreError'));
+ return false;
+ }
+ setList(await getSnapshots(guideId));
+ onRestored();
+ return true;
+ } catch (e) {
+ setError(i18n.t(isQuotaError(e) ? 'history.storageFull' : 'history.restoreError'));
+ return false;
+ } finally {
+ setRestoring(false);
+ }
+ };
+
+ const rename = async (snapshot: Snapshot, name: string | undefined) => {
+ try {
+ await renameSnapshot(snapshot.id, name ?? '');
+ setList((prev) => prev.map((s) => (s.id === snapshot.id ? { ...s, name } : s)));
+ } catch {
+ setError(i18n.t('history.renameError'));
+ }
+ };
+
+ return { list, loading, error, restoring, clearError: () => setError(null), rename, restore };
+}
diff --git a/packages/ui/src/lib/use-settings-autosave.ts b/packages/ui/src/lib/use-settings-autosave.ts
new file mode 100644
index 0000000..421d3eb
--- /dev/null
+++ b/packages/ui/src/lib/use-settings-autosave.ts
@@ -0,0 +1,69 @@
+import { localStorage } from '@mimik/core/env';
+import { logger } from '@mimik/ui/lib/logger';
+import { changedSettings, type SettingsSnapshot } from '@mimik/ui/lib/settings-autosave';
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+const SAVE_DEBOUNCE_MS = 400;
+const SAVED_BADGE_MS = 1600;
+
+export interface SettingsAutosave {
+ saved: boolean;
+ queue: (patch: SettingsSnapshot) => void;
+}
+
+export function useSettingsAutosave(stored: SettingsSnapshot, ready: boolean): SettingsAutosave {
+ const [saved, setSaved] = useState(false);
+ const snapshot = useRef<SettingsSnapshot | null>(null);
+ const pending = useRef<SettingsSnapshot>({});
+ const timer = useRef<number | undefined>(undefined);
+
+ const flush = useCallback(async () => {
+ const patch = pending.current;
+ pending.current = {};
+ if (Object.keys(patch).length === 0) return;
+ try {
+ await localStorage.set(patch);
+ setSaved(true);
+ } catch (err) {
+ logger.error('Settings autosave failed', err);
+ setSaved(false);
+ }
+ }, []);
+
+ const queue = useCallback(
+ (patch: SettingsSnapshot) => {
+ Object.assign(pending.current, patch);
+ window.clearTimeout(timer.current);
+ timer.current = window.setTimeout(() => void flush(), SAVE_DEBOUNCE_MS);
+ },
+ [flush],
+ );
+
+ useEffect(() => {
+ if (!ready) return;
+ if (!snapshot.current) {
+ snapshot.current = stored;
+ return;
+ }
+ const patch = changedSettings(stored, snapshot.current);
+ if (!patch) return;
+ snapshot.current = stored;
+ queue(patch);
+ });
+
+ useEffect(
+ () => () => {
+ window.clearTimeout(timer.current);
+ void flush();
+ },
+ [flush],
+ );
+
+ useEffect(() => {
+ if (!saved) return;
+ const badge = window.setTimeout(() => setSaved(false), SAVED_BADGE_MS);
+ return () => window.clearTimeout(badge);
+ }, [saved]);
+
+ return { saved, queue };
+}
diff --git a/packages/ui/src/shared/AnnotationEditor.tsx b/packages/ui/src/shared/AnnotationEditor.tsx
index 1b37f68..d279eb6 100644
--- a/packages/ui/src/shared/AnnotationEditor.tsx
+++ b/packages/ui/src/shared/AnnotationEditor.tsx
@@ -22,7 +22,6 @@ import type {
} from '@mimik/core/screenshot/types';
import {
ARROW_ENDS,
- DEFAULT_FONT_SIZE,
DEFAULT_LINE_HEIGHT,
DEFAULT_TARGET_COLOR,
FONT_FAMILIES,
@@ -42,6 +41,8 @@ import {
} from '@mimik/ui/components/ui/dropdown-menu';
import { Popover, PopoverContent, PopoverTrigger } from '@mimik/ui/components/ui/popover';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@mimik/ui/components/ui/tooltip';
+import { useEditHistory } from '@mimik/ui/shared/use-edit-history';
+import { useTextStyle } from '@mimik/ui/shared/use-text-style';
import {
ArrowUpRight,
ChevronDown,
@@ -98,7 +99,6 @@ const MIN_SHAPE_SIZE = 6;
const MIN_CROP_SIZE = 20;
const HANDLE_DISPLAY_SIZE = 10;
const HANDLE_HIT_PX = 10;
-const HISTORY_LIMIT = 49;
function clampNumber(raw: string | number, min: number, max: number): number {
const n = Number(raw);
@@ -332,34 +332,22 @@ export default function AnnotationEditor({ screenshot, tool, onDone, onCancel }:
const [lineWidth] = useState<LineWidth>('ms');
const [radius] = useState(0);
const [arrowEnd] = useState<ArrowEnd>('arrow-solid');
- const [fontFamily, setFontFamily] = useState<FontFamily>('sans-serif');
- const [bold, setBold] = useState(false);
- const [italic, setItalic] = useState(false);
- const [fontSize, setFontSize] = useState(DEFAULT_FONT_SIZE);
- const [lineHeight, setLineHeight] = useState(DEFAULT_LINE_HEIGHT);
- const [past, setPast] = useState<Annotation[][]>([]);
- const [future, setFuture] = useState<Annotation[][]>([]);
+ const text = useTextStyle();
const annotationsRef = useRef(annotations);
annotationsRef.current = annotations;
- const pushHistory = useCallback(() => {
- setPast((p) => [...p.slice(-HISTORY_LIMIT), annotationsRef.current]);
- setFuture([]);
- }, []);
+ const edits = useEditHistory(annotationsRef);
+ const pushHistory = edits.push;
const undo = () => {
- if (!past.length) return;
- setFuture((f) => [annotationsRef.current, ...f]);
- setAnnotations(past[past.length - 1]);
- setPast((p) => p.slice(0, -1));
+ const previous = edits.undo();
+ if (previous) setAnnotations(previous);
};
const redo = () => {
- if (!future.length) return;
- setPast((p) => [...p, annotationsRef.current]);
- setAnnotations(future[0]);
- setFuture((f) => f.slice(1));
+ const next = edits.redo();
+ if (next) setAnnotations(next);
};
const mode = modeForTool(activeTool);
@@ -624,7 +612,7 @@ export default function AnnotationEditor({ screenshot, tool, onDone, onCancel }:
const rect = canvasRef.current?.getBoundingClientRect();
setTextEditor({
x: p.x,
- y: p.y + fontSize,
+ y: p.y + text.fontSize,
left: rect ? e.clientX - rect.left : 0,
top: rect ? e.clientY - rect.top : 0,
});
@@ -800,11 +788,7 @@ export default function AnnotationEditor({ screenshot, tool, onDone, onCancel }:
size?: number;
lineHeight?: number;
}) => {
- if (patch.fontFamily) setFontFamily(patch.fontFamily);
- if (patch.bold !== undefined) setBold(patch.bold);
- if (patch.italic !== undefined) setItalic(patch.italic);
- if (patch.size !== undefined) setFontSize(patch.size);
- if (patch.lineHeight !== undefined) setLineHeight(patch.lineHeight);
+ text.apply({ ...patch, fontSize: patch.size });
if (!selected || selected.type !== 'text') return;
const next = {
fontFamily: patch.fontFamily ?? selected.fontFamily ?? 'sans-serif',
@@ -848,12 +832,12 @@ export default function AnnotationEditor({ screenshot, tool, onDone, onCancel }:
y: textEditor.y,
text: textValue.trim(),
color,
- size: fontSize,
- ...measureText(textValue.trim(), fontSize, fontFamily, bold, italic),
- fontFamily,
- bold,
- italic,
- lineHeight,
+ size: text.fontSize,
+ ...measureText(textValue.trim(), text.fontSize, text.fontFamily, text.bold, text.italic),
+ fontFamily: text.fontFamily,
+ bold: text.bold,
+ italic: text.italic,
+ lineHeight: text.lineHeight,
},
]);
}
@@ -899,7 +883,7 @@ export default function AnnotationEditor({ screenshot, tool, onDone, onCancel }:
<button
type="button"
onClick={undo}
- disabled={past.length === 0}
+ disabled={!edits.canUndo}
className="flex items-center justify-center w-8 h-8 rounded-lg text-foreground/75 hover:bg-secondary hover:text-foreground disabled:opacity-25"
>
<Undo2 size={15} />
@@ -909,7 +893,7 @@ export default function AnnotationEditor({ screenshot, tool, onDone, onCancel }:
<button
type="button"
onClick={redo}
- disabled={future.length === 0}
+ disabled={!edits.canRedo}
className="flex items-center justify-center w-8 h-8 rounded-lg text-foreground/75 hover:bg-secondary hover:text-foreground disabled:opacity-25"
>
<Redo2 size={15} />
@@ -1018,13 +1002,13 @@ export default function AnnotationEditor({ screenshot, tool, onDone, onCancel }:
className="absolute z-10 rounded-[2px] border-2 border-accent bg-transparent px-1 outline-none leading-tight"
style={{
left: textEditor.left,
- top: textEditor.top - fontSize / getScale(),
+ top: textEditor.top - text.fontSize / getScale(),
color,
- fontFamily: FONT_FAMILIES[fontFamily],
- fontSize: `${fontSize / getScale()}px`,
- fontWeight: bold ? 700 : 500,
- fontStyle: italic ? 'italic' : 'normal',
- lineHeight,
+ fontFamily: FONT_FAMILIES[text.fontFamily],
+ fontSize: `${text.fontSize / getScale()}px`,
+ fontWeight: text.bold ? 700 : 500,
+ fontStyle: text.italic ? 'italic' : 'normal',
+ lineHeight: text.lineHeight,
width: `${Math.max(i18n.t('annotationEditor.textPlaceholder').length + 1, textValue.length + 4)}ch`,
}}
/>
diff --git a/packages/ui/src/shared/use-edit-history.ts b/packages/ui/src/shared/use-edit-history.ts
new file mode 100644
index 0000000..655ee5a
--- /dev/null
+++ b/packages/ui/src/shared/use-edit-history.ts
@@ -0,0 +1,38 @@
+import type { Annotation } from '@mimik/core/screenshot/types';
+import { type RefObject, useCallback, useState } from 'react';
+
+const HISTORY_LIMIT = 50;
+
+export interface EditHistory {
+ canUndo: boolean;
+ canRedo: boolean;
+ push: () => void;
+ undo: () => Annotation[] | null;
+ redo: () => Annotation[] | null;
+}
+
+export function useEditHistory(current: RefObject<Annotation[]>): EditHistory {
+ const [past, setPast] = useState<Annotation[][]>([]);
+ const [future, setFuture] = useState<Annotation[][]>([]);
+
+ const push = useCallback(() => {
+ setPast((p) => [...p.slice(-HISTORY_LIMIT), current.current]);
+ setFuture([]);
+ }, [current]);
+
+ const undo = (): Annotation[] | null => {
+ if (!past.length) return null;
+ setFuture((f) => [current.current, ...f]);
+ setPast((p) => p.slice(0, -1));
+ return past[past.length - 1];
+ };
+
+ const redo = (): Annotation[] | null => {
+ if (!future.length) return null;
+ setPast((p) => [...p, current.current]);
+ setFuture((f) => f.slice(1));
+ return future[0];
+ };
+
+ return { canUndo: past.length > 0, canRedo: future.length > 0, push, undo, redo };
+}
diff --git a/packages/ui/src/shared/use-text-style.ts b/packages/ui/src/shared/use-text-style.ts
new file mode 100644
index 0000000..8171bd4
--- /dev/null
+++ b/packages/ui/src/shared/use-text-style.ts
@@ -0,0 +1,49 @@
+import { DEFAULT_FONT_SIZE, DEFAULT_LINE_HEIGHT, type FontFamily } from '@mimik/core/screenshot/types';
+import { useState } from 'react';
+
+export interface TextStyle {
+ fontFamily: FontFamily;
+ bold: boolean;
+ italic: boolean;
+ fontSize: number;
+ lineHeight: number;
+}
+
+export interface TextStyleState extends TextStyle {
+ setFontFamily: (next: FontFamily) => void;
+ setBold: (next: boolean) => void;
+ setItalic: (next: boolean) => void;
+ setFontSize: (next: number) => void;
+ setLineHeight: (next: number) => void;
+ apply: (patch: Partial<TextStyle>) => void;
+}
+
+export function useTextStyle(): TextStyleState {
+ const [fontFamily, setFontFamily] = useState<FontFamily>('sans-serif');
+ const [bold, setBold] = useState(false);
+ const [italic, setItalic] = useState(false);
+ const [fontSize, setFontSize] = useState(DEFAULT_FONT_SIZE);
+ const [lineHeight, setLineHeight] = useState(DEFAULT_LINE_HEIGHT);
+
+ const apply = (patch: Partial<TextStyle>) => {
+ if (patch.fontFamily) setFontFamily(patch.fontFamily);
+ if (patch.bold !== undefined) setBold(patch.bold);
+ if (patch.italic !== undefined) setItalic(patch.italic);
+ if (patch.fontSize !== undefined) setFontSize(patch.fontSize);
+ if (patch.lineHeight !== undefined) setLineHeight(patch.lineHeight);
+ };
+
+ return {
+ fontFamily,
+ bold,
+ italic,
+ fontSize,
+ lineHeight,
+ setFontFamily,
+ setBold,
+ setItalic,
+ setFontSize,
+ setLineHeight,
+ apply,
+ };
+}
diff --git a/src/ui/shared/SettingsView.tsx b/src/ui/shared/SettingsView.tsx
index 8b922c8..3df6cff 100644
--- a/src/ui/shared/SettingsView.tsx
+++ b/src/ui/shared/SettingsView.tsx
@@ -10,8 +10,7 @@ import { Button } from '@mimik/ui/components/ui/button';
import { Input } from '@mimik/ui/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@mimik/ui/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@mimik/ui/components/ui/select';
-import { logger } from '@mimik/ui/lib/logger';
-import { changedSettings, type SettingsSnapshot } from '@mimik/ui/lib/settings-autosave';
+import { useSettingsAutosave } from '@mimik/ui/lib/use-settings-autosave';
import AiSettings from '@mimik/ui/shared/AiSettings';
import ColorPicker from '@mimik/ui/shared/ColorPicker';
import {
@@ -30,7 +29,7 @@ import {
Trash2,
TriangleAlert,
} from 'lucide-react';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { localStorage } from '@/lib/browser-api';
import { KeyStatusNote, ModelList, SecretInput, useKeyCheck } from '@/ui/shared/key-check';
import MicrophonePicker from '@/ui/shared/MicrophonePicker';
@@ -39,9 +38,6 @@ interface SettingsViewProps {
onBack?: () => void;
}
-const SAVE_DEBOUNCE_MS = 400;
-const SAVED_BADGE_MS = 1600;
-
const FOOTER_PRESETS = () => [
defaultFooterLine(),
i18n.t('settings.footerPresetConfidential'),
@@ -51,14 +47,9 @@ const FOOTER_PRESETS = () => [
export default function SettingsView({ onBack }: SettingsViewProps) {
const [provider, setProvider] = useState<AIProviderKey>('openai');
const [apiKey, setApiKey] = useState('');
- const [saved, setSaved] = useState(false);
const aiKeyCheck = useKeyCheck();
const voiceKeyCheck = useKeyCheck();
const [loaded, setLoaded] = useState(false);
- const savedSnapshot = useRef<SettingsSnapshot | null>(null);
- const flushRef = useRef<() => Promise<void>>(async () => {});
- const pending = useRef<SettingsSnapshot>({});
- const saveTimer = useRef<number | undefined>(undefined);
const [voiceProvider, setVoiceProvider] = useState<VoiceProvider>('openai');
const [voiceApiKey, setVoiceApiKey] = useState('');
const [voiceMicrophoneId, setVoiceMicrophoneId] = useState('');
@@ -121,51 +112,7 @@ export default function SettingsView({ onBack }: SettingsViewProps) {
brandAttribution,
};
- const flush = useCallback(async () => {
- const patch = pending.current;
- pending.current = {};
- if (Object.keys(patch).length === 0) return;
- try {
- await localStorage.set(patch);
- setSaved(true);
- } catch (err) {
- logger.error('Settings autosave failed', err);
- setSaved(false);
- }
- }, []);
-
- flushRef.current = flush;
-
- useEffect(() => {
- if (!loaded) return;
- const snapshot = savedSnapshot.current;
- if (!snapshot) {
- savedSnapshot.current = stored;
- return;
- }
-
- const patch = changedSettings(stored, snapshot);
- if (!patch) return;
-
- savedSnapshot.current = stored;
- Object.assign(pending.current, patch);
- window.clearTimeout(saveTimer.current);
- saveTimer.current = window.setTimeout(() => void flush(), SAVE_DEBOUNCE_MS);
- });
-
- useEffect(
- () => () => {
- window.clearTimeout(saveTimer.current);
- void flush();
- },
- [flush],
- );
-
- useEffect(() => {
- if (!saved) return;
- const timer = window.setTimeout(() => setSaved(false), SAVED_BADGE_MS);
- return () => window.clearTimeout(timer);
- }, [saved]);
+ const { saved } = useSettingsAutosave(stored, loaded);
const handleLogoPick = async (file: File | undefined) => {
if (!file) return;