@timber-js/app 0.2.0-alpha.225 → 0.2.0-alpha.226

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"navigation-root-M3B2ZrdO.js","names":[],"sources":["../../src/client/router-ref.ts","../../src/client/use-pending-navigation.ts","../../src/client/top-loader.tsx","../../src/client/navigation-root.tsx"],"sourcesContent":["// Global router reference — shared between browser-entry and client hooks.\n//\n// Delegates to client/state.ts for the actual module-level variable.\n// This ensures singleton semantics regardless of import path — all\n// callers converge on the same state.ts instance via the barrel.\n//\n// See design/18-build-system.md §\"Module Singleton Strategy\"\n\nimport type { RouterInstance } from './router-types.ts';\nimport { globalRouter, _setGlobalRouter } from './state.ts';\n\n/**\n * Set the global router instance. Called once during bootstrap.\n */\nexport function setGlobalRouter(router: RouterInstance): void {\n _setGlobalRouter(router);\n}\n\n/**\n * Get the global router instance. Throws if called before bootstrap.\n * Used by client-side hooks (usePendingNavigation, etc.)\n */\nexport function getRouter(): RouterInstance {\n if (!globalRouter) {\n throw new Error('[timber] Router not initialized. getRouter() was called before bootstrap().');\n }\n return globalRouter;\n}\n\n/**\n * Get the global router instance or null if not yet initialized.\n * Used by useRouter() methods to avoid silent failures — callers\n * can log a meaningful warning instead of silently no-oping.\n */\nexport function getRouterOrNull(): RouterInstance | null {\n return globalRouter;\n}\n\n/**\n * Reset the global router to null. Used only in tests to isolate\n * module-level state between test cases.\n * @internal\n */\nexport function resetGlobalRouter(): void {\n _setGlobalRouter(null);\n}\n","import { useSyncExternalStore } from 'react';\nimport { getRouterOrNull } from './router-ref.ts';\n\nfunction subscribe(onStoreChange: () => void): () => void {\n const router = getRouterOrNull();\n if (!router) return () => {};\n return router.onPendingChange(onStoreChange);\n}\n\nfunction getSnapshot(): boolean {\n const router = getRouterOrNull();\n return router ? router.isPending() : false;\n}\n\nconst getServerSnapshot = getSnapshot;\n\n/**\n * Returns true while an RSC navigation is in flight.\n *\n * Reads from the router's external pending store via useSyncExternalStore.\n * Only components that call this hook re-render when pending state\n * changes — no full-tree re-render.\n *\n * ```tsx\n * 'use client'\n * import { usePendingNavigation } from '@timber-js/app/client'\n *\n * export function NavBar() {\n * const isPending = usePendingNavigation()\n * return (\n * <nav className={isPending ? 'opacity-50' : ''}>\n * <Link href=\"/dashboard\">Dashboard</Link>\n * </nav>\n * )\n * }\n * ```\n */\nexport function usePendingNavigation(): boolean {\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n","/**\n * TopLoader — Built-in progress bar for client navigations.\n *\n * Shows an animated progress bar at the top of the viewport while an RSC\n * navigation is in flight. Injected automatically by the framework into\n * NavigationRoot — users never render this component directly.\n *\n * Configuration is via timber.config.ts `topLoader` key. Enabled by default.\n * Users who want a fully custom progress indicator disable the built-in one\n * (`topLoader: { enabled: false }`) and use `usePendingNavigation()` directly.\n *\n * Animation approach: pure CSS @keyframes. The bar crawls from 0% to ~90%\n * width over ~30s using ease-out timing. When navigation completes, the bar\n * snaps to 100% and fades out over 200ms. No JS animation loops (RAF, setInterval).\n *\n * Phase transitions are derived synchronously during render (React's\n * getDerivedStateFromProps pattern) — no useEffect needed for state tracking.\n * The finishing → hidden cleanup uses onTransitionEnd from the CSS transition.\n *\n * When delay > 0, CSS animation-delay + a visibility keyframe ensure the bar\n * stays invisible during the delay period. If navigation finishes before the\n * delay, the bar was never visible so the finish transition is also invisible.\n *\n * See design/19-client-navigation.md §\"usePendingNavigation()\"\n * See LOCAL-336 for design decisions.\n */\n\n'use client';\n\nimport { useState, createElement } from 'react';\nimport { usePendingNavigation } from './use-pending-navigation.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface TopLoaderConfig {\n /** Whether the top-loader is enabled. Default: true. */\n enabled?: boolean;\n /** Bar color. Default: '#2299DD'. */\n color?: string;\n /** Bar height in pixels. Default: 3. */\n height?: number;\n /** Show subtle glow/shadow effect. Default: false. */\n shadow?: boolean;\n /** Delay in ms before showing the bar. Default: 0. */\n delay?: number;\n /** CSS z-index. Default: 1600. */\n zIndex?: number;\n}\n\n// ─── Defaults ────────────────────────────────────────────────────\n\nconst DEFAULT_COLOR = '#2299DD';\nconst DEFAULT_HEIGHT = 3;\nconst DEFAULT_SHADOW = false;\nconst DEFAULT_DELAY = 0;\nconst DEFAULT_Z_INDEX = 1600;\n\n// ─── Keyframes ───────────────────────────────────────────────────\n\n// Unique keyframes name to avoid collisions with user styles.\nconst CRAWL_KEYFRAMES = '__timber_top_loader_crawl';\nconst APPEAR_KEYFRAMES = '__timber_top_loader_appear';\nconst FINISH_KEYFRAMES = '__timber_top_loader_finish';\n\n// Track whether the @keyframes rules have been injected into the document.\nlet keyframesInjected = false;\n\n/**\n * Inject the @keyframes rules into the document head once.\n * Called during render (idempotent). Uses a <style> tag so the\n * animations are available for inline-styled elements.\n */\nfunction ensureKeyframes(): void {\n if (keyframesInjected) return;\n if (typeof document === 'undefined') return;\n\n const style = document.createElement('style');\n style.textContent = `\n@keyframes ${CRAWL_KEYFRAMES} {\n 0% { width: 0%; }\n 100% { width: 90%; }\n}\n@keyframes ${APPEAR_KEYFRAMES} {\n from { opacity: 0; }\n to { opacity: 1; }\n}\n@keyframes ${FINISH_KEYFRAMES} {\n 0% { width: 90%; opacity: 1; }\n 50% { width: 100%; opacity: 1; }\n 100% { width: 100%; opacity: 0; }\n}\n`;\n document.head.appendChild(style);\n keyframesInjected = true;\n}\n\n// ─── Component ───────────────────────────────────────────────────\n\n/**\n * Internal top-loader component. Injected by NavigationRoot.\n *\n * Reads pending navigation state from the router's external store, via\n * usePendingNavigation() — the one pending representation (TIM-1307).\n * Phase transitions are derived synchronously during render:\n *\n * hidden → crawling: when isPending becomes true\n * crawling → finishing: when isPending becomes false\n * finishing → hidden: when CSS transition ends (onTransitionEnd)\n * finishing → crawling: when isPending becomes true again\n *\n * No useEffect — all state changes are either derived during render\n * (getDerivedStateFromProps pattern) or triggered by DOM events.\n */\nexport function TopLoader({ config }: { config?: TopLoaderConfig }): React.ReactElement | null {\n // Read pending state from the router's external store via\n // useSyncExternalStore (inside usePendingNavigation). Only this\n // component re-renders when pending changes — no full-tree re-render.\n const isPending = usePendingNavigation();\n\n const color = config?.color ?? DEFAULT_COLOR;\n const height = config?.height ?? DEFAULT_HEIGHT;\n const shadow = config?.shadow ?? DEFAULT_SHADOW;\n const delay = config?.delay ?? DEFAULT_DELAY;\n const zIndex = config?.zIndex ?? DEFAULT_Z_INDEX;\n\n const [phase, setPhase] = useState<'hidden' | 'crawling' | 'finishing'>('hidden');\n\n // ─── Synchronous phase derivation (getDerivedStateFromProps) ──\n // React allows setState during render if the value changes — it\n // immediately re-renders with the updated state before committing.\n\n if (isPending && (phase === 'hidden' || phase === 'finishing')) {\n setPhase('crawling');\n }\n if (!isPending && phase === 'crawling') {\n setPhase('finishing');\n }\n\n // Inject keyframes on first visible render (idempotent)\n if (phase !== 'hidden') {\n ensureKeyframes();\n }\n\n if (phase === 'hidden') return null;\n\n // ─── Styles ──────────────────────────────────────────────────\n\n const containerStyle: React.CSSProperties = {\n position: 'fixed',\n top: 0,\n left: 0,\n width: '100%',\n height: `${height}px`,\n zIndex,\n pointerEvents: 'none',\n };\n\n const barStyle: React.CSSProperties = {\n height: '100%',\n backgroundColor: color,\n ...(phase === 'crawling'\n ? {\n // Crawl from 0% to 90% over 30s. When delay > 0, both the crawl\n // and a visibility animation are delayed — the bar stays at width 0%\n // and opacity 0 during the delay, then appears and starts crawling.\n // With delay 0, the appear animation is instant (0s duration, no delay).\n animation: [\n `${CRAWL_KEYFRAMES} 30s ease-out ${delay}ms forwards`,\n `${APPEAR_KEYFRAMES} 0s ${delay}ms both`,\n ].join(', '),\n }\n : {\n // Finishing: fill to 100% then fade out via a keyframe animation.\n // We use a keyframe instead of a CSS transition because the\n // animation-to-transition handoff is unreliable — the browser\n // may not capture the animated width as the transition's \"from\"\n // value when both the animation removal and transition are\n // applied in the same render frame.\n animation: `${FINISH_KEYFRAMES} 400ms ease forwards`,\n }),\n ...(shadow\n ? {\n boxShadow: `0 0 10px ${color}, 0 0 5px ${color}`,\n }\n : {}),\n };\n\n // Clean up the finishing phase when the finish animation completes.\n const handleAnimationEnd =\n phase === 'finishing'\n ? (e: React.AnimationEvent) => {\n if (e.animationName === FINISH_KEYFRAMES) {\n setPhase('hidden');\n }\n }\n : undefined;\n\n return createElement(\n 'div',\n {\n 'style': containerStyle,\n 'aria-hidden': 'true',\n 'data-timber-top-loader': '',\n },\n createElement('div', { style: barStyle, onAnimationEnd: handleAnimationEnd })\n );\n}\n","/**\n * NavigationRoot — the component the router renders the page through.\n *\n * It is stateless. The router owns the displayed tree and drives React with\n * `root.render(<NavigationRoot rendered={{ element, publish }} />)` inside a\n * synchronous `startTransition` (see `client/react-root.ts`). A transition\n * update keeps the committed tree on screen while the incoming one resolves,\n * instead of replacing it with a Suspense fallback — the reason this\n * component exists (TIM-1306).\n *\n * It used to hold the tree in `useState` and register `setState` closures\n * into module globals during render so the router could reach into it, with a\n * second set of stand-in closures for the window before a root existed\n * (TIM-600). Inverting that — router calls React, not the reverse — deleted\n * all of it (TIM-1431). Next.js's `use-action-queue.ts` says it wants this\n * shape and cannot have it because it must decode Flight during render;\n * timber decodes in `router-pipeline.ts`, so nothing stands in the way.\n *\n * What this component does own is **the commit-time publish**: a navigation's\n * state (segment cache, address bar, history stack, pathname) is published\n * from a layout effect keyed on the tree object, so the event that puts a\n * route on screen is the event that makes it current (TIM-1301). Props work\n * for that exactly as state did.\n *\n * This component holds no pending state. The `TopLoader` it renders and the\n * public `usePendingNavigation()` both subscribe to the router's external\n * pending store; NavigationRoot's own `pendingUrl` was a second, unread\n * representation of the same fact and is gone (TIM-1307).\n *\n * Hard navigation guard: When a hard navigation is triggered (500 error,\n * version skew), the component throws an unresolved thenable AFTER all\n * hooks to suspend forever — preventing React from rendering children\n * during page teardown. The throw must come after hooks to satisfy\n * React's rules (same hook count every render) while still preventing\n * child renders that could hit hook count mismatches in components\n * whose positions shift during teardown. This pattern is borrowed from\n * Next.js (app-router.tsx pushRef.mpaNavigation — also after hooks).\n *\n * See design/05-streaming.md §\"deferSuspenseFor\"\n * See design/19-client-navigation.md §\"NavigationContext\"\n */\n\nimport { createElement, Fragment, useLayoutEffect, useRef, type ReactNode } from 'react';\nimport { TopLoader, type TopLoaderConfig } from './top-loader.tsx';\n\n// ─── Rendered Tree ──────────────────────────────────────────────\n\n/**\n * The tree the router has handed to React, and the state publish that belongs\n * to it. They travel as one object so React's commit of the tree is the event\n * that publishes — see the effect in NavigationRoot. Every `render` builds a\n * fresh one, which is what keys that effect: a tree is published once, however\n * many times React re-runs the effect for it.\n */\nexport interface RenderedTree {\n element: ReactNode;\n /**\n * Publishes the navigation's state — segment cache, pathname, address bar,\n * history stack, and the client's record of the mounted tree — and\n * announces it to listeners outside React. Runs when React commits\n * `element`, never before (TIM-1301). Null for a render that has nothing to\n * publish on commit (hydration, the shallow search re-wrap).\n */\n publish: (() => void) | null;\n}\n\n/**\n * Hand a tree to React in a transition. `publish` runs when React commits it.\n *\n * Every path that puts a page on screen goes through one of these — a\n * navigation, a revalidation, a popstate replay, a shallow search re-wrap —\n * and it is always a synchronous `startTransition` around `root.render`.\n * The production one is `createReactRoot().render`.\n *\n * `types` are the view transition types this render animates as\n * (design/37-navigation-api.md §\"Transition types\"). They are added with\n * `addTransitionType` inside that same `startTransition`, and nowhere else:\n * React queues types per root and hands them to the next transition-only\n * commit, so a type added in any other scope describes whichever tree commits\n * next rather than this one (TIM-1463, TIM-1471). Empty for the shallow search\n * re-wrap, which re-renders the displayed page rather than changing it.\n */\nexport type NavigationRender = (\n element: ReactNode,\n publish: (() => void) | null,\n types: readonly string[]\n) => void;\n\n// ─── Hard Navigation Guard ──────────────────────────────────────\n\n/**\n * Module-level flag indicating a hard (MPA) navigation is in progress.\n *\n * When true:\n * - NavigationRoot throws an unresolved thenable to suspend forever,\n * preventing React from rendering children during page teardown\n * (avoids \"Rendered more hooks\" crashes).\n * - The Navigation API handler skips interception, letting the browser\n * perform a full page load (prevents infinite loops where\n * window.location.href → navigate event → router.navigate → 500 →\n * window.location.href → ...).\n *\n * Uses globalThis for singleton guarantee across chunks (same pattern\n * as NavigationContext). See design/19-client-navigation.md §\"Singleton\n * Guarantee via globalThis\".\n */\nconst HARD_NAV_KEY = Symbol.for('__timber_hard_navigating');\n\nfunction getHardNavStore(): { value: boolean } {\n const g = globalThis as Record<symbol, unknown>;\n if (!g[HARD_NAV_KEY]) {\n g[HARD_NAV_KEY] = { value: false };\n }\n return g[HARD_NAV_KEY] as { value: boolean };\n}\n\n/**\n * Set the hard-navigating flag. Call this BEFORE setting\n * window.location.href or window.location.reload() to prevent:\n * 1. React from rendering children during page teardown\n * 2. Navigation API from intercepting the hard navigation\n */\nexport function setHardNavigating(value: boolean): void {\n getHardNavStore().value = value;\n}\n\n/**\n * Check if a hard navigation is in progress.\n * Used by NavigationRoot (throw unresolvedThenable) and by the\n * Navigation API handler (skip interception).\n */\nexport function isHardNavigating(): boolean {\n return getHardNavStore().value;\n}\n\n/**\n * A thenable that never resolves. When thrown during React render,\n * it causes the component to suspend forever — React keeps the\n * old committed tree visible and never attempts to render children.\n *\n * This is the same pattern Next.js uses in app-router.tsx for MPA\n * navigations (pushRef.mpaNavigation → throw unresolvedThenable).\n */\n// for React's Suspense mechanism. Same pattern as Next.js's unresolvedThenable.\n// eslint-disable-next-line unicorn/no-thenable -- Intentionally a never-resolving thenable\nconst unresolvedThenable = { then() {} } as PromiseLike<never>;\n\n// ─── Component ───────────────────────────────────────────────────\n\n/**\n * Root component the router renders the page through.\n *\n * Renders the TopLoader alongside the tree it is given. Neither adds a DOM\n * element on the hydration path, so the tree matches the server HTML.\n *\n * Rendered only by `createReactRoot` (client/react-root.ts): hydration passes\n * `{ element, publish: null }`, and every later render is a synchronous\n * `startTransition(() => root.render(...))` with a fresh `rendered` object.\n */\nexport function NavigationRoot({\n rendered,\n topLoaderConfig,\n}: {\n rendered: RenderedTree;\n topLoaderConfig?: TopLoaderConfig;\n}): ReactNode {\n // Publish the navigation's state when React commits its tree — not when the\n // tree is handed over. A tree React is still waiting on, or one a later\n // navigation replaces before React renders it, has been *given* to React\n // without being on screen; publishing then describes a route the user never\n // saw, which is the defect this ordering exists to prevent (TIM-1301).\n //\n // A **layout** effect, so the publish lands before the browser paints and,\n // more importantly, before every descendant's passive effect. A destination\n // component that navigates from a mount effect — a redirect guard, a\n // `refresh()` on mount — would otherwise start its navigation while the\n // segment cache, address bar and pathname still described the departing\n // route, and send an X-Timber-State-Tree for a tree that is no longer\n // mounted (codex on #998).\n //\n // Descendant *layout* effects still run first: React runs layout effects\n // child-before-parent, and the only way to precede them would be a fiber\n // rendered as an earlier sibling of the payload. That is not free here —\n // `server/ssr-wrappers.tsx` mirrors this component's fiber shape so `useId`\n // agrees across hydration, and an extra sibling shifts every id in the\n // payload subtree. A layout effect that navigates on mount is the price.\n //\n // Keyed on the tree object rather than on the effect run. A publish moves\n // the address bar, which is not idempotent, so any second invocation for the\n // same tree — an effect re-run React is entitled to perform, StrictMode's\n // double-invoke — must be a no-op rather than a second history entry.\n const publishedRef = useRef<RenderedTree | null>(null);\n useLayoutEffect(() => {\n if (publishedRef.current === rendered) return;\n publishedRef.current = rendered;\n rendered.publish?.();\n }, [rendered]);\n\n // ─── Hard navigation guard ─────────────────────────────────\n // When a hard navigation is in progress (500 error, version skew),\n // suspend forever to prevent React from rendering children during\n // page teardown. This avoids \"Rendered more hooks\" crashes in\n // CHILD components whose hook counts may shift during teardown.\n //\n // CRITICAL: This throw MUST come AFTER all hooks (the useRef and\n // useLayoutEffect above). React requires the same hooks to run on every\n // render. If we threw before hooks, React would see 0 hooks on the\n // re-render vs 2 on the initial render — triggering the exact \"Rendered\n // more hooks\" error we're trying to prevent.\n //\n // By placing it after hooks but before the return, all hooks\n // satisfy React's rules, but the thrown thenable prevents any\n // children from rendering. Same pattern as Next.js app-router.tsx\n // (pushRef.mpaNavigation — also placed after all hooks).\n if (isHardNavigating()) {\n throw unresolvedThenable;\n }\n\n // Inject TopLoader alongside the element tree. It subscribes to the router's\n // pending store itself, so it takes no props from here beyond its config,\n // and only it re-renders when a navigation starts or ends. Rendered only\n // when not explicitly disabled via config.\n //\n // This Fragment is a FORK — two children — so it advances React's tree\n // context and shifts every `useId` below it. `server/ssr-wrappers.tsx`\n // mirrors it for exactly that reason; a single-child wrapper would not need\n // a mirror. See tests/ssr-wrapper-parity.test.ts.\n const showTopLoader = topLoaderConfig?.enabled !== false;\n if (!showTopLoader) return rendered.element;\n return createElement(\n Fragment,\n null,\n createElement(TopLoader, { config: topLoaderConfig }),\n rendered.element\n );\n}\n"],"mappings":";;;;;;AAcA,SAAgB,gBAAgB,QAA8B;CAC5D,iBAAiB,MAAM;AACzB;;;;;AAMA,SAAgB,YAA4B;CAC1C,IAAI,CAAC,cACH,MAAM,IAAI,MAAM,6EAA6E;CAE/F,OAAO;AACT;;;;;;AAOA,SAAgB,kBAAyC;CACvD,OAAO;AACT;;ACjCA,SAAS,UAAU,eAAuC;CACxD,MAAM,SAAS,gBAAgB;CAC/B,IAAI,CAAC,QAAQ,aAAa,CAAC;CAC3B,OAAO,OAAO,gBAAgB,aAAa;AAC7C;AAEA,SAAS,cAAuB;CAC9B,MAAM,SAAS,gBAAgB;CAC/B,OAAO,SAAS,OAAO,UAAU,IAAI;AACvC;AAEA,IAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;AAuB1B,SAAgB,uBAAgC;CAC9C,OAAO,qBAAqB,WAAW,aAAa,iBAAiB;AACvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEmEA,IAAM,eAAe,OAAO,IAAI,0BAA0B;AAE1D,SAAS,kBAAsC;CAC7C,MAAM,IAAI;CACV,IAAI,CAAC,EAAE,eACL,EAAE,gBAAgB,EAAE,OAAO,MAAM;CAEnC,OAAO,EAAE;AACX;;;;;;;AAQA,SAAgB,kBAAkB,OAAsB;CACtD,gBAAgB,CAAC,CAAC,QAAQ;AAC5B"}
1
+ {"version":3,"file":"navigation-root-M3B2ZrdO.js","names":[],"sources":["../../src/client/router-ref.ts","../../src/client/use-pending-navigation.ts","../../src/client/top-loader.tsx","../../src/client/navigation-root.tsx"],"sourcesContent":["// Global router reference — shared between browser-entry and client hooks.\n//\n// Delegates to client/state.ts for the actual module-level variable.\n// This ensures singleton semantics regardless of import path — all\n// callers converge on the same state.ts instance via the barrel.\n//\n// See design/18-build-system.md §\"Module Singleton Strategy\"\n\nimport type { RouterInstance } from './router-types.ts';\nimport { globalRouter, _setGlobalRouter } from './state.ts';\n\n/**\n * Set the global router instance. Called once during bootstrap.\n */\nexport function setGlobalRouter(router: RouterInstance): void {\n _setGlobalRouter(router);\n}\n\n/**\n * Get the global router instance. Throws if called before bootstrap.\n * Used by client-side hooks (usePendingNavigation, etc.)\n */\nexport function getRouter(): RouterInstance {\n if (!globalRouter) {\n throw new Error('[timber] Router not initialized. getRouter() was called before bootstrap().');\n }\n return globalRouter;\n}\n\n/**\n * Get the global router instance or null if not yet initialized.\n * Used by useRouter() methods to avoid silent failures — callers\n * can log a meaningful warning instead of silently no-oping.\n */\nexport function getRouterOrNull(): RouterInstance | null {\n return globalRouter;\n}\n\n/**\n * Reset the global router to null. Used only in tests to isolate\n * module-level state between test cases.\n * @internal\n */\nexport function resetGlobalRouter(): void {\n _setGlobalRouter(null);\n}\n","import { useSyncExternalStore } from 'react';\nimport { getRouterOrNull } from './router-ref.ts';\n\nfunction subscribe(onStoreChange: () => void): () => void {\n const router = getRouterOrNull();\n if (!router) return () => {};\n return router.onPendingChange(onStoreChange);\n}\n\nfunction getSnapshot(): boolean {\n const router = getRouterOrNull();\n return router ? router.isPending() : false;\n}\n\nconst getServerSnapshot = getSnapshot;\n\n/**\n * Returns true while an RSC navigation is in flight.\n *\n * Reads from the router's external pending store via useSyncExternalStore.\n * Only components that call this hook re-render when pending state\n * changes — no full-tree re-render.\n *\n * ```tsx\n * 'use client'\n * import { usePendingNavigation } from '@timber-js/app/client'\n *\n * export function NavBar() {\n * const isPending = usePendingNavigation()\n * return (\n * <nav className={isPending ? 'opacity-50' : ''}>\n * <Link href=\"/dashboard\">Dashboard</Link>\n * </nav>\n * )\n * }\n * ```\n */\nexport function usePendingNavigation(): boolean {\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n","/**\n * TopLoader — Built-in progress bar for client navigations.\n *\n * Shows an animated progress bar at the top of the viewport while an RSC\n * navigation is in flight. Injected automatically by the framework into\n * NavigationRoot — users never render this component directly.\n *\n * Configuration is via timber.config.ts `topLoader` key. Enabled by default.\n * Users who want a fully custom progress indicator disable the built-in one\n * (`topLoader: { enabled: false }`) and use `usePendingNavigation()` directly.\n *\n * Animation approach: pure CSS @keyframes. The bar crawls from 0% to ~90%\n * width over ~30s using ease-out timing. When navigation completes, the bar\n * snaps to 100% and fades out over 200ms. No JS animation loops (RAF, setInterval).\n *\n * Phase transitions are derived synchronously during render (React's\n * getDerivedStateFromProps pattern) — no useEffect needed for state tracking.\n * The finishing → hidden cleanup uses onTransitionEnd from the CSS transition.\n *\n * When delay > 0, CSS animation-delay + a visibility keyframe ensure the bar\n * stays invisible during the delay period. If navigation finishes before the\n * delay, the bar was never visible so the finish transition is also invisible.\n *\n * See design/19-client-navigation.md §\"usePendingNavigation()\"\n * See LOCAL-336 for design decisions.\n */\n\n'use client';\n\nimport { useState, createElement } from 'react';\nimport { usePendingNavigation } from './use-pending-navigation.ts';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface TopLoaderConfig {\n /** Whether the top-loader is enabled. Default: true. */\n enabled?: boolean;\n /** Bar color. Default: '#2299DD'. */\n color?: string;\n /** Bar height in pixels. Default: 3. */\n height?: number;\n /** Show subtle glow/shadow effect. Default: false. */\n shadow?: boolean;\n /** Delay in ms before showing the bar. Default: 0. */\n delay?: number;\n /** CSS z-index. Default: 1600. */\n zIndex?: number;\n}\n\n// ─── Defaults ────────────────────────────────────────────────────\n\nconst DEFAULT_COLOR = '#2299DD';\nconst DEFAULT_HEIGHT = 3;\nconst DEFAULT_SHADOW = false;\nconst DEFAULT_DELAY = 0;\nconst DEFAULT_Z_INDEX = 1600;\n\n// ─── Keyframes ───────────────────────────────────────────────────\n\n// Unique keyframes name to avoid collisions with user styles.\nconst CRAWL_KEYFRAMES = '__timber_top_loader_crawl';\nconst APPEAR_KEYFRAMES = '__timber_top_loader_appear';\nconst FINISH_KEYFRAMES = '__timber_top_loader_finish';\n\n// Track whether the @keyframes rules have been injected into the document.\nlet keyframesInjected = false;\n\n/**\n * Inject the @keyframes rules into the document head once.\n * Called during render (idempotent). Uses a <style> tag so the\n * animations are available for inline-styled elements.\n */\nfunction ensureKeyframes(): void {\n if (keyframesInjected) return;\n if (typeof document === 'undefined') return;\n\n const style = document.createElement('style');\n style.textContent = `\n@keyframes ${CRAWL_KEYFRAMES} {\n 0% { width: 0%; }\n 100% { width: 90%; }\n}\n@keyframes ${APPEAR_KEYFRAMES} {\n from { opacity: 0; }\n to { opacity: 1; }\n}\n@keyframes ${FINISH_KEYFRAMES} {\n 0% { width: 90%; opacity: 1; }\n 50% { width: 100%; opacity: 1; }\n 100% { width: 100%; opacity: 0; }\n}\n`;\n document.head.appendChild(style);\n keyframesInjected = true;\n}\n\n// ─── Component ───────────────────────────────────────────────────\n\n/**\n * Internal top-loader component. Injected by NavigationRoot.\n *\n * Reads pending navigation state from the router's external store, via\n * usePendingNavigation() — the one pending representation (TIM-1307).\n * Phase transitions are derived synchronously during render:\n *\n * hidden → crawling: when isPending becomes true\n * crawling → finishing: when isPending becomes false\n * finishing → hidden: when CSS transition ends (onTransitionEnd)\n * finishing → crawling: when isPending becomes true again\n *\n * No useEffect — all state changes are either derived during render\n * (getDerivedStateFromProps pattern) or triggered by DOM events.\n */\nexport function TopLoader({ config }: { config?: TopLoaderConfig }): React.ReactElement | null {\n // Read pending state from the router's external store via\n // useSyncExternalStore (inside usePendingNavigation). Only this\n // component re-renders when pending changes — no full-tree re-render.\n const isPending = usePendingNavigation();\n\n const color = config?.color ?? DEFAULT_COLOR;\n const height = config?.height ?? DEFAULT_HEIGHT;\n const shadow = config?.shadow ?? DEFAULT_SHADOW;\n const delay = config?.delay ?? DEFAULT_DELAY;\n const zIndex = config?.zIndex ?? DEFAULT_Z_INDEX;\n\n const [phase, setPhase] = useState<'hidden' | 'crawling' | 'finishing'>('hidden');\n\n // ─── Synchronous phase derivation (getDerivedStateFromProps) ──\n // React allows setState during render if the value changes — it\n // immediately re-renders with the updated state before committing.\n\n if (isPending && (phase === 'hidden' || phase === 'finishing')) {\n setPhase('crawling');\n }\n if (!isPending && phase === 'crawling') {\n setPhase('finishing');\n }\n\n // Inject keyframes on first visible render (idempotent)\n if (phase !== 'hidden') {\n ensureKeyframes();\n }\n\n if (phase === 'hidden') return null;\n\n // ─── Styles ──────────────────────────────────────────────────\n\n const containerStyle: React.CSSProperties = {\n position: 'fixed',\n top: 0,\n left: 0,\n width: '100%',\n height: `${height}px`,\n zIndex,\n pointerEvents: 'none',\n };\n\n const barStyle: React.CSSProperties = {\n height: '100%',\n backgroundColor: color,\n ...(phase === 'crawling'\n ? {\n // Crawl from 0% to 90% over 30s. When delay > 0, both the crawl\n // and a visibility animation are delayed — the bar stays at width 0%\n // and opacity 0 during the delay, then appears and starts crawling.\n // With delay 0, the appear animation is instant (0s duration, no delay).\n animation: [\n `${CRAWL_KEYFRAMES} 30s ease-out ${delay}ms forwards`,\n `${APPEAR_KEYFRAMES} 0s ${delay}ms both`,\n ].join(', '),\n }\n : {\n // Finishing: fill to 100% then fade out via a keyframe animation.\n // We use a keyframe instead of a CSS transition because the\n // animation-to-transition handoff is unreliable — the browser\n // may not capture the animated width as the transition's \"from\"\n // value when both the animation removal and transition are\n // applied in the same render frame.\n animation: `${FINISH_KEYFRAMES} 400ms ease forwards`,\n }),\n ...(shadow\n ? {\n boxShadow: `0 0 10px ${color}, 0 0 5px ${color}`,\n }\n : {}),\n };\n\n // Clean up the finishing phase when the finish animation completes.\n const handleAnimationEnd =\n phase === 'finishing'\n ? (e: React.AnimationEvent) => {\n if (e.animationName === FINISH_KEYFRAMES) {\n setPhase('hidden');\n }\n }\n : undefined;\n\n return createElement(\n 'div',\n {\n 'style': containerStyle,\n 'aria-hidden': 'true',\n 'data-timber-top-loader': '',\n },\n createElement('div', { style: barStyle, onAnimationEnd: handleAnimationEnd })\n );\n}\n","/**\n * NavigationRoot — the component the router renders the page through.\n *\n * It is stateless. The router owns the displayed tree and drives React with\n * `root.render(<NavigationRoot rendered={{ element, publish }} />)` inside a\n * synchronous `startTransition` (see `client/react-root.ts`). A transition\n * update keeps the committed tree on screen while the incoming one resolves,\n * instead of replacing it with a Suspense fallback — the reason this\n * component exists (TIM-1306).\n *\n * It used to hold the tree in `useState` and register `setState` closures\n * into module globals during render so the router could reach into it, with a\n * second set of stand-in closures for the window before a root existed\n * (TIM-600). Inverting that — router calls React, not the reverse — deleted\n * all of it (TIM-1431). Next.js's `use-action-queue.ts` says it wants this\n * shape and cannot have it because it must decode Flight during render;\n * timber decodes in `router-pipeline.ts`, so nothing stands in the way.\n *\n * What this component does own is **the commit-time publish**: a navigation's\n * state (segment cache, address bar, history stack, pathname) is published\n * from a layout effect keyed on the tree object, so the event that puts a\n * route on screen is the event that makes it current (TIM-1301). Props work\n * for that exactly as state did.\n *\n * This component holds no pending state. The `TopLoader` it renders and the\n * public `usePendingNavigation()` both subscribe to the router's external\n * pending store; NavigationRoot's own `pendingUrl` was a second, unread\n * representation of the same fact and is gone (TIM-1307).\n *\n * Hard navigation guard: When a hard navigation is triggered (500 error,\n * version skew), the component throws an unresolved thenable AFTER all\n * hooks to suspend forever — preventing React from rendering children\n * during page teardown. The throw must come after hooks to satisfy\n * React's rules (same hook count every render) while still preventing\n * child renders that could hit hook count mismatches in components\n * whose positions shift during teardown. This pattern is borrowed from\n * Next.js (app-router.tsx pushRef.mpaNavigation — also after hooks).\n *\n * See design/05-streaming.md §\"deferSuspenseFor\"\n * See design/19-client-navigation.md §\"NavigationContext\"\n */\n\nimport { createElement, Fragment, useLayoutEffect, useRef, type ReactNode } from 'react';\nimport { TopLoader, type TopLoaderConfig } from './top-loader.tsx';\n\n// ─── Rendered Tree ──────────────────────────────────────────────\n\n/**\n * The tree the router has handed to React, and the state publish that belongs\n * to it. They travel as one object so React's commit of the tree is the event\n * that publishes — see the effect in NavigationRoot. Every `render` builds a\n * fresh one, which is what keys that effect: a tree is published once, however\n * many times React re-runs the effect for it.\n */\nexport interface RenderedTree {\n element: ReactNode;\n /**\n * Publishes the navigation's state — segment cache, pathname, address bar,\n * history stack, and the client's record of the mounted tree — and\n * announces it to listeners outside React. Runs when React commits\n * `element`, never before (TIM-1301). Null for a render that has nothing to\n * publish on commit (hydration, the shallow search re-wrap).\n */\n publish: (() => void) | null;\n}\n\n/**\n * Hand a tree to React in a transition. `publish` runs when React commits it.\n *\n * Every path that puts a page on screen goes through one of these — a\n * navigation, a revalidation, a popstate replay, a shallow search re-wrap —\n * and it is always a synchronous `startTransition` around `root.render`.\n * The production one is `createReactRoot().render`.\n *\n * `types` are the view transition types this render animates as\n * (design/37-navigation-api.md §\"Transition types\"). They are added with\n * `addTransitionType` inside that same `startTransition`, and nowhere else:\n * React queues types per root and hands them to the next transition-only\n * commit, so a type added in any other scope describes whichever tree commits\n * next rather than this one (TIM-1463, TIM-1471). Empty for the shallow search\n * re-wrap, which re-renders the displayed page rather than changing it.\n */\nexport type NavigationRender = (\n element: ReactNode,\n publish: (() => void) | null,\n types: readonly string[]\n) => void;\n\n// ─── Hard Navigation Guard ──────────────────────────────────────\n\n/**\n * Module-level flag indicating a hard (MPA) navigation is in progress.\n *\n * When true:\n * - NavigationRoot throws an unresolved thenable to suspend forever,\n * preventing React from rendering children during page teardown\n * (avoids \"Rendered more hooks\" crashes).\n * - The Navigation API handler skips interception, letting the browser\n * perform a full page load (prevents infinite loops where\n * window.location.href → navigate event → router.navigate → 500 →\n * window.location.href → ...).\n *\n * Uses globalThis for singleton guarantee across chunks (same pattern\n * as NavigationContext). See design/19-client-navigation.md §\"Singleton\n * Guarantee via globalThis\".\n */\nconst HARD_NAV_KEY = Symbol.for('__timber_hard_navigating');\n\nfunction getHardNavStore(): { value: boolean } {\n const g = globalThis as Record<symbol, unknown>;\n if (!g[HARD_NAV_KEY]) {\n g[HARD_NAV_KEY] = { value: false };\n }\n return g[HARD_NAV_KEY] as { value: boolean };\n}\n\n/**\n * Set the hard-navigating flag. Call this BEFORE setting\n * window.location.href or window.location.reload() to prevent:\n * 1. React from rendering children during page teardown\n * 2. Navigation API from intercepting the hard navigation\n */\nexport function setHardNavigating(value: boolean): void {\n getHardNavStore().value = value;\n}\n\n/**\n * Check if a hard navigation is in progress.\n * Used by NavigationRoot (throw unresolvedThenable) and by the\n * Navigation API handler (skip interception).\n */\nexport function isHardNavigating(): boolean {\n return getHardNavStore().value;\n}\n\n/**\n * A thenable that never resolves. When thrown during React render,\n * it causes the component to suspend forever — React keeps the\n * old committed tree visible and never attempts to render children.\n *\n * This is the same pattern Next.js uses in app-router.tsx for MPA\n * navigations (pushRef.mpaNavigation → throw unresolvedThenable).\n */\n// for React's Suspense mechanism. Same pattern as Next.js's unresolvedThenable.\n// eslint-disable-next-line unicorn/no-thenable -- Intentionally a never-resolving thenable\nconst unresolvedThenable = { then() {} } as PromiseLike<never>;\n\n// ─── Component ───────────────────────────────────────────────────\n\n/**\n * Root component the router renders the page through.\n *\n * Renders the TopLoader alongside the tree it is given. Neither adds a DOM\n * element on the hydration path, so the tree matches the server HTML.\n *\n * Rendered only by `createReactRoot` (client/react-root.ts): hydration passes\n * `{ element, publish: null }`, and every later render is a synchronous\n * `startTransition(() => root.render(...))` with a fresh `rendered` object.\n */\nexport function NavigationRoot({\n rendered,\n topLoaderConfig,\n}: {\n rendered: RenderedTree;\n topLoaderConfig?: TopLoaderConfig;\n}): ReactNode {\n // Publish the navigation's state when React commits its tree — not when the\n // tree is handed over. A tree React is still waiting on, or one a later\n // navigation replaces before React renders it, has been *given* to React\n // without being on screen; publishing then describes a route the user never\n // saw, which is the defect this ordering exists to prevent (TIM-1301).\n //\n // A **layout** effect, so the publish lands before the browser paints and,\n // more importantly, before every descendant's passive effect. A destination\n // component that navigates from a mount effect — a redirect guard, a\n // `refresh()` on mount — would otherwise start its navigation while the\n // segment cache, address bar and pathname still described the departing\n // route, and send an X-Timber-State-Tree for a tree that is no longer\n // mounted (codex on #998).\n //\n // Descendant *layout* effects still run first: React runs layout effects\n // child-before-parent, and the only way to precede them would be a fiber\n // rendered as an earlier sibling of the payload. That is not free here —\n // `server/ssr-wrappers.tsx` mirrors this component's fiber shape so `useId`\n // agrees across hydration, and an extra sibling shifts every id in the\n // payload subtree. A layout effect that navigates on mount is the price.\n //\n // Keyed on the tree object rather than on the effect run. A publish moves\n // the address bar, which is not idempotent, so any second invocation for the\n // same tree — an effect re-run React is entitled to perform, StrictMode's\n // double-invoke — must be a no-op rather than a second history entry.\n const publishedRef = useRef<RenderedTree | null>(null);\n useLayoutEffect(() => {\n if (publishedRef.current === rendered) return;\n publishedRef.current = rendered;\n rendered.publish?.();\n }, [rendered]);\n\n // ─── Hard navigation guard ─────────────────────────────────\n // When a hard navigation is in progress (500 error, version skew),\n // suspend forever to prevent React from rendering children during\n // page teardown. This avoids \"Rendered more hooks\" crashes in\n // CHILD components whose hook counts may shift during teardown.\n //\n // CRITICAL: This throw MUST come AFTER all hooks (the useRef and\n // useLayoutEffect above). React requires the same hooks to run on every\n // render. If we threw before hooks, React would see 0 hooks on the\n // re-render vs 2 on the initial render — triggering the exact \"Rendered\n // more hooks\" error we're trying to prevent.\n //\n // By placing it after hooks but before the return, all hooks\n // satisfy React's rules, but the thrown thenable prevents any\n // children from rendering. Same pattern as Next.js app-router.tsx\n // (pushRef.mpaNavigation — also placed after all hooks).\n if (isHardNavigating()) {\n throw unresolvedThenable;\n }\n\n // Inject TopLoader alongside the element tree. It subscribes to the router's\n // pending store itself, so it takes no props from here beyond its config,\n // and only it re-renders when a navigation starts or ends. Its slot holds\n // `null` when the loader is disabled via config.\n //\n // This Fragment is a FORK — two children — so it advances React's tree\n // context and shifts every `useId` below it. `server/ssr-wrappers.tsx`\n // mirrors it for exactly that reason, and renders the document's default\n // <meta> tags in the first slot. The fork is unconditional so the server\n // never needs to know whether the loader is enabled: a `null` child still\n // counts toward the fork on both sides. See tests/ssr-wrapper-parity.test.ts.\n const showTopLoader = topLoaderConfig?.enabled !== false;\n return createElement(\n Fragment,\n null,\n showTopLoader ? createElement(TopLoader, { config: topLoaderConfig }) : null,\n rendered.element\n );\n}\n"],"mappings":";;;;;;AAcA,SAAgB,gBAAgB,QAA8B;CAC5D,iBAAiB,MAAM;AACzB;;;;;AAMA,SAAgB,YAA4B;CAC1C,IAAI,CAAC,cACH,MAAM,IAAI,MAAM,6EAA6E;CAE/F,OAAO;AACT;;;;;;AAOA,SAAgB,kBAAyC;CACvD,OAAO;AACT;;ACjCA,SAAS,UAAU,eAAuC;CACxD,MAAM,SAAS,gBAAgB;CAC/B,IAAI,CAAC,QAAQ,aAAa,CAAC;CAC3B,OAAO,OAAO,gBAAgB,aAAa;AAC7C;AAEA,SAAS,cAAuB;CAC9B,MAAM,SAAS,gBAAgB;CAC/B,OAAO,SAAS,OAAO,UAAU,IAAI;AACvC;AAEA,IAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;AAuB1B,SAAgB,uBAAgC;CAC9C,OAAO,qBAAqB,WAAW,aAAa,iBAAiB;AACvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEmEA,IAAM,eAAe,OAAO,IAAI,0BAA0B;AAE1D,SAAS,kBAAsC;CAC7C,MAAM,IAAI;CACV,IAAI,CAAC,EAAE,eACL,EAAE,gBAAgB,EAAE,OAAO,MAAM;CAEnC,OAAO,EAAE;AACX;;;;;;;AAQA,SAAgB,kBAAkB,OAAsB;CACtD,gBAAgB,CAAC,CAAC,QAAQ;AAC5B"}
@@ -1 +1 @@
1
- {"version":3,"file":"navigation-root.d.ts","sourceRoot":"","sources":["../../src/client/navigation-root.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,OAAO,EAAoD,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AACzF,OAAO,EAAa,KAAK,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAInE;;;;;;GAMG;AACH,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,SAAS,CAAC;IACnB;;;;;;OAMG;IACH,OAAO,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAC7B,OAAO,EAAE,SAAS,EAClB,OAAO,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,EAC5B,KAAK,EAAE,SAAS,MAAM,EAAE,KACrB,IAAI,CAAC;AA8BV;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAEtD;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAE1C;AAgBD;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,EAC7B,QAAQ,EACR,eAAe,GAChB,EAAE;IACD,QAAQ,EAAE,YAAY,CAAC;IACvB,eAAe,CAAC,EAAE,eAAe,CAAC;CACnC,GAAG,SAAS,CAsEZ"}
1
+ {"version":3,"file":"navigation-root.d.ts","sourceRoot":"","sources":["../../src/client/navigation-root.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,OAAO,EAAoD,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AACzF,OAAO,EAAa,KAAK,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAInE;;;;;;GAMG;AACH,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,SAAS,CAAC;IACnB;;;;;;OAMG;IACH,OAAO,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAC7B,OAAO,EAAE,SAAS,EAClB,OAAO,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,EAC5B,KAAK,EAAE,SAAS,MAAM,EAAE,KACrB,IAAI,CAAC;AA8BV;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAEtD;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAE1C;AAgBD;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,EAC7B,QAAQ,EACR,eAAe,GAChB,EAAE;IACD,QAAQ,EAAE,YAAY,CAAC;IACvB,eAAe,CAAC,EAAE,eAAe,CAAC;CACnC,GAAG,SAAS,CAuEZ"}
@@ -3,7 +3,10 @@ import { type ReactNode } from 'react';
3
3
  * Wraps the React tree with nuqs's adapter context, configured with
4
4
  * timber's default options.
5
5
  *
6
- * Auto-injected in browser-entry.ts — no user setup required.
6
+ * Auto-injected around the app on both sides — the browser's root render
7
+ * (browser-entry/router-init.ts) and the SSR wrapper chain
8
+ * (server/ssr-wrappers.tsx) — no user setup required. It must sit above
9
+ * NavigationProvider's consumers, which every `useQueryStates` caller is.
7
10
  */
8
11
  export declare function TimberNuqsAdapter({ children }: {
9
12
  children: ReactNode;
@@ -1 +1 @@
1
- {"version":3,"file":"nuqs-adapter.d.ts","sourceRoot":"","sources":["../../src/client/nuqs-adapter.tsx"],"names":[],"mappings":"AAcA,OAAO,EAAgC,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AA+FrE;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,SAAS,CAAA;CAAE,+BAatE"}
1
+ {"version":3,"file":"nuqs-adapter.d.ts","sourceRoot":"","sources":["../../src/client/nuqs-adapter.tsx"],"names":[],"mappings":"AAcA,OAAO,EAAW,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AA8GhD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,SAAS,CAAA;CAAE,+BAatE"}
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-entry.d.ts","sourceRoot":"","sources":["../../src/server/ssr-entry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AA4BH,OAAO,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AA4CvD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,SAAS,CAC7B,SAAS,EAAE,YAAY,EACvB,UAAU,EAAE,UAAU,GACrB,OAAO,CAAC,eAAe,CAAC,CAkN1B;eAEc,SAAS"}
1
+ {"version":3,"file":"ssr-entry.d.ts","sourceRoot":"","sources":["../../src/server/ssr-entry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AA4BH,OAAO,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AA4CvD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,SAAS,CAC7B,SAAS,EAAE,YAAY,EACvB,UAAU,EAAE,UAAU,GACrB,OAAO,CAAC,eAAe,CAAC,CAgN1B;eAEc,SAAS"}
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * The client tree (`renderTree` in browser-entry/router-init.ts, used by
11
11
  * hydrate.ts too) wraps the RSC element with:
12
- * NavigationRoot → Fragment(TopLoader, ...) →
12
+ * NavigationRoot → Fragment(TopLoader | null, ...) →
13
13
  * TimberNuqsAdapter → NuqsAdapterProvider →
14
14
  * SlotContentCacheContext.Provider → SegmentUpdateContext.Provider →
15
15
  * NavigationProvider → PayloadRoot → ParamsProvider → element
@@ -21,8 +21,9 @@
21
21
  * during SSR — the same code path as the browser — with the request's
22
22
  * pathname and raw search string. The raw string preserves repeated
23
23
  * query keys (`?tag=a&tag=b`) and, since TIM-1428, is the only
24
- * representation of search state here — it feeds the nuqs SSR adapter
25
- * too, so no collapsed record exists to drift from it.
24
+ * representation of search state here — nuqs reads it too, through the
25
+ * same TimberNuqsAdapter the browser renders, so no collapsed record
26
+ * exists to drift from it.
26
27
  * 2. `useSegmentParams()` resolves from ParamsContext, published by
27
28
  * PayloadRoot from the same payload root row the browser will read —
28
29
  * one derivation on both sides instead of two that must agree.
@@ -51,7 +52,7 @@ export interface SsrWrapOptions {
51
52
  pathname: string;
52
53
  /**
53
54
  * Raw app-visible query string (`''` or `?…`) for NavigationProvider AND
54
- * the nuqs SSR adapter — one representation, preserving repeated keys
55
+ * nuqs (through NavigationContext) — one representation, preserving repeated keys
55
56
  * (`?tag=a&tag=b`) on both consumers (TIM-1428).
56
57
  */
57
58
  search: string;
@@ -61,8 +62,6 @@ export interface SsrWrapOptions {
61
62
  * hands to the same component during hydration.
62
63
  */
63
64
  paramsSource: unknown;
64
- /** Whether the top loader is enabled (must match client config). */
65
- hasTopLoader: boolean;
66
65
  }
67
66
  /**
68
67
  * Wrap the SSR element tree with the same component boundaries as the
@@ -71,7 +70,7 @@ export interface SsrWrapOptions {
71
70
  *
72
71
  * Client tree (browser-entry/hydrate.ts):
73
72
  * NavigationRoot
74
- * → Fragment(TopLoader, element)
73
+ * → Fragment(TopLoader | null, element)
75
74
  * → TimberNuqsAdapter
76
75
  * → NuqsAdapterProvider (from createAdapterProvider)
77
76
  * → SlotContentCacheContext.Provider (client-only, single child)
@@ -82,9 +81,9 @@ export interface SsrWrapOptions {
82
81
  *
83
82
  * SSR tree (this function):
84
83
  * SsrNavigationRoot
85
- * → Fragment(SsrTopLoader, element)
86
- * → SsrNuqsWrapper
87
- * → NuqsAdapterProvider (from withNuqsSsrAdapter → createAdapterProvider)
84
+ * → Fragment(DocumentDefaults, element)
85
+ * → TimberNuqsAdapter (real — same component)
86
+ * → NuqsAdapterProvider
88
87
  * → NavigationProvider (real — same component)
89
88
  * → PayloadRoot → ParamsProvider (real — same components)
90
89
  * → [RSC element]
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-wrappers.d.ts","sourceRoot":"","sources":["../../src/server/ssr-wrappers.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AAEH,OAAO,EAA2B,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAkDhE,oDAAoD;AACpD,MAAM,WAAW,cAAc;IAC7B,+CAA+C;IAC/C,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,YAAY,EAAE,OAAO,CAAC;IACtB,oEAAoE;IACpE,YAAY,EAAE,OAAO,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,cAAc,GAAG,SAAS,CAmBlF"}
1
+ {"version":3,"file":"ssr-wrappers.d.ts","sourceRoot":"","sources":["../../src/server/ssr-wrappers.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAA2B,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAyChE,oDAAoD;AACpD,MAAM,WAAW,cAAc;IAC7B,+CAA+C;IAC/C,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,YAAY,EAAE,OAAO,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,cAAc,GAAG,SAAS,CAmBlF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timber-js/app",
3
- "version": "0.2.0-alpha.225",
3
+ "version": "0.2.0-alpha.226",
4
4
  "description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
5
5
  "keywords": [
6
6
  "cloudflare-workers",
@@ -218,19 +218,20 @@ export function NavigationRoot({
218
218
 
219
219
  // Inject TopLoader alongside the element tree. It subscribes to the router's
220
220
  // pending store itself, so it takes no props from here beyond its config,
221
- // and only it re-renders when a navigation starts or ends. Rendered only
222
- // when not explicitly disabled via config.
221
+ // and only it re-renders when a navigation starts or ends. Its slot holds
222
+ // `null` when the loader is disabled via config.
223
223
  //
224
224
  // This Fragment is a FORK — two children — so it advances React's tree
225
225
  // context and shifts every `useId` below it. `server/ssr-wrappers.tsx`
226
- // mirrors it for exactly that reason; a single-child wrapper would not need
227
- // a mirror. See tests/ssr-wrapper-parity.test.ts.
226
+ // mirrors it for exactly that reason, and renders the document's default
227
+ // <meta> tags in the first slot. The fork is unconditional so the server
228
+ // never needs to know whether the loader is enabled: a `null` child still
229
+ // counts toward the fork on both sides. See tests/ssr-wrapper-parity.test.ts.
228
230
  const showTopLoader = topLoaderConfig?.enabled !== false;
229
- if (!showTopLoader) return rendered.element;
230
231
  return createElement(
231
232
  Fragment,
232
233
  null,
233
- createElement(TopLoader, { config: topLoaderConfig }),
234
+ showTopLoader ? createElement(TopLoader, { config: topLoaderConfig }) : null,
234
235
  rendered.element
235
236
  );
236
237
  }
@@ -12,7 +12,7 @@
12
12
  */
13
13
  'use client';
14
14
 
15
- import { useState, useEffect, useMemo, type ReactNode } from 'react';
15
+ import { useMemo, type ReactNode } from 'react';
16
16
  import {
17
17
  unstable_createAdapterProvider as createAdapterProvider,
18
18
  renderQueryString,
@@ -22,6 +22,7 @@ import {
22
22
  import { getRouter } from './router-ref.ts';
23
23
  import { getNavigationApi } from './navigation-api.ts';
24
24
  import { locationSearch } from './location-search.ts';
25
+ import { useNavigationContext } from './navigation-context.ts';
25
26
 
26
27
  // ─── Adapter Hook ─────────────────────────────────────────────────
27
28
 
@@ -29,28 +30,36 @@ import { locationSearch } from './location-search.ts';
29
30
  * Custom adapter hook for nuqs. Returns the current search params
30
31
  * and an updateUrl function that integrates with timber's router.
31
32
  *
32
- * @param _watchKeys - param keys this hook instance cares about
33
- * (used by nuqs for selective re-rendering)
33
+ * nuqs calls this once per `useQueryStates` call, from the calling
34
+ * component, so every instance must read ONE source. It reads the router's:
35
+ * `NavigationContext.search`, the value `useSearchParams()` reads. The router
36
+ * moves it on every navigation, traversal and shallow write — the Navigation
37
+ * API's shallow handler and the History API patch both run
38
+ * `syncShallowSearch` (browser-entry/router-init.ts) — so the adapter needs
39
+ * no listeners of its own, and nuqs and `useSearchParams()` cannot disagree.
40
+ * During SSR the same provider carries the request's raw query string, so
41
+ * this one hook serves both sides.
42
+ *
43
+ * Per-instance state used to live here instead: a shallow write moved only
44
+ * the writer's copy, and every other `useQueryStates` call snapped back to
45
+ * the old value on its next render.
46
+ *
47
+ * @param watchKeys - URL keys this hook instance reads. The returned params
48
+ * hold only those keys and keep their identity while those keys are
49
+ * unchanged, so a write to another key does not re-render this instance's
50
+ * consumers through nuqs.
34
51
  */
35
- function useTimberAdapter(_watchKeys: string[]): AdapterInterface {
36
- const [searchParams, setSearchParams] = useState(() => new URLSearchParams(locationSearch()));
37
-
38
- // Sync search params on popstate (back/forward) and after
39
- // timber navigations that change the URL.
40
- useEffect(() => {
41
- function sync() {
42
- setSearchParams(new URLSearchParams(locationSearch()));
43
- }
44
-
45
- window.addEventListener('popstate', sync);
46
- // timber dispatches a custom event after client navigations complete
47
- window.addEventListener('timber:navigation-end', sync);
48
-
49
- return () => {
50
- window.removeEventListener('popstate', sync);
51
- window.removeEventListener('timber:navigation-end', sync);
52
- };
53
- }, []);
52
+ function useTimberAdapter(watchKeys: string[]): AdapterInterface {
53
+ const nav = useNavigationContext();
54
+ if (nav === null) {
55
+ throw new Error(
56
+ '[timber] useQueryStates() was called outside the timber app tree ' +
57
+ '(no NavigationProvider found). In tests, render the component ' +
58
+ 'inside the timber providers.'
59
+ );
60
+ }
61
+ const watched = filterKeys(new URLSearchParams(nav.search), watchKeys).toString();
62
+ const searchParams = useMemo(() => new URLSearchParams(watched), [watched]);
54
63
 
55
64
  const updateUrl = useMemo(() => {
56
65
  return (search: URLSearchParams, options: Required<AdapterOptions>) => {
@@ -63,9 +72,9 @@ function useTimberAdapter(_watchKeys: string[]): AdapterInterface {
63
72
  // info: { shallow: true } so the navigate event handler knows to
64
73
  // skip interception. Without this, the navigate event fired by
65
74
  // history.pushState/replaceState would trigger a full RSC fetch.
66
- const nav = getNavigationApi();
67
- if (nav) {
68
- nav.navigate(url.toString(), {
75
+ const navigation = getNavigationApi();
76
+ if (navigation) {
77
+ navigation.navigate(url.toString(), {
69
78
  history: options.history === 'push' ? 'push' : 'replace',
70
79
  info: { shallow: true },
71
80
  });
@@ -75,8 +84,8 @@ function useTimberAdapter(_watchKeys: string[]): AdapterInterface {
75
84
  method.call(window.history, window.history.state, '', url.toString());
76
85
  }
77
86
 
78
- // Update local state to reflect the new URL
79
- setSearchParams(new URLSearchParams(url.search));
87
+ // No local state to set: both paths reach the router's
88
+ // syncShallowSearch, which re-renders NavigationContext.
80
89
  } else {
81
90
  // Non-shallow (timber default): trigger RSC navigation to fetch
82
91
  // fresh server data for the new search params.
@@ -100,6 +109,12 @@ function useTimberAdapter(_watchKeys: string[]): AdapterInterface {
100
109
  };
101
110
  }
102
111
 
112
+ /** The entries of `search` whose key is in `keys`; all of them when `keys` is empty. */
113
+ function filterKeys(search: URLSearchParams, keys: string[]): URLSearchParams {
114
+ if (keys.length === 0) return search;
115
+ return new URLSearchParams([...search].filter(([key]) => keys.includes(key)));
116
+ }
117
+
103
118
  // ─── Provider Component ───────────────────────────────────────────
104
119
 
105
120
  // Lazily created — createAdapterProvider calls React.createElement internally,
@@ -111,7 +126,10 @@ let _TimberNuqsProvider: ReturnType<typeof createAdapterProvider> | undefined;
111
126
  * Wraps the React tree with nuqs's adapter context, configured with
112
127
  * timber's default options.
113
128
  *
114
- * Auto-injected in browser-entry.ts — no user setup required.
129
+ * Auto-injected around the app on both sides — the browser's root render
130
+ * (browser-entry/router-init.ts) and the SSR wrapper chain
131
+ * (server/ssr-wrappers.tsx) — no user setup required. It must sit above
132
+ * NavigationProvider's consumers, which every `useQueryStates` caller is.
115
133
  */
116
134
  export function TimberNuqsAdapter({ children }: { children: ReactNode }) {
117
135
  const Provider = (_TimberNuqsProvider ??= createAdapterProvider(useTimberAdapter));
@@ -175,12 +175,10 @@ export async function handleSsr(
175
175
  // real NavigationProvider and PayloadRoot, not no-op mirrors —
176
176
  // so hooks resolve identically and useId() matches on both sides.
177
177
  // See TIM-532, TIM-1424.
178
- const hasTopLoader = _runtimeConfig.topLoader?.enabled !== false;
179
178
  const wrappedElement = wrapSsrElement(element, {
180
179
  pathname: navContext.pathname,
181
180
  search: navContext.search,
182
181
  paramsSource: params,
183
- hasTopLoader,
184
182
  });
185
183
 
186
184
  // Render to HTML stream (waits for onShellReady).
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * The client tree (`renderTree` in browser-entry/router-init.ts, used by
11
11
  * hydrate.ts too) wraps the RSC element with:
12
- * NavigationRoot → Fragment(TopLoader, ...) →
12
+ * NavigationRoot → Fragment(TopLoader | null, ...) →
13
13
  * TimberNuqsAdapter → NuqsAdapterProvider →
14
14
  * SlotContentCacheContext.Provider → SegmentUpdateContext.Provider →
15
15
  * NavigationProvider → PayloadRoot → ParamsProvider → element
@@ -21,8 +21,9 @@
21
21
  * during SSR — the same code path as the browser — with the request's
22
22
  * pathname and raw search string. The raw string preserves repeated
23
23
  * query keys (`?tag=a&tag=b`) and, since TIM-1428, is the only
24
- * representation of search state here — it feeds the nuqs SSR adapter
25
- * too, so no collapsed record exists to drift from it.
24
+ * representation of search state here — nuqs reads it too, through the
25
+ * same TimberNuqsAdapter the browser renders, so no collapsed record
26
+ * exists to drift from it.
26
27
  * 2. `useSegmentParams()` resolves from ParamsContext, published by
27
28
  * PayloadRoot from the same payload root row the browser will read —
28
29
  * one derivation on both sides instead of two that must agree.
@@ -46,53 +47,44 @@
46
47
  */
47
48
 
48
49
  import { createElement, Fragment, type ReactNode } from 'react';
49
- import { withNuqsSsrAdapter } from './nuqs-ssr-provider.tsx';
50
+ import { TimberNuqsAdapter } from '../client/nuqs-adapter.tsx';
50
51
  import { NavigationProvider } from '../client/navigation-context.ts';
51
52
  import { PayloadRoot } from '../client/params-context.ts';
52
53
 
53
54
  /**
54
55
  * SSR equivalent of NavigationRoot.
55
56
  *
56
- * On the client, the router renders NavigationRoot via `root.render` in a transition,
57
- * rendering `Fragment(TopLoader, element)` — or the element alone when the top
58
- * loader is disabled.
59
- *
60
- * The Fragment is the part that matters: it forks, so it advances React's tree
61
- * context. Both sides must agree on whether it is there, which is why
62
- * `hasTopLoader` is threaded in from the same config the client reads.
63
- */
64
- function SsrNavigationRoot({
65
- children,
66
- hasTopLoader,
67
- }: {
68
- children?: ReactNode;
69
- hasTopLoader: boolean;
70
- }): ReactNode {
71
- if (hasTopLoader) {
72
- return createElement(Fragment, null, createElement(SsrTopLoader, null), children);
73
- }
74
- return children as ReactNode;
75
- }
76
-
77
- /**
78
- * SSR equivalent of TopLoader.
79
- * Exists as a fiber node to match the client tree depth; renders nothing.
57
+ * On the client, the router renders NavigationRoot via `root.render` in a
58
+ * transition, rendering `Fragment(TopLoader | null, element)`. The Fragment is
59
+ * the part that matters: it forks, so it advances React's tree context, and it
60
+ * is unconditional on both sides — the loader's config only decides what fills
61
+ * the first slot.
80
62
  */
81
- function SsrTopLoader(): ReactNode {
82
- return null;
63
+ function SsrNavigationRoot({ children }: { children?: ReactNode }): ReactNode {
64
+ return createElement(Fragment, null, createElement(DocumentDefaults, null), children);
83
65
  }
84
66
 
85
67
  /**
86
- * SSR equivalent of TimberNuqsAdapter component boundary.
87
- * The actual NuqsAdapterProvider (from createAdapterProvider) is added
88
- * inside this wrapper via withNuqsSsrAdapter, matching the client's
89
- * TimberNuqsAdapter → NuqsAdapterProvider nesting.
68
+ * The document's framework defaults (design/16-metadata.md §"No Separate
69
+ * Viewport Type"), in the TopLoader's slot.
70
+ *
71
+ * Server-only: the browser renders TopLoader (or nothing) here, and React
72
+ * leaves head nodes it did not render alone during hydration, so the tags
73
+ * stay for the life of the document — no RSC payload, partial or full,
74
+ * carries them.
75
+ *
76
+ * Rendered before the payload so these are the FIRST charset/viewport tags
77
+ * Fizz collects. React writes every viewport <meta> into the head in render
78
+ * order, and browsers apply the last one, so a viewport <meta> in the app's
79
+ * root layout overrides this default rather than being overridden by it.
90
80
  */
91
- function SsrNuqsWrapper({ search, children }: { search: string; children?: ReactNode }): ReactNode {
92
- // withNuqsSsrAdapter creates a NuqsAdapterProvider (from createAdapterProvider),
93
- // which is the same component factory used by TimberNuqsAdapter on the client.
94
- // Both produce the same internal component boundary depth.
95
- return withNuqsSsrAdapter(search, children);
81
+ function DocumentDefaults(): ReactNode {
82
+ return createElement(
83
+ Fragment,
84
+ null,
85
+ createElement('meta', { charSet: 'utf-8' }),
86
+ createElement('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1' })
87
+ );
96
88
  }
97
89
 
98
90
  /** Per-request inputs for the SSR wrapper chain. */
@@ -101,7 +93,7 @@ export interface SsrWrapOptions {
101
93
  pathname: string;
102
94
  /**
103
95
  * Raw app-visible query string (`''` or `?…`) for NavigationProvider AND
104
- * the nuqs SSR adapter — one representation, preserving repeated keys
96
+ * nuqs (through NavigationContext) — one representation, preserving repeated keys
105
97
  * (`?tag=a&tag=b`) on both consumers (TIM-1428).
106
98
  */
107
99
  search: string;
@@ -111,8 +103,6 @@ export interface SsrWrapOptions {
111
103
  * hands to the same component during hydration.
112
104
  */
113
105
  paramsSource: unknown;
114
- /** Whether the top loader is enabled (must match client config). */
115
- hasTopLoader: boolean;
116
106
  }
117
107
 
118
108
  /**
@@ -122,7 +112,7 @@ export interface SsrWrapOptions {
122
112
  *
123
113
  * Client tree (browser-entry/hydrate.ts):
124
114
  * NavigationRoot
125
- * → Fragment(TopLoader, element)
115
+ * → Fragment(TopLoader | null, element)
126
116
  * → TimberNuqsAdapter
127
117
  * → NuqsAdapterProvider (from createAdapterProvider)
128
118
  * → SlotContentCacheContext.Provider (client-only, single child)
@@ -133,9 +123,9 @@ export interface SsrWrapOptions {
133
123
  *
134
124
  * SSR tree (this function):
135
125
  * SsrNavigationRoot
136
- * → Fragment(SsrTopLoader, element)
137
- * → SsrNuqsWrapper
138
- * → NuqsAdapterProvider (from withNuqsSsrAdapter → createAdapterProvider)
126
+ * → Fragment(DocumentDefaults, element)
127
+ * → TimberNuqsAdapter (real — same component)
128
+ * → NuqsAdapterProvider
139
129
  * → NavigationProvider (real — same component)
140
130
  * → PayloadRoot → ParamsProvider (real — same components)
141
131
  * → [RSC element]
@@ -154,9 +144,9 @@ export function wrapSsrElement(element: ReactNode, opts: SsrWrapOptions): ReactN
154
144
  withParams
155
145
  );
156
146
 
157
- // 3. TimberNuqsAdapter equivalent (wraps withNuqsSsrAdapter for the actual nuqs provider)
158
- const withNuqs = createElement(SsrNuqsWrapper, { search: opts.search }, withNav);
147
+ // 3. The nuqs adapter — the browser's own; it reads search from NavigationContext.
148
+ const withNuqs = createElement(TimberNuqsAdapter, null, withNav);
159
149
 
160
150
  // 4. Outermost: NavigationRoot equivalent (the TopLoader fork)
161
- return createElement(SsrNavigationRoot, { hasTopLoader: opts.hasTopLoader }, withNuqs);
151
+ return createElement(SsrNavigationRoot, null, withNuqs);
162
152
  }
@@ -1,32 +0,0 @@
1
- /**
2
- * Server-side nuqs adapter provider for SSR rendering.
3
- *
4
- * During SSR, `'use client'` components that call nuqs hooks (useQueryStates,
5
- * useQueryState) need the nuqs adapter context. The client adapter
6
- * (TimberNuqsAdapter) relies on `window` and React hooks that are
7
- * client-only. This provider supplies a static, SSR-safe adapter
8
- * that feeds the current request's search params into the nuqs context.
9
- *
10
- * The returned component wraps the React tree so that nuqs hooks render
11
- * the correct initial values during server-side rendering. On the client,
12
- * TimberNuqsAdapter (injected by browser-entry.ts) takes over.
13
- *
14
- * Design doc: design/23-search-params.md §"Custom Adapter"
15
- */
16
- import { type ReactNode } from 'react';
17
- /**
18
- * Wrap the SSR element tree with a nuqs adapter context.
19
- *
20
- * Called by ssr-entry.ts before passing the element to renderSsrStream.
21
- * Takes the NavContext raw query string and provides it to nuqs hooks
22
- * running during SSR so they render with the correct initial values.
23
- *
24
- * The raw string — not a collapsed record — is what preserves repeated
25
- * query keys (`?tag=a&tag=b`) for nuqs multi parsers, matching the raw
26
- * `location.search` the client adapter reads after hydration (TIM-1428).
27
- *
28
- * @param search - The request's raw app-visible query string (`''` or `?…`)
29
- * @param children - The React element tree to wrap
30
- */
31
- export declare function withNuqsSsrAdapter(search: string, children: ReactNode): ReactNode;
32
- //# sourceMappingURL=nuqs-ssr-provider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"nuqs-ssr-provider.d.ts","sourceRoot":"","sources":["../../src/server/nuqs-ssr-provider.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAiB,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AA2BtD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,GAAG,SAAS,CAMjF"}
@@ -1,64 +0,0 @@
1
- /**
2
- * Server-side nuqs adapter provider for SSR rendering.
3
- *
4
- * During SSR, `'use client'` components that call nuqs hooks (useQueryStates,
5
- * useQueryState) need the nuqs adapter context. The client adapter
6
- * (TimberNuqsAdapter) relies on `window` and React hooks that are
7
- * client-only. This provider supplies a static, SSR-safe adapter
8
- * that feeds the current request's search params into the nuqs context.
9
- *
10
- * The returned component wraps the React tree so that nuqs hooks render
11
- * the correct initial values during server-side rendering. On the client,
12
- * TimberNuqsAdapter (injected by browser-entry.ts) takes over.
13
- *
14
- * Design doc: design/23-search-params.md §"Custom Adapter"
15
- */
16
-
17
- import { createElement, type ReactNode } from 'react';
18
- import {
19
- unstable_createAdapterProvider as createAdapterProvider,
20
- type unstable_AdapterInterface as AdapterInterface,
21
- } from 'nuqs/adapters/custom';
22
-
23
- // ─── SSR Adapter ──────────────────────────────────────────────────
24
-
25
- /**
26
- * Create a nuqs adapter provider for SSR that serves a static snapshot
27
- * of search params. The `updateUrl` is a no-op because URL updates
28
- * cannot happen on the server.
29
- */
30
- function makeNuqsSsrAdapter(searchParams: URLSearchParams) {
31
- function useNuqsSsrAdapter(_watchKeys: string[]): AdapterInterface {
32
- return {
33
- searchParams,
34
- updateUrl: () => {},
35
- getSearchParamsSnapshot: () => searchParams,
36
- };
37
- }
38
-
39
- return createAdapterProvider(useNuqsSsrAdapter);
40
- }
41
-
42
- // ─── Provider Component ───────────────────────────────────────────
43
-
44
- /**
45
- * Wrap the SSR element tree with a nuqs adapter context.
46
- *
47
- * Called by ssr-entry.ts before passing the element to renderSsrStream.
48
- * Takes the NavContext raw query string and provides it to nuqs hooks
49
- * running during SSR so they render with the correct initial values.
50
- *
51
- * The raw string — not a collapsed record — is what preserves repeated
52
- * query keys (`?tag=a&tag=b`) for nuqs multi parsers, matching the raw
53
- * `location.search` the client adapter reads after hydration (TIM-1428).
54
- *
55
- * @param search - The request's raw app-visible query string (`''` or `?…`)
56
- * @param children - The React element tree to wrap
57
- */
58
- export function withNuqsSsrAdapter(search: string, children: ReactNode): ReactNode {
59
- const searchParams = new URLSearchParams(search);
60
- const Provider = makeNuqsSsrAdapter(searchParams);
61
- // AdapterProvider types require children in the props object (not as 3rd arg)
62
- // eslint-disable-next-line react/no-children-prop
63
- return createElement(Provider, { defaultOptions: { shallow: false, scroll: true }, children });
64
- }