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
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
<a href="https://github.com/uiwwsw/stackflow-next/blob/main/LICENSE"><img alt="license" src="https://img.shields.io/npm/l/@uiwwsw/stackflow-next?style=flat-square"></a>
<a href="https://github.com/uiwwsw/stackflow-next/actions/workflows/public-docs.yml"><img alt="commit hygiene workflow" src="https://img.shields.io/github/actions/workflow/status/uiwwsw/stackflow-next/public-docs.yml?branch=main&style=flat-square&label=hygiene"></a>
<img alt="types: TypeScript" src="https://img.shields.io/npm/types/@uiwwsw/stackflow-next?style=flat-square">
<img alt="next 16.4.6 or later" src="https://img.shields.io/badge/next-%E2%89%A5%2016.4.6-black?style=flat-square">
<img alt="react 19.3.1 or later" src="https://img.shields.io/badge/react-%E2%89%A5%2019.3.1-087ea4?style=flat-square">
<img alt="next 13.4 or later" src="https://img.shields.io/badge/next-%E2%89%A5%2013.4-black?style=flat-square">
<img alt="react 18.2 or later" src="https://img.shields.io/badge/react-%E2%89%A5%2018.2-087ea4?style=flat-square">
</p>

<p>
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down
8 changes: 5 additions & 3 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 15 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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"
Expand Down
37 changes: 27 additions & 10 deletions src/next/config.ts
Original file line number Diff line number Diff line change
@@ -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
* <Activity>, 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 <Activity>, 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;
}
22 changes: 15 additions & 7 deletions src/next/index.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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';
Expand Down Expand Up @@ -202,18 +203,25 @@ export function useStackState<T>(key:string,initial:T|(()=>T)): [T,Dispatch<SetS
},[engine,key]);
return [value,set];
}
export type StackLinkProps = Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>,'href'> & Omit<LinkProps,'href'> & {href:string};
export function StackLink({href,onNavigate,replace,...props}:StackLinkProps) {
export type StackLinkProps = Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>,'href'> & Omit<LinkProps,'href'|'onNavigate'> & {
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<HTMLAnchorElement, StackLinkProps>(function StackLink({href,onNavigate,onClick,replace,...props},ref) {
const router=useStackRouter();
const engine=useEngine();
return <Link {...props} href={href} replace={replace} onNavigate={event=>{
// onClick instead of Link's onNavigate, which only exists from Next.js 15.3.
return <Link {...props} ref={ref} href={href} replace={replace} onClick={event=>{
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);
}}/>;
}
});
15 changes: 10 additions & 5 deletions src/next/motion.tsx
Original file line number Diff line number Diff line change
@@ -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<ComponentPropsWithRef<'div'>, 'hidden'> & {
export type StackMotionProps = Omit<ComponentPropsWithoutRef<'div'>, '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 <div {...props} data-sfn-enter={enter} data-sfn-exit={exit} hidden={!open} inert={!open || inert} />;
}
export const StackMotion = forwardRef<HTMLDivElement, StackMotionProps>(function StackMotion(
{open, animation = 'ios', enter = animation, exit = animation, inert, ...props},
ref,
) {
return <div {...props} {...inertProp(!open || !!inert)} ref={ref} data-sfn-enter={enter} data-sfn-exit={exit} hidden={!open} />;
});
31 changes: 31 additions & 0 deletions src/next/react-compat.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> {
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');
}
10 changes: 10 additions & 0 deletions test/next/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
30 changes: 30 additions & 0 deletions test/next/react-compat.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {}) => ({
getAttribute: (name: string) => attrs[name] ?? null,
hasAttribute: (name: string) => name in attrs,
});
const click = (overrides: Record<string, unknown> = {}) => ({
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 });
});
Loading