Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<Suspense>`, 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
Expand Down
12 changes: 7 additions & 5 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 13 additions & 2 deletions src/next/config.ts
Original file line number Diff line number Diff line change
@@ -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
* <Activity>, 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,
};
}
8 changes: 4 additions & 4 deletions src/next/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
}
Expand Down
21 changes: 15 additions & 6 deletions src/next/scroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down Expand Up @@ -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
Expand All @@ -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;
}

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down
16 changes: 16 additions & 0 deletions test/next/config.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
35 changes: 35 additions & 0 deletions test/next/scroll.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `
<div class="stackflow-next"><div><div class="stackflow-next-content"><button>toggle</button></div><div hidden></div></div></div>`;
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();
}
});
Loading