Repository navigation
fix(core): prevent IS redirect hang and improve scroll restoration - #3437
Conversation
Segment facets sharing the productClusterIds key (e.g. an inclusion and an exclusion cluster) were collapsed into a single query param via a plain object, so the last one silently overwrote the others. The surviving value was then sent as a singular `productClusterId` query param, a shape Intelligent Search does not recognize — it expects each occurrence as a repeated path segment (productClusterIds/X/productClusterIds/not:Y/), same as any other facet. productClusterIds now flows through the existing extraFacets/path pipeline like other repeated facets, instead of through a single-value query param.
Set the base.jsonc $id from `vtex.faststore4` to `vtex.faststore` so it matches the base schema in the Schema Registry (published as [email protected]), which merchants pull by default via the toolbelt. Stop committing the generated cms/faststore/schema.json: it is produced by `vtex content generate-schema` and now lives in the Schema Registry, so it is treated as an autogen artifact and added to .gitignore.
Revert the removal of cms/faststore/schema.json and its .gitignore entry. The generated schema is kept committed as the quick reference / double-check source for the base CMS schema published to the Schema Registry ([email protected]). Regenerated via `vtex content generate-schema`.
Move Intelligent Search redirects out of render (SO-651) and harden PLP↔PDP scroll restore so back navigation lands on the product without footer flash or layout collapse under infinite scroll.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThe PR adds per-page gallery height preservation, deduplicated Intelligent Search redirects, and session-backed, anchor-aware scroll restoration. It also adds document cloaking styles during restoration. ChangesProduct listing stability
Estimated code review effort: 5 (Critical) | ~90 minutes Sequence Diagram(s)sequenceDiagram
participant ProductLink
participant Router
participant useScrollRestoration
participant sessionStorage
participant ProductGallery
ProductLink->>useScrollRestoration: capture listing position and PDP path
useScrollRestoration->>sessionStorage: save restoration data
ProductLink->>Router: navigate to product page
Router->>useScrollRestoration: notify route completion or popstate
useScrollRestoration->>ProductGallery: find product-card anchor
useScrollRestoration->>sessionStorage: read pending restoration data
useScrollRestoration->>ProductGallery: restore anchor or coordinates
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (7)
packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx (4)
83-85: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename the props type to
GalleryPageHeightLockProps.The coding guidelines require prop types named
{ComponentName}Props. Export the type so consumers can reuse it.Based on learnings from the coding guidelines: "TypeScript prop interfaces MUST be named
{ComponentName}Props".🤖 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 `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx` around lines 83 - 85, Rename the ProductGallery page height lock props type to the exported GalleryPageHeightLockProps, and update all references to the existing Props type in GalleryPageHeightLock accordingly.Source: Coding guidelines
152-158: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueCancel the pending animation frame in the cleanup function.
requestAnimationFrameruns after the effect can be cleaned up. It then measures a detached element and writes the result tosessionStorage. Store the handle and cancel it in the returned cleanup.🤖 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 `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx` around lines 152 - 158, Update the effect containing the requestAnimationFrame callback to store its returned handle, then cancel that pending frame in the effect’s cleanup before the element is detached. Preserve the existing height measurement, sessionStorage write via writeGalleryPageHeight, and setPendingMinHeight behavior when the frame executes.
99-103: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueThrottle the resize handler.
onResizeruns on every resize event and callssetViewport. The value only changes at bucket boundaries, but each call still schedules a render for every gallery page. Compare the new bucket with the current one before you set state, or debounce withrequestAnimationFrame.🔧 Proposed fix
- const onResize = () => setViewport(getGalleryViewportBucket()) + const onResize = () => { + const next = getGalleryViewportBucket() + setViewport((current) => (current === next ? current : next)) + }🤖 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 `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx` around lines 99 - 103, Throttle the resize handling in the GalleryPageHeightLock effect so setViewport is not invoked for every resize event. Update onResize to schedule at most one requestAnimationFrame callback at a time and compare the computed gallery viewport bucket with the current state before updating it; cancel any pending frame during effect cleanup while preserving the existing resize listener cleanup.
31-39: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winTruncating the serialized key can create collisions.
rawstarts withpath,termandsort, so a longselectedFacetslist is cut at 180 characters. Two different facet selections then map to the same key and one page reads the other page's height. Hash the full string instead of slicing it.🔧 Proposed fix
- return `__fs_gallery_page_h_${raw.replace(/\W/g, '_').slice(0, 180)}` + let hash = 0 + for (let i = 0; i < raw.length; i++) { + hash = (hash * 31 + raw.charCodeAt(i)) | 0 + } + return `__fs_gallery_page_h_${hash >>> 0}`🤖 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 `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx` around lines 31 - 39, Update the key generation logic around the raw serialized search state to hash the complete raw string instead of truncating it with slice(0, 180). Preserve the existing key prefix and ensure the full path, term, sort, selectedFacets, page, and viewport values contribute uniquely to the resulting key.packages/core/src/sdk/ui/useScrollRestoration.tsx (2)
390-407: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueThe PDP detection misses trailing slashes.
destinationPathnamedoes not normalize the path, so/product-slug/p/fails theendsWith('/p')test and the anchor is not saved.normalizePathalready removes the trailing slash. Apply it before the check here and at Line 417.🤖 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 `@packages/core/src/sdk/ui/useScrollRestoration.tsx` around lines 390 - 407, Update the PDP path checks in the onClickCapture handler and the corresponding logic around line 417 to pass destinationPathname(href) through normalizePath before testing for the /p suffix or comparing paths, ensuring trailing-slash PDP URLs are handled consistently.
102-119: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winScope the anchor lookup to reduce work during page load.
findAnchorCardrunsdocument.querySelectorAll('a[data-testid="product-link"], a[href*="/p"]')over the whole document. Thea[href*="/p"]part also matches unrelated links such as/promotions. TheMutationObserverat Line 261 observesdocument.bodywithsubtree: true, so this full-document query runs on every DOM mutation while the PLP hydrates and loads pages.Scope the query and the observer to the results container (
[data-fs-product-listing-results]) and drop the broadhref*="/p"selector, or keep it only as a fallback after thedata-testidquery returns nothing.Also applies to: 259-266
🤖 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 `@packages/core/src/sdk/ui/useScrollRestoration.tsx` around lines 102 - 119, Update findAnchorCard to query only within the [data-fs-product-listing-results] container and use the data-testid="product-link" selector instead of the broad href selector, returning null when the container is unavailable. Update the MutationObserver setup around the observer at lines 259-266 to observe that results container rather than document.body, while preserving subtree observation.packages/core/src/components/templates/SearchPage/SearchWrapper.tsx (1)
44-55: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueMoving the redirect into an effect is correct. Handle a rejected navigation.
void router.replace(...)discards the returned promise. If the navigation fails, the browser reports an unhandled rejection andlastRedirectedUrl.currentstays set, so no retry happens. Add acatchthat resets the ref.🔧 Proposed fix
lastRedirectedUrl.current = redirectUrl - void router.replace(redirectUrl) + router.replace(redirectUrl).catch(() => { + lastRedirectedUrl.current = null + })🤖 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 `@packages/core/src/components/templates/SearchPage/SearchWrapper.tsx` around lines 44 - 55, Update the redirect effect around router.replace so its rejected promise is caught and lastRedirectedUrl.current is reset to null, allowing a later retry while preserving the existing successful-navigation deduplication.
🤖 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 `@packages/core/src/components/ui/ProductGallery/ProductGallery.tsx`:
- Around line 162-174: Prevent hydration mismatches from client-only height
reads: in packages/core/src/components/ui/ProductGallery/ProductGallery.tsx
lines 162-174, gate reservedGalleryHeight behind a mounted flag or populate it
via state in an effect so the initial render returns 0; in
packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx lines
116-128, initialize pendingMinHeight to null and rely on the existing storageKey
effect to apply the stored height after mount.
In `@packages/core/src/sdk/ui/useScrollRestoration.tsx`:
- Around line 409-423: Update isSamePathNavigation in onRouteChangeStart to
compare normalized pathname values rather than using url.includes(currentPath).
Reuse the existing normalizePath and destinationPathname helpers, comparing the
normalized current pathname with the destination pathname so root and prefix
paths only match when they are actually equal.
---
Nitpick comments:
In `@packages/core/src/components/templates/SearchPage/SearchWrapper.tsx`:
- Around line 44-55: Update the redirect effect around router.replace so its
rejected promise is caught and lastRedirectedUrl.current is reset to null,
allowing a later retry while preserving the existing successful-navigation
deduplication.
In `@packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx`:
- Around line 83-85: Rename the ProductGallery page height lock props type to
the exported GalleryPageHeightLockProps, and update all references to the
existing Props type in GalleryPageHeightLock accordingly.
- Around line 152-158: Update the effect containing the requestAnimationFrame
callback to store its returned handle, then cancel that pending frame in the
effect’s cleanup before the element is detached. Preserve the existing height
measurement, sessionStorage write via writeGalleryPageHeight, and
setPendingMinHeight behavior when the frame executes.
- Around line 99-103: Throttle the resize handling in the GalleryPageHeightLock
effect so setViewport is not invoked for every resize event. Update onResize to
schedule at most one requestAnimationFrame callback at a time and compare the
computed gallery viewport bucket with the current state before updating it;
cancel any pending frame during effect cleanup while preserving the existing
resize listener cleanup.
- Around line 31-39: Update the key generation logic around the raw serialized
search state to hash the complete raw string instead of truncating it with
slice(0, 180). Preserve the existing key prefix and ensure the full path, term,
sort, selectedFacets, page, and viewport values contribute uniquely to the
resulting key.
In `@packages/core/src/sdk/ui/useScrollRestoration.tsx`:
- Around line 390-407: Update the PDP path checks in the onClickCapture handler
and the corresponding logic around line 417 to pass destinationPathname(href)
through normalizePath before testing for the /p suffix or comparing paths,
ensuring trailing-slash PDP URLs are handled consistently.
- Around line 102-119: Update findAnchorCard to query only within the
[data-fs-product-listing-results] container and use the
data-testid="product-link" selector instead of the broad href selector,
returning null when the container is unavailable. Update the MutationObserver
setup around the observer at lines 259-266 to observe that results container
rather than document.body, while preserving subtree observation.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: e53c273a-eebc-433f-84f7-2ac586f52cef
📒 Files selected for processing (7)
packages/core/src/components/product/ProductGrid/ProductGrid.tsxpackages/core/src/components/skeletons/ProductGridSkeleton/ProductGridSkeleton.tsxpackages/core/src/components/templates/SearchPage/SearchWrapper.tsxpackages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsxpackages/core/src/components/ui/ProductGallery/ProductGallery.tsxpackages/core/src/sdk/ui/useScrollRestoration.tsxpackages/core/src/styles/global/index.scss
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
Add unit/browser tests for SO-651 redirect behavior, scroll restore helpers, ProductGridSkeleton count, and GalleryPageHeightLock reserved heights so Sonar new-code coverage meets the 75% gate.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx (1)
132-135: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace the unchecked DOM type assertions.
querySelectorcan returnnull. Theas HTMLElementassertion hides that condition. Accessinglock.stylethen fails with a less usefulTypeError.
packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx#L132-L135: use a checked helper to get the height-lock element.packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx#L166-L169: use the same helper.Proposed change
+function getGalleryPageHeightLock(container: HTMLElement) { + const lock = container.querySelector<HTMLElement>( + '[data-fs-gallery-page-height-lock]' + ) + + if (lock === null) { + throw new Error('Expected gallery page height lock') + } + + return lock +} + - const lock = container.querySelector( - '[data-fs-gallery-page-height-lock]' - ) as HTMLElement + const lock = getGalleryPageHeightLock(container)As per path instructions, TypeScript files must avoid type assertions when possible.
🤖 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 `@packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx` around lines 132 - 135, Replace the unchecked HTMLElement assertions in both occurrences of the gallery height-lock lookup in GalleryPageHeightLock.browser.test.tsx (anchor lines 132-135 and sibling lines 166-169) with a shared checked helper that retrieves the [data-fs-gallery-page-height-lock] element and fails clearly when absent; use that helper before accessing style.minHeight at both sites.Source: Path instructions
packages/core/test/components/templates/SearchPage/SearchWrapper.browser.test.tsx (1)
87-115: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTest a changed redirect URL.
The test only verifies deduplication for the same URL. A boolean redirect guard would pass this test but would break the required once-per-distinct-URL behavior.
Change the mocked URL, rerender
SearchWrapper, and assert a secondrouter.replacecall with the new URL.Based on the provided
SearchWrapperruntime snippet,lastRedirectedUrlmust allow a new redirect URL.🤖 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 `@packages/core/test/components/templates/SearchPage/SearchWrapper.browser.test.tsx` around lines 87 - 115, The test should verify redirects occur once per distinct URL, not merely once overall. In the existing test around SearchWrapper, change the mocked redirect URL before rerendering, then assert router.replace was called a second time with the new URL; ensure the implementation tracks lastRedirectedUrl and permits a different URL while still deduplicating the original.
🤖 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.
Nitpick comments:
In
`@packages/core/test/components/templates/SearchPage/SearchWrapper.browser.test.tsx`:
- Around line 87-115: The test should verify redirects occur once per distinct
URL, not merely once overall. In the existing test around SearchWrapper, change
the mocked redirect URL before rerendering, then assert router.replace was
called a second time with the new URL; ensure the implementation tracks
lastRedirectedUrl and permits a different URL while still deduplicating the
original.
In
`@packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx`:
- Around line 132-135: Replace the unchecked HTMLElement assertions in both
occurrences of the gallery height-lock lookup in
GalleryPageHeightLock.browser.test.tsx (anchor lines 132-135 and sibling lines
166-169) with a shared checked helper that retrieves the
[data-fs-gallery-page-height-lock] element and fails clearly when absent; use
that helper before accessing style.minHeight at both sites.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 3a31c5b2-072b-404f-a6b9-792705bc8949
📒 Files selected for processing (5)
packages/core/src/sdk/ui/useScrollRestoration.tsxpackages/core/test/components/skeletons/ProductGridSkeleton.browser.test.tsxpackages/core/test/components/templates/SearchPage/SearchWrapper.browser.test.tsxpackages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsxpackages/core/test/sdk/ui/useScrollRestoration.browser.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/core/src/sdk/ui/useScrollRestoration.tsx
…ghts Compare normalized pathnames for same-route detection, and defer gallery height reads until after mount to avoid SSR/client mismatches.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
packages/core/src/sdk/ui/useScrollRestoration.tsx (3)
480-487: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winCancel active restoration when navigation fails.
onPopStatestartsscheduleRestore()before route completion. WhenrouteChangeErrorfires,onRouteChangeStartwas skipped becausependingPopRestorewas set. This handler clears flags but does not cancel the active retries orMutationObserver, so a failed navigation can continue callingscrollToon the current page. CallcancelRestore()before clearing the restoration state.Proposed fix
const onRouteChangeError = () => { + cancelRestore() pendingPopRestore = false endRestoringPaint()🤖 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 `@packages/core/src/sdk/ui/useScrollRestoration.tsx` around lines 480 - 487, Update onRouteChangeError to call cancelRestore() before clearing pendingPopRestore and ending the restoration paint, so failed navigation stops active retries and disconnects the MutationObserver before the restoration state is reset.
428-449: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winIgnore clicks that do not start an in-app navigation.
The capture listener also records PDP state for modified clicks, middle-clicks, external links, downloads, and links with a non-
_selftarget. These actions do not trigger the Next.js route events, so they can leave a stale anchor for the current history key. Filter these cases before callingsaveScrollPos.Proposed fix
const onClickCapture = (event: MouseEvent) => { if (pendingPopRestore) return if (!(event.target instanceof Element)) return + if ( + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) return const link = event.target.closest('a') if (!(link instanceof HTMLAnchorElement)) return + if ( + link.origin !== window.location.origin || + link.hasAttribute('download') || + (link.target && link.target !== '_self') + ) return🤖 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 `@packages/core/src/sdk/ui/useScrollRestoration.tsx` around lines 428 - 449, Update onClickCapture to call saveScrollPos only for unmodified primary-button clicks that use the _self target, point to an internal same-origin URL, and are not downloads; reject modified, middle-click, external, downloadable, and non-_self link activations before destinationPathname and saveScrollPos.
468-473: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUse the normalized pathname for the
/sguard.If
currentPathis/s/, the raw check does not skipresetInfiniteScroll(0). UsenormalizePath(currentPath) === '/s'.🤖 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 `@packages/core/src/sdk/ui/useScrollRestoration.tsx` around lines 468 - 473, Update the `/s` guard in the scroll restoration logic to compare `normalizePath(currentPath)` with `'/s'`, ensuring both `/s` and `/s/` skip `resetInfiniteScroll(0)`.
🤖 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.
Outside diff comments:
In `@packages/core/src/sdk/ui/useScrollRestoration.tsx`:
- Around line 480-487: Update onRouteChangeError to call cancelRestore() before
clearing pendingPopRestore and ending the restoration paint, so failed
navigation stops active retries and disconnects the MutationObserver before the
restoration state is reset.
- Around line 428-449: Update onClickCapture to call saveScrollPos only for
unmodified primary-button clicks that use the _self target, point to an internal
same-origin URL, and are not downloads; reject modified, middle-click, external,
downloadable, and non-_self link activations before destinationPathname and
saveScrollPos.
- Around line 468-473: Update the `/s` guard in the scroll restoration logic to
compare `normalizePath(currentPath)` with `'/s'`, ensuring both `/s` and `/s/`
skip `resetInfiniteScroll(0)`.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ad454cdc-5a01-420a-8ee6-033774e280fc
📒 Files selected for processing (5)
packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsxpackages/core/src/components/ui/ProductGallery/ProductGallery.tsxpackages/core/src/sdk/ui/useScrollRestoration.tsxpackages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsxpackages/core/test/sdk/ui/useScrollRestoration.browser.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- packages/core/test/sdk/ui/useScrollRestoration.browser.test.ts
- packages/core/test/components/ui/ProductGallery/GalleryPageHeightLock.browser.test.tsx
- packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx
- packages/core/src/components/ui/ProductGallery/ProductGallery.tsx
Use globalThis instead of window, replaceAll for key sanitization, and a positive SSR guard so the quality gate stops flagging the new issues.
renatomaurovtex
left a comment
There was a problem hiding this comment.
Reviewed the full diff plus _app.tsx gating and the i18n config. The SearchWrapper root-cause fix (render-time router.replace re-firing on every state update) is correct and well tested, the scroll-restoration rewrite is a big but coherent state machine, and the 665-line test suite covering each helper is genuinely appreciated. useScrollRestoration stays gated behind experimental.scrollRestoration; the gallery/skeleton changes apply to everyone but are strict CLS improvements.
packages/core/src/sdk/ui/useScrollRestoration.tsx
🟠 The /s check misses locale-prefixed search paths. localization.enabled turns on Next i18n (see next.config.js), so on non-default-locale paths location.pathname is /en/s, not /s — the skip-reset guard never fires there and the SO-651 redirect race this PR fixes can persist on localized bindings. router.pathname is the locale-agnostic route and router is already in scope:
- if (currentPath === '/s') return
+ if (router.pathname === '/s') return(routeChangeStart fires before the route updates, so router.pathname is still the page being left.)
🟡 A stale anchor beats fresh coordinates. saveScrollPos(undefined) preserves a previously saved anchor for the history entry (meant for duplicate routeChangeStart), but it also survives PLP → non-PDP navigations, and onClickCapture saves an anchor for clicks that never navigate (cmd/ctrl+click, middle-click, preventDefaulted). Scenario: open product A, come back, scroll somewhere else, leave via a menu link, press Back — restoreByAnchor wins and centers product A instead of the user's actual last position. Suggest (a) only carrying prev.anchor forward when the navigation target is a PDP, and (b) bailing early in onClickCapture:
const onClickCapture = (event: MouseEvent) => {
if (pendingPopRestore) return
+ if (event.defaultPrevented || event.button !== 0) return
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
if (!(event.target instanceof Element)) returnpackages/core/src/styles/global/index.scss
🟡 body { opacity: 0 } keeps an invisible page interactive. Under the cloak the page still hit-tests and stays in the accessibility tree, and the safety timeout is 3.5s — on a slow connection a user can click invisible links or have a screen reader announce content mid-jump. visibility: hidden removes both while still preventing the footer flash; alternatively shorten RESTORING_PAINT_TIMEOUT_MS.
html.fs-restoring-scroll {
overflow-x: hidden;
body {
- opacity: 0;
+ visibility: hidden;
}
}packages/core/src/components/templates/SearchPage/SearchWrapper.tsx
💬 The old call was router.replace(url, null, { shallow: true }); the new effect drops shallow. Cross-page replaces were never actually shallow, so this looks like an accidental improvement rather than a regression — just confirm it's intentional (the redirect target does need its getStaticProps data).
packages/core/src/components/ui/ProductGallery/GalleryPageHeightLock.tsx
💬 The measurement effect lists children in its deps, so both observers disconnect/reconnect on every parent render. The comment explains why (jsdom/CI reliability), and the setState calls bail on equal values, so this is acceptable — flagging only in case gallery renders become hot.
Verdict: Approved with comments
Blocking (🔴/🟠):
- 🟠
/sguard vs locale-prefixed paths — one-line fix (router.pathname), please address before merge since it re-opens SO-651 exactly where localization is on.
Non-blocking (🟡/💬):
- 🟡 Stale-anchor-over-coordinates edge + modified-click guard in
onClickCapture. - 🟡
opacity: 0cloak keeps the page interactive/AT-visible for up to 3.5s → prefervisibility: hidden. - 💬 Confirm dropping
shallow: trueon the redirect replace. - 💬 Observer churn on
childrendep in GalleryPageHeightLock.
Checks to confirm before merge: pnpm turbo run test --filter=@faststore/core · build · pnpm size (core touched) · manual pass of the 5 test steps with scrollRestoration: true on a localized binding as well
| page, | ||
| viewport: search.viewport ?? getGalleryViewportBucket(), | ||
| }) | ||
| return `__fs_gallery_page_h_${raw.replaceAll(/\W/g, '_').slice(0, 180)}` |
There was a problem hiding this comment.
Como page e viewport são as últimas chave do objeto, cortar em 180 pode acabar truncando essa parte importante da key.
Esse cenário aqui por ex:
path: "/eletronicos/celulares-e-smartphones"
sort: "score_desc"
selectedFacets: [brand=samsung, price=1000-to-2000]
Com 2 facets (201 chars), mobile e desktop geram a mesma chave.
Dúvida, como chegamos nesse 180 ? Será que vale aumentar? Ou reordenar a lista de chaves aqui por prioridade ?
There was a problem hiding this comment.
Boa captura — o 180 era arbitrário da 1ª versão e no teu exemplo (path longo + 2 facets) o slice realmente derrubava page/viewport, colidindo mobile↔desktop.
Em 9e98043 passei a hashear o payload completo e mantive page/viewport no prefixo só pra debug:
__fs_gallery_page_h_p{page}_{viewport}_{hash}
Assim path/facets longos não truncam mais nada discriminante. Também cobri o cenário no teste do HeightLock.
Use router.pathname for the /s reset guard so locale-prefixed search paths still skip resetInfiniteScroll, stop carrying stale PDP anchors on non-PDP exits, ignore modified clicks when saving anchors, and cloak restore with visibility:hidden instead of opacity:0.
|
@renatomaurovtex thanks for the review — addressed in a5fe6a3:
Also added coverage for locale-prefixed |
Long PLP paths with multiple facets exceeded the 180-char sanitized key limit and dropped page/viewport, so mobile and desktop (and adjacent pages) could share the same sessionStorage height entry.
Use Math.trunc and String#codePointAt instead of | 0 / charCodeAt.
PDP → home was calling resetInfiniteScroll(0) and wiping in-memory pages while sessionStorage still held [0,1,2] for the PLP. Back then scrolled to the saved Y with only page 0 mounted, leaving the viewport in empty reserved height near the footer. Skip reset when leaving PDPs and rehydrate pages from sessionStorage before scroll restore.
Satisfies Sonar preference for String#replaceAll over replace with a global regex.
Remove the /s and PDP leave guards that leaked Zustand pages into the next PLP when scrollRestoration is on. Back-nav still rehydrates pages from pathname-keyed sessionStorage; SO-651 stays covered by SearchWrapper.
|
renatomaurovtex
left a comment
There was a problem hiding this comment.
Follow-up on the commits since my last review (a5fe6a35…249226a3). All prior points were addressed — thanks — and the new pieces check out, with one gap in the new rehydration flow.
Verified on head:
pendingPopRestoreearly-return inonRouteChangeStartprotects the just-rehydrated pages from the unconditionalresetInfiniteScroll(0)on back-nav.- The synchronous
addNextPage()loop inrestoreInfiniteScrollPagesis safe: the SDK store actions read fresh state via zustandget(), so there's no stale-closure batching. hashGalleryPageHeightKeyfix is sound — keepingp{page}_{viewport}in the prefix means even a 32-bit hash collision can't cross page/viewport buckets, so the mobile↔desktop collision @lemagnetic found is structurally gone.- New tests cover the
/sguard removal (incl. locale-prefixed/s), stale-anchor clearing, modified clicks, and popstate rehydration. Nice.
🟡 [bug] PLP → non-PDP → Back still loses infinite-scroll pages
restoreInfiniteScrollPages only helps PDP round-trips. The SDK's setPagesSessionStorage keys on window.location.pathname at call time, and onRouteChangeStart fires while the URL is still the departing page — so resetInfiniteScroll(0) persists [0] under the departing PLP's key, destroying the rehydration source.
- PDP → anywhere: reset writes
[0]under the PDP's (irrelevant) key → PLP key survives → Back works ✓ - PLP (pages
[0,1,2]) → home/about/another PLP: reset writes[0]under the PLP's own key → Back restores saved coords (y is still saved viasaveScrollPos(undefined)) with only page 0 mounted → viewport lands in empty reserved height / near the footer — the exact symptom described inrestoreInfiniteScrollPages's doc comment, still live for this flow.
Minimal core-side fix — snapshot the departing key around the reset:
+ // resetInfiniteScroll persists [0] under the *departing* pathname —
+ // preserve the listing's pages so back-nav rehydration still works.
+ const departingKey = infiniteScrollPagesStorageKey()
+ let snapshot: string | null = null
+ try {
+ snapshot = departingKey ? sessionStorage.getItem(departingKey) : null
+ } catch {}
resetInfiniteScroll(0)
+ if (departingKey && snapshot) {
+ try {
+ sessionStorage.setItem(departingKey, snapshot)
+ } catch {}
+ }Cleaner long-term: an opt-out on the SDK action (resetInfiniteScroll(page, { persist: false })), but the snapshot keeps this PR self-contained.
💬 [maintainability] SDK storage-key derivation duplicated in core
infiniteScrollPagesStorageKey() re-implements useSearchState.ts's __fs_gallery_page_ + pathname.replace(/\W/g,'_') derivation. They match today, but if the SDK key ever changes shape (e.g. to include facets/sort — plausible given the height-lock collision discussion), core's rehydration silently stops finding data. Consider exporting a getInfiniteScrollStorageKey() from @faststore/sdk (core → sdk is the allowed dependency direction) so there's one source of truth.
Verdict: Approved with comments
Blocking (🔴/🟠):
- None.
Non-blocking (🟡/💬):
- 🟡 PLP → non-PDP → Back loses pages (departing-key wipe) — quick win ⚡
- 💬 export the storage-key builder from the SDK instead of duplicating
Checks to confirm before merge: pnpm lint · build · core browser tests · pnpm size (core)
…-LD (#3508) ## What Puts `StoreProduct.releaseDate` back to the raw value Intelligent Search returns. The ISO 8601 normalization added in #3465 now runs only where the PDP builds its `application/ld+json`. | | Before (4.7.0 – 4.8.x) | After | |---|---|---| | `StoreProduct.releaseDate` (GraphQL) | `"2026-03-23"` | `"1774224000000"`, as returned upstream (same as before 4.7.0) | | PDP JSON-LD `releaseDate` | `"2026-03-23"` | `"2026-03-23"`, unchanged | ## Why #3465 (SO-666) needed an ISO date in the structured data, but it did the normalization in the API resolver. That changed the field's format for everyone who reads it, and store customizations that parse the epoch-ms value broke. Search & Recommendation reported this as a bug against FS 4.8.0, related feature ELOR-5408. The change first shipped in 4.7.0. The JSON-LD is the only consumer that needs ISO, and it is built in `@faststore/core`, so the conversion now lives there. ## Changes - **`@faststore/api`**: the resolver returns `releaseDate ?? ''` again, and `utils/releaseDate.ts` is removed. The schema description no longer says ISO 8601, because upstream doesn't guarantee that format. The type stays `String!`. - **`@faststore/core`**: the normalizer moves to `src/utils/productJsonLd.ts` as `toProductJsonLdReleaseDate`, next to `toProductJsonLdOffer`. `p.tsx` applies it only to `ProductJsonLd`. Its behavior is unchanged: epoch ms or seconds and ISO strings become a UTC calendar day, and empty or unparseable input gives `''`. - **Generated**: `__generated__/schema.ts` and `@generated/graphql.ts` were regenerated with codegen. Only the description text changed. ## Notes for review - **Behavior change**: this reverts the format change from 4.7.0. A store that already adapted to ISO on 4.7 or 4.8 gets epoch ms again. That seems unlikely, since the ISO format was out for about a month and the epoch format had been the contract since #1438, but it should go in the changelog. - **Hotfix to `main`**: this targets `main` directly, following the precedent of #3437 (4.5.1), so it ships as **4.9.1** without waiting for the next `dev → main` graduation. It should be back-merged into `dev` afterwards. There are no 4.7.x/4.8.x maintenance branches, so stores on 4.7 or 4.8 get the fix by bumping to 4.9.1. ## Testing - `packages/api`: the resolver tests pass (25). The new `releaseDate` tests check that epoch ms and ISO values come through unchanged and that null or undefined give `''`. - `packages/core`: `productJsonLd.test.ts` and `productJsonLdRendering.test.tsx` pass (37). This includes the 13 normalizer cases that moved over from the API. - `tsc --noEmit` reports no errors in `src` for either package, and Biome is clean. - [ ] Render the reported SKU through `ci/codesandbox`. Check that a customization reading `releaseDate` gets epoch ms and that the JSON-LD still passes the Google Rich Results Test. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Improvements** * Product data now returns catalog-provided release dates unchanged, or an empty string when no value is available. * Structured product metadata converts interpretable release dates to UTC dates and omits missing or invalid dates. * Structured metadata supports release dates provided as epoch milliseconds, epoch seconds, or ISO 8601 strings. * Empty product identifiers are omitted from structured metadata. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
## What's the purpose of this pull request? Backport the Intelligent Search redirect fix from [#3437](#3437), released in FastStore 4.6.0, to the 3.x branch. When search redirects interact with scroll restoration, calling router.replace during rendering can trigger an infinite render and redirect loop, freezing the UI. Version 3.x still contained this behavior. This behavior is causing the UI to freeze in production stores that are still using version 3.x, whenever an IS redirect is employed. ## How it works? This PR replicates exactly the SearchWrapper.tsx implementation introduced in #3437: - Moves router.replace into a useEffect. - Uses a useRef to track the last redirected URL and prevent repeated redirects to the same destination. - Removes the shallow: true option, matching the original fix. - Preserves the empty search UI while the redirect takes place. ## How to test it? - Install this branch's @faststore/core package in a store using FastStore 3.x. - Configure an Intelligent Search redirect in VTEX Admin for a specific search term. Path: `/admin/search/v4/redirects` - With scroll restoration enabled, load additional search result pages, then search for the configured term. - Verify that the store navigates to the configured destination without freezing or entering a redirect loop. - Repeat the search flow and confirm that redirects continue to work. - Search for a term without a configured redirect and confirm that regular results and infinite scrolling still work. Local validation completed: Biome and git diff --check passed. Store validation is pending. ### Starters Deploy Preview Pending. ## References [#3437 — fix(core): prevent IS redirect hang and improve scroll restoration](#3437): original fix in FastStore 4.x. This PR replicates its SearchWrapper.tsx changes exactly in 3.x. ## Checklist **PR Title and Commit Messages** - [x] PR title and commit messages follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification - Available prefixes: `feat`, `fix`, `chore`, `docs`, `style`, `refactor`, `ci` and `test` **PR Description** - [ ] Added a label according to the PR goal - `breaking change`, `bug`, `contributing`, `performance`, `documentation`.. **Dependencies** - [ ] Committed the `pnpm-lock.yaml` file when there were changes to the packages **Documentation** - [x] PR description - [ ] For documentation changes, ping `@Mariana-Caetano` to review and update (Or submit a doc request)

0 New Issues
0 Fixed Issues
0 Accepted Issues
What's the purpose of this pull request?
Fixes SO-651: with
experimental.scrollRestoration: true, Intelligent Search redirects could loop/router.replaceduring render until the tab hung. Also hardens PLP ↔ PDP back navigation so scroll restoration lands on the product without footer flash or infinite-scroll layout collapse.How it works?
SO-651 — Intelligent Search redirect hang
SearchWrapper: movesrouter.replaceinto auseEffect(with a ref guard) instead of calling it during render. Render-time replace re-fired on every state update (e.g.resetInfiniteScroll) and looped.useScrollRestoration: skipsresetInfiniteScroll(0)when leaving/s, so IS client redirects are not raced by a search-state reset.Scroll restoration UX (PLP → PDP → back)
routeChangeStart.popstate+routeChangeCompletewith retries /MutationObserverwhile infinite-scroll pages mount.[data-fs-product-card]into view (not only rawscrollY/ tiny title link).popstate+routeChangeCompletedo not cancel each other.html.fs-restoring-scrollso the footer does not flash at the top before the viewport jumps to the saved card.Gallery CLS / height stability
SuspenseinProductGalleryso a refetch on page N does not unmount pages that already have data.ProductGridSkeletoncount={itemsPerPage}so skeletons match page size.GalleryPageHeightLock: reserves last-measured page height while skeletons show; releases the lock once product cards mount (so viewport resize cannot leave huge gaps); keys heights by viewport bucket (mobile/tablet/notebook/desktop).minHeightwhile products are still loading.How to test it?
experimental.scrollRestoration: truelocally (do not commit that default flip).storeframework, termrefil→/office), search that term with the flag on — navigation should complete without hanging / console replace loops.Starters Deploy Preview
References
experimental.scrollRestorationChecklist
PR Title and Commit Messages
feat,fix,chore,docs,style,refactor,ciandtestPR Description
breaking change,bug,contributing,performance,documentation..Dependencies
pnpm-lock.yamlfile when there were changes to the packages (N/A — no lockfile changes)Documentation
@Mariana-Caetanoto review and update (Or submit a doc request)Made with Cursor
Summary by CodeRabbit
Bug Fixes
Enhancements