From 6c5731b810d7b0f3f266b72ee7923a28384c9db3 Mon Sep 17 00:00:00 2001
From: codexy
Date: Fri, 27 Nov 2026 10:46:24 +0900
Subject: [PATCH] feat: support Next.js 13.4+ and React 18.2+
StackLink handles the click itself instead of Link's onNavigate (Next.js
15.3+), StackLink and StackMotion forward refs on React 18, inert renders
in the form each React version accepts, and withStackflow only adds the
Cache Components and Partial Prefetching keys on Next.js versions that
know them. Top-level types and typesVersions let older TypeScript module
resolution find the declarations.
Co-Authored-By: Claude Opus 5.5
---
README.md | 8 ++++----
docs/ARCHITECTURE.md | 8 +++++---
docs/REFERENCE.md | 2 +-
package-lock.json | 6 +++---
package.json | 18 ++++++++++++++---
src/next/config.ts | 37 +++++++++++++++++++++++++---------
src/next/index.tsx | 22 +++++++++++++-------
src/next/motion.tsx | 15 +++++++++-----
src/next/react-compat.ts | 31 ++++++++++++++++++++++++++++
test/next/config.test.ts | 10 +++++++++
test/next/react-compat.test.ts | 30 +++++++++++++++++++++++++++
11 files changed, 151 insertions(+), 36 deletions(-)
create mode 100644 src/next/react-compat.ts
create mode 100644 test/next/react-compat.test.ts
diff --git a/README.md b/README.md
index 8060f08..922426c 100644
--- a/README.md
+++ b/README.md
@@ -9,8 +9,8 @@
-
-
+
+
@@ -61,7 +61,7 @@ Not made by or affiliated with the [Stackflow](https://github.com/daangn/stackfl
- No state retention of its own. State survives only while Next.js keeps the route, and not across a reload.
- No fallback animation. Browsers without View Transitions use ordinary navigation.
- The swipe preview is a DOM clone; canvas, video and embedded content may differ.
-- Next.js below 16.4.6 and React below 19.3.1 are untested.
+- Next.js 13 to 15 do not keep ordinary component state on Back; that needs Cache Components in Next.js 16. `useStackState` works on every version.
- No benchmarks against other libraries.
- No physics or spring animation. Motion is CSS and the Web Animations API.
- The drawn scrollbar no longer shrinks during elastic overscroll; `edgeBounce` still compresses it.
@@ -72,7 +72,7 @@ Not made by or affiliated with the [Stackflow](https://github.com/daangn/stackfl
npm install @uiwwsw/stackflow-next
```
-Requires Next.js 16.4.6 or later and React 19.3.1 or later.
+Works with Next.js 13.4 or later (App Router) and React 18.2 or later. Builds and navigation were checked on Next.js 13.4, 13.5, 14.2, 15.1, 15.5, 16.0 and 16.4 with React 18.2, 18.3, 19.0, 19.2 and 19.3.
```js
// next.config.mjs
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 4cc246e..4e9b69b 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -150,9 +150,11 @@ The `./dom` entry has no dependencies.
## Limits
-- Needs Next.js 16.4.6 or later and React 19.3.1 or later; versions below
- that are not tested.
-- State retention depends on Next.js Cache Components and can be evicted by
+- Needs Next.js 13.4 or later (App Router) and React 18.2 or later.
+ `withStackflow` adds `cacheComponents` only on Next.js 16 and
+ `partialPrefetching` only on 16.3 or later; older versions get the config
+ back unchanged.
+- State retention depends on Next.js 16 Cache Components and can be evicted by
Next; it does not survive a reload.
- The page slide uses View Transitions. Browsers without
them navigate normally.
diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md
index 5f10dd1..94111cc 100644
--- a/docs/REFERENCE.md
+++ b/docs/REFERENCE.md
@@ -454,7 +454,7 @@ reloads, and links activated before hydration follow browser navigation. Only sa
HTTP(S) destinations are supported by the router helper. Ordinary Next Links
still work but forward snapshot motion requires StackLink or useStackRouter.
-The current version targets Next.js 16.4.6+, React 19.3.1+ and Stackflow core 3.1.0.
+The current version supports Next.js 13.4+ (App Router), React 18.2+ and Stackflow core 3.1.0. On Next.js 13 to 15, ordinary component state is not kept on Back; `useStackState` is.
Parallel/intercepting routes and real-device mobile gestures are not yet certified.
## Other options
diff --git a/package-lock.json b/package-lock.json
index f48a664..2ee3ed7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -27,9 +27,9 @@
"node": ">=20.9.0"
},
"peerDependencies": {
- "next": "^16.4.6",
- "react": "^19.3.1",
- "react-dom": "^19.3.1"
+ "next": "^13.4.0 || ^14.0.0 || ^15.0.0 || ^16.0.0",
+ "react": "^18.2.0 || ^19.0.0",
+ "react-dom": "^18.2.0 || ^19.0.0"
}
},
"node_modules/@emnapi/runtime": {
diff --git a/package.json b/package.json
index 280e9cf..16a76bd 100644
--- a/package.json
+++ b/package.json
@@ -15,6 +15,18 @@
"navigation",
"scroll-restoration"
],
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "typesVersions": {
+ "*": {
+ "config": [
+ "./dist/config.d.ts"
+ ],
+ "dom": [
+ "./src/index.d.ts"
+ ]
+ }
+ },
"exports": {
".": {
"types": "./dist/index.d.ts",
@@ -70,9 +82,9 @@
"overlayscrollbars": "^2.17.1"
},
"peerDependencies": {
- "next": "^16.4.6",
- "react": "^19.3.1",
- "react-dom": "^19.3.1"
+ "next": "^13.4.0 || ^14.0.0 || ^15.0.0 || ^16.0.0",
+ "react": "^18.2.0 || ^19.0.0",
+ "react-dom": "^18.2.0 || ^19.0.0"
},
"publishConfig": {
"access": "public"
diff --git a/src/next/config.ts b/src/next/config.ts
index 524fa0d..c854a21 100644
--- a/src/next/config.ts
+++ b/src/next/config.ts
@@ -1,16 +1,33 @@
+import { createRequire } from 'node:module';
import type { NextConfig } from 'next';
+
+function installedNextVersion(): string | undefined {
+ try {
+ return (createRequire(import.meta.url)('next/package.json') as {version?: string}).version;
+ } catch {
+ return undefined;
+ }
+}
+
+function atLeast(version: string, major: number, minor: number): boolean {
+ const [a = 0, b = 0] = version.split('.').map(part => Number.parseInt(part, 10));
+ return a > major || (a === major && b >= minor);
+}
+
/**
- * 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
+ * Turns on Next.js Cache Components (Next.js 16+) and Partial Prefetching
+ * (Next.js 16.3+) 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, so older Next.js versions get the config back unchanged. 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: config.cacheComponents ?? true,
- partialPrefetching: config.partialPrefetching ?? true,
- };
+export function withStackflow(config: NextConfig = {}, nextVersion = installedNextVersion()): NextConfig {
+ const version = nextVersion ?? '999.0.0';
+ const result: NextConfig & {cacheComponents?: boolean; partialPrefetching?: boolean} = {...config};
+ const current = config as {cacheComponents?: boolean; partialPrefetching?: boolean};
+ if (atLeast(version, 16, 0)) result.cacheComponents = current.cacheComponents ?? true;
+ if (atLeast(version, 16, 3)) result.partialPrefetching = current.partialPrefetching ?? true;
+ return result;
}
diff --git a/src/next/index.tsx b/src/next/index.tsx
index 89ca0e7..58dc96e 100644
--- a/src/next/index.tsx
+++ b/src/next/index.tsx
@@ -1,5 +1,5 @@
'use client';
-import { createContext, Suspense, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode, type CSSProperties, type Dispatch, type SetStateAction } from 'react';
+import { createContext, forwardRef, Suspense, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode, type CSSProperties, type Dispatch, type SetStateAction } from 'react';
import Link, { type LinkProps } from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { NavigationEngine, safeHref, type RouteTransition, type SlideDirection } from './engine.js';
@@ -8,6 +8,7 @@ import { attachScrollViewport, attachWindowScroll, createOverlayScrollbarFactory
import type { FixedTarget } from './fixed-targets.js';
import { createSkeletonRouteMatcher, type SkeletonRoute } from './skeleton-routes.js';
import { loadingMessage } from './loading-message.js';
+import { isPlainNavigationClick } from './react-compat.js';
export type { FixedTarget } from './fixed-targets.js';
export type { RouteTransition } from './engine.js';
export type { SkeletonRoute } from './skeleton-routes.js';
@@ -202,18 +203,25 @@ export function useStackState(key:string,initial:T|(()=>T)): [T,Dispatch,'href'> & Omit & {href:string};
-export function StackLink({href,onNavigate,replace,...props}:StackLinkProps) {
+export type StackLinkProps = Omit,'href'> & Omit & {
+ href:string;
+ /** Called before a client-side navigation; preventDefault cancels it. Works on every supported Next.js version. */
+ onNavigate?: (event:{preventDefault():void}) => void;
+};
+export const StackLink = forwardRef(function StackLink({href,onNavigate,onClick,replace,...props},ref) {
const router=useStackRouter();
const engine=useEngine();
- return {
+ // onClick instead of Link's onNavigate, which only exists from Next.js 15.3.
+ return {
+ onClick?.(event);
+ if(!isPlainNavigationClick(event))return;
let cancelled=false;
- onNavigate?.({preventDefault(){cancelled=true;event.preventDefault();}});
- if(cancelled)return;
+ onNavigate?.({preventDefault(){cancelled=true;}});
+ if(cancelled){event.preventDefault();return;}
const url=new URL(href,window.location.href);
if(url.origin!==window.location.origin||!['http:','https:'].includes(url.protocol))return;
// Let Next handle same-document anchors and unchanged routes.
if(engine ? engine.isCurrentRoute(href) : url.pathname===window.location.pathname&&url.search===window.location.search)return;
event.preventDefault(); (replace?router.replace:router.push)(href);
}}/>;
-}
+});
diff --git a/src/next/motion.tsx b/src/next/motion.tsx
index aa95e55..ce85564 100644
--- a/src/next/motion.tsx
+++ b/src/next/motion.tsx
@@ -1,17 +1,22 @@
'use client';
-import { type ComponentPropsWithRef } from 'react';
+import { forwardRef, type ComponentPropsWithoutRef } from 'react';
+import { inertProp } from './react-compat.js';
export type StackMotionPreset = 'ios' | 'modal' | 'none';
-export type StackMotionProps = Omit, 'hidden'> & {
+export type StackMotionProps = Omit, 'hidden' | 'inert'> & {
open: boolean;
animation?: StackMotionPreset;
enter?: StackMotionPreset;
exit?: StackMotionPreset;
+ inert?: boolean;
};
/** Apply the route slide to a component controlled by local state. */
-export function StackMotion({open, animation = 'ios', enter = animation, exit = animation, inert, ...props}: StackMotionProps) {
- return ;
-}
+export const StackMotion = forwardRef(function StackMotion(
+ {open, animation = 'ios', enter = animation, exit = animation, inert, ...props},
+ ref,
+) {
+ return ;
+});
diff --git a/src/next/react-compat.ts b/src/next/react-compat.ts
new file mode 100644
index 0000000..bde5caa
--- /dev/null
+++ b/src/next/react-compat.ts
@@ -0,0 +1,31 @@
+import { version } from 'react';
+
+const major = Number.parseInt(version, 10);
+
+/**
+ * React 19 treats `inert` as a boolean. React 18 does not know the attribute,
+ * so it only renders a string value and warns about `true`.
+ */
+export function inertProp(value: boolean): Record {
+ if (major >= 19) return {inert: value};
+ return value ? {inert: ''} : {};
+}
+
+export interface LinkClick {
+ button: number;
+ metaKey: boolean;
+ ctrlKey: boolean;
+ shiftKey: boolean;
+ altKey: boolean;
+ defaultPrevented: boolean;
+ currentTarget: {getAttribute(name: string): string | null; hasAttribute(name: string): boolean};
+}
+
+/** True when a link click is one Next.js would turn into a client-side navigation. */
+export function isPlainNavigationClick(event: LinkClick): boolean {
+ if (event.defaultPrevented || event.button !== 0) return false;
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false;
+ const target = event.currentTarget.getAttribute('target');
+ if (target && target !== '_self') return false;
+ return !event.currentTarget.hasAttribute('download');
+}
diff --git a/test/next/config.test.ts b/test/next/config.test.ts
index a229bd1..3a55371 100644
--- a/test/next/config.test.ts
+++ b/test/next/config.test.ts
@@ -14,3 +14,13 @@ test('withStackflow keeps values the app sets', () => {
assert.equal(config.cacheComponents, false);
assert.equal(config.partialPrefetching, false);
});
+
+test('withStackflow leaves options older Next.js versions do not know', () => {
+ const v15 = withStackflow({ basePath: '/app' }, '15.5.0');
+ assert.equal('cacheComponents' in v15, false);
+ assert.equal('partialPrefetching' in v15, false);
+ const v16 = withStackflow({}, '16.2.1');
+ assert.equal(v16.cacheComponents, true);
+ assert.equal('partialPrefetching' in v16, false);
+ assert.equal(withStackflow({}, '16.3.0').partialPrefetching, true);
+});
diff --git a/test/next/react-compat.test.ts b/test/next/react-compat.test.ts
new file mode 100644
index 0000000..42cd09b
--- /dev/null
+++ b/test/next/react-compat.test.ts
@@ -0,0 +1,30 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { isPlainNavigationClick, inertProp } from '../../src/next/react-compat.ts';
+
+const link = (attrs: Record = {}) => ({
+ getAttribute: (name: string) => attrs[name] ?? null,
+ hasAttribute: (name: string) => name in attrs,
+});
+const click = (overrides: Record = {}) => ({
+ button: 0, metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, defaultPrevented: false,
+ currentTarget: link(), ...overrides,
+});
+
+test('a plain left click is a client-side navigation', () => {
+ assert.equal(isPlainNavigationClick(click()), true);
+ assert.equal(isPlainNavigationClick(click({ currentTarget: link({ target: '_self' }) })), true);
+});
+
+test('modified, non-primary, prevented, new-tab and download clicks are left to the browser', () => {
+ for (const key of ['metaKey', 'ctrlKey', 'shiftKey', 'altKey']) assert.equal(isPlainNavigationClick(click({ [key]: true })), false);
+ assert.equal(isPlainNavigationClick(click({ button: 1 })), false);
+ assert.equal(isPlainNavigationClick(click({ defaultPrevented: true })), false);
+ assert.equal(isPlainNavigationClick(click({ currentTarget: link({ target: '_blank' }) })), false);
+ assert.equal(isPlainNavigationClick(click({ currentTarget: link({ download: '' }) })), false);
+});
+
+test('inert uses the form the installed React renders', () => {
+ assert.deepEqual(inertProp(true), { inert: true });
+ assert.deepEqual(inertProp(false), { inert: false });
+});