Unverified Commit befa5fb0 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Add experimental_gesturePush to App Router (#88776)

## Summary

This adds a new experimental router method `experimental_gesturePush`
that enables gesture-driven navigation. The feature is gated behind a
new `experimental.gestureTransition` config flag, which implicitly opts
the app into using the experimental React build.

It is _not_ suitable for production use yet; it's a proof-of-concept so
we can test the integration between the Next.js client router and
React's Gesture Transitions experiment. You can use it to build demos,
but it shouldn't be used in a real app.

It dispatches updates through React's useOptimistic hook instead of the
main router state queue, essentially forking the router state until the
gesture completes.

This should only be called inside `startGestureTransition`. It's a
low-level method that is not meant to be used in application code, only
in libraries that know how to properly integrate with both Next and
React.

## Test Plan

- E2E test that simulates a gesture by holding an async transition open
between button clicks
- Run: `pnpm testonly test/e2e/app-dir/gesture-transitions`
parent 9e33529b
......@@ -1012,6 +1012,7 @@ pub struct ExperimentalConfig {
server_source_maps: Option<bool>,
swc_trace_profiling: Option<bool>,
transition_indicator: Option<bool>,
gesture_transition: Option<bool>,
/// @internal Used by the Next.js internals only.
trust_host_header: Option<bool>,
......@@ -1782,6 +1783,11 @@ impl NextConfig {
Vc::cell(self.experimental.transition_indicator.unwrap_or(false))
}
#[turbo_tasks::function]
pub fn enable_gesture_transition(&self) -> Vc<bool> {
Vc::cell(self.experimental.gesture_transition.unwrap_or(false))
}
#[turbo_tasks::function]
pub fn enable_cache_components(&self) -> Vc<bool> {
Vc::cell(self.cache_components.unwrap_or(false))
......
......@@ -130,7 +130,8 @@ pub async fn get_next_client_import_map(
// Keep in sync with file:///./../../../packages/next/src/lib/needs-experimental-react.ts
let taint = *next_config.enable_taint().await?;
let transition_indicator = *next_config.enable_transition_indicator().await?;
let react_channel = if taint || transition_indicator {
let gesture_transition = *next_config.enable_gesture_transition().await?;
let react_channel = if taint || transition_indicator || gesture_transition {
"-experimental"
} else {
""
......@@ -834,7 +835,8 @@ async fn apply_vendored_react_aliases_server(
) -> Result<()> {
let taint = *next_config.enable_taint().await?;
let transition_indicator = *next_config.enable_transition_indicator().await?;
let react_channel = if taint || transition_indicator {
let gesture_transition = *next_config.enable_gesture_transition().await?;
let react_channel = if taint || transition_indicator || gesture_transition {
"-experimental"
} else {
""
......
......@@ -343,6 +343,8 @@ export function getDefineEnv({
config.experimental.reactDebugChannel ?? false,
'process.env.__NEXT_TRANSITION_INDICATOR':
config.experimental.transitionIndicator ?? false,
'process.env.__NEXT_GESTURE_TRANSITION':
config.experimental.gestureTransition ?? false,
'process.env.__NEXT_CACHE_LIFE': config.cacheLife,
'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS':
config.experimental.clientParamParsingOrigins || [],
......
......@@ -19,7 +19,12 @@ import {
type PrefetchTaskFetchStrategy,
} from './segment-cache/types'
import { prefetch as prefetchWithSegmentCache } from './segment-cache/prefetch'
import { dispatchAppRouterAction } from './use-action-queue'
import { navigate } from './segment-cache/navigation'
import {
dispatchAppRouterAction,
dispatchGestureState,
} from './use-action-queue'
import { FreshnessPolicy } from './router-reducer/ppr-navigations'
import { addBasePath } from '../add-base-path'
import { isExternalURL } from './app-router-utils'
import type {
......@@ -313,6 +318,59 @@ export function dispatchTraverseAction(
})
}
/**
* (Experimental) Perform a gesture navigation. This dispatches through React's
* useOptimistic instead of the main action queue, allowing the state to be
* shown during a gesture transition and discarded when the canonical navigation
* completes.
*
* Only available when experimental.gestureTransition is enabled.
*/
function gesturePush(href: string, options?: NavigateOptions): void {
if (process.env.__NEXT_GESTURE_TRANSITION) {
// TODO: Trigger a prefetch so the cache starts populating if there isn't
// already a prefetch for this route.
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
const state = getCurrentAppRouterState()
if (state === null) {
return
}
const url = new URL(addBasePath(href), location.href)
if (isExternalURL(url)) {
return
}
// Fork the router state for the duration of the gesture transition.
const currentUrl = new URL(state.canonicalUrl, location.href)
const shouldScroll = options?.scroll ?? true
// This is a special freshness policy that prevents dynamic requests from
// being spawned. During the gesture, we should only show the cached
// prefetched UI, not dynamic data.
// TODO: In the case of navigations to an unknown route, this will still
// end up performing a dynamic request. The plan is to do prefetch instead.
// There's a separate TODO for this.
const freshnessPolicy = FreshnessPolicy.Gesture
const forkedGestureState = navigate(
state,
url,
currentUrl,
state.renderedSearch,
state.cache,
state.tree,
state.nextUrl,
freshnessPolicy,
shouldScroll,
'push'
)
dispatchGestureState(forkedGestureState)
}
}
/**
* The app router that is exposed through `useRouter`. These are public API
* methods. Internal Next.js code should call the lower level methods directly
......@@ -407,6 +465,11 @@ export const publicAppRouterInstance: AppRouterInstance = {
},
}
// Conditionally add experimental_gesturePush when gestureTransition is enabled
if (process.env.__NEXT_GESTURE_TRANSITION) {
;(publicAppRouterInstance as any).experimental_gesturePush = gesturePush
}
// Exists for debugging purposes. Don't use in application code.
if (typeof window !== 'undefined' && window.next) {
window.next.router = publicAppRouterInstance
......
......@@ -73,6 +73,7 @@ export const enum FreshnessPolicy {
HistoryTraversal,
RefreshAll,
HMRRefresh,
Gesture,
}
const enum NavigationTaskStatus {
......@@ -315,6 +316,7 @@ function updateCacheNodeOnNavigation(
case FreshnessPolicy.Default:
case FreshnessPolicy.HistoryTraversal:
case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav
case FreshnessPolicy.Gesture:
// We should never drop dynamic data in shared layouts, except during
// a refresh.
shouldRefreshDynamicData = false
......@@ -954,6 +956,7 @@ function createCacheNodeForSegment(
break
case FreshnessPolicy.RefreshAll:
case FreshnessPolicy.HMRRefresh:
case FreshnessPolicy.Gesture:
// Don't consult the BFCache.
break
default:
......@@ -1118,7 +1121,12 @@ function createCacheNodeForSegment(
// Now that we're creating a new segment, write its data to the BFCache. A
// subsequent back/forward navigation will reuse this same data, until or
// unless it's cleared by a refresh/revalidation.
writeToBFCache(now, tree.varyPath, rsc, prefetchRsc, head, prefetchHead)
//
// Skip BFCache writes for optimistic navigations since they are transient
// and will be replaced by the canonical navigation.
if (freshness !== FreshnessPolicy.Gesture) {
writeToBFCache(now, tree.varyPath, rsc, prefetchRsc, head, prefetchHead)
}
return {
cacheNode: createCacheNode(rsc, prefetchRsc, head, prefetchHead),
......
......@@ -102,6 +102,8 @@ export function navigate(
}
// There's no matching prefetch for this route in the cache.
// TODO: If this is an optimistic navigation, instead of performing a
// dynamic request, we should do a runtime prefetch.
return navigateToUnknownRoute(
now,
state,
......@@ -176,7 +178,12 @@ export function navigateToKnownRoute(
accumulation
)
if (task !== null) {
spawnDynamicRequests(task, url, nextUrl, freshnessPolicy, accumulation)
// Skip spawning dynamic requests for gesture navigations. Only the
// cached UI will be shown. The gesture state will be discarded when
// the canonical navigation completes.
if (freshnessPolicy !== FreshnessPolicy.Gesture) {
spawnDynamicRequests(task, url, nextUrl, freshnessPolicy, accumulation)
}
return completeSoftNavigation(
state,
url,
......@@ -278,6 +285,7 @@ async function navigateToUnknownRoute(
switch (freshnessPolicy) {
case FreshnessPolicy.Default:
case FreshnessPolicy.HistoryTraversal:
case FreshnessPolicy.Gesture:
dynamicRequestTree = currentFlightRouterState
break
case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav
......
import type { Dispatch } from 'react'
import React, { use, useMemo } from 'react'
import React, { use, useMemo, useOptimistic } from 'react'
import { isThenable } from '../../shared/lib/is-thenable'
import type { AppRouterActionQueue } from './app-router-instance'
import type {
......@@ -22,6 +22,19 @@ export function dispatchAppRouterAction(action: ReducerActions) {
dispatch(action)
}
// Optimistic state setter for experimental_gesturePush. Only should be used
// during a gesture transition.
let setGestureRouterState: ((state: ReducerState) => void) | null = null
export function dispatchGestureState(state: ReducerState) {
if (setGestureRouterState === null) {
throw new Error(
'Internal Next.js error: Router action dispatched before initialization.'
)
}
setGestureRouterState(state)
}
const __DEV__ = process.env.NODE_ENV !== 'production'
const promisesWithDebugInfo: WeakMap<
Promise<AppRouterState>,
......@@ -31,7 +44,16 @@ const promisesWithDebugInfo: WeakMap<
export function useActionQueue(
actionQueue: AppRouterActionQueue
): AppRouterState {
const [state, setState] = React.useState<ReducerState>(actionQueue.state)
const [canonicalState, setState] = React.useState<ReducerState>(
actionQueue.state
)
// Wrap the canonical state in useOptimistic to support
// experimental_gesturePush. During a gesture transition, this returns a fork
// of the router state that represents the eventual target if/when the gesture
// completes. Otherwise it returns the canonical state.
const [state, setGesture] = useOptimistic(canonicalState)
setGestureRouterState = setGesture
// Because of a known issue that requires to decode Flight streams inside the
// render phase, we have to be a bit clever and assign the dispatch method to
......
......@@ -2,6 +2,7 @@ import type { NextConfig } from '../server/config-shared'
// Keep in sync with Turbopack's experimental React switch: file://./../../../../crates/next-core/src/next_import_map.rs
export function needsExperimentalReact(config: NextConfig) {
const { taint, transitionIndicator } = config.experimental || {}
return Boolean(taint || transitionIndicator)
const { taint, transitionIndicator, gestureTransition } =
config.experimental || {}
return Boolean(taint || transitionIndicator || gestureTransition)
}
......@@ -292,6 +292,7 @@ export const experimentalSchema = {
])
.optional(),
transitionIndicator: z.boolean().optional(),
gestureTransition: z.boolean().optional(),
typedRoutes: z.boolean().optional(),
webpackBuildWorker: z.boolean().optional(),
webpackMemoryOptimizations: z.boolean().optional(),
......
......@@ -400,6 +400,12 @@ export interface ExperimentalConfig {
*/
transitionIndicator?: boolean
/**
* Enables experimental gesture transition APIs for optimistic client
* navigations. Requires experimental React.
*/
gestureTransition?: boolean
/**
* A target memory limit for turbo, in bytes.
*/
......@@ -1583,6 +1589,7 @@ export const defaultConfig = Object.freeze({
staticGenerationMaxConcurrency: 8,
staticGenerationMinPagesPerWorker: 25,
transitionIndicator: false,
gestureTransition: false,
inlineCss: false,
useCache: undefined,
slowModuleDetection: undefined,
......
......@@ -54,6 +54,12 @@ export interface AppRouterInstance {
* Prefetch the provided href.
*/
prefetch(href: string, options?: PrefetchOptions): void
/**
* Perform a gesture navigation using prefetched data.
* Only available when experimental.gestureTransition is enabled.
* @experimental
*/
experimental_gesturePush?(href: string, options?: NavigateOptions): void
}
export const AppRouterContext = React.createContext<AppRouterInstance | null>(
......
'use client'
import { ReactNode, startTransition } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import Link from 'next/link'
const pendingResolvers = new Set<() => void>()
export default function Root({ children }: { children: ReactNode }) {
const router = useRouter()
const pathname = usePathname()
const isOnHomePage = pathname === '/'
const startGesture = (href: string) => {
// NOTE: In a real scenario, this would be startGestureTransition,
// not startTransition.
startTransition(async () => {
// Call gesture push to show prefetched content immediately
;(router as any).experimental_gesturePush(href)
// Create a promise that won't resolve until the "end gesture" button
// is clicked. This simulates a gesture that takes time to complete.
await new Promise<void>((resolve) => {
pendingResolvers.add(resolve)
})
// After the gesture ends, perform the canonical navigation
router.push(href)
})
}
const endGesture = () => {
// Resolve all pending gestures
for (const resolve of pendingResolvers) {
resolve()
}
pendingResolvers.clear()
}
return (
<html>
<body>
<header>
<h1>Gesture Transitions Test</h1>
<p>
This test simulates a gesture transition using two buttons. "Start
Gesture" calls <code>experimental_gesturePush</code> and begins an
async transition that doesn't complete until "End Gesture" is
clicked. This allows observing the intermediate gesture state before
the canonical navigation completes.
</p>
</header>
<nav>
<Link href="/target-page">Link to target</Link>
<button
data-testid="start-gesture"
onClick={() => startGesture('/target-page')}
disabled={!isOnHomePage}
>
Start Gesture
</button>
<button data-testid="end-gesture" onClick={endGesture}>
End Gesture
</button>
</nav>
<main>{children}</main>
</body>
</html>
)
}
export default function HomePage() {
return (
<div data-testid="home-page">
<h1>Home</h1>
<p>This is the home page.</p>
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
async function DynamicContent() {
await connection()
return <div data-testid="dynamic-content">Dynamic content</div>
}
export default function TargetPage() {
return (
<div data-testid="target-page">
<h1>Target Page</h1>
<div data-testid="static-content">This is static content</div>
<Suspense fallback={<div data-testid="loading">Loading...</div>}>
<DynamicContent />
</Suspense>
</div>
)
}
/**
* Tests for experimental_gesturePush, which enables gesture-driven navigation
* via React's Gesture Transitions feature.
*
* The test simulates a gesture by using two buttons:
* - "Start Gesture" calls experimental_gesturePush and begins an async
* transition that doesn't complete until "End Gesture" is clicked
* - "End Gesture" resolves the pending promise and triggers the canonical
* router.push
*
* This allows us to observe the intermediate gesture state before the
* canonical navigation completes.
*/
import { nextTestSetup } from 'e2e-utils'
describe('gesture-transitions', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('shows optimistic state during gesture, then canonical state after', async () => {
const browser = await next.browser('/')
// Verify we're on the home page
expect(
await browser.elementByCss('[data-testid="home-page"]').text()
).toContain('Home')
// Click "Start Gesture" to begin the optimistic navigation
await browser.elementByCss('[data-testid="start-gesture"]').click()
// The target page content should be visible (optimistic state)
const targetPage = await browser.elementByCss('[data-testid="target-page"]')
expect(await targetPage.text()).toContain('Target Page')
// Static content should be visible
expect(
await browser.elementByCss('[data-testid="static-content"]').text()
).toBe('This is static content')
// The URL should have updated to /target-page
expect(await browser.url()).toContain('/target-page')
// Click "End Gesture" to complete the canonical navigation
await browser.elementByCss('[data-testid="end-gesture"]').click()
// After the gesture ends, we should still be on the target page
// with the canonical state (dynamic content fully loaded)
const dynamicContent = await browser.elementByCss(
'[data-testid="dynamic-content"]'
)
expect(await dynamicContent.text()).toBe('Dynamic content')
// URL should still be /target-page
expect(await browser.url()).toContain('/target-page')
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
gestureTransition: true,
},
cacheComponents: true,
}
module.exports = nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment