fix(651): review round 2 — hydrate untouched fields, never merge a selection field-by-field
Re-review of a04d9f0b came back BLOCKED: the F1 merge fixed a visible data loss and introduced a silent one. Four blockers, all web-only. BLOCKER 1: `selectedId` and `selectedName` were coalesced independently, but they are one value. Against a Song response (id resolves, name does not), a user selecting a different song while the detail GET was in flight got the NEW name paired with the STORED id — chip read "New Song", Save wrote 42, no error and no visual cue. Strictly worse than the original defect, which at least cleared the field visibly. The same merge resurrected a deliberate clear and reverted a type switch. Replaced with two rules. The id/name pair resolves atomically (no id in the response -> keep ours whole; same id -> its name may fill ours in; different id -> take theirs whole). And hydration loses every race against the user: a `touchedRef`, fed by a single `edit()` funnel so "touched" cannot drift from "changed", limits the refresh to fields the user has not edited; an explicit conflict-reload clears it, since discarding local edits is its entire purpose. Three interleaving tests hold the detail response open, act as the user, then release it. BLOCKER 2: Enter could commit a result from the previous query — highlight Alpha for "Al", retype "Be", press Enter before the debounce. The highlight now drops on input change rather than when the next response happens to arrive, and every keyboard action is gated on the results matching what is typed. The stale list stays visible (hiding it flickers on each keystroke), it just stops being actionable. BLOCKER 3: Escape closed the popup while focus stayed in the input, where `onFocus` can never re-arm it — the picker was dead until the user blurred and refocused. Typing and ArrowDown now both reopen it. BLOCKER 4: the LCG boundary test recomputed the divisor instead of exercising `lcg`, so all three tests passed with the old `/ 0xffffffff`. Since the recurrence is a bijection mod 2^32, the seed whose first step lands on 0xffffffff is solvable exactly (653637408); the tests now drive the real generator into that state. Also: the rerun #id-degrade and re-save tests did not await the refresh, so they were satisfiable from the initial draft; they now await it and re-read live textContent. The Episode/MusicVideo cases are relabelled as error-path guards — a 500 never reaches the hydrate. FillerPresets' render-time id comparison is dropped as unreachable (every writer sets label and id together, and the one async writer refuses a mismatched id); an unreachable guard is an untested one. #671 is referenced from spa-conventions §3b as the server-side root cause the client guard defends against. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -164,7 +164,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
|
||||
| `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.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.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) |
|
||||
| `spa.library-pickers-resolve-by-search` | A picker over a media-library table (Episode/Song/Image/Movie/MusicVideo/TelevisionShow/TelevisionSeason/Artist/OtherVideo/RemoteStream) resolves its options by SEARCH — a debounced `SearchPicker` calling `searchLibraryPickerOptions`, which issues at most ONE `getLibraryBrowseItems` request per settled query, bounded to `LIBRARY_PICKER_RESULTS` (25) rows — CLAMPED inside the helper, not merely defaulted — and gated on `LIBRARY_PICKER_MIN_QUERY` (2) characters. It list-loads NOTHING on mount or on a type switch, so there is no truncation to surface and no truncation hint. The typed text is COMPILED (`titleContainsQuery` → `title:*<escaped>*`), never forwarded raw. The current selection renders from the OWNING RECORD, not from the result set (`selectedName` on a rerun collection / playlist item; a single by-id detail read — `getShow`/`getSeason`/`getArtist` — for a filler preset, which stores only the id), and an edit-load refresh MERGES rather than replaces so a response that fails to NAME a selection can never CLEAR its id; an asynchronously-resolved name is keyed to the id it was resolved for and never overwrites a label naming a different id. The typeahead implements the full ARIA combobox keyboard contract, because it replaces a natively keyboard-operable `<select>`. The other half of the superseded record is UNCHANGED: bounded-by-construction admin lists (collections, multi-collections, smart collections, playlists) still page to completeness via `loadAllPages` and still report `complete`/`hint: incomplete`. Server-side caps are not raised — this is a web-only change. | 2026-07-26 | [link](records/spa/library-pickers-resolve-by-search.md) |
|
||||
| `spa.library-pickers-resolve-by-search` | A picker over a media-library table (Episode/Song/Image/Movie/MusicVideo/TelevisionShow/TelevisionSeason/Artist/OtherVideo/RemoteStream) resolves its options by SEARCH — a debounced `SearchPicker` calling `searchLibraryPickerOptions`, which issues at most ONE `getLibraryBrowseItems` request per settled query, bounded to `LIBRARY_PICKER_RESULTS` (25) rows — CLAMPED inside the helper, not merely defaulted — and gated on `LIBRARY_PICKER_MIN_QUERY` (2) characters. It list-loads NOTHING on mount or on a type switch, so there is no truncation to surface and no truncation hint. The typed text is COMPILED (`titleContainsQuery` → `title:*<escaped>*`), never forwarded raw. The current selection renders from the OWNING RECORD, not from the result set (`selectedName` on a rerun collection / playlist item; a single by-id detail read — `getShow`/`getSeason`/`getArtist` — for a filler preset, which stores only the id), and an edit-load refresh HYDRATES ONLY USER-UNTOUCHED FIELDS — resolving the id/name pair ATOMICALLY, never field-by-field — so a response that fails to NAME a selection can never CLEAR its id and a late refresh can never overwrite a live edit; an asynchronously-resolved name is keyed to the id it was resolved for and never overwrites a label naming a different id. The typeahead implements the full ARIA combobox keyboard contract, because it replaces a natively keyboard-operable `<select>`. The other half of the superseded record is UNCHANGED: bounded-by-construction admin lists (collections, multi-collections, smart collections, playlists) still page to completeness via `loadAllPages` and still report `complete`/`hint: incomplete`. Server-side caps are not raised — this is a web-only change. | 2026-07-26 | [link](records/spa/library-pickers-resolve-by-search.md) |
|
||||
| `spa.logs-page-size-local` | The Logs page rows-per-page preference is stored in `window.localStorage` (`ctv-logs-page-size`), not a server `ConfigElement`. | 2026-07-11 | [link](records/spa/logs-page-size-local.md) |
|
||||
| `spa.playback-troubleshoot-poll` | The playback-troubleshooting screen reports FFmpeg completion by polling `GET /api/troubleshoot/playback/status` (~2s) rather than a server push channel. | 2026-07-09 | [link](records/spa/playback-troubleshoot-poll.md) |
|
||||
| `spa.playout-reset-button` | The SPA keeps a single Reset action (server picks the default build mode) and drops Blazor's separate "Schedule reset" button since its capability already exists via the playout's Edit-details flow. | 2026-07-09 | [link](records/spa/playout-reset-button.md) |
|
||||
|
||||
@@ -5,8 +5,8 @@ status: active
|
||||
since: '2026-07-26'
|
||||
supersedes: spa.list-completeness-vs-bounded-pickers@2026-07-26
|
||||
superseded-by: none
|
||||
rule: 'A picker over a media-library table (Episode/Song/Image/Movie/MusicVideo/TelevisionShow/TelevisionSeason/Artist/OtherVideo/RemoteStream) resolves its options by SEARCH — a debounced `SearchPicker` calling `searchLibraryPickerOptions`, which issues at most ONE `getLibraryBrowseItems` request per settled query, bounded to `LIBRARY_PICKER_RESULTS` (25) rows — CLAMPED inside the helper, not merely defaulted — and gated on `LIBRARY_PICKER_MIN_QUERY` (2) characters. It list-loads NOTHING on mount or on a type switch, so there is no truncation to surface and no truncation hint. The typed text is COMPILED (`titleContainsQuery` → `title:*<escaped>*`), never forwarded raw. The current selection renders from the OWNING RECORD, not from the result set (`selectedName` on a rerun collection / playlist item; a single by-id detail read — `getShow`/`getSeason`/`getArtist` — for a filler preset, which stores only the id), and an edit-load refresh MERGES rather than replaces so a response that fails to NAME a selection can never CLEAR its id; an asynchronously-resolved name is keyed to the id it was resolved for and never overwrites a label naming a different id. The typeahead implements the full ARIA combobox keyboard contract, because it replaces a natively keyboard-operable `<select>`. The other half of the superseded record is UNCHANGED: bounded-by-construction admin lists (collections, multi-collections, smart collections, playlists) still page to completeness via `loadAllPages` and still report `complete`/`hint: incomplete`. Server-side caps are not raised — this is a web-only change.'
|
||||
signals: 'library picker typeahead, SearchPicker, searchLibraryPickerOptions, titleContainsQuery, LIBRARY_PICKER_RESULTS, LIBRARY_PICKER_MIN_QUERY, LIBRARY_PICKER_LUCENE_SPECIALS, compile typed text not raw Lucene, Lucene && || escaping, picker truncation hint removed, loadAllPages Class A, LuceneSearchIndex.Search hitsLimit, useIsMountedRef, aria-activedescendant combobox keyboard, refresh must not clear an unnamed id · paths: `web/src/api/libraryBrowse.ts`, `web/src/schedules/pickers.tsx`, `web/src/hooks.ts`, `web/src/screens/RerunCollectionsScreen.tsx`, `web/src/screens/PlaylistsScreen.tsx`, `web/src/screens/FillerPresetsScreen.tsx`, `web/src/api/paging.ts`, `docs/spa-conventions.md` §3b · issues: #651, #644, #578, #440'
|
||||
rule: 'A picker over a media-library table (Episode/Song/Image/Movie/MusicVideo/TelevisionShow/TelevisionSeason/Artist/OtherVideo/RemoteStream) resolves its options by SEARCH — a debounced `SearchPicker` calling `searchLibraryPickerOptions`, which issues at most ONE `getLibraryBrowseItems` request per settled query, bounded to `LIBRARY_PICKER_RESULTS` (25) rows — CLAMPED inside the helper, not merely defaulted — and gated on `LIBRARY_PICKER_MIN_QUERY` (2) characters. It list-loads NOTHING on mount or on a type switch, so there is no truncation to surface and no truncation hint. The typed text is COMPILED (`titleContainsQuery` → `title:*<escaped>*`), never forwarded raw. The current selection renders from the OWNING RECORD, not from the result set (`selectedName` on a rerun collection / playlist item; a single by-id detail read — `getShow`/`getSeason`/`getArtist` — for a filler preset, which stores only the id), and an edit-load refresh HYDRATES ONLY USER-UNTOUCHED FIELDS — resolving the id/name pair ATOMICALLY, never field-by-field — so a response that fails to NAME a selection can never CLEAR its id and a late refresh can never overwrite a live edit; an asynchronously-resolved name is keyed to the id it was resolved for and never overwrites a label naming a different id. The typeahead implements the full ARIA combobox keyboard contract, because it replaces a natively keyboard-operable `<select>`. The other half of the superseded record is UNCHANGED: bounded-by-construction admin lists (collections, multi-collections, smart collections, playlists) still page to completeness via `loadAllPages` and still report `complete`/`hint: incomplete`. Server-side caps are not raised — this is a web-only change.'
|
||||
signals: 'library picker typeahead, SearchPicker, searchLibraryPickerOptions, titleContainsQuery, LIBRARY_PICKER_RESULTS, LIBRARY_PICKER_MIN_QUERY, LIBRARY_PICKER_LUCENE_SPECIALS, compile typed text not raw Lucene, Lucene && || escaping, picker truncation hint removed, loadAllPages Class A, LuceneSearchIndex.Search hitsLimit, useIsMountedRef, aria-activedescendant combobox keyboard, refresh must not clear an unnamed id, hydrate-untouched-fields not field-wise merge, stale result set not committable · paths: `web/src/api/libraryBrowse.ts`, `web/src/schedules/pickers.tsx`, `web/src/hooks.ts`, `web/src/screens/RerunCollectionsScreen.tsx`, `web/src/screens/PlaylistsScreen.tsx`, `web/src/screens/FillerPresetsScreen.tsx`, `web/src/api/paging.ts`, `docs/spa-conventions.md` §3b · issues: #651, #644, #578, #440'
|
||||
mechanics: '`docs/spa-conventions.md` §3b'
|
||||
---
|
||||
|
||||
@@ -57,10 +57,28 @@ derives both `selectedId` and `selectedName` from the same eager-loaded navigati
|
||||
`MediaCollections/Mapper` maps RemoteStream through `_ => null` — so opening a RemoteStream rerun
|
||||
collection returned HTTP 200 with a null selection and the edit-load refresh *cleared a stored id*,
|
||||
leaving Save permanently disabled. The rule is therefore stated as a prohibition on the client:
|
||||
**no code path may clear a stored id it merely failed to name.** The refresh merges
|
||||
(`refreshed.selectedId ?? current.selectedId`) instead of replacing, and every affected type
|
||||
(RemoteStream, Episode, MusicVideo, Song, OtherVideo, Image) is covered by its own test. The
|
||||
underlying read-model gaps are server-side and tracked separately; this branch is web-only.
|
||||
**no code path may clear a stored id it merely failed to name.** Every affected type (RemoteStream,
|
||||
Episode, MusicVideo, Song, OtherVideo, Image) is covered by its own test. The underlying read-model
|
||||
gaps are server-side, tracked as **#671**; this branch is web-only and the client guard stays after
|
||||
that lands.
|
||||
|
||||
**The obvious form of that fix is worse than the bug, and this is the part worth remembering.** The
|
||||
first attempt coalesced the two fields independently — `refreshed.selectedId ?? current.selectedId`
|
||||
and `refreshed.selectedName || current.selectedName`. But an id and its display name are ONE value:
|
||||
against a `Song` response (id resolves, name does not), a user selecting a different song while the
|
||||
refresh was in flight got the *new* name paired with the *stored* id. The chip read "New Song" and
|
||||
Save wrote 42 — the user's choice discarded with no error and no visual cue, where the original
|
||||
defect at least cleared the field visibly. A second cold review caught it. The trade is: a visible
|
||||
failure is strictly better than a silent one, so a "smarter coalesce" is the wrong shape of fix.
|
||||
|
||||
What replaced it is two rules. The pair resolves **atomically** — no id in the response keeps ours
|
||||
wholesale, the same id lets the response's name fill ours in, a different id takes the response's
|
||||
pair whole. And hydration **loses every race against the user**: a `touchedRef` records which fields
|
||||
have been edited (through a single `edit()` funnel, so "touched" cannot drift from "changed") and
|
||||
the refresh writes only untouched ones, which also stops it resurrecting a deliberate clear or
|
||||
reverting a type switch. An explicit conflict-reload clears the touched set, since discarding local
|
||||
edits is exactly what it is for. All three interleavings are tested by holding the detail response
|
||||
open, acting as the user, then releasing it.
|
||||
|
||||
Symmetrically, a name resolved asynchronously is **keyed to the id it was resolved for** and refuses
|
||||
to overwrite a label that already names a different id — otherwise a slow edit-load read landing
|
||||
@@ -82,7 +100,12 @@ keyboard-operable, so an input-plus-listbox that only responds to Tab and click
|
||||
introduced by this change rather than a pre-existing gap. `SearchPicker` implements the ARIA
|
||||
combobox pattern: `role="combobox"` with `aria-expanded`/`aria-controls`/`aria-autocomplete`,
|
||||
Arrow/Home/End moving a virtual cursor exposed through `aria-activedescendant`, Enter committing,
|
||||
Escape dismissing, and options as non-tab-stops. The cursor resets whenever a new result set lands.
|
||||
Escape dismissing, and options as non-tab-stops. Two defects specific to an *asynchronous* combobox
|
||||
also had to be closed: a stale result set was committable (highlight Alpha for "Al", retype "Be",
|
||||
press Enter before the debounce — Enter selected Alpha), so the highlight now drops on input change
|
||||
and every keyboard action is gated on the results matching what is typed; and Escape closed the
|
||||
popup while focus stayed in the input, where `onFocus` can never re-arm it, so the picker was dead
|
||||
until the user blurred and refocused — typing and ArrowDown now both reopen it.
|
||||
|
||||
Folded in from #578 (same components): the rule-builder facet typeahead arms on **focus** rather
|
||||
than on mount, so an N-row rule tree no longer fires N unrequested `search/fields/*/values`
|
||||
@@ -95,9 +118,9 @@ read `current` and saw `false`. #578's remaining item — extending the `artist`
|
||||
entity artists — is a `GetSearchFieldValuesHandler` change, out of scope for a web-only fix, and is
|
||||
being done on its own branch.
|
||||
|
||||
*(Over the 60-line prose ceiling at 84: checked for redundancy against
|
||||
*(Over the 60-line prose ceiling: checked for redundancy against
|
||||
`spa.list-completeness-vs-bounded-pickers` in `archive/` and declined to cut. The length is six
|
||||
distinct findings — the search bound, the compile rule, selection preservation, the
|
||||
clear-what-you-cannot-name prohibition, the async-name keying, and the keyboard contract — four of
|
||||
which came from review rounds and each of which names a specific way the obvious implementation is
|
||||
wrong. Summarising any of them back out would lose the counter-example that makes it actionable.)*
|
||||
clear-what-you-cannot-name prohibition, the async-name keying, and the keyboard contract — most of
|
||||
which came from review rounds, and each of which names a specific way the obvious implementation is
|
||||
wrong (twice over, for the hydration rule, whose first fix was itself the defect). Summarising any of them back out would lose the counter-example that makes it actionable.)*
|
||||
|
||||
+37
-10
@@ -205,16 +205,33 @@ the #644 follow-up got Class A right and Class B only half right):
|
||||
id and the name from the same eager-loaded navigation returns *no selection at all* when the
|
||||
navigation isn't loaded — a successful 200 that looks identical to "the user cleared it".
|
||||
(`RerunCollectionsController.ProjectToResponseModel` does exactly this, and
|
||||
`MediaCollections/Mapper` maps RemoteStream through `_ => null`.) So an edit-load refresh
|
||||
**merges** rather than replaces: `selectedId: refreshed.selectedId ?? current.selectedId`,
|
||||
`selectedName: refreshed.selectedName || current.selectedName`. Degrading the label to `#id` is
|
||||
`MediaCollections/Mapper` maps RemoteStream through `_ => null`; the server-side defect is
|
||||
**#671** — the client guard stays even once that lands.) Degrading the label to `#id` is
|
||||
acceptable; dropping the id strands the user on a record they cannot re-save, because Save is
|
||||
gated on it. Test this per affected type, not on the one type that happens to work.
|
||||
- **A name resolved asynchronously must be keyed to the id it was resolved FOR**, and must not
|
||||
overwrite a label that already names a different id. A slow by-id read that lands after the user
|
||||
- **Hydrate untouched fields; never merge field-by-field.** The obvious fix — coalescing each
|
||||
field independently (`refreshed.selectedId ?? current.selectedId`,
|
||||
`refreshed.selectedName || current.selectedName`) — is *worse than the bug it fixes*, and this
|
||||
is the trap to internalise: an id and its display name are **one value**, so coalescing them
|
||||
separately pairs one selection's id with another's name. The chip then shows what the user
|
||||
picked while Save writes what the server sent — silent, with no error and no visual cue, where
|
||||
the original defect at least cleared the field visibly. Two rules, both required:
|
||||
1. **Resolve the pair atomically.** No id in the response ⇒ keep ours wholesale; the *same* id
|
||||
⇒ the response's name may fill ours in; a *different* id ⇒ take the response's pair whole.
|
||||
2. **A late hydrate must lose every race against the user.** Track which fields the user has
|
||||
edited (a ref, updated by a single `edit()` funnel so "touched" cannot drift from "changed")
|
||||
and hydrate only untouched ones. Field-wise coalescing also resurrects a deliberate clear and
|
||||
reverts a type switch. Clear the touched set on an explicit conflict-reload, whose entire
|
||||
purpose is to discard local edits.
|
||||
|
||||
Test this by **interleaving**: issue the refresh, have the user act while it is in flight, then
|
||||
release it. A test that doesn't interleave proves nothing about a race.
|
||||
- **A name resolved asynchronously must be keyed to the id it was resolved FOR**, and must refuse
|
||||
to overwrite a label that already names a different id. A slow by-id read landing after the user
|
||||
has picked something else would otherwise label the new selection with the old item's title
|
||||
while the id — and therefore what gets saved — says otherwise. Both halves are needed: keying
|
||||
the render alone stops the mislabelling but still discards the newer, correct label.
|
||||
while the id — and therefore what gets saved — says otherwise. Keep the guard at the *writer*,
|
||||
where it is reachable and testable; a second render-time id comparison is unreachable once
|
||||
every writer sets the label and the id together, and an unreachable guard is an untested one.
|
||||
- **Only Lucene-backed types.** `GetLibraryBrowseItemsHandler` applies `query` as a Lucene clause
|
||||
for media items but as a plain SQL `LIKE` on `Name` for the collection-family types (Collection /
|
||||
SmartCollection / MultiCollection / RerunCollection / Playlist). A compiled `title:*x*` sent at
|
||||
@@ -239,9 +256,19 @@ fully keyboard-operable; swapping in a listbox-and-input is an accessibility *re
|
||||
implements the ARIA combobox pattern — `role="combobox"` + `aria-expanded`/`aria-controls`/
|
||||
`aria-autocomplete` on the input, ArrowUp/ArrowDown to move a virtual cursor exposed via
|
||||
`aria-activedescendant`, Enter to commit, Escape to dismiss, options as non-tab-stops
|
||||
(`tabIndex={-1}`) marked with `aria-selected`. Reset the cursor whenever a new result set lands —
|
||||
index 2 of the old list is not index 2 of the new one. Note this changes what
|
||||
`getAllByRole('combobox')` matches in tests: count `<select>` elements when that is what you mean.
|
||||
(`tabIndex={-1}`) marked with `aria-selected`. Note this changes what `getAllByRole('combobox')`
|
||||
matches in tests: count `<select>` elements when that is what you mean. Two failure modes that only
|
||||
appear once the widget is asynchronous:
|
||||
|
||||
- **A stale result set must not be committable.** Between a keystroke and its response, `results`
|
||||
still describe the *previous* query — so highlighting an option, retyping, and pressing Enter
|
||||
commits the old option while the box reads the new text. Drop the highlight on **input change**
|
||||
(not when the next response arrives) and gate every keyboard action on
|
||||
`resultsQuery === query.trim()`. Keep the stale list *visible* — hiding it flickers on every
|
||||
keystroke — just not actionable.
|
||||
- **Escape must not strand the user.** Closing the popup while focus stays in the input means
|
||||
`onFocus` can never re-arm it, so typing does nothing and the user has to blur and refocus to
|
||||
recover. Typing and ArrowDown must both reopen it.
|
||||
|
||||
**Testing an is-mounted guard: React 19 does not warn on a setState-after-unmount, and an unmounted
|
||||
tree renders nothing either way** — so no DOM assertion can distinguish "the guard stopped it" from
|
||||
|
||||
@@ -103,18 +103,29 @@ describe('round-trip: parse(compile(tree)) === tree', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// #578: the divisor fix has no natural regression test — the max-state case is unreachable with the
|
||||
// seeds this file uses today — so exercise the two helpers directly at the boundary instead. These
|
||||
// fail on the old `/ 0xffffffff` divisor.
|
||||
describe('LCG generator', () => {
|
||||
it('never returns 1.0, even at the maximum 32-bit state', () => {
|
||||
// Feed `pick` the largest value the LCG can produce. With `/ 0xffffffff` this is exactly 1.0.
|
||||
const maxState = 0xffffffff;
|
||||
expect(maxState / 0x100000000).toBeLessThan(1);
|
||||
// #578 / #651 review round 2: drive the REAL `lcg` into its maximum state instead of recomputing
|
||||
// the divisor in the test. The generator is `s -> (1664525*s + 1013904223) mod 2^32`, which is a
|
||||
// bijection (the multiplier is odd), so the seed whose FIRST step lands on 0xffffffff can be solved
|
||||
// exactly: seed = (0xffffffff - 1013904223) * 1664525^-1 mod 2^32 = 653637408. On the old
|
||||
// `/ 0xffffffff` divisor that first value is exactly 1.0 and `pick` indexes one past the end; a
|
||||
// test that recomputes the formula would pass either way and prove nothing.
|
||||
const MAX_STATE_SEED = 653637408;
|
||||
|
||||
const alwaysMax = () => maxState / 0x100000000;
|
||||
expect(pick(alwaysMax, ['a', 'b', 'c'])).toBe('c');
|
||||
expect(pick(alwaysMax, ['only'])).toBe('only');
|
||||
describe('LCG generator', () => {
|
||||
it('never returns 1.0 — not even on the step that reaches the maximum 32-bit state', () => {
|
||||
const value = lcg(MAX_STATE_SEED)();
|
||||
|
||||
// Guards the seed itself: if the recurrence ever changes, this stops silently testing a
|
||||
// mid-range state that would pass under either divisor.
|
||||
expect(value).toBeGreaterThan(0.9999999);
|
||||
expect(value).toBeLessThan(1);
|
||||
});
|
||||
|
||||
it('pick() stays in bounds on the maximum-state step', () => {
|
||||
const arr = ['a', 'b', 'c'];
|
||||
// `arr[Math.floor(1.0 * 3)]` is `arr[3]` — undefined — on the old divisor.
|
||||
expect(pick(lcg(MAX_STATE_SEED), arr)).toBe('c');
|
||||
expect(pick(lcg(MAX_STATE_SEED), ['only'])).toBe('only');
|
||||
});
|
||||
|
||||
it('pick() stays in range across the whole output of a real generator', () => {
|
||||
@@ -128,7 +139,9 @@ describe('LCG generator', () => {
|
||||
});
|
||||
|
||||
it('stays within [0, 1) for every reachable state', () => {
|
||||
const rng = lcg(1);
|
||||
// Every 32-bit state IS reachable from any seed (full-period LCG), so walking a long stream
|
||||
// from the maximum-state seed covers the boundary rather than hoping to stumble on it.
|
||||
const rng = lcg(MAX_STATE_SEED);
|
||||
for (let i = 0; i < 20000; i += 1) {
|
||||
const value = rng();
|
||||
expect(value).toBeGreaterThanOrEqual(0);
|
||||
|
||||
@@ -249,5 +249,74 @@ describe('SearchPicker', () => {
|
||||
await waitFor(() => expect(screen.getByRole('option', { name: 'Zeta' })).toBeInTheDocument());
|
||||
expect(input).not.toHaveAttribute('aria-activedescendant');
|
||||
});
|
||||
|
||||
it('BLOCKER 2: Enter cannot commit a result from the PREVIOUS query', async () => {
|
||||
const onSelect = vi.fn();
|
||||
let release: ((items: SearchPickerOption[]) => void) | null = null;
|
||||
const search = vi
|
||||
.fn<(query: string) => Promise<SearchPickerOption[]>>()
|
||||
.mockResolvedValueOnce(OPTIONS)
|
||||
.mockImplementation(() => new Promise((resolve) => { release = resolve; }));
|
||||
|
||||
renderPicker({ onSelect, search });
|
||||
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: 'Al' } });
|
||||
await screen.findByRole('listbox', { name: 'Movie results' });
|
||||
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' });
|
||||
expect(activeOptionName(input)).toBe('Alpha');
|
||||
|
||||
// Retype: the results still describe "Al" until the next response lands.
|
||||
fireEvent.change(input, { target: { value: 'Be' } });
|
||||
// The highlight is dropped IMMEDIATELY, not when the response happens to arrive.
|
||||
expect(input).not.toHaveAttribute('aria-activedescendant');
|
||||
|
||||
// Neither re-highlighting nor Enter may commit a stale option while the box reads "Be".
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' });
|
||||
fireEvent.keyDown(input, { key: 'Enter' });
|
||||
expect(onSelect).not.toHaveBeenCalled();
|
||||
|
||||
// Once the response for "Be" lands, the keyboard is live again.
|
||||
await waitFor(() => expect(search).toHaveBeenCalledTimes(2));
|
||||
release?.([{ id: 7, name: 'Beta Two' }]);
|
||||
await waitFor(() => expect(screen.getByRole('option', { name: 'Beta Two' })).toBeInTheDocument());
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' });
|
||||
fireEvent.keyDown(input, { key: 'Enter' });
|
||||
expect(onSelect).toHaveBeenCalledWith(7, 'Beta Two');
|
||||
});
|
||||
|
||||
it('BLOCKER 3: the picker recovers from Escape by typing, without a blur', async () => {
|
||||
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue(OPTIONS);
|
||||
renderPicker({ search });
|
||||
|
||||
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: 'a' } });
|
||||
await screen.findByRole('listbox', { name: 'Movie results' });
|
||||
|
||||
fireEvent.keyDown(input, { key: 'Escape' });
|
||||
await waitFor(() => expect(screen.queryByRole('listbox', { name: 'Movie results' })).not.toBeInTheDocument());
|
||||
|
||||
// Focus never left the input, so onFocus cannot re-arm it. Typing must.
|
||||
fireEvent.change(input, { target: { value: 'al' } });
|
||||
expect(await screen.findByRole('listbox', { name: 'Movie results' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('BLOCKER 3: ArrowDown also reopens a popup Escape closed', async () => {
|
||||
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue(OPTIONS);
|
||||
renderPicker({ search });
|
||||
|
||||
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: 'a' } });
|
||||
await screen.findByRole('listbox', { name: 'Movie results' });
|
||||
|
||||
fireEvent.keyDown(input, { key: 'Escape' });
|
||||
await waitFor(() => expect(screen.queryByRole('listbox', { name: 'Movie results' })).not.toBeInTheDocument());
|
||||
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' });
|
||||
expect(await screen.findByRole('listbox', { name: 'Movie results' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -104,8 +104,15 @@ export function SearchPicker({
|
||||
}, [query, open, search, minQueryLength, mountedRef]);
|
||||
|
||||
const trimmedQuery = query.trim();
|
||||
const noMatches = open && !loading && results.length === 0 && resultsQuery !== null && resultsQuery === trimmedQuery;
|
||||
// Whether `results` actually describe what is currently typed. Between a keystroke and its
|
||||
// response they do not, and a stale list must not be committable: typing "Al", highlighting
|
||||
// Alpha, retyping to "Be" and pressing Enter would otherwise select Alpha while the box reads
|
||||
// "Be" (#651 review round 2, BLOCKER 2). The list stays VISIBLE while the next query loads —
|
||||
// hiding it would flicker on every keystroke — it just stops being actionable by keyboard.
|
||||
const resultsCurrent = resultsQuery !== null && resultsQuery === trimmedQuery;
|
||||
const noMatches = open && !loading && results.length === 0 && resultsCurrent;
|
||||
const listboxOpen = open && results.length > 0;
|
||||
const keyboardArmed = listboxOpen && resultsCurrent;
|
||||
|
||||
// Keyboard navigation (#651 F6). Replacing a native <select> with a custom widget removed
|
||||
// keyboard operability, which is a regression, not a pre-existing gap: without this the only way
|
||||
@@ -128,7 +135,16 @@ export function SearchPicker({
|
||||
return;
|
||||
}
|
||||
|
||||
if (!listboxOpen) {
|
||||
// Escape (or a selection) closes the popup while focus stays in the input, so ArrowDown has to
|
||||
// be able to REOPEN it. Without this the picker is stuck until the user blurs and refocuses,
|
||||
// because `onFocus` never fires again (#651 review round 2, BLOCKER 3).
|
||||
if (!open && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
|
||||
event.preventDefault();
|
||||
setOpen(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!keyboardArmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -193,9 +209,16 @@ export function SearchPicker({
|
||||
aria-controls={listboxId}
|
||||
aria-autocomplete="list"
|
||||
aria-activedescendant={
|
||||
listboxOpen && activeIndex >= 0 && activeIndex < results.length ? optionId(activeIndex) : undefined
|
||||
keyboardArmed && activeIndex >= 0 && activeIndex < results.length ? optionId(activeIndex) : undefined
|
||||
}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
onChange={(event) => {
|
||||
setQuery(event.target.value);
|
||||
// The highlight described the OLD result set; drop it now rather than when the next
|
||||
// response happens to arrive (BLOCKER 2). Typing also reopens a popup Escape closed,
|
||||
// so the picker recovers without a blur (BLOCKER 3).
|
||||
setActiveIndex(-1);
|
||||
setOpen(true);
|
||||
}}
|
||||
onFocus={() => setOpen(true)}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
@@ -214,8 +237,8 @@ export function SearchPicker({
|
||||
// input and moves a virtual cursor via aria-activedescendant. It stays a
|
||||
// <button> so pointer users get the same click target as before.
|
||||
tabIndex={-1}
|
||||
aria-selected={index === activeIndex}
|
||||
className={`ctv-picker-result${index === activeIndex ? ' ctv-picker-result-active' : ''}`}
|
||||
aria-selected={keyboardArmed && index === activeIndex}
|
||||
className={`ctv-picker-result${keyboardArmed && index === activeIndex ? ' ctv-picker-result-active' : ''}`}
|
||||
onMouseEnter={() => setActiveIndex(index)}
|
||||
onClick={() => choose(option)}
|
||||
>
|
||||
|
||||
@@ -492,8 +492,9 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
|
||||
// It is stored WITH the id it names (#651 F3) rather than as a bare string. A slow edit-load name
|
||||
// resolution for the stored id can otherwise land after the user has already picked something
|
||||
// else, labelling the new id with the old item's title while `mediaItemId` — and therefore what
|
||||
// gets saved — says otherwise. Keying the label means a stale resolution is simply ignored at
|
||||
// render time instead of having to be raced, and it self-heals if the user selects back.
|
||||
// gets saved — says otherwise. The id travels with the name so the resolution callback can tell
|
||||
// whether it is still describing the current selection; every OTHER writer sets the pair and the
|
||||
// draft id together, so the pair and the draft cannot disagree.
|
||||
const [selectedLabel, setSelectedLabel] = useState<null | { id: number; name: string }>(null);
|
||||
|
||||
const isEdit = mode.kind === 'edit';
|
||||
@@ -840,7 +841,11 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
|
||||
placeholder={`Search ${activeConfig.label.toLowerCase()}…`}
|
||||
search={searchLibrary}
|
||||
selectedId={pickerSelectedId}
|
||||
selectedName={selectedLabel?.id === pickerSelectedId ? selectedLabel.name : null}
|
||||
// No id comparison here: `selectedLabel` and the draft id are only ever written
|
||||
// together (select / clear / type-switch), and the one asynchronous writer refuses
|
||||
// to adopt a name for a different id. A render-time check would be unreachable, and
|
||||
// an unreachable guard is an untested one (#651 review round 2).
|
||||
selectedName={selectedLabel?.name ?? null}
|
||||
/>
|
||||
) : (
|
||||
<Select
|
||||
|
||||
@@ -40,12 +40,14 @@ const storedSelection = {
|
||||
|
||||
|
||||
interface MockOptions {
|
||||
browsePage?: unknown;
|
||||
list?: unknown[];
|
||||
onRequest?: (url: string, method: string, body: unknown) => Response | null;
|
||||
}
|
||||
|
||||
function mockApi(options: MockOptions = {}) {
|
||||
const list = options.list ?? rerunCollections;
|
||||
const browsePage = options.browsePage ?? { page: [], totalCount: 0 };
|
||||
|
||||
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = input.toString();
|
||||
@@ -84,7 +86,7 @@ function mockApi(options: MockOptions = {}) {
|
||||
}
|
||||
|
||||
if (url.startsWith('/api/v1/library/browse')) {
|
||||
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
|
||||
return Promise.resolve(jsonResponse(browsePage));
|
||||
}
|
||||
|
||||
return Promise.resolve(new Response(null, { status: 204 }));
|
||||
@@ -481,11 +483,14 @@ describe('RerunCollectionsScreen', () => {
|
||||
type: 'RemoteStream'
|
||||
},
|
||||
{
|
||||
// Error-path guard, NOT merge coverage: a 500 never reaches the hydrate at all. Kept so a
|
||||
// future change that clears the draft on a failed refresh is caught.
|
||||
detail: (): Response => new Response(null, { status: 500 }),
|
||||
name: 'Episode — detail 500 (NRE on the unloaded Season navigation)',
|
||||
type: 'Episode'
|
||||
},
|
||||
{
|
||||
// Error-path guard, NOT merge coverage — see the Episode case.
|
||||
detail: (): Response => new Response(null, { status: 500 }),
|
||||
name: 'MusicVideo — detail 500 (NRE on the unloaded Artist navigation)',
|
||||
type: 'MusicVideo'
|
||||
@@ -545,28 +550,38 @@ describe('RerunCollectionsScreen', () => {
|
||||
});
|
||||
|
||||
it('F1: degrades to #id (never to an empty picker) when no name is available at all', async () => {
|
||||
let detailCalls = 0;
|
||||
mockApi({
|
||||
list: [{ ...storedSelection, collectionType: 'RemoteStream', selectedName: null }],
|
||||
onRequest: (url, method) =>
|
||||
url === '/api/v1/rerun-collections/9' && method === 'GET'
|
||||
? jsonResponse({ ...storedSelection, collectionType: 'RemoteStream', selectedId: null, selectedName: null })
|
||||
: null
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
detailCalls += 1;
|
||||
return jsonResponse({ ...storedSelection, collectionType: 'RemoteStream', selectedId: null, selectedName: null });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
expect(await screen.findByText('#42')).toBeInTheDocument();
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('button', { name: 'Save rerun collection' })).not.toBeDisabled()
|
||||
);
|
||||
// Await the refresh: the pre-refresh draft already shows #42, so an assertion that races it is
|
||||
// satisfiable without the hydration guard at all.
|
||||
await waitFor(() => expect(detailCalls).toBe(1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const chip = screen.getByLabelText(/^Clear /).closest('.ctv-picker-selected');
|
||||
expect(chip?.textContent).toContain('#42');
|
||||
expect(screen.getByRole('button', { name: 'Save rerun collection' })).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('F1: re-saves the preserved id unchanged after an unnamed refresh', async () => {
|
||||
let detailCalls = 0;
|
||||
const fetchMock = mockApi({
|
||||
list: [{ ...storedSelection, collectionType: 'RemoteStream' }],
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
detailCalls += 1;
|
||||
return jsonResponse({ ...storedSelection, collectionType: 'RemoteStream', selectedId: null, selectedName: null });
|
||||
}
|
||||
return url === '/api/v1/rerun-collections/9' && method === 'PUT' ? jsonResponse({ id: 9 }, 200) : null;
|
||||
@@ -575,7 +590,12 @@ describe('RerunCollectionsScreen', () => {
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
expect(await screen.findByText('Stored Item')).toBeInTheDocument();
|
||||
|
||||
// Await the refresh before saving — otherwise the PUT can be issued from the pre-refresh draft
|
||||
// and the assertion passes with the hydration guard removed.
|
||||
await waitFor(() => expect(detailCalls).toBe(1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(screen.getByLabelText(/^Clear /).closest('.ctv-picker-selected')?.textContent).toContain('Stored Item');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save rerun collection' }));
|
||||
|
||||
@@ -587,4 +607,119 @@ describe('RerunCollectionsScreen', () => {
|
||||
expect(JSON.parse(String(putCall?.[1]?.body)).selectedId).toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- #651 review round 2, BLOCKER 1: hydration must lose every race against the user ----
|
||||
//
|
||||
// The round-1 fix merged `selectedId` and `selectedName` field-by-field, which paired one
|
||||
// selection's id with another's name: the chip showed what the user picked while Save wrote what
|
||||
// the server sent. These tests interleave a DELAYED detail refresh with a user edit — the whole
|
||||
// point is the ordering, so a non-interleaved test proves nothing.
|
||||
//
|
||||
// `Song` is the shape that makes it concrete: its response resolves an id but not a name.
|
||||
function mockWithDelayedDetail(detailBody: unknown, listRow: Record<string, unknown>) {
|
||||
let release: (() => void) | null = null;
|
||||
const fetchMock = mockApi({
|
||||
browsePage: { page: [{ id: 99, mediaItemId: 99, mediaType: 'Song', title: 'New Song' }], totalCount: 1 },
|
||||
list: [listRow],
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
// Returning null here would fall through to mockApi's own handler, so signal the delay by
|
||||
// returning a never-settling Response via the outer promise instead.
|
||||
return null;
|
||||
}
|
||||
return url === '/api/v1/rerun-collections/9' && method === 'PUT' ? jsonResponse({ id: 9 }, 200) : null;
|
||||
}
|
||||
});
|
||||
|
||||
const inner = fetchMock.getMockImplementation() as (i: RequestInfo | URL, r?: RequestInit) => Promise<Response>;
|
||||
fetchMock.mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = input.toString();
|
||||
const method = (init?.method ?? 'GET').toUpperCase();
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
return new Promise<Response>((resolve) => {
|
||||
release = () => resolve(jsonResponse(detailBody));
|
||||
});
|
||||
}
|
||||
return inner(input, init);
|
||||
});
|
||||
|
||||
return { fetchMock, releaseDetail: async () => { release?.(); await new Promise((r) => setTimeout(r, 0)); } };
|
||||
}
|
||||
|
||||
const songRow = {
|
||||
...storedSelection,
|
||||
collectionType: 'Song',
|
||||
selectedId: 42,
|
||||
selectedName: 'Stored Song'
|
||||
};
|
||||
|
||||
it('BLOCKER 1: a selection made DURING an in-flight refresh survives it — id and name stay one unit', async () => {
|
||||
// The server will answer with the STORED selection (id 42) and no name — the exact shape that
|
||||
// let the round-1 merge pair id 42 with the name of whatever the user had just picked.
|
||||
const { fetchMock, releaseDetail } = mockWithDelayedDetail(
|
||||
{ ...songRow, selectedName: null },
|
||||
songRow
|
||||
);
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
// The user picks a DIFFERENT song while the refresh is still in flight.
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Change' }));
|
||||
const input = await screen.findByLabelText('Song search');
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: 'New Song' } });
|
||||
fireEvent.click(await screen.findByRole('option', { name: 'New Song' }));
|
||||
|
||||
await releaseDetail();
|
||||
|
||||
// The chip and the saved id must agree. Round 1 showed "New Song" and saved 42.
|
||||
const chip = () => screen.getByLabelText(/^Clear /).closest('.ctv-picker-selected');
|
||||
expect(chip()?.textContent).toContain('New Song');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save rerun collection' }));
|
||||
await waitFor(() => {
|
||||
const put = fetchMock.mock.calls.find(
|
||||
([u, init]) => u === '/api/v1/rerun-collections/9' && (init?.method ?? '').toUpperCase() === 'PUT'
|
||||
);
|
||||
expect(put).toBeDefined();
|
||||
expect(JSON.parse(String(put?.[1]?.body)).selectedId).toBe(99);
|
||||
});
|
||||
});
|
||||
|
||||
it('BLOCKER 1: a deliberate CLEAR during an in-flight refresh is not resurrected', async () => {
|
||||
const { releaseDetail } = mockWithDelayedDetail(songRow, songRow);
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
fireEvent.click(await screen.findByLabelText('Clear Song'));
|
||||
await waitFor(() => expect(screen.getByLabelText('Song search')).toBeInTheDocument());
|
||||
|
||||
await releaseDetail();
|
||||
|
||||
// The refresh carries a perfectly good id 42 — and must still not undo the user's clear.
|
||||
expect(screen.getByLabelText('Song search')).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/^Clear /)).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Save rerun collection' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('BLOCKER 1: a type switch during an in-flight refresh is not reverted', async () => {
|
||||
const { releaseDetail } = mockWithDelayedDetail(songRow, songRow);
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
const typeSelect = (await screen.findAllByRole('combobox'))[0];
|
||||
fireEvent.change(typeSelect, { target: { value: 'Movie' } });
|
||||
await waitFor(() => expect(screen.getByLabelText('Movie search')).toBeInTheDocument());
|
||||
|
||||
await releaseDetail();
|
||||
|
||||
// Reverting the type while keeping the (now cleared) selection would leave a draft whose type
|
||||
// and selection disagree — a broken form and a failed save.
|
||||
expect((typeSelect as HTMLSelectElement).value).toBe('Movie');
|
||||
expect(screen.getByLabelText('Movie search')).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('Song search')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -229,25 +229,51 @@ function draftFromRerun(rerun: RerunCollection): Draft {
|
||||
};
|
||||
}
|
||||
|
||||
// A refresh that fails to NAME a selection does not mean the selection is gone — and the client
|
||||
// must never be the thing that destroys it. `RerunCollectionsController.ProjectToResponseModel`
|
||||
// derives BOTH `selectedId` and `selectedName` from the loaded navigation, so a response can carry
|
||||
// `selectedId: null` for a record that certainly has one:
|
||||
// - `GetRerunCollectionByIdHandler` eager-loads media metadata only for Show/Season/Artist/Movie;
|
||||
// - `MediaCollections/Mapper.ProjectToViewModel` maps RemoteStream through `_ => null` outright,
|
||||
// so a RemoteStream rerun collection returns HTTP 200 with a null selection;
|
||||
// - Song/OtherVideo/Image resolve their id but fall back to a placeholder name.
|
||||
// Replacing the draft wholesale would clear a stored id on the strength of a naming gap, leaving
|
||||
// the user unable to even re-save the record (Save is gated on `selectedId != null`). So merge:
|
||||
// take everything from the refresh EXCEPT an absent id/name, which fall back to what we hold.
|
||||
// Degrading to `#id` in the picker is acceptable; dropping the id is not. See #651 F1 — the
|
||||
// server-side naming gaps themselves are tracked separately.
|
||||
function mergeRerunDraft(current: Draft, rerun: RerunCollection): Draft {
|
||||
// Which draft fields the user has edited since the editor opened. The late edit-load refresh
|
||||
// hydrates ONLY untouched fields — see `hydrateDraft`. `selection` covers the id and its name
|
||||
// together, because they are one value, not two.
|
||||
type TouchedField = 'collectionType' | 'firstRunPlaybackOrder' | 'name' | 'rerunPlaybackOrder' | 'selection';
|
||||
|
||||
// The selection is ONE unit: an id and the name OF THAT id. Merging the two fields independently
|
||||
// pairs one selection's id with another's name — the chip shows the name the user picked while Save
|
||||
// writes the id the server sent, silently discarding their choice (#651 review round 2, BLOCKER 1).
|
||||
// So decide once, for the pair:
|
||||
// - the refresh could not identify a selection -> keep ours wholesale. The server derives BOTH
|
||||
// fields from the same eager-loaded navigation, so a naming gap presents as `selectedId: null`
|
||||
// on an otherwise-successful 200 (RemoteStream maps through `_ => null`; Episode/MusicVideo
|
||||
// 500 outright; Song/OtherVideo/Image resolve an id but not a name). Clearing a stored id on
|
||||
// the strength of that leaves the user unable to re-save at all, since Save is gated on it.
|
||||
// Tracked server-side as #671; this guard stays regardless of that fix.
|
||||
// - the refresh names the SAME id we hold -> same item, so its name may fill ours in.
|
||||
// - the refresh names a DIFFERENT id -> a genuinely different selection: take it whole.
|
||||
function hydrateSelection(current: Draft, refreshed: Draft): Pick<Draft, 'selectedId' | 'selectedName'> {
|
||||
if (refreshed.selectedId == null) {
|
||||
return { selectedId: current.selectedId, selectedName: current.selectedName };
|
||||
}
|
||||
|
||||
if (refreshed.selectedId === current.selectedId) {
|
||||
return { selectedId: refreshed.selectedId, selectedName: refreshed.selectedName || current.selectedName };
|
||||
}
|
||||
|
||||
return { selectedId: refreshed.selectedId, selectedName: refreshed.selectedName };
|
||||
}
|
||||
|
||||
// Hydration, not merging: a refresh that lands after the user has already touched a field must not
|
||||
// win. Anything else resurrects a deliberate clear, reverts a type switch, or overwrites a fresh
|
||||
// selection with the stored one — all silently, because a hydrate looks like a render.
|
||||
function hydrateDraft(current: Draft, rerun: RerunCollection, touched: ReadonlySet<TouchedField>): Draft {
|
||||
const refreshed = draftFromRerun(rerun);
|
||||
|
||||
return {
|
||||
...refreshed,
|
||||
selectedId: refreshed.selectedId ?? current.selectedId,
|
||||
selectedName: refreshed.selectedName || current.selectedName
|
||||
collectionType: touched.has('collectionType') ? current.collectionType : refreshed.collectionType,
|
||||
firstRunPlaybackOrder: touched.has('firstRunPlaybackOrder')
|
||||
? current.firstRunPlaybackOrder
|
||||
: refreshed.firstRunPlaybackOrder,
|
||||
name: touched.has('name') ? current.name : refreshed.name,
|
||||
rerunPlaybackOrder: touched.has('rerunPlaybackOrder') ? current.rerunPlaybackOrder : refreshed.rerunPlaybackOrder,
|
||||
...(touched.has('selection')
|
||||
? { selectedId: current.selectedId, selectedName: current.selectedName }
|
||||
: hydrateSelection(current, refreshed))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -284,6 +310,18 @@ function RerunCollectionEditor({
|
||||
// rerun collection, sent as If-Match on save. There's no rotation-on-save because the editor
|
||||
// always returns to the list after a successful save (see onSaved below).
|
||||
const etagRef = useRef<string | null>(null);
|
||||
// Fields the user has edited. A ref, not state: hydration reads it inside an async callback, and
|
||||
// it must never itself trigger a render.
|
||||
const touchedRef = useRef<Set<TouchedField>>(new Set());
|
||||
|
||||
// Every user edit goes through this, so "did the user touch it?" cannot drift from "did it
|
||||
// change?" — a field mutated anywhere else would silently become hydratable again.
|
||||
const edit = useCallback((fields: TouchedField[], patch: (current: Draft) => Partial<Draft>) => {
|
||||
for (const field of fields) {
|
||||
touchedRef.current.add(field);
|
||||
}
|
||||
setDraft((current) => ({ ...current, ...patch(current) }));
|
||||
}, []);
|
||||
|
||||
const { collectionType } = draft;
|
||||
|
||||
@@ -300,7 +338,7 @@ function RerunCollectionEditor({
|
||||
.then((meta) => {
|
||||
if (active) {
|
||||
etagRef.current = meta.etag;
|
||||
setDraft((current) => mergeRerunDraft(current, meta.data));
|
||||
setDraft((current) => hydrateDraft(current, meta.data, touchedRef.current));
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
@@ -342,9 +380,9 @@ function RerunCollectionEditor({
|
||||
};
|
||||
}, [collectionType]);
|
||||
|
||||
// A type switch clears the selection and rewrites both orders, so it dirties all four.
|
||||
const setCollectionType = (type: RerunCollectionType) => {
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
edit(['collectionType', 'firstRunPlaybackOrder', 'rerunPlaybackOrder', 'selection'], () => ({
|
||||
collectionType: type,
|
||||
firstRunPlaybackOrder: defaultOrderFor(type),
|
||||
rerunPlaybackOrder: defaultOrderFor(type),
|
||||
@@ -356,7 +394,7 @@ function RerunCollectionEditor({
|
||||
const setSelected = (value: string) => {
|
||||
const id = value === '' ? null : Number(value);
|
||||
const match = pickerItems.find((item) => item.id === id);
|
||||
setDraft((current) => ({ ...current, selectedId: id, selectedName: match?.name ?? current.selectedName }));
|
||||
edit(['selection'], (current) => ({ selectedId: id, selectedName: match?.name ?? current.selectedName }));
|
||||
};
|
||||
|
||||
const activeConfig = COLLECTION_TYPES.find((entry) => entry.value === collectionType);
|
||||
@@ -413,6 +451,9 @@ function RerunCollectionEditor({
|
||||
const reloadAfterConflict = () => {
|
||||
setConflictOpen(false);
|
||||
setSaveError(null);
|
||||
// A conflict reload exists precisely to throw local edits away and take the server's state, so
|
||||
// clear the touched set — otherwise the "don't overwrite user edits" rule would defeat it.
|
||||
touchedRef.current = new Set();
|
||||
setReloadKey((key) => key + 1);
|
||||
};
|
||||
|
||||
@@ -456,7 +497,7 @@ function RerunCollectionEditor({
|
||||
<Card title="Rerun collection">
|
||||
<Input
|
||||
label="Name"
|
||||
onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))}
|
||||
onChange={(event) => edit(['name'], () => ({ name: event.target.value }))}
|
||||
placeholder="Rerun collection name"
|
||||
value={draft.name}
|
||||
/>
|
||||
@@ -481,8 +522,8 @@ function RerunCollectionEditor({
|
||||
key={collectionType}
|
||||
label={activeConfig?.label ?? 'Selection'}
|
||||
minQueryLength={LIBRARY_PICKER_MIN_QUERY}
|
||||
onClear={() => setDraft((current) => ({ ...current, selectedId: null, selectedName: '' }))}
|
||||
onSelect={(id, name) => setDraft((current) => ({ ...current, selectedId: id, selectedName: name }))}
|
||||
onClear={() => edit(['selection'], () => ({ selectedId: null, selectedName: '' }))}
|
||||
onSelect={(id, name) => edit(['selection'], () => ({ selectedId: id, selectedName: name }))}
|
||||
placeholder={`Search ${(activeConfig?.label ?? 'items').toLowerCase()}…`}
|
||||
search={searchLibrary}
|
||||
selectedId={draft.selectedId}
|
||||
@@ -518,7 +559,7 @@ function RerunCollectionEditor({
|
||||
<Select
|
||||
label="First Run Playback Order"
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({ ...current, firstRunPlaybackOrder: event.target.value as PlaybackOrder }))
|
||||
edit(['firstRunPlaybackOrder'], () => ({ firstRunPlaybackOrder: event.target.value as PlaybackOrder }))
|
||||
}
|
||||
options={firstRunOrderOptions}
|
||||
value={draft.firstRunPlaybackOrder}
|
||||
@@ -529,7 +570,7 @@ function RerunCollectionEditor({
|
||||
<Select
|
||||
label="Rerun Playback Order"
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({ ...current, rerunPlaybackOrder: event.target.value as PlaybackOrder }))
|
||||
edit(['rerunPlaybackOrder'], () => ({ rerunPlaybackOrder: event.target.value as PlaybackOrder }))
|
||||
}
|
||||
options={rerunOrderOptions}
|
||||
value={draft.rerunPlaybackOrder}
|
||||
|
||||
Reference in New Issue
Block a user