fix(spa): clear dirty guard before saved navigation #349

Merged
timothy merged 2 commits from codex/344-dirty-guard into main 2026-07-14 08:02:35 +02:00
5 changed files with 160 additions and 5 deletions
+12
View File
@@ -327,6 +327,18 @@ draft to navigation. The shared module `web/src/navigationGuard.ts` is the seam:
Keep the guard predicate reading a **ref** (`dirtyRef`), not the `dirty` state value, so
`canLeaveCurrentScreen()` sees the current dirtiness synchronously at click time.
- **Successful save + same-callback navigation:** `useDirtyGuard` returns a `markClean` callback for
the narrow case where a successful save queues the new draft/baseline and immediately calls
`navigateToPath(...)` in that same promise callback. React has not committed the clean render before
the synthetic `popstate`, so call `markClean()` after the durable save succeeds and immediately before
navigating. Still queue the real clean draft/baseline state; the callback only transfers the synchronous
guard truth across that one event boundary. Only do this while the successful request still owns the
current draft: disable or otherwise gate draft mutations for the entire in-flight save, or revision-check
the completion before marking clean. Otherwise the completion can discard edits made after the request
started. Do not replace the callback with a timer or a forced render. Screens that remain mounted after
saving do not need the callback.
## 9. Review checklist — temporal semantics
- **For every effect / timer / async completion, ask: *when* does it fire (mount, dependency change,
+53
View File
@@ -595,6 +595,32 @@ describe('ChicoryTV SPA scaffold', () => {
confirmSpy.mockRestore();
});
it('successful remote connection save clears App guard and mounts the source screen (#344)', async () => {
mockDashboardApi({
jellyfinConnection: { address: 'http://jf:8096', hasApiKey: true },
jellyfinState: {
isAuthorized: true,
isLocked: false,
servers: [{ id: 2, name: 'Test Jellyfin', address: 'http://jf:9000' }]
}
});
window.history.replaceState(null, '', '/app/libraries/jellyfin/connection');
render(<App />);
const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement;
fireEvent.change(address, { target: { value: 'http://jf:9000' } });
const confirmSpy = vi.mocked(window.confirm);
confirmSpy.mockClear();
fireEvent.click(screen.getByRole('button', { name: 'Save connection' }));
expect(await screen.findByRole('heading', { name: 'Jellyfin' })).toBeInTheDocument();
expect(window.location.pathname).toBe('/app/libraries/jellyfin');
expect(screen.getByRole('button', { name: 'Edit connection' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Save connection' })).not.toBeInTheDocument();
expect(confirmSpy).not.toHaveBeenCalled();
});
it('opens the create-schedule dialog from the TopBar Add Schedule button', async () => {
mockDashboardApi({ schedules: [schedule({ id: 5, name: 'Prime Time Cartoons' })] });
@@ -2845,6 +2871,8 @@ function mockDashboardApi({
health = [],
libraryScanStatusFailAfterTrigger = false,
libraryScanStatuses = [],
jellyfinConnection = null,
jellyfinState = null,
localLibraryDetail = null,
libraryScanStatusesAfterMutation = null,
libraryScanStatusSequence = null,
@@ -2915,6 +2943,8 @@ function mockDashboardApi({
health?: unknown[];
libraryScanStatusFailAfterTrigger?: boolean;
libraryScanStatuses?: unknown[];
jellyfinConnection?: { address: string | null; hasApiKey: boolean } | null;
jellyfinState?: unknown;
localLibraryDetail?: unknown;
libraryScanStatusesAfterMutation?: unknown[] | null;
libraryScanStatusSequence?: unknown[][] | null;
@@ -2963,6 +2993,7 @@ function mockDashboardApi({
vi.spyOn(window, 'confirm').mockReturnValue(confirm);
vi.spyOn(window, 'prompt').mockReturnValue(prompt);
let currentLibraryScanStatuses = libraryScanStatuses;
let currentJellyfinConnection = jellyfinConnection;
let currentChannelTemplates = channelTemplates;
let currentScheduleItems = scheduleItems;
const remainingSettingsGetFailures: Record<string, number> = { ...settingsGetFailuresBeforeSuccess };
@@ -3133,6 +3164,28 @@ function mockDashboardApi({
return Promise.resolve(jsonResponse([]));
}
if (path === '/api/v1/media-sources/jellyfin/connection') {
if ((init?.method ?? 'GET') === 'PUT') {
const body = JSON.parse(String(init?.body ?? '{}')) as { address?: string };
currentJellyfinConnection = { address: body.address ?? null, hasApiKey: true };
return Promise.resolve(jsonResponse(currentJellyfinConnection));
}
return Promise.resolve(
currentJellyfinConnection
? jsonResponse(currentJellyfinConnection)
: jsonResponse(null, 404)
);
}
if (path === '/api/v1/media-sources/jellyfin') {
return Promise.resolve(jsonResponse(jellyfinState ?? {
isAuthorized: false,
isLocked: false,
servers: []
}));
}
if (path === '/api/v1/media-sources') {
if (remainingMediaSourcesFailures > 0) {
remainingMediaSourcesFailures -= 1;
+11 -2
View File
@@ -8,11 +8,18 @@
// each keystroke. A single hook keeps the three editors (connection / libraries / path-replacements)
// consistent instead of copy-pasting the guard block into each.
import { useEffect, useRef } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import { registerNavigationGuard } from '../navigationGuard';
export function useDirtyGuard(dirty: boolean, prompt: string): void {
export function useDirtyGuard(dirty: boolean, prompt: string): () => void {
const dirtyRef = useRef(dirty);
// A successful save may navigate in the same promise callback that queues the clean baseline.
// React has not rendered that baseline yet, so let the caller transfer the guard synchronously
// before dispatching the synthetic popstate. The normal render still owns the durable state.
const markClean = useCallback(() => {
dirtyRef.current = false;
}, []);
// Keep the ref current for the synchronous guard predicate. Updated in an effect (committed before
// any user pop/nav gesture can fire) rather than during render.
useEffect(() => {
@@ -32,4 +39,6 @@ export function useDirtyGuard(dirty: boolean, prompt: string): void {
window.addEventListener('beforeunload', handler);
return () => window.removeEventListener('beforeunload', handler);
}, [dirty]);
return markClean;
}
@@ -13,6 +13,7 @@ function json(body: unknown, status = 200): Response {
interface Options {
connection: { address: string | null; hasApiKey: boolean };
saveResponse?: Promise<Response>;
saveStatus?: number;
saveBody?: unknown;
}
@@ -28,6 +29,9 @@ function installFetch(family: string, options: Options) {
}
if (url.endsWith(`/api/v1/media-sources/${family}/connection`) && method === 'PUT') {
putBodies.push(String(init?.body ?? ''));
if (options.saveResponse) {
return options.saveResponse;
}
const status = options.saveStatus ?? 200;
if (status >= 400) {
return Promise.resolve(json({ title: 'Invalid', detail: 'Connection failed' }, status));
@@ -82,6 +86,72 @@ describe('RemoteConnectionEditScreen', () => {
expect(body.apiKey).toBe(''); // blank = retain existing key server-side
});
it.each(['jellyfin', 'emby'] as const)(
'successful %s save navigates without triggering the dirty guard',
async (family) => {
const editPath = `/app/libraries/${family}/connection`;
window.history.replaceState(null, '', editPath);
installFetch(family, {
connection: { address: `http://${family}:8096`, hasApiKey: true },
saveBody: { address: `http://${family}:9000`, hasApiKey: true }
});
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const onPopState = () => {
// Mirror App's dirty-guard veto: a rejected synthetic pop restores the editor path.
if (!canLeaveCurrentScreen()) {
window.history.pushState(null, '', editPath);
}
};
window.addEventListener('popstate', onPopState);
try {
render(<RemoteConnectionEditScreen family={family} />);
const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement;
fireEvent.change(address, { target: { value: `http://${family}:9000` } });
fireEvent.click(screen.getByRole('button', { name: 'Save connection' }));
await vi.waitFor(() => expect(window.location.pathname).toBe(`/app/libraries/${family}`));
expect(confirmSpy).not.toHaveBeenCalled();
} finally {
window.removeEventListener('popstate', onPopState);
}
}
);
it('blocks draft edits while a save is in flight so the completion cannot discard newer input', async () => {
let resolveSave: (response: Response) => void = () => {};
const saveResponse = new Promise<Response>((resolve) => {
resolveSave = resolve;
});
const { putBodies } = installFetch('jellyfin', {
connection: { address: 'http://jf:8096', hasApiKey: true },
saveResponse
});
render(<RemoteConnectionEditScreen family="jellyfin" />);
const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement;
const apiKey = screen.getByPlaceholderText(/leave blank to keep/i) as HTMLInputElement;
fireEvent.change(address, { target: { value: 'http://jf:9000' } });
fireEvent.click(screen.getByRole('button', { name: 'Save connection' }));
await vi.waitFor(() => expect(putBodies).toHaveLength(1));
expect(address).toBeDisabled();
expect(apiKey).toBeDisabled();
// A synthetic event cannot bypass the same mutation gate used by the disabled controls.
fireEvent.change(address, { target: { value: 'http://jf:newer' } });
fireEvent.change(apiKey, { target: { value: 'newer-key' } });
expect(address.value).toBe('http://jf:9000');
expect(apiKey.value).toBe('');
resolveSave(json({ address: 'http://jf:9000', hasApiKey: true }));
await vi.waitFor(() => expect(window.location.pathname).toBe('/app/libraries/jellyfin'));
expect(putBodies).toHaveLength(1);
});
it('first connect (no stored key) requires an api key before Save enables', async () => {
installFetch('jellyfin', { connection: { address: '', hasApiKey: false } });
+14 -3
View File
@@ -84,7 +84,7 @@ export function RemoteConnectionEditScreen({ family }: { family: RemoteFamilyWit
const valid = addressValid && apiKeyValid;
const dirty = JSON.stringify(draft) !== JSON.stringify(saved);
useDirtyGuard(dirty, DIRTY_PROMPT);
const markDirtyGuardClean = useDirtyGuard(dirty, DIRTY_PROMPT);
if (loadError) {
return (
@@ -129,6 +129,7 @@ export function RemoteConnectionEditScreen({ family }: { family: RemoteFamilyWit
setSaved(next);
setLoaded({ hasApiKey: connection.hasApiKey });
setSaving(false);
markDirtyGuardClean();
navigateToPath(familyRoute(family));
})
.catch((error: unknown) => {
@@ -157,17 +158,27 @@ export function RemoteConnectionEditScreen({ family }: { family: RemoteFamilyWit
<Card title={<h3>Connection</h3>} subtitle={`${meta.label} server address and API key.`}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 480 }}>
<Input
disabled={saving}
label="Address"
value={draft.address}
onChange={(event) => setDraft((current) => ({ ...current, address: event.target.value }))}
onChange={(event) => {
if (!saving) {
setDraft((current) => ({ ...current, address: event.target.value }));
}
}}
placeholder="http://192.168.1.50:8096"
error={draft.address.trim() && !addressValid ? 'Enter a valid absolute http(s) URL' : null}
/>
<Input
disabled={saving}
label="API key"
type="password"
value={draft.apiKey}
onChange={(event) => setDraft((current) => ({ ...current, apiKey: event.target.value }))}
onChange={(event) => {
if (!saving) {
setDraft((current) => ({ ...current, apiKey: event.target.value }));
}
}}
placeholder={hasApiKey ? 'Key is set — leave blank to keep, or enter a new key' : 'Enter an API key'}
error={!apiKeyValid && draft.apiKey.length === 0 && !hasApiKey ? 'API key is required' : null}
/>