fix(830): a write failure reports to a surface that outlives the dialog that started it
`AddItemsDialog.submit` POSTed to `/api/v1/collections/{id}/items` and reported failure into a
banner rendered from its OWN state. The dialog is dismissible mid-request through three paths that
never consult `adding` -- Escape and a backdrop click (both `useOverlayBehavior`) and the header
close button -- and the caller remounts it on `key={`add-${pickerOpen}`}`, so dismissal genuinely
unmounts it. Select 12 items, Add, press Escape, the request fails: nothing surfaces, the list
reloads unchanged, and the user believes 12 items were added.
drop deliberate rather than accidental. A deliberate drop is still a user who is told nothing.
The asymmetry is the finding: SUCCESS already outlived dismissal everywhere here, because it is
reported through a parent callback (`onAdded`/`onDone`, which the screens turn into a `Toast`).
Only failure died with the surface. So this is not a new notification system -- it routes failure
through the channel success already uses. `AddToMenu` had `onDone` and no counterpart at all.
`useDismissSafeError` (`web/src/hooks.ts`) renders the message INLINE while the surface is mounted
-- the better surface, since it keeps the user's selections and context -- and diverts to a
caller-supplied `onFailed` once it is gone. The surviving surface belongs to the parent and differs
per screen (a `role="alert"` banner on CollectionsScreen, `notice`+`Toast` on MediaBrowse/Search),
so it is a prop contract rather than a rendering decision. Gating dismissal on the busy flag was
considered and rejected: it traps the user behind an in-flight request with no cancel path, and
would not cancel the write anyway.
Applied to the A1 shape -- where the surface owns the error state and is really unmounted:
AddItemsDialog plus the four `web/src/media/addTo/` dialogs, whose failures previously could not
reach the screen Toast that already showed their successes.
Proofs, executed rather than described:
- deleting `reportRef.current(message)` alone reddens the new CollectionsScreen test on
`Unable to find an element with the text: Request failed with status 500`
- `hooks.test.tsx` pins both branches directly, plus that the report goes through the LATEST
callback rather than the one captured on first render
- `CollectionsScreen.guards.test.tsx`'s is-mounted read count moves 2 -> 1 because the catch's
guard migrated into the hook (its `...actual` module mock cannot see the hook's internal
`useIsMountedRef()`); removing the surviving `finally` guard takes it to 0 and reddens, so the
anti-masking property that count was added for is intact
Scope is stated rather than implied. A sweep of all 68 Dialog/ConfirmDialog/SlideOver call sites
found three shapes; only A1 is fixed here. A2 -- error state that survives but whose render site is
gated by the same condition dismissal clears, mostly delete-confirm flows -- is left open in #877
because its right answer is probably a shared surface, not twenty prop threads.
fixes #830
refs #877, #740, #685
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XE2tF2aUasK2hWPmBRsrMY
This commit is contained in:
@@ -195,6 +195,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
|
||||
| `spa.collection-custom-order-ui` | Collection custom ordering uses per-row Move up/Move down buttons (not drag) and is offered for any manual collection with custom order enabled, not just movies-only. | 2026-07-09 | [link](records/spa/collection-custom-order-ui.md) |
|
||||
| `spa.datetime-local-input` | The channel-mode date/time input uses a native `<input type="datetime-local">` instead of free-text Chronic natural-language parsing. | 2026-07-09 | [link](records/spa/datetime-local-input.md) |
|
||||
| `spa.deco-templates-table` | The deco-templates editor also renders its day/deco assignment as a table, extending (not replacing) the templates-editor-table convention. | 2026-07-09 | [link](records/spa/deco-templates-table.md) |
|
||||
| `spa.dismissible-write-failure-reporting` | A component that starts an async WRITE from inside a dismissible surface (`Dialog`, `SlideOver`, `ConfirmDialog`) must report failure through `useDismissSafeError` (`web/src/hooks.ts`), which renders the message INLINE while the surface is mounted and hands it to a caller-supplied `onFailed` once the surface is gone. Guarding the `setError` with an is-mounted check and stopping there is NOT sufficient: it converts a silent data-loss risk into a silent NO-OP the user reads as success. All three primitives dismiss through Escape and a backdrop/scrim click (`useOverlayBehavior`) plus a header close button, and NONE of those consult a busy flag — disabling the footer Cancel button, which every one of these dialogs does, looks like it closes the hole and does not. The surviving surface belongs to the PARENT and differs per screen (a screen-level `role="alert"` banner on `CollectionsScreen`, the `notice`+`Toast` pair on `MediaBrowseScreen`/`SearchScreen`), so the mechanism is a PROP CONTRACT rather than a rendering decision; there is no global toast host in this SPA and this decision does not add one. `onFailed` is optional because not every host screen has a surface to report onto — where it is omitted the failure is dropped exactly as before, which is a KNOWN remaining gap, not a claim of coverage. | 2026-08-29 | [link](records/spa/dismissible-write-failure-reporting.md) |
|
||||
| `spa.download-sample-gate` | The SPA disables both Download Media Sample and Download Results while a troubleshooting session is starting/running (Blazor only gated Download Results). | 2026-07-09 | [link](records/spa/download-sample-gate.md) |
|
||||
| `spa.field-progressive-disclosure` | A consequential settings field explains itself through one shared `FieldHelp` icon trigger beside the field name — never the label itself, never a widened `Tooltip` — with the paragraph declared `as const` in the screen's own `FIELD_HELP` record and the panel portalled to `document.body`. | 2026-08-26 | [link](records/spa/field-progressive-disclosure.md) |
|
||||
| `spa.legacy-redirect-matcher` | `LegacyUiRedirects.TryGetRedirect` is a two-tier matcher — an exact `OrdinalIgnoreCase` `Map` (Tier 1) then an ordered segment-template pattern list (Tier 2, first-match-wins) — collision-free by construction, with a guard invariant that no rule may prefix-match `/api`, `/artwork`, `/docs`, `/openapi`, `/iptv`, `/app`, or `/media/sources`. | 2026-07-11 | [link](records/spa/legacy-redirect-matcher.md) |
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
key: spa.dismissible-write-failure-reporting
|
||||
title: '2026-08-29 — A write failure reports to a surface that OUTLIVES the dismissible surface that started it (#830)'
|
||||
status: active
|
||||
since: '2026-08-29'
|
||||
supersedes: none
|
||||
superseded-by: none
|
||||
rule: 'A component that starts an async WRITE from inside a dismissible surface (`Dialog`, `SlideOver`, `ConfirmDialog`) must report failure through `useDismissSafeError` (`web/src/hooks.ts`), which renders the message INLINE while the surface is mounted and hands it to a caller-supplied `onFailed` once the surface is gone. Guarding the `setError` with an is-mounted check and stopping there is NOT sufficient: it converts a silent data-loss risk into a silent NO-OP the user reads as success. All three primitives dismiss through Escape and a backdrop/scrim click (`useOverlayBehavior`) plus a header close button, and NONE of those consult a busy flag — disabling the footer Cancel button, which every one of these dialogs does, looks like it closes the hole and does not. The surviving surface belongs to the PARENT and differs per screen (a screen-level `role="alert"` banner on `CollectionsScreen`, the `notice`+`Toast` pair on `MediaBrowseScreen`/`SearchScreen`), so the mechanism is a PROP CONTRACT rather than a rendering decision; there is no global toast host in this SPA and this decision does not add one. `onFailed` is optional because not every host screen has a surface to report onto — where it is omitted the failure is dropped exactly as before, which is a KNOWN remaining gap, not a claim of coverage.'
|
||||
signals: 'failed add silently swallowed · dialog closed mid-request · Escape backdrop close button ignore adding flag · error banner unmounts with the dialog · useDismissSafeError inline vs onFailed · success outlives dismissal but failure does not · onDone has no failure counterpart · paths: `web/src/hooks.ts`, `web/src/screens/CollectionsScreen.tsx`, `web/src/media/addTo/`, `web/src/components/overlay.tsx` · issues: #830, #877, #740, #685'
|
||||
mechanics: 'Pinned three ways. (1) `web/src/hooks.test.tsx` → "useDismissSafeError (#830)" pins both branches directly: mounted reports INLINE and does not call `onFailed`, unmounted calls `onFailed`, and the report goes through the LATEST callback rather than the one captured on first render. (2) `CollectionsScreen.test.tsx` → "reports a failed add on the screen when the dialog was dismissed before the request settled (#830)" drives the whole path — it parks the POST in flight, dismisses via Escape, then settles the request and asserts the message is on the screen and NOT inside a dialog. Executed: deleting `reportRef.current(message)` alone reddens it on `Unable to find an element with the text: Request failed with status 500`. (3) `CollectionsScreen.guards.test.tsx` counts is-mounted reads and moved from 2 to 1 when the catch''s guard migrated into the hook; its `...actual` module mock cannot see the hook''s internal `useIsMountedRef()`, which is why (1) exists. Executed: removing the surviving `finally` guard takes that count to 0 and reddens.'
|
||||
---
|
||||
|
||||
**The asymmetry is the whole finding.** At every one of these sites SUCCESS already outlives
|
||||
dismissal, because it is reported through a parent callback (`onAdded` / `onDone`, which
|
||||
`MediaBrowseScreen` and `SearchScreen` turn into a `Toast`). Only FAILURE was rendered from the
|
||||
dismissible component's own state. So the fix is not a new notification system — it is routing
|
||||
failure through the channel success already uses. `AddToMenu` had `onDone` and no counterpart at
|
||||
all, which is why a failed "Add to collection" from a media card reported nowhere.
|
||||
|
||||
**Why the inline branch is kept rather than always reporting to the parent.** While the dialog is
|
||||
up, inline is the better surface: it keeps the user's selections and the context they are looking
|
||||
at. Diverting to a parent banner in that case would be its own defect — the message would surface
|
||||
somewhere else while the dialog the user is staring at stays blank.
|
||||
|
||||
**Why not simply gate dismissal on the busy flag.** That was considered and rejected: gating
|
||||
Escape/backdrop/close on `adding` traps the user behind an in-flight request with no cancel path,
|
||||
which is exactly why `Dialog` does not do it by default. The request is also genuinely still
|
||||
running — cancelling the UI would not cancel the write.
|
||||
|
||||
**#740 guarded this and did not fix it, correctly.** That issue added the is-mounted guard so the
|
||||
`setError` could not fire on an unmounted tree. That is right and stays. Its scope was the async
|
||||
guards, and it deliberately did not change the UX — which left the guard making the drop
|
||||
*deliberate* rather than accidental. A deliberate drop is still a user who believes twelve items
|
||||
were added when none were, and that is the half this record closes.
|
||||
|
||||
**Scope, stated rather than implied.** A sweep of all 68 `Dialog`/`ConfirmDialog`/`SlideOver` call
|
||||
sites (2026-08-29) found three shapes: (A1) the surface hard-unmounts and takes its own error state
|
||||
with it — the shape fixed here, at `AddItemsDialog` and the four `web/src/media/addTo/` dialogs;
|
||||
(A2) the error state lives in a parent that never unmounts, but the JSX rendering it is nested
|
||||
inside the same `open`/`target` condition dismissal just cleared, so it has no DOM node to render
|
||||
into — the majority pattern, mostly delete-confirm flows; (B) a genuinely surviving screen-level
|
||||
banner, which `DecoTemplatesScreen` and `BlocksScreen` already have. Only A1 is fixed here. A2 is
|
||||
LEFT OPEN deliberately: it is a larger, mostly-delete-confirm population whose right answer may be
|
||||
a shared reporting surface rather than a per-site prop, and folding it in would have made this PR a
|
||||
rewrite of twenty screens. It is tracked in #877, which carries the sweep's verified-vs-inferred
|
||||
split forward, rather than being recorded as done here.
|
||||
@@ -404,6 +404,44 @@ double-invoke for the re-arm) **and** the *integration* (mock the hook module an
|
||||
component actually read `current` — and saw `false` — when the late response landed). Verify each by
|
||||
removing the mechanism and confirming the test fails.
|
||||
|
||||
## 3c. A write failure must outlive the dismissible surface that started it (#830)
|
||||
|
||||
`Dialog`, `SlideOver` and `ConfirmDialog` are all dismissible **mid-request** through three paths
|
||||
that never consult a busy flag: Escape and a backdrop/scrim click (both via `useOverlayBehavior`),
|
||||
and the header close button. Disabling the footer Cancel button — which nearly every dialog here
|
||||
does — looks like it closes that hole and does not.
|
||||
|
||||
So an error rendered from the dismissible component's own state has nowhere to go once the user
|
||||
dismisses it. The request still runs, still fails, and the screen reloads unchanged: the user reads
|
||||
that as success. Guarding the `setError` with an is-mounted check (§3b) is necessary but **not
|
||||
sufficient** — it makes the drop deliberate rather than accidental, which is still a drop.
|
||||
|
||||
**Use `useDismissSafeError` (`web/src/hooks.ts`).** It renders the message inline while the surface
|
||||
is mounted — the better surface, since it keeps the user's context — and hands it to a
|
||||
caller-supplied `onFailed` once the surface is gone:
|
||||
|
||||
```tsx
|
||||
const { inlineError, reportFailure, setInlineError } = useDismissSafeError(onFailed);
|
||||
// ...
|
||||
} catch (err) {
|
||||
reportFailure(messageFromXError(err, 'Unable to …'));
|
||||
}
|
||||
```
|
||||
|
||||
The surviving surface belongs to the **parent** and differs per screen — a screen-level
|
||||
`role="alert"` banner on `CollectionsScreen`, the `notice` + `Toast` pair on `MediaBrowseScreen` and
|
||||
`SearchScreen` — so `onFailed` is a prop contract, not a rendering decision. There is no global
|
||||
toast host in this SPA; do not add one for a single screen.
|
||||
|
||||
Note the asymmetry this exists to correct: **success already outlives dismissal** at these sites,
|
||||
because it is reported through `onAdded` / `onDone`. Failure was the half that died with the
|
||||
surface. When you add a success callback to a dialog, add its failure counterpart.
|
||||
|
||||
`onFailed` is optional, because not every host screen has a surface to report onto
|
||||
(`MediaDetailScreen` wires neither callback). Where it is omitted the failure is dropped as before —
|
||||
a known gap, not coverage (#877). Rationale and the full call-site sweep:
|
||||
`docs/decisions/records/spa/dismissible-write-failure-reporting.md`.
|
||||
|
||||
## 4. API client modules
|
||||
|
||||
One file per domain in `web/src/api/`, e.g. `logs.ts`, `blocks.ts`, `playouts.ts`. Pattern (see
|
||||
|
||||
+69
-2
@@ -1,7 +1,7 @@
|
||||
import { cleanup, render } from '@testing-library/react';
|
||||
import { act, cleanup, render } from '@testing-library/react';
|
||||
import { StrictMode, useEffect } from 'react';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { useIsMountedRef } from './hooks';
|
||||
import { useDismissSafeError, useIsMountedRef } from './hooks';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
@@ -56,3 +56,70 @@ describe('useIsMountedRef (#578)', () => {
|
||||
expect((captured as unknown as { current: boolean }).current).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useDismissSafeError (#830)', () => {
|
||||
interface Handle {
|
||||
inlineError: string | null;
|
||||
reportFailure: (message: string) => void;
|
||||
}
|
||||
|
||||
function renderProbe(report: (message: string) => void) {
|
||||
const handle: Handle = { inlineError: null, reportFailure: () => {} };
|
||||
|
||||
function Probe() {
|
||||
const hook = useDismissSafeError(report);
|
||||
handle.inlineError = hook.inlineError;
|
||||
handle.reportFailure = hook.reportFailure;
|
||||
return <span>{hook.inlineError}</span>;
|
||||
}
|
||||
|
||||
return { handle, ...render(<Probe />) };
|
||||
}
|
||||
|
||||
it('renders the failure INLINE while the surface is still mounted', async () => {
|
||||
const reported: string[] = [];
|
||||
const { handle, findByText } = renderProbe((message) => reported.push(message));
|
||||
|
||||
act(() => handle.reportFailure('nope'));
|
||||
|
||||
// Inline is the better surface while the dialog is up: it keeps the user's context. Diverting
|
||||
// to the parent here would ALSO be a defect — the message would appear somewhere else while the
|
||||
// dialog the user is looking at stays blank.
|
||||
expect(await findByText('nope')).toBeInTheDocument();
|
||||
expect(reported).toEqual([]);
|
||||
});
|
||||
|
||||
it('diverts the failure to the surviving surface once the surface is gone', () => {
|
||||
const reported: string[] = [];
|
||||
const { handle, unmount } = renderProbe((message) => reported.push(message));
|
||||
|
||||
unmount();
|
||||
handle.reportFailure('gone');
|
||||
|
||||
// This is the #830 defect itself: before the fix the message was dropped here and the user was
|
||||
// left believing the write succeeded. Delete `reportRef.current(message)` and this goes red.
|
||||
expect(reported).toEqual(['gone']);
|
||||
});
|
||||
|
||||
it('reports through the LATEST callback, not the one captured on first render', () => {
|
||||
const first: string[] = [];
|
||||
const second: string[] = [];
|
||||
|
||||
function Probe({ sink }: { sink: (message: string) => void }) {
|
||||
handle = useDismissSafeError(sink);
|
||||
return null;
|
||||
}
|
||||
|
||||
let handle: ReturnType<typeof useDismissSafeError> = null as never;
|
||||
const { rerender, unmount } = render(<Probe sink={(m) => first.push(m)} />);
|
||||
rerender(<Probe sink={(m) => second.push(m)} />);
|
||||
unmount();
|
||||
|
||||
handle.reportFailure('latest');
|
||||
|
||||
// Parents hand down a fresh closure every render (the same reason `useOverlayBehavior` keeps a
|
||||
// latest-ref). Capturing the first one would report into a stale closure.
|
||||
expect(first).toEqual([]);
|
||||
expect(second).toEqual(['latest']);
|
||||
});
|
||||
});
|
||||
|
||||
+51
-1
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
// Shared is-mounted guard for async callbacks (#578). A monotonic `seqRef` drops a STALE response
|
||||
// (an older request resolving after a newer one) but says nothing about whether the component is
|
||||
@@ -19,3 +19,53 @@ export function useIsMountedRef(): { readonly current: boolean } {
|
||||
|
||||
return ref;
|
||||
}
|
||||
|
||||
// A write failure must land on a surface that OUTLIVES the component that started it (#830).
|
||||
//
|
||||
// `Dialog` and `SlideOver` are dismissible mid-request through three paths that do not consult a
|
||||
// busy flag -- Escape and the backdrop/scrim click via `useOverlayBehavior`, plus the header close
|
||||
// button (`components/overlay.tsx`). Callers commonly disable only the footer Cancel button, which
|
||||
// looks like it closes the hole and does not. Dismissal unmounts the surface, so an error rendered
|
||||
// from ITS OWN state has nowhere to go: the request still runs, still fails, and the user is told
|
||||
// nothing while the list reloads unchanged.
|
||||
//
|
||||
// The asymmetry this fixes: SUCCESS already outlives dismissal at these sites, because it is
|
||||
// reported through a parent callback (`onAdded`/`onDone`, which the screen turns into a Toast).
|
||||
// Failure was the half that died with the surface. So the fix is not a new notification system --
|
||||
// it is routing failure through the channel success already uses.
|
||||
//
|
||||
// While mounted the error stays INLINE, which is the better surface: it keeps the user's selections
|
||||
// and their context. `reportFailure` only diverts once the surface is gone.
|
||||
//
|
||||
// `reportAfterDismiss` is read through a latest-ref for the same reason `useOverlayBehavior` does
|
||||
// it: parents hand down a fresh closure every render, and the ref must still be callable AFTER this
|
||||
// component unmounts, which is precisely when it is used. If the parent screen has itself unmounted
|
||||
// (the user navigated away entirely) the setState inside it is a no-op on React 18 -- there is no
|
||||
// surface left to report to in that case, so there is nothing better to do.
|
||||
export function useDismissSafeError(reportAfterDismiss: (message: string) => void): {
|
||||
readonly inlineError: string | null;
|
||||
readonly setInlineError: (message: string | null) => void;
|
||||
readonly reportFailure: (message: string) => void;
|
||||
} {
|
||||
const mountedRef = useIsMountedRef();
|
||||
const [inlineError, setInlineError] = useState<string | null>(null);
|
||||
const reportRef = useRef(reportAfterDismiss);
|
||||
|
||||
useEffect(() => {
|
||||
reportRef.current = reportAfterDismiss;
|
||||
});
|
||||
|
||||
const reportFailure = useCallback(
|
||||
(message: string) => {
|
||||
if (mountedRef.current) {
|
||||
setInlineError(message);
|
||||
return;
|
||||
}
|
||||
|
||||
reportRef.current(message);
|
||||
},
|
||||
[mountedRef]
|
||||
);
|
||||
|
||||
return { inlineError, reportFailure, setInlineError };
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type AddItemsToCollectionRequest,
|
||||
type MediaCollection
|
||||
} from '../../api';
|
||||
import { useDismissSafeError } from '../../hooks';
|
||||
import type { AddToItems } from './scheduleItem';
|
||||
|
||||
export interface AddToCollectionDialogProps {
|
||||
@@ -17,6 +18,11 @@ export interface AddToCollectionDialogProps {
|
||||
onClose: () => void;
|
||||
items: AddToItems;
|
||||
onAdded?: (collectionName: string) => void;
|
||||
// #830: `onFailed` is the SURVIVING surface. A write failure that lands after the dialog was
|
||||
// dismissed (Escape / backdrop / header X — none of which consult `submitting`) has nowhere to
|
||||
// render, so it is handed to the caller instead. Optional because not every host screen has a
|
||||
// surface to show it on; where it is omitted the failure is dropped exactly as it was before.
|
||||
onFailed?: (message: string) => void;
|
||||
}
|
||||
|
||||
const NEW_COLLECTION = '__new__';
|
||||
@@ -33,14 +39,14 @@ export function AddToCollectionDialog(props: AddToCollectionDialogProps) {
|
||||
return <AddToCollectionDialogBody {...props} />;
|
||||
}
|
||||
|
||||
function AddToCollectionDialogBody({ onClose, items, onAdded }: AddToCollectionDialogProps) {
|
||||
function AddToCollectionDialogBody({ onClose, items, onAdded, onFailed }: AddToCollectionDialogProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [collections, setCollections] = useState<MediaCollection[]>([]);
|
||||
const [selected, setSelected] = useState<string>(NEW_COLLECTION);
|
||||
const [newName, setNewName] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const { inlineError, reportFailure, setInlineError } = useDismissSafeError(onFailed ?? (() => {}));
|
||||
const activeRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -86,7 +92,7 @@ function AddToCollectionDialogBody({ onClose, items, onAdded }: AddToCollectionD
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
setSubmitError(null);
|
||||
setInlineError(null);
|
||||
|
||||
const request = resolveRequest(items);
|
||||
|
||||
@@ -111,11 +117,15 @@ function AddToCollectionDialogBody({ onClose, items, onAdded }: AddToCollectionD
|
||||
onClose();
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
// Reported BEFORE the activeRef gate: swallowing this on dismissal is the #830 defect.
|
||||
// `reportFailure` renders inline while the dialog is up, and diverts to `onFailed` once
|
||||
// it is gone. `setSubmitting` stays gated — that state died with the component.
|
||||
reportFailure(messageFromCollectionError(error, 'Unable to add items'));
|
||||
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitError(messageFromCollectionError(error, 'Unable to add items'));
|
||||
setSubmitting(false);
|
||||
});
|
||||
};
|
||||
@@ -172,9 +182,9 @@ function AddToCollectionDialogBody({ onClose, items, onAdded }: AddToCollectionD
|
||||
value={newName}
|
||||
/>
|
||||
)}
|
||||
{submitError && (
|
||||
{inlineError && (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{submitError}
|
||||
{inlineError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -15,13 +15,17 @@ export interface AddToMenuProps {
|
||||
items: LibraryBrowseItem[];
|
||||
targets?: AddToTarget[];
|
||||
onDone?: (message: string) => void;
|
||||
// #830: the failure counterpart of `onDone`. Success already outlives dismissal because it is
|
||||
// reported through the caller; failure did not, so it died with the dialog. Optional for the
|
||||
// same reason `onDone` is — MediaDetailScreen wires neither and is unchanged by this.
|
||||
onFailed?: (message: string) => void;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
// A small dropdown-button that opens the right Add-to dialog for the given items. Meant to be
|
||||
// dropped onto media cards / detail pages by the wiring screens; it owns the popover + which
|
||||
// dialog is open, and surfaces a success message to the caller via onDone.
|
||||
export function AddToMenu({ items, targets = DEFAULT_TARGETS, onDone, compact = false }: AddToMenuProps) {
|
||||
export function AddToMenu({ items, targets = DEFAULT_TARGETS, onDone, onFailed, compact = false }: AddToMenuProps) {
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [dialog, setDialog] = useState<AddToTarget | null>(null);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
@@ -106,13 +110,14 @@ export function AddToMenu({ items, targets = DEFAULT_TARGETS, onDone, compact =
|
||||
</div>
|
||||
)}
|
||||
|
||||
<AddToCollectionDialog items={items} onAdded={(name) => handleAdded(`Added to “${name}”`)} onClose={closeDialog} open={dialog === 'collection'} />
|
||||
<AddToPlaylistDialog items={items} onAdded={(name) => handleAdded(`Added to “${name}”`)} onClose={closeDialog} open={dialog === 'playlist'} />
|
||||
<AddToCollectionDialog items={items} onAdded={(name) => handleAdded(`Added to “${name}”`)} onClose={closeDialog} onFailed={onFailed} open={dialog === 'collection'} />
|
||||
<AddToPlaylistDialog items={items} onAdded={(name) => handleAdded(`Added to “${name}”`)} onClose={closeDialog} onFailed={onFailed} open={dialog === 'playlist'} />
|
||||
{scheduleItem && (
|
||||
<AddToScheduleDialog
|
||||
item={{ id: scheduleItem.id, mediaType: scheduleItem.mediaType, title: scheduleItem.title }}
|
||||
onAdded={(name) => handleAdded(`Added to “${name}”`)}
|
||||
onClose={closeDialog}
|
||||
onFailed={onFailed}
|
||||
open={dialog === 'schedule'}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type Playlist,
|
||||
type PlaylistGroup
|
||||
} from '../../api';
|
||||
import { useDismissSafeError } from '../../hooks';
|
||||
import type { AddToItems } from './scheduleItem';
|
||||
|
||||
export interface AddToPlaylistDialogProps {
|
||||
@@ -18,6 +19,10 @@ export interface AddToPlaylistDialogProps {
|
||||
onClose: () => void;
|
||||
items: AddToItems;
|
||||
onAdded?: (playlistName: string) => void;
|
||||
// #830: the SURVIVING surface. A write failure landing after dismissal (Escape / backdrop /
|
||||
// header X — none of which consult `submitting`) has nowhere to render, so it is handed to the
|
||||
// caller. Optional: where a host screen has no surface for it, the failure is dropped as before.
|
||||
onFailed?: (message: string) => void;
|
||||
}
|
||||
|
||||
function resolveRequest(items: AddToItems): AddItemsToCollectionRequest {
|
||||
@@ -32,7 +37,7 @@ export function AddToPlaylistDialog(props: AddToPlaylistDialogProps) {
|
||||
return <AddToPlaylistDialogBody {...props} />;
|
||||
}
|
||||
|
||||
function AddToPlaylistDialogBody({ onClose, items, onAdded }: AddToPlaylistDialogProps) {
|
||||
function AddToPlaylistDialogBody({ onClose, items, onAdded, onFailed }: AddToPlaylistDialogProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [groups, setGroups] = useState<PlaylistGroup[]>([]);
|
||||
@@ -41,7 +46,7 @@ function AddToPlaylistDialogBody({ onClose, items, onAdded }: AddToPlaylistDialo
|
||||
const [playlistsLoading, setPlaylistsLoading] = useState(false);
|
||||
const [selectedPlaylist, setSelectedPlaylist] = useState<string>('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const { inlineError, reportFailure, setInlineError } = useDismissSafeError(onFailed ?? (() => {}));
|
||||
const activeRef = useRef(true);
|
||||
const groupSeqRef = useRef(0);
|
||||
|
||||
@@ -78,10 +83,12 @@ function AddToPlaylistDialogBody({ onClose, items, onAdded }: AddToPlaylistDialo
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitError(messageFromPlaylistError(error, 'Unable to load playlists'));
|
||||
setInlineError(messageFromPlaylistError(error, 'Unable to load playlists'));
|
||||
setPlaylistsLoading(false);
|
||||
});
|
||||
}, []);
|
||||
// `setInlineError` is a useState setter behind `useDismissSafeError`, so it is referentially
|
||||
// stable; it is listed because exhaustive-deps cannot see that through a custom hook.
|
||||
}, [setInlineError]);
|
||||
|
||||
const load = useCallback(() => {
|
||||
getPlaylistGroups()
|
||||
@@ -116,7 +123,7 @@ function AddToPlaylistDialogBody({ onClose, items, onAdded }: AddToPlaylistDialo
|
||||
|
||||
const onGroupChange = (value: string) => {
|
||||
setSelectedGroup(value);
|
||||
setSubmitError(null);
|
||||
setInlineError(null);
|
||||
loadPlaylists(Number(value));
|
||||
};
|
||||
|
||||
@@ -128,7 +135,7 @@ function AddToPlaylistDialogBody({ onClose, items, onAdded }: AddToPlaylistDialo
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
setSubmitError(null);
|
||||
setInlineError(null);
|
||||
|
||||
const playlistId = Number(selectedPlaylist);
|
||||
const name = playlists.find((playlist) => String(playlist.id) === selectedPlaylist)?.name ?? 'playlist';
|
||||
@@ -143,11 +150,15 @@ function AddToPlaylistDialogBody({ onClose, items, onAdded }: AddToPlaylistDialo
|
||||
onClose();
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
// Reported BEFORE the activeRef gate: swallowing this on dismissal is the #830 defect.
|
||||
// `reportFailure` renders inline while the dialog is up, and diverts to `onFailed` once it
|
||||
// is gone. `setSubmitting` stays gated — that state died with the component.
|
||||
reportFailure(messageFromPlaylistError(error, 'Unable to add items'));
|
||||
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitError(messageFromPlaylistError(error, 'Unable to add items'));
|
||||
setSubmitting(false);
|
||||
});
|
||||
};
|
||||
@@ -204,9 +215,9 @@ function AddToPlaylistDialogBody({ onClose, items, onAdded }: AddToPlaylistDialo
|
||||
}
|
||||
value={selectedPlaylist}
|
||||
/>
|
||||
{submitError && (
|
||||
{inlineError && (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{submitError}
|
||||
{inlineError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type LibraryBrowseMediaType,
|
||||
type ProgramSchedule
|
||||
} from '../../api';
|
||||
import { useDismissSafeError } from '../../hooks';
|
||||
import { ApiError } from '../../api/client';
|
||||
import { collectionTypeForMediaType, scheduleItemRequestForMediaItem } from './scheduleItem';
|
||||
|
||||
@@ -21,6 +22,10 @@ export interface AddToScheduleDialogProps {
|
||||
onClose: () => void;
|
||||
item: AddToScheduleItem;
|
||||
onAdded?: (scheduleName: string) => void;
|
||||
// #830: the SURVIVING surface. A write failure landing after dismissal (Escape / backdrop /
|
||||
// header X — none of which consult `submitting`) has nowhere to render, so it is handed to the
|
||||
// caller. Optional: where a host screen has no surface for it, the failure is dropped as before.
|
||||
onFailed?: (message: string) => void;
|
||||
}
|
||||
|
||||
function messageFromError(error: unknown, fallback: string): string {
|
||||
@@ -43,13 +48,13 @@ export function AddToScheduleDialog(props: AddToScheduleDialogProps) {
|
||||
return <AddToScheduleDialogBody {...props} />;
|
||||
}
|
||||
|
||||
function AddToScheduleDialogBody({ onClose, item, onAdded }: AddToScheduleDialogProps) {
|
||||
function AddToScheduleDialogBody({ onClose, item, onAdded, onFailed }: AddToScheduleDialogProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [schedules, setSchedules] = useState<ProgramSchedule[]>([]);
|
||||
const [selected, setSelected] = useState<string>('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const { inlineError, reportFailure, setInlineError } = useDismissSafeError(onFailed ?? (() => {}));
|
||||
const activeRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -95,7 +100,7 @@ function AddToScheduleDialogBody({ onClose, item, onAdded }: AddToScheduleDialog
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
setSubmitError(null);
|
||||
setInlineError(null);
|
||||
|
||||
const scheduleId = Number(selected);
|
||||
const name = schedules.find((schedule) => String(schedule.id) === selected)?.name ?? 'schedule';
|
||||
@@ -111,11 +116,15 @@ function AddToScheduleDialogBody({ onClose, item, onAdded }: AddToScheduleDialog
|
||||
onClose();
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
// Reported BEFORE the activeRef gate: swallowing this on dismissal is the #830 defect.
|
||||
// `reportFailure` renders inline while the dialog is up, and diverts to `onFailed` once it
|
||||
// is gone. `setSubmitting` stays gated — that state died with the component.
|
||||
reportFailure(messageFromError(error, 'Unable to add to schedule'));
|
||||
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitError(messageFromError(error, 'Unable to add to schedule'));
|
||||
setSubmitting(false);
|
||||
});
|
||||
};
|
||||
@@ -163,9 +172,9 @@ function AddToScheduleDialogBody({ onClose, item, onAdded }: AddToScheduleDialog
|
||||
options={schedules.map((schedule) => ({ value: String(schedule.id), label: schedule.name ?? `Schedule ${schedule.id}` }))}
|
||||
value={selected}
|
||||
/>
|
||||
{submitError && (
|
||||
{inlineError && (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{submitError}
|
||||
{inlineError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
updateSmartCollection,
|
||||
type SmartCollection
|
||||
} from '../../api';
|
||||
import { useDismissSafeError } from '../../hooks';
|
||||
|
||||
export interface SaveAsSmartCollectionDialogProps {
|
||||
open: boolean;
|
||||
@@ -15,6 +16,10 @@ export interface SaveAsSmartCollectionDialogProps {
|
||||
// The search query the saved smart collection will store.
|
||||
query: string;
|
||||
onSaved?: (collectionName: string) => void;
|
||||
// #830: the SURVIVING surface. A write failure landing after dismissal (Escape / backdrop /
|
||||
// header X — none of which consult `submitting`) has nowhere to render, so it is handed to the
|
||||
// caller. Optional: where a host screen has no surface for it, the failure is dropped as before.
|
||||
onFailed?: (message: string) => void;
|
||||
}
|
||||
|
||||
const NEW_COLLECTION = '__new__';
|
||||
@@ -27,14 +32,14 @@ export function SaveAsSmartCollectionDialog(props: SaveAsSmartCollectionDialogPr
|
||||
return <SaveAsSmartCollectionDialogBody {...props} />;
|
||||
}
|
||||
|
||||
function SaveAsSmartCollectionDialogBody({ onClose, query, onSaved }: SaveAsSmartCollectionDialogProps) {
|
||||
function SaveAsSmartCollectionDialogBody({ onClose, query, onSaved, onFailed }: SaveAsSmartCollectionDialogProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [collections, setCollections] = useState<SmartCollection[]>([]);
|
||||
const [selected, setSelected] = useState<string>(NEW_COLLECTION);
|
||||
const [newName, setNewName] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const { inlineError, reportFailure, setInlineError } = useDismissSafeError(onFailed ?? (() => {}));
|
||||
const activeRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -80,7 +85,7 @@ function SaveAsSmartCollectionDialogBody({ onClose, query, onSaved }: SaveAsSmar
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
setSubmitError(null);
|
||||
setInlineError(null);
|
||||
|
||||
// New: create with the query baked in. Existing: overwrite its query (keeping its name).
|
||||
const save: Promise<string> = isNew
|
||||
@@ -103,11 +108,15 @@ function SaveAsSmartCollectionDialogBody({ onClose, query, onSaved }: SaveAsSmar
|
||||
onClose();
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
// Reported BEFORE the activeRef gate: swallowing this on dismissal is the #830 defect.
|
||||
// `reportFailure` renders inline while the dialog is up, and diverts to `onFailed` once it
|
||||
// is gone. `setSubmitting` stays gated — that state died with the component.
|
||||
reportFailure(messageFromCollectionError(error, 'Unable to save smart collection'));
|
||||
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitError(messageFromCollectionError(error, 'Unable to save smart collection'));
|
||||
setSubmitting(false);
|
||||
});
|
||||
};
|
||||
@@ -167,9 +176,9 @@ function SaveAsSmartCollectionDialogBody({ onClose, query, onSaved }: SaveAsSmar
|
||||
value={newName}
|
||||
/>
|
||||
)}
|
||||
{submitError && (
|
||||
{inlineError && (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{submitError}
|
||||
{inlineError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -300,11 +300,18 @@ describe('AddItemsDialog async guards (#740)', () => {
|
||||
mountedReads.length = 0;
|
||||
parked[0].fail();
|
||||
|
||||
// `submit` has exactly TWO post-await writes to this component's own state — `setError` in the
|
||||
// catch and `setAdding` in the finally — and the invariant is that BOTH consult the guard.
|
||||
// Counting them is what keeps the two from masking each other: asserting only that SOME read
|
||||
// saw `false` stays green with either one removed, because the survivor still reads the ref.
|
||||
await waitFor(() => expect(mountedReads).toHaveLength(2));
|
||||
// `submit` has exactly ONE post-await write left to state THIS component owns directly —
|
||||
// `setAdding` in the finally. It was two until #830 moved the catch's report into
|
||||
// `useDismissSafeError`, which keeps its own is-mounted guard and decides between the inline
|
||||
// banner and the parent's surviving surface; that guard is invisible here because the mock
|
||||
// above spreads `...actual`, so the hook's INTERNAL `useIsMountedRef()` call resolves to the
|
||||
// real one rather than this proxy. Both halves of it are pinned directly by
|
||||
// `hooks.test.tsx` → "useDismissSafeError (#830)".
|
||||
//
|
||||
// The exact count still does the anti-masking work it was added for: asserting only that SOME
|
||||
// read saw `false` would stay green with the remaining guard deleted, because there would be no
|
||||
// read left to contradict it. Pinning the number means removing this one gives 0 and reddens.
|
||||
await waitFor(() => expect(mountedReads).toHaveLength(1));
|
||||
expect(mountedReads.every((read) => read === false)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,6 +49,9 @@ interface MockOptions {
|
||||
manual?: unknown[];
|
||||
smart?: unknown[];
|
||||
onRequest?: (url: string, method: string, body: unknown) => Response | null;
|
||||
// Returns a promise the TEST settles, so a request can be left in flight while the surface that
|
||||
// started it is dismissed (#830). `onRequest` cannot express that: it answers synchronously.
|
||||
onRequestDeferred?: (url: string, method: string, body: unknown) => Promise<Response> | null;
|
||||
}
|
||||
|
||||
function mockApi(options: MockOptions = {}) {
|
||||
@@ -60,6 +63,14 @@ function mockApi(options: MockOptions = {}) {
|
||||
const method = (init?.method ?? 'GET').toUpperCase();
|
||||
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
|
||||
|
||||
if (options.onRequestDeferred) {
|
||||
const deferred = options.onRequestDeferred(url, method, body);
|
||||
|
||||
if (deferred) {
|
||||
return deferred;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.onRequest) {
|
||||
const override = options.onRequest(url, method, body);
|
||||
|
||||
@@ -360,8 +371,9 @@ describe('CollectionsScreen', () => {
|
||||
RemoteStream: { id: 10, mediaType: 'RemoteStream', title: 'Live Feed' }
|
||||
};
|
||||
|
||||
function mockAddItemsApi() {
|
||||
function mockAddItemsApi(onRequestDeferred?: MockOptions['onRequestDeferred']) {
|
||||
return mockApi({
|
||||
onRequestDeferred,
|
||||
onRequest: (url) => {
|
||||
if (url.startsWith('/api/v1/library/browse')) {
|
||||
const params = new URL(url, 'http://localhost').searchParams;
|
||||
@@ -452,6 +464,61 @@ describe('CollectionsScreen', () => {
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// #830. The dialog is dismissible mid-request through three paths that never consult `adding`
|
||||
// (Escape, backdrop click, header close button — `components/overlay.tsx`); only the footer Cancel
|
||||
// is disabled, which looks like it closes the hole. Dismissal genuinely unmounts the instance,
|
||||
// because the caller keys it on `add-${pickerOpen}`. #740 guarded the in-dialog `setError` so the
|
||||
// drop became deliberate; the user-visible half is that a deliberate drop still reads as success.
|
||||
//
|
||||
// The request is left IN FLIGHT across the dismissal on purpose — settling it before the Escape
|
||||
// would take the still-mounted path and prove nothing about the bug.
|
||||
it('reports a failed add on the screen when the dialog was dismissed before the request settled (#830)', async () => {
|
||||
let failAdd: (() => void) | undefined;
|
||||
const addInFlight = new Promise<Response>((resolve) => {
|
||||
failAdd = () => resolve(new Response(null, { status: 500 }));
|
||||
});
|
||||
|
||||
const fetchMock = mockAddItemsApi((url, method) =>
|
||||
url === '/api/v1/collections/1/items' && method === 'POST' ? addInFlight : null
|
||||
);
|
||||
|
||||
const dialog = await openAddItemsDialog();
|
||||
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
|
||||
target: { value: 'za' }
|
||||
});
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Search' }));
|
||||
expect(await within(dialog).findByText('Zathura')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(within(dialog).getByText('Zathura'));
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: /Add 1 item/ }));
|
||||
|
||||
// The POST is out, and nothing has answered it yet.
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
fetchMock.mock.calls.some(
|
||||
([u, init]) => u === '/api/v1/collections/1/items' && (init?.method ?? '').toUpperCase() === 'POST'
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// Dismiss via Escape — the path the disabled Cancel button does not cover.
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
});
|
||||
|
||||
failAdd?.();
|
||||
|
||||
// The failure lands on the SCREEN's own role="alert" banner, which outlives the dialog. Asserting
|
||||
// the message rather than merely "an alert exists" keeps this from passing on an unrelated banner.
|
||||
const alert = await screen.findByText('Request failed with status 500');
|
||||
expect(alert).toBeInTheDocument();
|
||||
|
||||
// ...and it is genuinely on the screen, not inside a dialog that somehow survived.
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
expect(alert.closest('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('selecting a newly-addable kind filter (Song) surfaces it and buckets it correctly on add', async () => {
|
||||
const fetchMock = mockAddItemsApi();
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ import {
|
||||
type MediaCollection,
|
||||
type SmartCollection
|
||||
} from '../api';
|
||||
import { useIsMountedRef } from '../hooks';
|
||||
import { useDismissSafeError, useIsMountedRef } from '../hooks';
|
||||
import { TYPE_LABEL } from '../media/mediaKinds';
|
||||
import { SmartCollectionDialog } from '../builder/SmartCollectionDialog';
|
||||
|
||||
@@ -224,11 +224,13 @@ function NameDialog({
|
||||
function AddItemsDialog({
|
||||
collection,
|
||||
onAdded,
|
||||
onAddFailed,
|
||||
onClose,
|
||||
open
|
||||
}: {
|
||||
collection: MediaCollection;
|
||||
onAdded: () => void;
|
||||
onAddFailed: (message: string) => void;
|
||||
onClose: () => void;
|
||||
open: boolean;
|
||||
}) {
|
||||
@@ -242,7 +244,9 @@ function AddItemsDialog({
|
||||
const [submittedQuery, setSubmittedQuery] = useState('');
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [selected, setSelected] = useState<Map<string, LibraryBrowseItem>>(() => new Map());
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// #830: `inlineError` renders here while the dialog is up; `reportFailure` diverts to
|
||||
// `onAddFailed` once it has been dismissed, so a failed add cannot vanish with the surface.
|
||||
const { inlineError, reportFailure, setInlineError } = useDismissSafeError(onAddFailed);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [kindFilter, setKindFilter] = useState<MediaKindFilter>('all');
|
||||
const seqRef = useRef(0);
|
||||
@@ -271,7 +275,7 @@ function AddItemsDialog({
|
||||
const isCurrent = () => mountedRef.current && seqRef.current === seq;
|
||||
|
||||
setSearching(true);
|
||||
setError(null);
|
||||
setInlineError(null);
|
||||
|
||||
try {
|
||||
const kinds = filter === 'all' ? DEFAULT_SEARCH_KINDS : [filter];
|
||||
@@ -298,7 +302,7 @@ function AddItemsDialog({
|
||||
if (!isCurrent()) {
|
||||
return;
|
||||
}
|
||||
setError(messageFromCollectionError(searchError, 'Unable to search library'));
|
||||
setInlineError(messageFromCollectionError(searchError, 'Unable to search library'));
|
||||
// A failed search must not leave a stale results/totalMatches pair rendering a confident
|
||||
// "Showing N of M matches" hint beside the error banner (#685 review).
|
||||
setResults([]);
|
||||
@@ -342,7 +346,7 @@ function AddItemsDialog({
|
||||
}
|
||||
|
||||
setAdding(true);
|
||||
setError(null);
|
||||
setInlineError(null);
|
||||
|
||||
try {
|
||||
await addItemsToCollection(collection.id, toAddItemsRequest([...selected.values()]));
|
||||
@@ -352,15 +356,15 @@ function AddItemsDialog({
|
||||
onAdded();
|
||||
onClose();
|
||||
} catch (addError) {
|
||||
// Guarded: these two are this component's own state. The dialog is unmount-reachable while a
|
||||
// request is in flight even though the Add button is disabled — Escape, a backdrop click and
|
||||
// the header close button all reach `onClose` without consulting `adding`
|
||||
// (`components/overlay.tsx`), and the caller remounts on `key={`add-${pickerOpen}`}`. This is
|
||||
// the is-mounted guard's own trigger, unmount-while-in-flight, and it needs no `seq`: the
|
||||
// disabled Add button means there is never a second submission to be superseded by.
|
||||
if (mountedRef.current) {
|
||||
setError(messageFromCollectionError(addError, 'Unable to add items'));
|
||||
}
|
||||
// The dialog is unmount-reachable while a request is in flight even though the Add button is
|
||||
// disabled — Escape, a backdrop click and the header close button all reach `onClose` without
|
||||
// consulting `adding` (`components/overlay.tsx`), and the caller remounts on
|
||||
// `key={`add-${pickerOpen}`}`. #740 guarded this `setError` so the drop was deliberate rather
|
||||
// than accidental; #830 is the missing half — a deliberate drop still leaves the user believing
|
||||
// the add succeeded. `reportFailure` renders inline while the dialog is up and hands the
|
||||
// message to the parent screen once it is gone. No `seq` is needed: the disabled Add button
|
||||
// means there is never a second submission to supersede this one.
|
||||
reportFailure(messageFromCollectionError(addError, 'Unable to add items'));
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setAdding(false);
|
||||
@@ -428,9 +432,9 @@ function AddItemsDialog({
|
||||
{/* Conditionally mounted, unlike the aria-live hint below — deliberately, not by oversight:
|
||||
`role="alert"` is the one live-region role screen readers reliably announce on INSERTION,
|
||||
so mounting it together with its content is right here and would be wrong there (#685). */}
|
||||
{error && (
|
||||
{inlineError && (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{error}
|
||||
{inlineError}
|
||||
</span>
|
||||
)}
|
||||
{submittedQuery !== '' && (
|
||||
@@ -448,7 +452,7 @@ function AddItemsDialog({
|
||||
{totalMatches > results.length ? `Showing ${results.length} of ${totalMatches} matches — narrow your search.` : ''}
|
||||
</p>
|
||||
<div className="ctv-collections-picker-results">
|
||||
{results.length === 0 && submittedQuery === '' && !error ? (
|
||||
{results.length === 0 && submittedQuery === '' && !inlineError ? (
|
||||
// Keyed to submittedQuery, not the live input: without it, backspacing the query back
|
||||
// below the min-query length after a successful search wiped the rendered rows AND their
|
||||
// checkmarks while `selected` (and the Add button's count) still held them (#685) — and,
|
||||
@@ -457,8 +461,8 @@ function AddItemsDialog({
|
||||
<div className="ctv-collections-picker-empty">
|
||||
Type at least {LIBRARY_PICKER_MIN_QUERY} characters to search.
|
||||
</div>
|
||||
) : results.length === 0 && !searching && !error ? (
|
||||
// Also suppressed on `error`: "No results" asserts a search that COMPLETED and found
|
||||
) : results.length === 0 && !searching && !inlineError ? (
|
||||
// Also suppressed on `inlineError`: "No results" asserts a search that COMPLETED and found
|
||||
// nothing, which is false when the request failed. The role="alert" banner above is the
|
||||
// whole message in that state (#685).
|
||||
<div className="ctv-collections-picker-empty">No results — try a search above.</div>
|
||||
@@ -821,6 +825,9 @@ function ManualItemsView({
|
||||
collection={collection}
|
||||
key={`add-${pickerOpen}`}
|
||||
onAdded={load}
|
||||
// #830: the surviving surface. This screen's own `role="alert"` banner outlives the dialog,
|
||||
// so a failure that lands after dismissal is still reported where the user actually is.
|
||||
onAddFailed={setError}
|
||||
onClose={() => setPickerOpen(false)}
|
||||
open={pickerOpen}
|
||||
/>
|
||||
|
||||
@@ -285,12 +285,14 @@ export function MediaBrowseScreen() {
|
||||
items={selectedItems}
|
||||
onAdded={onBulkAdded}
|
||||
onClose={() => setBulkDialog(null)}
|
||||
onFailed={(message) => setNotice({ tone: 'error', message })}
|
||||
open={bulkDialog === 'collection'}
|
||||
/>
|
||||
<AddToPlaylistDialog
|
||||
items={selectedItems}
|
||||
onAdded={onBulkAdded}
|
||||
onClose={() => setBulkDialog(null)}
|
||||
onFailed={(message) => setNotice({ tone: 'error', message })}
|
||||
open={bulkDialog === 'playlist'}
|
||||
/>
|
||||
|
||||
@@ -334,7 +336,12 @@ export function MediaBrowseScreen() {
|
||||
// card navigation stays live.
|
||||
actions={
|
||||
selectMode || refreshing ? undefined : (
|
||||
<AddToMenu compact items={[item]} onDone={(message) => setNotice({ tone: 'ok', message })} />
|
||||
<AddToMenu
|
||||
compact
|
||||
items={[item]}
|
||||
onDone={(message) => setNotice({ tone: 'ok', message })}
|
||||
onFailed={(message) => setNotice({ tone: 'error', message })}
|
||||
/>
|
||||
)
|
||||
}
|
||||
item={item}
|
||||
|
||||
@@ -387,7 +387,12 @@ export function SearchScreen() {
|
||||
// card navigation stays live.
|
||||
actions={
|
||||
selectMode || refreshing ? undefined : (
|
||||
<AddToMenu compact items={[item]} onDone={(message) => setNotice({ tone: 'ok', message })} />
|
||||
<AddToMenu
|
||||
compact
|
||||
items={[item]}
|
||||
onDone={(message) => setNotice({ tone: 'ok', message })}
|
||||
onFailed={(message) => setNotice({ tone: 'error', message })}
|
||||
/>
|
||||
)
|
||||
}
|
||||
item={item}
|
||||
@@ -412,12 +417,14 @@ export function SearchScreen() {
|
||||
items={dialog?.kind === 'collection' ? dialog.items : []}
|
||||
onAdded={onAddedToSelectionTarget('collection')}
|
||||
onClose={() => setDialog(null)}
|
||||
onFailed={(message) => setNotice({ tone: 'error', message })}
|
||||
open={dialog?.kind === 'collection'}
|
||||
/>
|
||||
<AddToPlaylistDialog
|
||||
items={dialog?.kind === 'playlist' ? dialog.items : []}
|
||||
onAdded={onAddedToSelectionTarget('playlist')}
|
||||
onClose={() => setDialog(null)}
|
||||
onFailed={(message) => setNotice({ tone: 'error', message })}
|
||||
open={dialog?.kind === 'playlist'}
|
||||
/>
|
||||
<SaveAsSmartCollectionDialog
|
||||
@@ -427,6 +434,7 @@ export function SearchScreen() {
|
||||
clearSelection();
|
||||
setNotice({ tone: 'ok', message: `Saved smart collection “${name}”` });
|
||||
}}
|
||||
onFailed={(message) => setNotice({ tone: 'error', message })}
|
||||
open={dialog?.kind === 'save-smart'}
|
||||
query={query.trim()}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user