Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor(writers-room): extract useMounted + useClickOutside, name string discriminators

Adam Eivy956169818e07
diff --git a/client/src/components/writers-room/AnalysisHistory.jsx b/client/src/components/writers-room/AnalysisHistory.jsx
index 645963912c..72ad4ad5eb 100644
--- a/client/src/components/writers-room/AnalysisHistory.jsx
+++ b/client/src/components/writers-room/AnalysisHistory.jsx
@@ -1,8 +1,9 @@
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
import { AlertTriangle, Check, Clapperboard, FileSignature, Loader2, RotateCcw, Sparkles, Users } from 'lucide-react';
import toast from '../ui/Toast';
import { listWritersRoomAnalyses, getWritersRoomAnalysis } from '../../services/apiWritersRoom';
import { timeAgo } from '../../utils/formatters';
+import useMounted from '../../hooks/useMounted';
const KIND_ICON = { evaluate: Sparkles, format: FileSignature, script: Clapperboard, characters: Users };
const KIND_LABEL = { evaluate: 'Evaluate', format: 'Format', script: 'Adapt', characters: 'Characters' };
@@ -14,19 +15,14 @@ const SEVERITY_COLOR = {
};
// Read-only history of past Evaluate / Format / Adapt / Characters runs.
-// "Apply" actions for Format pass go through onApplyFormat — caller hooks
-// this to the prose buffer (currently only WorkEditor needs that).
+// `onApplyFormat` is the only mutation hook — Format-pass results call it
+// with the cleaned text and the caller decides what to do with it.
export default function AnalysisHistory({ work, activeHash, onApplyFormat }) {
const [analyses, setAnalyses] = useState([]);
const [loading, setLoading] = useState(false);
const [details, setDetails] = useState({});
const [expanded, setExpanded] = useState(null);
- const mountedRef = useRef(true);
-
- useEffect(() => {
- mountedRef.current = true;
- return () => { mountedRef.current = false; };
- }, []);
+ const mountedRef = useMounted();
const refresh = async () => {
setLoading(true);
diff --git a/client/src/components/writers-room/CharactersBible.jsx b/client/src/components/writers-room/CharactersBible.jsx
index d912edbb32..8e50fec91e 100644
--- a/client/src/components/writers-room/CharactersBible.jsx
+++ b/client/src/components/writers-room/CharactersBible.jsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
import { AlertTriangle, Check, Loader2, Pencil, Plus, Trash2, X } from 'lucide-react';
import toast from '../ui/Toast';
import {
@@ -7,6 +7,7 @@ import {
updateWritersRoomCharacter,
deleteWritersRoomCharacter,
} from '../../services/apiWritersRoom';
+import useMounted from '../../hooks/useMounted';
const CHARACTER_FIELDS = [
{ key: 'aliases', label: 'Aliases', placeholder: 'nicknames, titles (comma-separated)', kind: 'csv' },
@@ -17,32 +18,29 @@ const CHARACTER_FIELDS = [
{ key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline' },
];
-// Character bible — editable, persistent across analysis runs. Used by image
-// gen to inject physicalDescription into per-scene prompts.
+// Editable character bible — persistent across analysis runs and consumed by
+// image gen to inject physicalDescription into per-scene prompts.
+//
+// Controlled vs. uncontrolled: caller may pass `characters` to keep multiple
+// mounts in sync (e.g. drawer + storyboard chip count). When omitted we fetch
+// and own the list so this can stand alone.
export default function CharactersBible({ workId, characters: charactersProp, onCharactersChange, readingTheme = 'dark' }) {
- // Internal vs. controlled: caller can pass `characters` to keep multiple
- // mounts in sync (e.g. drawer + storyboard chip count). When omitted we
- // fetch and own the list ourselves so this can stand alone.
const [internalCharacters, setInternalCharacters] = useState(charactersProp || []);
const characters = charactersProp ?? internalCharacters;
const [editingId, setEditingId] = useState(null);
const [creating, setCreating] = useState(false);
const [loading, setLoading] = useState(false);
- const mountedRef = useRef(true);
- useEffect(() => {
- mountedRef.current = true;
- return () => { mountedRef.current = false; };
- }, []);
+ const mountedRef = useMounted();
useEffect(() => {
- if (charactersProp) return; // controlled — caller is fetching
+ if (charactersProp) return;
if (!workId) return;
setLoading(true);
listWritersRoomCharacters(workId)
.then((list) => { if (mountedRef.current) setInternalCharacters(list); })
.catch(() => { if (mountedRef.current) setInternalCharacters([]); })
.finally(() => { if (mountedRef.current) setLoading(false); });
- }, [workId, charactersProp]);
+ }, [workId, charactersProp, mountedRef]);
const upsert = (next) => {
const update = (prev) => {
diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsx
index 683aaad172..63e3437e2d 100644
--- a/client/src/components/writers-room/SceneCard.jsx
+++ b/client/src/components/writers-room/SceneCard.jsx
@@ -14,6 +14,7 @@ import {
attachWritersRoomSceneImage,
} from '../../services/apiWritersRoom';
import socket from '../../services/socket';
+import useClickOutside from '../../hooks/useClickOutside';
import {
WR_IMAGE_DEFAULTS,
buildScenePromptWithCharacters,
@@ -21,10 +22,6 @@ import {
normCharKey,
} from './sceneCardHelpers';
-// One scene in the storyboard. Renders heading, image (or empty/in-progress
-// state), characters, action/dialogue snippets, and a per-card Debug menu that
-// scopes AI tools (re-extract scene, check characters, why this image) to this
-// one scene.
export default function SceneCard({
scene,
workId,
@@ -62,9 +59,8 @@ export default function SceneCard({
const jobIdRef = useRef(null);
const debugMenuRef = useRef(null);
- // initialImage prop changes when the parent reloads analyses (e.g. after a
- // re-Adapt). Sync the local rendered state so a fresh image actually appears
- // without needing the user to re-click Generate.
+ // Sync local image state when parent reloads analyses (e.g. post-re-Adapt)
+ // so a fresh image appears without forcing the user to re-click Generate.
useEffect(() => {
if (!initialImage) return;
setGenerated({
@@ -75,14 +71,7 @@ export default function SceneCard({
setGenStatus('done');
}, [initialImage?.filename]);
- useEffect(() => {
- if (!showDebugMenu) return;
- const onClick = (e) => {
- if (!debugMenuRef.current?.contains(e.target)) setShowDebugMenu(false);
- };
- window.addEventListener('mousedown', onClick);
- return () => window.removeEventListener('mousedown', onClick);
- }, [showDebugMenu]);
+ useClickOutside(debugMenuRef, showDebugMenu, () => setShowDebugMenu(false));
useEffect(() => {
const onStarted = (data) => {
diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsx
index 41e883f98b..0c16dcc5dd 100644
--- a/client/src/components/writers-room/StoryboardPanel.jsx
+++ b/client/src/components/writers-room/StoryboardPanel.jsx
@@ -8,6 +8,7 @@ import {
import { getSettings, updateSettings } from '../../services/apiSystem';
import { listImageModels } from '../../services/apiImageVideo';
import { timeAgo } from '../../utils/formatters';
+import useMounted from '../../hooks/useMounted';
import SceneCard from './SceneCard';
import {
WR_IMAGE_DEFAULTS,
@@ -15,10 +16,6 @@ import {
readWrImageSettings,
} from './sceneCardHelpers';
-// Vertical storyboard companion — the scene-by-scene visual interpretation of
-// the active draft. Renders cards from the latest successful Adapt analysis.
-// When the Adapt is older than the current draft hash, surfaces a stale
-// banner inviting a re-run.
export default function StoryboardPanel({
work,
characters = [],
@@ -34,15 +31,8 @@ export default function StoryboardPanel({
const [imageCfg, setImageCfg] = useState(WR_IMAGE_DEFAULTS);
const [models, setModels] = useState([]);
const [showSettings, setShowSettings] = useState(false);
- const mountedRef = useRef(true);
+ const mountedRef = useMounted();
- useEffect(() => {
- mountedRef.current = true;
- return () => { mountedRef.current = false; };
- }, []);
-
- // Image-gen settings + model catalog — fetched once per mount, persisted to
- // settings.json so the user's resolution + model choice sticks.
useEffect(() => {
let cancelled = false;
Promise.all([
@@ -66,8 +56,7 @@ export default function StoryboardPanel({
setLoading(false);
return;
}
- // We need the full snapshot (scenes + sceneImages) — list returns metadata
- // only.
+ // listAnalyses returns metadata only — fetch the full snapshot for scenes + sceneImages.
const full = await getWritersRoomAnalysis(work.id, latest.id).catch(() => null);
if (!mountedRef.current) return;
setLatestScript(full);
@@ -79,8 +68,7 @@ export default function StoryboardPanel({
loadLatestScript();
}, [loadLatestScript]);
- // After Adapt finishes the parent will toggle runningAdapt false — that's
- // our cue to refetch the latest.
+ // Refetch when Adapt completes — parent toggles runningAdapt true→false.
const prevRunning = useRef(runningAdapt);
useEffect(() => {
if (prevRunning.current && !runningAdapt) {
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index b81f0a7805..4ca01e8b06 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -19,6 +19,8 @@ import {
} from 'lucide-react';
import toast from '../ui/Toast';
import Drawer from '../Drawer';
+import useMounted from '../../hooks/useMounted';
+import useClickOutside from '../../hooks/useClickOutside';
import {
saveWritersRoomDraft,
snapshotWritersRoomDraft,
@@ -33,6 +35,17 @@ import StoryboardPanel from './StoryboardPanel';
import CharactersBible from './CharactersBible';
import AnalysisHistory from './AnalysisHistory';
+const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', EVALUATE: 'evaluate', FORMAT: 'format' };
+const DRAWER = { OUTLINE: 'outline', VERSIONS: 'versions', CHARACTERS: 'characters', HISTORY: 'history' };
+const MOBILE_TAB = { WRITING: 'writing', STORYBOARD: 'storyboard' };
+
+const ANALYSIS_LABELS = {
+ [ANALYSIS_KIND.SCRIPT]: 'Adapt',
+ [ANALYSIS_KIND.CHARACTERS]: 'Characters',
+ [ANALYSIS_KIND.EVALUATE]: 'Editorial pass',
+ [ANALYSIS_KIND.FORMAT]: 'Format pass',
+};
+
const SIDEBAR_WIDTH_KEY = 'wr.sidebarWidth';
const SIDEBAR_DEFAULT = 480;
const SIDEBAR_MIN = 320;
@@ -55,25 +68,20 @@ function persistSidebarWidth(width) {
try { window.localStorage.setItem(SIDEBAR_WIDTH_KEY, String(Math.round(width))); } catch {}
}
-const ANALYSIS_LABELS = {
- script: 'Adapt',
- characters: 'Characters',
- evaluate: 'Editorial pass',
- format: 'Format pass',
-};
-
export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOpen }) {
const [body, setBody] = useState(work.activeDraftBody || '');
const [title, setTitle] = useState(work.title);
+ // Optimistic mirror of work.status so the dropdown changes show immediately
+ // before the PATCH round-trip resolves. Re-synced from the prop when it changes.
const [status, setStatus] = useState(work.status);
const [savedBody, setSavedBody] = useState(work.activeDraftBody || '');
const [saving, setSaving] = useState(false);
const [readingTheme, setReadingTheme] = useState(readReadingTheme);
const [characters, setCharacters] = useState([]);
- const [runningKind, setRunningKind] = useState(null); // 'script' | 'characters' | 'evaluate' | 'format'
- const [drawer, setDrawer] = useState(null); // 'outline' | 'versions' | 'characters' | 'history' | null
+ const [runningKind, setRunningKind] = useState(null);
+ const [drawer, setDrawer] = useState(null);
const [overflowOpen, setOverflowOpen] = useState(false);
- const [mobileTab, setMobileTab] = useState('writing'); // 'writing' | 'storyboard'
+ const [mobileTab, setMobileTab] = useState(MOBILE_TAB.WRITING);
const [activeSceneId, setActiveSceneId] = useState(null);
const textareaRef = useRef(null);
@@ -94,10 +102,8 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
useEffect(() => { setStatus(work.status); }, [work.status]);
useEffect(() => { setTitle(work.title); }, [work.title]);
- // Load character bible for the active work — passed into the storyboard so
- // physicalDescription gets injected into per-scene image prompts. The
- // CharactersBible drawer is the canonical editor; we re-fetch when it
- // notifies us via onCharactersChange.
+ // The CharactersBible drawer is the canonical editor; mirror its list here
+ // so the storyboard's image-prompt enrichment picks up edits immediately.
useEffect(() => {
listWritersRoomCharacters(work.id)
.then((list) => setCharacters(list || []))
@@ -107,14 +113,10 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const dirty = body !== savedBody;
const wordCount = useMemo(() => countWords(body), [body]);
- const mountedRef = useRef(true);
- useEffect(() => {
- mountedRef.current = true;
- return () => { mountedRef.current = false; };
- }, []);
+ const mountedRef = useMounted();
- // Saving uses refs so the once-bound key listener reads fresh values
- // without re-registering on every keystroke.
+ // savingRef gates parallel saves synchronously — `saving` state lags React
+ // re-renders, so rapid Cmd+S key-repeats can slip past it otherwise.
const savingRef = useRef(false);
const handleSaveRef = useRef(null);
handleSaveRef.current = async () => {
@@ -146,16 +148,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
return () => window.removeEventListener('keydown', onKey);
}, []);
- // Close the overflow menu on outside click — keeping it open while the
- // user clicks something else would feel sticky.
- useEffect(() => {
- if (!overflowOpen) return;
- const onClick = (e) => {
- if (!overflowRef.current?.contains(e.target)) setOverflowOpen(false);
- };
- window.addEventListener('mousedown', onClick);
- return () => window.removeEventListener('mousedown', onClick);
- }, [overflowOpen]);
+ useClickOutside(overflowRef, overflowOpen, () => setOverflowOpen(false));
const handleSnapshot = async () => {
if (dirty) {
@@ -252,25 +245,15 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
);
const activeHash = activeDraft?.contentHash || null;
- // Click-to-jump from a storyboard card → scroll the prose textarea so the
- // scene's heading is visible. The Adapt LLM often paraphrases the user's
- // headings (e.g. user wrote `## Chapter 1`, LLM emits "Scene 1 — The Curry
- // Burns"), so we try a few candidates in order:
- // 1. Common markdown prefixes + the LLM heading
- // 2. Raw LLM heading
- // 3. First chunk of scene.summary or scene.action — these often quote
- // actual prose phrases
- // 4. Proportional scrollTop based on the scene's index in the storyboard
- // (sceneIndex / totalScenes) — guarantees we land somewhere reasonable
- // even when nothing matches.
- // setSelectionRange + focus uses the browser's caret-into-view scroll;
- // setting scrollTop afterward guarantees we land "near" the line in cases
- // where the browser doesn't re-scroll an already-visible caret.
+ // Click-to-jump tries the LLM heading (with markdown prefixes), then a
+ // summary/action snippet, then proportional by scene index. Browsers don't
+ // always re-scroll on focus alone if the caret was already visible, so we
+ // always set scrollTop explicitly after focusing.
const jumpToScene = useCallback((scene, sceneIndex = -1, totalScenes = 0) => {
const ta = textareaRef.current;
if (!ta || !scene || !body) return;
setActiveSceneId(scene.id || null);
- setMobileTab('writing');
+ setMobileTab(MOBILE_TAB.WRITING);
const heading = scene.heading || '';
let idx = -1;
for (const prefix of ['## ', '### ', '# ', '']) {
@@ -279,8 +262,6 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
if (idx >= 0) break;
}
if (idx < 0) {
- // Try a chunk of the scene's summary or action — the LLM may have
- // pulled from real prose phrases.
for (const candidate of [scene.summary, scene.action]) {
if (!candidate) continue;
const snippet = String(candidate).trim().slice(0, 40);
@@ -296,7 +277,6 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const fraction = idx / body.length;
target = Math.max(0, fraction * (ta.scrollHeight - ta.clientHeight));
} else if (totalScenes > 0 && sceneIndex >= 0) {
- // Last resort: position by scene index in the storyboard.
const fraction = sceneIndex / totalScenes;
target = Math.max(0, fraction * (ta.scrollHeight - ta.clientHeight));
} else {
@@ -305,14 +285,13 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
ta.scrollTop = target;
}, [body]);
- // Per-scene Debug menu actions from SceneCard — for now everything except
- // "Jump to prose" (handled directly via onJumpToProse) opens the most
- // relevant drawer. Scoping AI tools to a single scene is a follow-up.
+ // Per-scene Debug menu actions — until scoped tools land, route to the
+ // most relevant drawer.
const handleDebug = useCallback(({ kind, scene }) => {
if (scene) setActiveSceneId(scene.id || null);
- if (kind === 'check-characters') setDrawer('characters');
- else if (kind === 'editorial') setDrawer('history');
- else if (kind === 'why-image') setDrawer('history');
+ if (kind === 'check-characters') setDrawer(DRAWER.CHARACTERS);
+ else if (kind === 'editorial') setDrawer(DRAWER.HISTORY);
+ else if (kind === 'why-image') setDrawer(DRAWER.HISTORY);
}, []);
// Drag-to-resize sidebar (desktop only).
@@ -419,16 +398,16 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
{overflowOpen && (
<div className="absolute right-0 top-full mt-1 z-30 w-60 rounded-md border border-port-border bg-port-card shadow-xl py-1 text-xs">
<MenuSection label="AI">
- <MenuItem icon={Clapperboard} label="Run Adapt (rebuild storyboard)" running={runningKind === 'script'} onClick={closeOverflowAnd(() => runAnalysis('script'))} />
- <MenuItem icon={Users} label="Refresh characters" running={runningKind === 'characters'} onClick={closeOverflowAnd(() => runAnalysis('characters'))} />
- <MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === 'evaluate'} onClick={closeOverflowAnd(() => runAnalysis('evaluate'))} />
- <MenuItem icon={FileSignature} label="Format pass" running={runningKind === 'format'} onClick={closeOverflowAnd(() => runAnalysis('format'))} />
+ <MenuItem icon={Clapperboard} label="Run Adapt (rebuild storyboard)" running={runningKind === ANALYSIS_KIND.SCRIPT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.SCRIPT))} />
+ <MenuItem icon={Users} label="Refresh characters" running={runningKind === ANALYSIS_KIND.CHARACTERS} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.CHARACTERS))} />
+ <MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === ANALYSIS_KIND.EVALUATE} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.EVALUATE))} />
+ <MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} />
</MenuSection>
<MenuSection label="Open">
- <MenuItem icon={ListTree} label="Outline" onClick={closeOverflowAnd(() => setDrawer('outline'))} />
- <MenuItem icon={Clock} label="Versions" onClick={closeOverflowAnd(() => setDrawer('versions'))} />
- <MenuItem icon={Users} label="Characters" badge={characters.length || null} onClick={closeOverflowAnd(() => setDrawer('characters'))} />
- <MenuItem icon={History} label="Analysis history" onClick={closeOverflowAnd(() => setDrawer('history'))} />
+ <MenuItem icon={ListTree} label="Outline" onClick={closeOverflowAnd(() => setDrawer(DRAWER.OUTLINE))} />
+ <MenuItem icon={Clock} label="Versions" onClick={closeOverflowAnd(() => setDrawer(DRAWER.VERSIONS))} />
+ <MenuItem icon={Users} label="Characters" badge={characters.length || null} onClick={closeOverflowAnd(() => setDrawer(DRAWER.CHARACTERS))} />
+ <MenuItem icon={History} label="Analysis history" onClick={closeOverflowAnd(() => setDrawer(DRAWER.HISTORY))} />
</MenuSection>
<MenuSection label="View">
<MenuItem
@@ -452,12 +431,12 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
{/* Mobile-only Writing/Storyboard toggle — desktop renders both side-by-side. */}
<div className="lg:hidden flex border-b border-port-border bg-port-bg/40 shrink-0">
- <MobileTab active={mobileTab === 'writing'} onClick={() => setMobileTab('writing')} icon={PenLine} label="Writing" />
- <MobileTab active={mobileTab === 'storyboard'} onClick={() => setMobileTab('storyboard')} icon={Clapperboard} label="Storyboard" />
+ <MobileTab active={mobileTab === MOBILE_TAB.WRITING} onClick={() => setMobileTab(MOBILE_TAB.WRITING)} icon={PenLine} label="Writing" />
+ <MobileTab active={mobileTab === MOBILE_TAB.STORYBOARD} onClick={() => setMobileTab(MOBILE_TAB.STORYBOARD)} icon={Clapperboard} label="Storyboard" />
</div>
<div ref={splitRef} className="flex-1 flex flex-col lg:flex-row min-h-0">
- <div className={`relative min-h-0 flex-1 ${mobileTab === 'storyboard' ? 'hidden lg:block' : 'block'}`}>
+ <div className={`relative min-h-0 flex-1 ${mobileTab === MOBILE_TAB.STORYBOARD ? 'hidden lg:block' : 'block'}`}>
<textarea
ref={textareaRef}
value={body}
@@ -495,7 +474,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<aside
style={{ '--sidebar-w': `${sidebarWidth}px` }}
className={`border-t lg:border-t-0 border-port-border bg-port-card/60 flex flex-col text-xs min-h-0 w-full flex-1 lg:flex-initial lg:w-[var(--sidebar-w)] lg:shrink-0 ${
- mobileTab === 'writing' ? 'hidden lg:flex' : 'flex'
+ mobileTab === MOBILE_TAB.WRITING ? 'hidden lg:flex' : 'flex'
}`}
>
<StoryboardPanel
@@ -503,22 +482,21 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
characters={characters}
onJumpToScene={jumpToScene}
onDebug={handleDebug}
- onRunAdapt={() => runAnalysis('script')}
- runningAdapt={runningKind === 'script'}
+ onRunAdapt={() => runAnalysis(ANALYSIS_KIND.SCRIPT)}
+ runningAdapt={runningKind === ANALYSIS_KIND.SCRIPT}
readingTheme={readingTheme}
activeSceneId={activeSceneId}
/>
</aside>
</div>
- {/* Slide-over drawers — only one open at a time */}
- <Drawer open={drawer === 'outline'} onClose={() => setDrawer(null)} title="Outline">
- <OutlineList activeDraft={activeDraft} onClose={() => setDrawer(null)} />
+ <Drawer open={drawer === DRAWER.OUTLINE} onClose={() => setDrawer(null)} title="Outline">
+ <OutlineList activeDraft={activeDraft} />
</Drawer>
- <Drawer open={drawer === 'versions'} onClose={() => setDrawer(null)} title="Versions">
+ <Drawer open={drawer === DRAWER.VERSIONS} onClose={() => setDrawer(null)} title="Versions">
<VersionsList work={work} dirty={dirty} onSwitch={(id) => { switchToDraft(id); setDrawer(null); }} />
</Drawer>
- <Drawer open={drawer === 'characters'} onClose={() => setDrawer(null)} title="Characters">
+ <Drawer open={drawer === DRAWER.CHARACTERS} onClose={() => setDrawer(null)} title="Characters">
<CharactersBible
workId={work.id}
characters={characters}
@@ -526,7 +504,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
readingTheme={readingTheme}
/>
</Drawer>
- <Drawer open={drawer === 'history'} onClose={() => setDrawer(null)} title="Analysis history">
+ <Drawer open={drawer === DRAWER.HISTORY} onClose={() => setDrawer(null)} title="Analysis history">
<AnalysisHistory work={work} activeHash={activeHash} onApplyFormat={applyFormatText} />
</Drawer>
</div>
@@ -575,7 +553,7 @@ function MobileTab({ active, onClick, icon: Icon, label }) {
);
}
-function OutlineList({ activeDraft, onClose }) {
+function OutlineList({ activeDraft }) {
const segs = activeDraft?.segmentIndex || [];
if (segs.length === 0) {
return (
diff --git a/client/src/hooks/useClickOutside.js b/client/src/hooks/useClickOutside.js
new file mode 100644
index 0000000000..3f133fc869
--- /dev/null
+++ b/client/src/hooks/useClickOutside.js
@@ -0,0 +1,15 @@
+import { useEffect } from 'react';
+
+// Calls onOutside when a mousedown lands outside the ref'd element.
+// Listener only attaches while `active` is true so closed menus don't pay
+// the per-click cost.
+export default function useClickOutside(ref, active, onOutside) {
+ useEffect(() => {
+ if (!active) return;
+ const onDown = (e) => {
+ if (!ref.current?.contains(e.target)) onOutside();
+ };
+ window.addEventListener('mousedown', onDown);
+ return () => window.removeEventListener('mousedown', onDown);
+ }, [active, ref, onOutside]);
+}
diff --git a/client/src/hooks/useMounted.js b/client/src/hooks/useMounted.js
new file mode 100644
index 0000000000..079e54389d
--- /dev/null
+++ b/client/src/hooks/useMounted.js
@@ -0,0 +1,15 @@
+import { useEffect, useRef } from 'react';
+
+// Returns a ref whose `.current` is true while the component is mounted.
+// Use to gate post-await setState so an async resolve after unmount doesn't
+// trigger a "set state on unmounted component" warning. The ref is reset
+// to true on every mount so React 18 StrictMode's mount→cleanup→remount
+// cycle doesn't leave it permanently false.
+export default function useMounted() {
+ const mountedRef = useRef(true);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => { mountedRef.current = false; };
+ }, []);
+ return mountedRef;
+}