fix(spa): guard schedule editor against destructive cross-save + lost updates (F1/F3/F4/F5)

F1: switching schedules synchronously clears items/baseline/selection/dirty
before setActiveId (applySwitch) and gates every mutation surface on a
successful items load for the CURRENT activeId (itemsLoaded) — a failed items
GET for schedule B can no longer leave B's header over A's dirty draft and PUT
A's lineup into B.
F3: key={selectedItem._key} on ScheduleItemInspector so per-item child state
(PlaylistPicker groupId, SearchPicker query) resets on selection change.
F4: mutate() no-ops and all edit surfaces disable while saving, so edits during
an in-flight Save can't be silently discarded by the Save .then.
F5: create-schedule auto-switch routes through guardedSwitch so a dirty draft
gets the same discard confirm.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-11 01:00:34 +02:00
co-authored by Claude Fable 5
parent 8feb9a1367
commit 4bc43893c1
3 changed files with 154 additions and 22 deletions
+10 -2
View File
@@ -97,15 +97,23 @@ export interface ScheduleItemInspectorProps {
item: DraftItem;
shuffleScheduleItems: boolean;
pickers: SchedulePickerData;
// When true, the whole inspector is non-interactive (an items load is in flight/failed, or a Save
// is in flight) — interaction is suppressed so no edit is dropped by the Save .then (F4). The
// parent's mutate() also no-ops in this state; this is the matching visual/pointer block.
disabled?: boolean;
onChange: (next: DraftItem) => void;
}
export function ScheduleItemInspector({ item, shuffleScheduleItems, pickers, onChange }: ScheduleItemInspectorProps) {
export function ScheduleItemInspector({ item, shuffleScheduleItems, pickers, disabled, onChange }: ScheduleItemInspectorProps) {
const patch = (changes: Partial<DraftItem>) => onChange({ ...item, ...changes });
const duration = parseDuration(item.playoutDuration);
return (
<div className="ctv-schedule-inspector-body">
<div
className="ctv-schedule-inspector-body"
aria-disabled={disabled || undefined}
style={disabled ? { opacity: 0.6, pointerEvents: 'none' } : undefined}
>
<SourceSection item={item} onChange={onChange} pickers={pickers} />
<fieldset className="ctv-schedule-fieldset">
+94
View File
@@ -259,6 +259,100 @@ describe('SchedulesScreen — error + dirty handling', () => {
});
});
describe('SchedulesScreen — review fixes (F1/F3/F4/F5)', () => {
it('F1: a failed items load after switching does not leave the prior draft saveable', async () => {
const handle = await renderReady({
schedules: [schedule, { ...schedule, id: 2, name: 'Late' }],
onRequest: (url, method) =>
url === '/api/schedules/2/items' && method === 'GET'
? jsonResponse({ title: 'Boom', detail: 'Load failed' }, 500)
: null
});
// Make schedule 1 dirty (draft lineup differs from server).
fireEvent.change(screen.getByLabelText('Custom title'), { target: { value: 'Nightly' } });
expect((screen.getByRole('button', { name: /^Save$/ }) as HTMLButtonElement).disabled).toBe(false);
// Switch to schedule 2 (confirm mocked true); its items GET fails.
fireEvent.change(screen.getByLabelText('Active schedule'), { target: { value: '2' } });
await screen.findByText('Load failed');
// Header moved to schedule 2, but there is no stale schedule-1 lineup, Save is disabled, and no
// PUT could ever be issued (which would have destructively replaced schedule 2 with A's draft).
expect(screen.getByRole('heading', { name: 'Late' })).toBeTruthy();
expect(screen.queryByLabelText('Schedule lineup')).toBeNull();
expect(screen.getByText('No schedule items')).toBeTruthy();
expect((screen.getByRole('button', { name: /^Save$/ }) as HTMLButtonElement).disabled).toBe(true);
expect(handle.requests.some((r) => r.url === '/api/schedules/2/items' && r.method === 'PUT')).toBe(false);
});
it('F3: selecting a different item resets per-item picker state (playlist group)', async () => {
await renderReady({
items: [
responseItem({ id: 10, index: 0, collectionType: 'Playlist', collectionId: null, collectionName: null, playbackOrder: 'None', playlistId: 100, playlistName: 'PL A', playlistGroupId: 1, name: 'PL A' }),
responseItem({ id: 11, index: 1, collectionType: 'Playlist', collectionId: null, collectionName: null, playbackOrder: 'None', playlistId: 200, playlistName: 'PL B', playlistGroupId: 2, name: 'PL B' })
],
onRequest: (url) =>
url === '/api/playlists/groups'
? jsonResponse([{ id: 1, name: 'Group One' }, { id: 2, name: 'Group Two' }])
: url.startsWith('/api/playlists?playlistGroupId=')
? jsonResponse([])
: null
});
const groupSelect = () => screen.getByLabelText('Playlist group') as HTMLSelectElement;
// Item A is selected by default → PlaylistPicker seeded with group 1.
expect(groupSelect().value).toBe('1');
// Select item B; with key={_key} the PlaylistPicker remounts and re-seeds groupId from item B.
const lineup = screen.getByLabelText('Schedule lineup');
fireEvent.click(within(lineup).getByText('PL B').closest('button') as HTMLButtonElement);
expect(groupSelect().value).toBe('2');
});
it('F4: edits during an in-flight Save are blocked (no lost update)', async () => {
let resolvePut: (r: Response) => void = () => {};
const putPromise = new Promise<Response>((res) => {
resolvePut = res;
});
const handle = await renderReady({
onRequest: (url, method) =>
url === '/api/schedules/1/items' && method === 'PUT'
? (putPromise as unknown as Response) // mockApi wraps in Promise.resolve, which adopts this thenable
: null
});
const title = () => screen.getByLabelText('Custom title') as HTMLInputElement;
fireEvent.change(title(), { target: { value: 'First' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
await waitFor(() => expect(handle.requests.some((r) => r.method === 'PUT')).toBe(true));
// Attempt an edit while the Save is in flight — mutate() must no-op, so the input does NOT
// optimistically show 'Second' (without the guard it would, then be silently clobbered by the
// Save .then's setItems — the lost update). The PUT already sent 'First'.
fireEvent.change(title(), { target: { value: 'Second' } });
expect(title().value).toBe('First');
resolvePut(jsonResponse([responseItem({ id: 500, index: 0, customTitle: 'First', name: 'Item 0' })]));
await waitFor(() => expect(title().value).toBe('First'));
// The mid-save edit never produced a second PUT and never survived the reload.
expect(handle.requests.filter((r) => r.method === 'PUT').length).toBe(1);
});
it('F5: creating a schedule while the draft is dirty confirms before switching focus', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const handle = await renderReady();
fireEvent.change(screen.getByLabelText('Custom title'), { target: { value: 'Nightly' } });
fireEvent.click(screen.getByRole('button', { name: /Add schedule/ }));
const dialog = screen.getByRole('dialog');
fireEvent.change(within(dialog).getByLabelText('Name'), { target: { value: 'Weekend' } });
fireEvent.click(within(dialog).getByRole('button', { name: /^Save$/ }));
await waitFor(() => expect(handle.requests.some((r) => r.url === '/api/schedules' && r.method === 'POST')).toBe(true));
// The auto-switch to the new schedule went through the dirty guard; confirm=false aborted it.
await waitFor(() => expect(confirmSpy).toHaveBeenCalledWith(expect.stringContaining('unsaved')));
expect(handle.requests.some((r) => r.url === '/api/schedules/99/items')).toBe(false);
});
});
describe('SchedulesScreen — schedule CRUD', () => {
it('create flow POSTs and switches to the new schedule', async () => {
const handle = await renderReady();
+50 -20
View File
@@ -80,6 +80,9 @@ export function SchedulesScreen() {
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const [dirty, setDirty] = useState(false);
const [itemsLoading, setItemsLoading] = useState(false);
// True only after a successful items GET for the CURRENT activeId. Gates every mutation surface so
// a failed/in-flight load can't leave a stale draft editable (F1) — see guardedSwitch/applySwitch.
const [itemsLoaded, setItemsLoaded] = useState(false);
const [saving, setSaving] = useState(false);
const [mutationError, setMutationError] = useState<string | null>(null);
const [form, setForm] = useState<null | 'create' | 'edit'>(null);
@@ -140,6 +143,7 @@ export function SchedulesScreen() {
setDirtyState(false);
setMutationError(null);
setItemsLoading(false);
setItemsLoaded(true);
})
.catch((error: unknown) => {
if (!activeRef.current || itemSeq.current !== seq) {
@@ -147,6 +151,7 @@ export function SchedulesScreen() {
}
setMutationError(messageFromScheduleError(error, 'Unable to load schedule items'));
setItemsLoading(false);
setItemsLoaded(false);
});
}, [setDirtyState]);
@@ -213,18 +218,39 @@ export function SchedulesScreen() {
const shuffleScheduleItems = activeSchedule?.shuffleScheduleItems ?? false;
const selectedItem = items.find((i) => i._key === selectedKey) ?? items[0] ?? null;
// Editing is only permitted once the CURRENT schedule's items have loaded and while no Save is in
// flight. Blocks the F1 destructive-cross-save (stale draft PUT into a different schedule) and the
// F4 lost-update (edits made during a Save that the .then's setItems would silently discard).
const canEdit = itemsLoaded && !saving;
// Synchronously drop the outgoing schedule's draft state BEFORE switching activeId, so a failed or
// in-flight items GET for the new schedule can never leave the previous (possibly dirty) draft
// visible/saveable (F1). The subsequent load re-arms itemsLoaded on success.
const applySwitch = (scheduleId: number | null) => {
setItems([]);
baselineRef.current = [];
setSelectedKey(null);
setDirtyState(false);
setMutationError(null);
setItemsLoaded(false);
setItemsLoading(scheduleId != null);
setActiveId(scheduleId);
};
const guardedSwitch = (scheduleId: number) => {
if (scheduleId === activeId) {
if (saving || scheduleId === activeId) {
return;
}
if (dirtyRef.current && !window.confirm(DIRTY_PROMPT)) {
return;
}
setItemsLoading(true);
setActiveId(scheduleId);
applySwitch(scheduleId);
};
const mutate = (nextItems: DraftItem[], nextSelected?: string | null) => {
if (!canEdit) {
return;
}
setItems(nextItems);
setDirtyState(true);
if (nextSelected !== undefined) {
@@ -279,7 +305,7 @@ export function SchedulesScreen() {
};
const save = () => {
if (activeId == null) {
if (activeId == null || saving || !itemsLoaded) {
return;
}
const validationError = validateDraft(items);
@@ -326,8 +352,9 @@ export function SchedulesScreen() {
return { ...current, schedules: schedulesNext };
});
if (!schedules.some((s) => s.id === saved.id)) {
// new schedule: switch to it (guarded — a create replaces focus)
setActiveId(saved.id);
// New schedule: switch focus to it, but through the same dirty guard as the schedule picker so
// an unsaved draft on the current schedule isn't silently wiped without a confirm (F5).
guardedSwitch(saved.id);
}
};
@@ -348,12 +375,9 @@ export function SchedulesScreen() {
return { ...current, schedules: current.schedules.filter((s) => s.id !== activeId) };
});
const remaining = schedules.filter((s) => s.id !== activeId);
setDirtyState(false);
setActiveId(remaining[0]?.id ?? null);
if (remaining.length === 0) {
setItems([]);
baselineRef.current = [];
}
// Drop the deleted schedule's draft and load the next one (or clear when none remain) — same
// synchronous state reset as a picker switch so no stale draft survives (F1).
applySwitch(remaining[0]?.id ?? null);
})
.catch((error: unknown) => {
if (activeRef.current) {
@@ -379,6 +403,7 @@ export function SchedulesScreen() {
<Select
label="Active schedule"
size="sm"
disabled={saving}
value={`${activeSchedule.id}`}
onChange={(e) => guardedSwitch(Number(e.target.value))}
options={schedules.map((s) => ({ value: `${s.id}`, label: s.name ?? `Schedule ${s.id}` }))}
@@ -411,11 +436,11 @@ export function SchedulesScreen() {
) : (
<>
<div className="ctv-schedule-toolbar">
<Button size="sm" variant="ghost" startIcon={<Plus aria-hidden="true" size={14} />} onClick={addItem}>Add item</Button>
<Button size="sm" variant="ghost" disabled={!canEdit} startIcon={<Plus aria-hidden="true" size={14} />} onClick={addItem}>Add item</Button>
<div className="ctv-schedule-toolbar-spacer" />
{itemsLoading && <Spinner size={14} tone="muted" />}
<Button size="sm" variant="ghost" disabled={!dirty || saving} startIcon={<Undo2 aria-hidden="true" size={14} />} onClick={discard}>Discard</Button>
<Button size="sm" disabled={!dirty || saving} loading={saving} startIcon={<Save aria-hidden="true" size={14} />} onClick={save}>Save</Button>
<Button size="sm" disabled={!dirty || saving || !itemsLoaded} loading={saving} startIcon={<Save aria-hidden="true" size={14} />} onClick={save}>Save</Button>
</div>
<div className="ctv-schedule-grid">
@@ -434,6 +459,7 @@ export function SchedulesScreen() {
index={index}
active={item._key === selectedItem?._key}
canReorder={canReorder}
disabled={!canEdit}
isFirst={index === 0}
isLast={index === items.length - 1}
onSelect={() => setSelectedKey(item._key)}
@@ -454,13 +480,15 @@ export function SchedulesScreen() {
<strong>{draftItemLabel(selectedItem)}</strong>
<span>{humanizeEnum(selectedItem.collectionType)}</span>
</div>
<IconButton title="Copy item" onClick={() => copyItem(selectedItem)}><Copy aria-hidden="true" size={15} /></IconButton>
<IconButton title="Remove item" onClick={() => removeItem(selectedItem)}><Trash2 aria-hidden="true" size={15} /></IconButton>
<IconButton title="Copy item" disabled={!canEdit} onClick={() => copyItem(selectedItem)}><Copy aria-hidden="true" size={15} /></IconButton>
<IconButton title="Remove item" disabled={!canEdit} onClick={() => removeItem(selectedItem)}><Trash2 aria-hidden="true" size={15} /></IconButton>
</div>
<ScheduleItemInspector
key={selectedItem._key}
item={selectedItem}
shuffleScheduleItems={shuffleScheduleItems}
pickers={pickers}
disabled={!canEdit}
onChange={updateItem}
/>
</>
@@ -499,6 +527,7 @@ function LineupRow({
index,
active,
canReorder,
disabled,
isFirst,
isLast,
onSelect,
@@ -510,6 +539,7 @@ function LineupRow({
index: number;
active: boolean;
canReorder: boolean;
disabled: boolean;
isFirst: boolean;
isLast: boolean;
onSelect: () => void;
@@ -540,16 +570,16 @@ function LineupRow({
<div className="ctv-schedule-block-actions">
{canReorder && (
<>
<IconButton size="sm" disabled={isFirst} title={`Move ${label} up`} onClick={() => onMove(-1)}>
<IconButton size="sm" disabled={isFirst || disabled} title={`Move ${label} up`} onClick={() => onMove(-1)}>
<span aria-hidden="true">↑</span>
</IconButton>
<IconButton size="sm" disabled={isLast} title={`Move ${label} down`} onClick={() => onMove(1)}>
<IconButton size="sm" disabled={isLast || disabled} title={`Move ${label} down`} onClick={() => onMove(1)}>
<span aria-hidden="true">↓</span>
</IconButton>
</>
)}
<IconButton size="sm" title={`Copy ${label}`} onClick={onCopy}><Copy aria-hidden="true" size={14} /></IconButton>
<IconButton size="sm" title={`Remove ${label}`} onClick={onRemove}><Trash2 aria-hidden="true" size={14} /></IconButton>
<IconButton size="sm" disabled={disabled} title={`Copy ${label}`} onClick={onCopy}><Copy aria-hidden="true" size={14} /></IconButton>
<IconButton size="sm" disabled={disabled} title={`Remove ${label}`} onClick={onRemove}><Trash2 aria-hidden="true" size={14} /></IconButton>
</div>
</div>
</div>