Repository navigation
perf(web): eliminate item detail interaction jank - #540
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (28)
🚧 Files skipped from review as they are similar to previous changes (25)
Included review availability: Your plan provides up to 2 included reviews per hour; 1 remains after this review. 📝 WalkthroughWalkthroughThis PR adds targeted media-surface refresh scheduling, optimistic cache updates, shared detail popovers, a portal-based overflow menu, action-bar wrappers, CSS star-rating states, and memoized detail components. ChangesMedia refresh and cache updates
Detail interaction components
Detail presentation updates
Estimated code review effort: 4 (Complex) | ~60 minutes Merge Risk: ⚪ Minimal · up to This change improves detail-page interaction performance while preserving the documented popover, optimistic-state, invalidation, and realtime behavior; no actionable merge-blocking risk remains beyond normal checks and review. Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 8.11% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 27 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (8)
web/src/components/StarRating.tsx (1)
33-35: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueKeep this concern scoped to button radiogroups.
StarRatingnow has roving focus, butStarRatingis the only button radiogroup in the changed code flow. Generalize this when multiple radiogroups need arrow-key focus rotation, rather than introducing the issue here.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/components/StarRating.tsx` around lines 33 - 35, Keep the roving-focus change scoped to the StarRating button radiogroup: retain the focus lookup and preventScroll behavior within StarRating, and do not generalize arrow-key focus rotation into shared radiogroup logic or other components unless multiple radiogroups require it.Source: Learnings
web/src/pages/ItemDetail/components/DetailPopover.test.tsx (1)
23-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the controlled
openpath.The tests exercise only the uncontrolled mode.
VersionDropdownandSubtitlesPopoverboth passopenandonOpenChange, so the controlled branch insetOpen(which must not update internal state) is untested. Add one test that renders withopenand assertsonOpenChangereceivesfalseon Escape while the dialog stays mounted until the owner flips the prop.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/ItemDetail/components/DetailPopover.test.tsx` around lines 23 - 83, The DetailPopover tests cover only uncontrolled behavior; add a controlled-open test around renderPopover that supplies open and onOpenChange, dispatches Escape, and verifies onOpenChange is called with false while the dialog remains mounted because the owner has not changed open. Anchor the test to the existing Escape handling and controlled setOpen path, preserving the current focus and close assertions for uncontrolled mode.web/src/pages/ItemDetail/components/MediaUserActionBar.tsx (1)
33-50: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueBoth action-bar wrappers depend on mutation result objects instead of
mutate.useMutationreturns a new result object on every state transition, so theuseCallbackwrappers in both wrappers gain a new identity wheneverisPendingchanges. Destructure the stablemutatefunction, and readisPendingseparately, ashandleRatingChangealready does withuseSetRating.
web/src/pages/ItemDetail/components/MediaUserActionBar.tsx#L33-L50: destructuremutatefromuseWatchedStateMutation,useToggleFavorite, anduseToggleWatchlist, and keepisPendingfrom the watched mutation forisUpdatingWatched.web/src/pages/ItemDetail/components/WatchedActionBar.tsx#L15-L19: destructuremutatefromuseWatchedStateMutationand depend on it inhandleToggleWatched, keepingisPendingforisUpdatingWatched.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/ItemDetail/components/MediaUserActionBar.tsx` around lines 33 - 50, Both action-bar components should depend on stable mutation functions rather than changing mutation result objects. In web/src/pages/ItemDetail/components/MediaUserActionBar.tsx lines 33-50, destructure mutate from useWatchedStateMutation, useToggleFavorite, and useToggleWatchlist, retain isPending separately for isUpdatingWatched, and update the callbacks to depend on the destructured functions. In web/src/pages/ItemDetail/components/WatchedActionBar.tsx lines 15-19, destructure mutate and isPending from useWatchedStateMutation, use mutate in handleToggleWatched dependencies, and retain isPending for isUpdatingWatched.web/src/pages/ItemDetail/components/ActionBar.tsx (1)
282-377: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftExtract the shared portal positioning and dismissal logic.
Lines 282-377 duplicate
DetailPopover.tsxlines 63-158 almost exactly: the sameviewportPadding/gapconstants, the same flip-above math, the samepointerdown/keydown/focusin/scrolllistener set, the samerequestAnimationFramecoalescing, and the same focus-restore cleanup. Two copies will drift when positioning or dismissal is later adjusted.Extract a hook, for example
useAnchoredPortal({ open, triggerRef, contentRef, onClose, align }), and consume it from bothDetailPopoverand this menu. The only real difference is horizontal alignment:DetailPopoveraligns totriggerRect.left, and this menu aligns totriggerRect.right - menuRect.width.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/ItemDetail/components/ActionBar.tsx` around lines 282 - 377, Extract the shared anchored-portal positioning, dismissal listeners, scroll-frame handling, and focus restoration from positionOverflowMenu/useLayoutEffect and DetailPopover into a reusable hook such as useAnchoredPortal. Support the existing open state, trigger/content refs, close callback, and horizontal alignment so DetailPopover preserves left alignment while the overflow menu preserves right-edge alignment, then replace both duplicated implementations with the hook.web/src/hooks/queries/items.test.ts (1)
147-171: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the field-level revert.
This test covers the optimistic write. The new
onErrorhandler restores onlyplayedand keepsis_favoriteandin_watchlist. That branch has no test. Add a case that runs theonErrorupdater against a detail withis_favorite: trueand asserts the favorite value survives the revert.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/hooks/queries/items.test.ts` around lines 147 - 171, Extend the watched-state mutation test around useWatchedStateMutation to invoke its onError handler and apply the item-detail updater to a detail with is_favorite: true. Assert that the revert restores played while preserving is_favorite (and the existing in_watchlist field), covering the field-level revert behavior.web/src/hooks/queries/mediaSurfaceRefresh.test.ts (1)
169-191: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRestore real timers in
afterEach.Four tests call
vi.useFakeTimers()and thenvi.useRealTimers()as the last statement. If an assertion fails before that last line, fake timers stay installed and every later test in the file inherits them. The original failure is then hidden behind cascading timeouts. Move the restore into anafterEachhook and delete the trailing calls.♻️ Proposed fix
-import { describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest";describe("invalidateMediaSurfaceQueries", () => { + afterEach(() => { + vi.useRealTimers(); + }); +🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/hooks/queries/mediaSurfaceRefresh.test.ts` around lines 169 - 191, Update the media surface refresh test suite to restore real timers in an afterEach hook, and remove the trailing vi.useRealTimers calls from the individual tests that use fake timers. Ensure cleanup runs even when assertions fail.web/src/hooks/queries/mediaSurfaceRefresh.ts (1)
157-165: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winHoist
surfacePrefixesout of the predicate.
shouldInvalidateMediaSurfaceQueryruns once per cached query on every invalidation pass. This block rebuilds the array and callsadminKeys.playbackHistory({}).slice(0, 2)on each of those calls. Move the list to module scope so it is built once.The
JSON.stringifyfallback inqueryKeyStartsWith(Lines 131-135) also runs on this hot path. Restrict it to non-primitive key parts.♻️ Proposed fix
+const MEDIA_SURFACE_PREFIXES = [ + itemKeys.all, + progressKeys.all, + historyKeys.all, + favoriteKeys.all, + watchlistKeys.all, + personKeys.all, + adminKeys.playbackHistory({}).slice(0, 2), +]; + function shouldInvalidateMediaSurfaceQuery(- const surfacePrefixes = [ - itemKeys.all, - progressKeys.all, - historyKeys.all, - favoriteKeys.all, - watchlistKeys.all, - personKeys.all, - adminKeys.playbackHistory({}).slice(0, 2), - ]; - if (surfacePrefixes.some((prefix) => queryKeyStartsWith(queryKey, prefix))) { + if (MEDIA_SURFACE_PREFIXES.some((prefix) => queryKeyStartsWith(queryKey, prefix))) { return true; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/hooks/queries/mediaSurfaceRefresh.ts` around lines 157 - 165, Hoist the surfacePrefixes list out of shouldInvalidateMediaSurfaceQuery to module scope so it is constructed once, preserving all existing key entries including the sliced adminKeys.playbackHistory value. In queryKeyStartsWith, only use the JSON.stringify fallback for non-primitive key parts, while retaining direct comparisons for primitive values.web/src/hooks/queries/ratingsSurfaceRefresh.ts (1)
27-31: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsolidate the two prefix-matching helpers.
This
startsWithduplicatesqueryKeyStartsWithinweb/src/hooks/queries/mediaSurfaceRefresh.ts(Lines 128-137), but the two use different comparison rules: this one compares with===only, while the other adds aJSON.stringifyfallback for non-primitive key parts. If a key prefix later contains an object or array part, the two helpers will disagree.Export one shared helper and use it in both files.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/hooks/queries/ratingsSurfaceRefresh.ts` around lines 27 - 31, Consolidate the duplicate prefix-matching logic by exporting one shared helper, preserving the comparison behavior of queryKeyStartsWith including its JSON.stringify fallback for non-primitive parts. Remove the local startsWith implementation in ratingsSurfaceRefresh.ts and update both ratingsSurfaceRefresh.ts and mediaSurfaceRefresh.ts to import and use the shared helper consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/app.css`:
- Around line 1060-1061: Update the fill declarations in both
.star-rating-star[data-filled="true"] svg and the corresponding second location
to use the configured lowercase CSS keyword currentcolor instead of
currentColor, resolving the value-keyword-case violations.
In `@web/src/hooks/queries/mediaSurfaceRefresh.test.ts`:
- Around line 38-40: Update the cancel assertion in the media surface refresh
test to inspect the captured filters argument directly, verifying the predicate
and that revert is not false. Replace the broad expect.any(Object) check while
preserving the existing cancellation behavior.
In `@web/src/hooks/queries/mediaSurfaceRefresh.ts`:
- Around line 221-223: Update the promise chain around
invalidateMediaSurfaceQueries to invoke bumpHomeRefreshSignal in a finally
handler rather than then. Preserve the existing queryClient and mergedOptions
arguments so the Home refresh signal is bumped whether invalidation succeeds or
rejects.
In `@web/src/hooks/queries/ratings.ts`:
- Line 16: Update the snapshots in useSetRating and useDeleteRating to use the
shared item-detail predicate, covering both ["items","detail",itemId] and
["catalog","items",itemId,"detail"] cache shapes. Keep rollback scoped
consistently with cancelItemDetailQueries and updateCatalogItemDetail.
In `@web/src/pages/ItemDetail/components/ActionBar.tsx`:
- Around line 547-560: Gate the overflow trigger Button around
toggleOverflowMenu so it renders only when hasOverflowActions || hasAdminActions
|| hasMetadataActions || Boolean(contentId) is true. Reuse this existing guard
from the portal content and keep the button’s current props and behavior
unchanged when actions are available.
In `@web/src/pages/ItemDetail/DetailHero.tsx`:
- Around line 121-124: Remove the remaining Ken Burns animation assignment from
the backdrop image in DetailHero, including the animation style or class that
applies var(--animate-ken-burns-a). Keep the existing opacity transition and
image layout styling unchanged.
---
Nitpick comments:
In `@web/src/components/StarRating.tsx`:
- Around line 33-35: Keep the roving-focus change scoped to the StarRating
button radiogroup: retain the focus lookup and preventScroll behavior within
StarRating, and do not generalize arrow-key focus rotation into shared
radiogroup logic or other components unless multiple radiogroups require it.
In `@web/src/hooks/queries/items.test.ts`:
- Around line 147-171: Extend the watched-state mutation test around
useWatchedStateMutation to invoke its onError handler and apply the item-detail
updater to a detail with is_favorite: true. Assert that the revert restores
played while preserving is_favorite (and the existing in_watchlist field),
covering the field-level revert behavior.
In `@web/src/hooks/queries/mediaSurfaceRefresh.test.ts`:
- Around line 169-191: Update the media surface refresh test suite to restore
real timers in an afterEach hook, and remove the trailing vi.useRealTimers calls
from the individual tests that use fake timers. Ensure cleanup runs even when
assertions fail.
In `@web/src/hooks/queries/mediaSurfaceRefresh.ts`:
- Around line 157-165: Hoist the surfacePrefixes list out of
shouldInvalidateMediaSurfaceQuery to module scope so it is constructed once,
preserving all existing key entries including the sliced
adminKeys.playbackHistory value. In queryKeyStartsWith, only use the
JSON.stringify fallback for non-primitive key parts, while retaining direct
comparisons for primitive values.
In `@web/src/hooks/queries/ratingsSurfaceRefresh.ts`:
- Around line 27-31: Consolidate the duplicate prefix-matching logic by
exporting one shared helper, preserving the comparison behavior of
queryKeyStartsWith including its JSON.stringify fallback for non-primitive
parts. Remove the local startsWith implementation in ratingsSurfaceRefresh.ts
and update both ratingsSurfaceRefresh.ts and mediaSurfaceRefresh.ts to import
and use the shared helper consistently.
In `@web/src/pages/ItemDetail/components/ActionBar.tsx`:
- Around line 282-377: Extract the shared anchored-portal positioning, dismissal
listeners, scroll-frame handling, and focus restoration from
positionOverflowMenu/useLayoutEffect and DetailPopover into a reusable hook such
as useAnchoredPortal. Support the existing open state, trigger/content refs,
close callback, and horizontal alignment so DetailPopover preserves left
alignment while the overflow menu preserves right-edge alignment, then replace
both duplicated implementations with the hook.
In `@web/src/pages/ItemDetail/components/DetailPopover.test.tsx`:
- Around line 23-83: The DetailPopover tests cover only uncontrolled behavior;
add a controlled-open test around renderPopover that supplies open and
onOpenChange, dispatches Escape, and verifies onOpenChange is called with false
while the dialog remains mounted because the owner has not changed open. Anchor
the test to the existing Escape handling and controlled setOpen path, preserving
the current focus and close assertions for uncontrolled mode.
In `@web/src/pages/ItemDetail/components/MediaUserActionBar.tsx`:
- Around line 33-50: Both action-bar components should depend on stable mutation
functions rather than changing mutation result objects. In
web/src/pages/ItemDetail/components/MediaUserActionBar.tsx lines 33-50,
destructure mutate from useWatchedStateMutation, useToggleFavorite, and
useToggleWatchlist, retain isPending separately for isUpdatingWatched, and
update the callbacks to depend on the destructured functions. In
web/src/pages/ItemDetail/components/WatchedActionBar.tsx lines 15-19,
destructure mutate and isPending from useWatchedStateMutation, use mutate in
handleToggleWatched dependencies, and retain isPending for isUpdatingWatched.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ab527966-9e79-495a-afae-aaa529a488b2
📒 Files selected for processing (25)
web/src/app.cssweb/src/components/CastCarousel.tsxweb/src/components/RealtimeEventsProvider.test.tsxweb/src/components/RealtimeEventsProvider.tsxweb/src/components/StarRating.tsxweb/src/hooks/queries/favorites.tsweb/src/hooks/queries/items.test.tsweb/src/hooks/queries/items.tsweb/src/hooks/queries/mediaSurfaceRefresh.test.tsweb/src/hooks/queries/mediaSurfaceRefresh.tsweb/src/hooks/queries/ratings.tsweb/src/hooks/queries/ratingsSurfaceRefresh.test.tsweb/src/hooks/queries/ratingsSurfaceRefresh.tsweb/src/hooks/queries/watchlist.tsweb/src/pages/ItemDetail/DetailHero.tsxweb/src/pages/ItemDetail/EpisodeContent.tsxweb/src/pages/ItemDetail/MovieContent.tsxweb/src/pages/ItemDetail/components/ActionBar.tsxweb/src/pages/ItemDetail/components/AudioTracksPopover.tsxweb/src/pages/ItemDetail/components/DetailPopover.test.tsxweb/src/pages/ItemDetail/components/DetailPopover.tsxweb/src/pages/ItemDetail/components/MediaUserActionBar.tsxweb/src/pages/ItemDetail/components/SubtitlesPopover.tsxweb/src/pages/ItemDetail/components/VersionDropdown.tsxweb/src/pages/ItemDetail/components/WatchedActionBar.tsx
|
Review-body follow-up for commit 2bc0aa2:
Validation: 30 focused tests pass, production build passes, Prettier passes, ESLint reports 0 errors and 157 pre-existing warnings. Local browser smoke testing confirmed no hero animation, a working overflow menu and Escape dismissal, and no console errors. |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/pages/ItemDetail/components/DetailPopover.test.tsx`:
- Around line 89-90: Update the DetailPopover controlled-close test to assert
that the dialog remains visible, not merely present in the document, after
onOpenChange(false). Also preserve the popover position while controlledOpen
remains true, clearing it only when the controlling owner actually closes the
popover.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c22da8af-0e99-456b-9a65-aa11919c9263
📒 Files selected for processing (11)
web/src/app.cssweb/src/hooks/queries/items.test.tsweb/src/hooks/queries/mediaSurfaceRefresh.test.tsweb/src/hooks/queries/mediaSurfaceRefresh.tsweb/src/hooks/queries/ratings.test.tsweb/src/hooks/queries/ratings.tsweb/src/pages/ItemDetail/DetailHero.tsxweb/src/pages/ItemDetail/components/ActionBar.tsxweb/src/pages/ItemDetail/components/DetailPopover.test.tsxweb/src/pages/ItemDetail/components/MediaUserActionBar.tsxweb/src/pages/ItemDetail/components/WatchedActionBar.tsx
💤 Files with no reviewable changes (1)
- web/src/pages/ItemDetail/DetailHero.tsx
🚧 Files skipped from review as they are similar to previous changes (8)
- web/src/hooks/queries/ratings.ts
- web/src/hooks/queries/mediaSurfaceRefresh.test.ts
- web/src/pages/ItemDetail/components/WatchedActionBar.tsx
- web/src/pages/ItemDetail/components/MediaUserActionBar.tsx
- web/src/hooks/queries/items.test.ts
- web/src/hooks/queries/mediaSurfaceRefresh.ts
- web/src/pages/ItemDetail/components/ActionBar.tsx
- web/src/app.css
- keep main's library-collection invalidation scope in the surface-refresh predicate - keep main's compositor-only hover classes and MediaActionIcon menu icons - adopt main's longest-entry overflow menu sizing - retarget the home refresh signal test at mediaSurfaceKeys.refreshSignal - align StarRating and ActionBar tests with the CSS-driven hover design
6ad4504 to
5023781
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
|
Rebased onto current main (
Validation: Rebase and reconciliation performed with Claude Code at the maintainer's request. |
Problem
No linked issue; this was reported and reproduced locally on movie and episode detail pages.
Opening or hovering the Version, Audio, Subs, rating, watched, favorite, and overflow controls could stall the main thread. Scrolling immediately after an action or while hovering these controls visibly dropped frames, and optimistic user-state changes triggered broad synchronous cache work.
Approach
Cold browser measurements while hovering and scrolling the seeded detail page reported a maximum frame of approximately 9.4 ms for Version, Audio, and Subs, with zero frames over 20 ms. Dropdown selection, Escape behavior, page-scroll dismissal, internal popup scrolling, overflow-menu navigation, and browser console output were also verified against the local server.
Screenshots are not included because this is a performance-focused change with no intentional layout redesign.
Testing
The six excluded frontend files fail identically on unchanged
mainin this local Node/jsdom environment because of the invalid built-inlocalStorage, missingResizeObserver, and an unrelated existing query invalidation assertion.make lintwas also run and reports 303 pre-existing Go lint findings; this PR changes no Go files. Relevant Go tests are therefore not applicable.AI Disclosure
Checklist
make lint,cd web && pnpm run lint,cd web && pnpm run format:check, and relevantgo test ./....The frontend commands and local-path verifier pass as described above. The repository-wide Go lint gate remains red on unchanged baseline findings, and no Go packages were modified.
Summary by CodeRabbit
New Features
Bug Fixes