From 10d92981d47417765a25afe20eada56a233e94e6 Mon Sep 17 00:00:00 2001 From: codexy Date: Thu, 26 Nov 2026 11:28:58 +0900 Subject: [PATCH] perf: respect Next config, observe only layout changes - withStackflow sets cacheComponents and partialPrefetching only when the app's config leaves them unset. It used to overwrite an explicit false, forcing a Cache Components migration. A production build without them still animates push and Back and restores scroll; only screen state resets, as in plain Next.js. - The track observers watch class, style, hidden and data-stackflow-fixed-key only. Thirty aria-pressed/data-state toggles caused 90 getBoundingClientRect and 90 getComputedStyle calls; now 0. - The track writes styles only when a value changes. - Scroll capture reads only scrollTop on each scroll event; the range is clamped by the browser on restore. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +++++++++++ docs/REFERENCE.md | 12 +++++++----- src/next/config.ts | 15 +++++++++++++-- src/next/engine.ts | 8 ++++---- src/next/scroll.ts | 21 +++++++++++++++------ test/next/config.test.ts | 16 ++++++++++++++++ test/next/scroll.test.ts | 35 +++++++++++++++++++++++++++++++++++ 7 files changed, 101 insertions(+), 17 deletions(-) create mode 100644 test/next/config.test.ts diff --git a/README.md b/README.md index 52e5323..66d1757 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,17 @@ One maintainer, no known production users, not tested on real devices. Compared - This package fits an app-like Next.js site that wants swipe Back, per-entry scroll and a scrollbar that respects its fixed header and tab bar together. - iOS Safari uses the same left edge for its own Back gesture; how the two interact has not been checked on a device. +## Next.js compatibility + +Checked against the code and a production build (November 2026): + +- Server Components and SSR are untouched: `StackflowProvider` is a Client Component that renders its children as passed, and the only `useSearchParams` call sits in its own ``, so no route falls back to client rendering. +- `StackLink` renders `next/link` and only intercepts `onNavigate`, so prefetching and RSC payloads work as with plain links. +- `withStackflow` turns on Cache Components only when your config does not set it. Without it, transitions, swipe Back and scroll restoration still work; screen state resets on Back as in plain Next.js. +- The document stays the scroller; `window.scrollTo`, `scrollY` and scroll events are unchanged. +- Client JavaScript, all exports bundled, minified and gzipped: about 31.5 KB (OverlayScrollbars 15.3 KB, `@stackflow/core` 6.0 KB, this package about 10 KB). The same measurement for `@ssgoi/react` with its view-transitions entry gives 44.0 KB. CSS adds 5.2 KB gzipped. +- Only layout-relevant DOM changes (`class`, `style`, `hidden`) make it re-measure the scrollbar track; UI state attributes such as `aria-*` or `data-state` do not. + ## Install ```sh diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 8e56028..5f10dd1 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -33,11 +33,13 @@ import { withStackflow } from '@uiwwsw/stackflow-next/config'; export default withStackflow({}); ``` -The helper enables Next.js `cacheComponents` and `partialPrefetching`. This is -what preserves actual React component state and DOM across supported client -navigations. Retention belongs to Next, not to a second router or a private -router-context workaround. Existing applications must follow Next's Cache -Components migration requirements, including Suspense around request-time data. +The helper turns on Next.js `cacheComponents` and `partialPrefetching` unless +your config already sets them. Cache Components is what preserves React +component state and DOM across client navigations; retention belongs to Next, +not to a second router. It also changes how the app renders, so an app that has +not migrated (for example one using the `runtime` segment config) can pass +`withStackflow({ cacheComponents: false })`. Slide transitions, swipe Back and +scroll restoration work either way; only screen state resets on Back. See [Next's state preservation guide](https://nextjs.org/docs/app/guides/preserving-ui-state). ```tsx diff --git a/src/next/config.ts b/src/next/config.ts index f107bd8..524fa0d 100644 --- a/src/next/config.ts +++ b/src/next/config.ts @@ -1,5 +1,16 @@ import type { NextConfig } from 'next'; -/** Enable Next's supported Activity route retention; no private router contexts. */ +/** + * Turns on Next.js Cache Components and Partial Prefetching unless the config + * already sets them. Cache Components keeps hidden routes mounted with React + * , which is what preserves screen state on Back. Transitions, + * swipe Back and scroll restoration work without it; pass + * `cacheComponents: false` for an app that has not migrated to Cache + * Components (for example one that uses the `runtime` segment config). + */ export function withStackflow(config: NextConfig = {}): NextConfig { - return {...config, cacheComponents: true, partialPrefetching: true}; + return { + ...config, + cacheComponents: config.cacheComponents ?? true, + partialPrefetching: config.partialPrefetching ?? true, + }; } diff --git a/src/next/engine.ts b/src/next/engine.ts index ba220f9..5d94641 100644 --- a/src/next/engine.ts +++ b/src/next/engine.ts @@ -329,13 +329,13 @@ export class NavigationEngine { } capture(element = this.scrollElement()) { if (!this.current || !element) return; - const offset = element.scrollTop; - this.current.scroll = this.isWindowScroll(element) - ? Math.max(0, Math.min(element.scrollHeight - element.clientHeight, offset)) : offset; + // Runs on every scroll event: read only the offset. Elastic overscroll is + // clamped when the offset is restored. + this.current.scroll = element.scrollTop; } restoreScroll(element = this.scrollElement()) { if (!this.options.preserveScroll || !element) return; - const top = this.current?.scroll ?? 0; + const top = Math.max(0, this.current?.scroll ?? 0); if (this.isWindowScroll(element)) { if (this.win.scrollY !== top) this.win.scrollTo({ top, behavior: 'instant' }); } diff --git a/src/next/scroll.ts b/src/next/scroll.ts index 5d2ac90..9617982 100644 --- a/src/next/scroll.ts +++ b/src/next/scroll.ts @@ -5,6 +5,9 @@ const targetAttribute = 'data-stackflow-scroll-target'; const delegatedAttribute = 'data-stackflow-scroll-delegated'; const nativeScrollbarAttribute = 'data-stackflow-native-scrollbar-hidden'; const sourceAttribute = 'data-stackflow-scroll-source'; +// Only attributes that can move or resize the track are observed, so UI state +// attributes (aria-*, data-state and the like) never cause layout reads. +const layoutAttributes = ['class', 'style', 'hidden', 'data-stackflow-fixed-key']; type ScrollBounds = { top: number; right: number; bottom: number; left: number }; type ScrollbarOrigin = { top: number; right: number } | { viewportRight: number }; @@ -149,6 +152,10 @@ export function previewScrollElement(content: HTMLElement) { * Returns true when the slot's containing block moves with the document, * which means the track must be placed again after each document scroll. */ +function setStyle(element: HTMLElement, property: string, value: string) { + if (element.style.getPropertyValue(property) !== value) element.style.setProperty(property, value); +} + function placeTrack(slot: HTMLElement, track: ScrollBounds, origin: ScrollbarOrigin) { const trackHeight = track.bottom - track.top; // Each drawn bar hides itself when its axis does not overflow, so the slot @@ -169,11 +176,12 @@ function placeTrack(slot: HTMLElement, track: ScrollBounds, origin: ScrollbarOri // Track geometry is in viewport pixels. CSS lengths are scaled again by // the slot's effective zoom, including when inherited from an ancestor. const zoom = slot.currentCSSZoom || 1; - slot.style.height = `${trackHeight / zoom}px`; + // Write only what changed: an unchanged track costs no style invalidation. + setStyle(slot, 'height', `${trackHeight / zoom}px`); // The horizontal bar runs along the bottom of the track, leftward from its right edge. - slot.style.setProperty('--stackflow-track-width', `${(track.right - track.left) / zoom}px`); - slot.style.right = `${(originRight - track.right) / zoom}px`; - slot.style.transform = `translateY(${(track.top - originTop) / zoom}px)`; + setStyle(slot, '--stackflow-track-width', `${(track.right - track.left) / zoom}px`); + setStyle(slot, 'right', `${(originRight - track.right) / zoom}px`); + setStyle(slot, 'transform', `translateY(${(track.top - originTop) / zoom}px)`); return !!parent; } @@ -445,7 +453,7 @@ export function attachWindowScroll(content: HTMLElement, selector: string | unde resize.observe(content); resize.observe(doc.body); if (provider) for (const slot of provider.children) resize.observe(slot); - mutation.observe(provider ?? content, { subtree: true, childList: true, attributes: true }); + mutation.observe(provider ?? content, { subtree: true, childList: true, attributes: true, attributeFilter: layoutAttributes }); win.addEventListener('scroll', scrolled, { capture: true, passive: true }); win.addEventListener('resize', invalidate); viewport?.addEventListener('resize', schedule); @@ -570,7 +578,8 @@ export function attachScrollViewport( } resize.observe(content); - mutation.observe(content.closest('.stackflow-next') ?? content, { subtree: true, childList: true, characterData: true, attributes: true }); + // Size changes of the scroller itself arrive through the ResizeObserver. + mutation.observe(content.closest('.stackflow-next') ?? content, { subtree: true, childList: true, attributes: true, attributeFilter: layoutAttributes }); content.addEventListener('load', invalidate, true); win.addEventListener('resize', invalidate); getElement(); diff --git a/test/next/config.test.ts b/test/next/config.test.ts new file mode 100644 index 0000000..a229bd1 --- /dev/null +++ b/test/next/config.test.ts @@ -0,0 +1,16 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { withStackflow } from '../../src/next/config.ts'; + +test('withStackflow turns on Cache Components and Partial Prefetching by default', () => { + const config = withStackflow({ basePath: '/app' }); + assert.equal(config.cacheComponents, true); + assert.equal(config.partialPrefetching, true); + assert.equal(config.basePath, '/app'); +}); + +test('withStackflow keeps values the app sets', () => { + const config = withStackflow({ cacheComponents: false, partialPrefetching: false }); + assert.equal(config.cacheComponents, false); + assert.equal(config.partialPrefetching, false); +}); diff --git a/test/next/scroll.test.ts b/test/next/scroll.test.ts index d8e69b0..6233b93 100644 --- a/test/next/scroll.test.ts +++ b/test/next/scroll.test.ts @@ -308,3 +308,38 @@ test('the track stays available for a horizontal-only overflow and exposes its w controller.dispose(); } }); + +test('UI state attributes do not schedule a layout pass', async t => { + const win = new Window(); + const root = win.document.documentElement; + Object.defineProperties(root, { + clientHeight: { value: 700 }, clientWidth: { value: 400 }, scrollHeight: { value: 1400 }, + }); + Object.defineProperty(win, 'visualViewport', { value: undefined }); + Object.defineProperty(win, 'scrollY', { get: () => 0 }); + let paint: FrameRequestCallback; + let scheduled = 0; + t.mock.method(win, 'requestAnimationFrame', (callback: FrameRequestCallback) => { paint = callback; scheduled++; return 1; }); + win.document.body.innerHTML = ` +
`; + const content = win.document.querySelector('.stackflow-next-content')! as unknown as HTMLElement; + const slot = content.nextElementSibling as HTMLElement; + const button = content.querySelector('button')!; + const { factory } = recordScrollbars(); + const controller = attachWindowScroll(content, undefined, () => {}, slot, [], false, factory); + const settle = () => new Promise(resolve => setTimeout(resolve, 0)); + try { + paint!(0); + await settle(); + const before = scheduled; + button.setAttribute('aria-pressed', 'true'); + button.setAttribute('data-state', 'open'); + await settle(); + assert.equal(scheduled, before); + button.setAttribute('style', 'height:40px'); + await settle(); + assert.equal(scheduled, before + 1); + } finally { + controller.dispose(); + } +});