@real-router/react 0.28.17 → 0.28.19

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.
@@ -0,0 +1,2 @@
1
+ const e=require("./useRoute-D2vAzKWM.js"),t=require("./RouterProviderCore-DE6VCzL6.js");let n=require("react"),r=require("react/jsx-runtime"),i=require("@real-router/sources");const a=`data-real-router-announcer`,o=Object.freeze({destroy:()=>{}});let s=0,c=0;function l(e,t){if(typeof document>`u`)return o;let n=t?.prefix??`Navigated to `,r=t?.getAnnouncementText,i=!0,a=!1,l=!1,m=``,h=null,g,{element:_,generation:v}=u();s+=1;let y=(e,t)=>{m=e,clearTimeout(g),_.textContent=e,g=setTimeout(()=>{_.textContent=``,m=``},7e3),p(t)},b=setTimeout(()=>{if(a=!0,h!==null&&!l){let e=h;h=null,y(e,document.querySelector(`h1`))}},100),x=e.subscribe(({route:e})=>{if(i){i=!1;return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(l)return;let t=document.querySelector(`h1`),i=f(e,n,r,t);if(!(!i||i===m)){if(!a){h=i;return}y(i,t)}})})});return{destroy(){l||(l=!0,x(),clearTimeout(g),clearTimeout(b),v===c&&(--s,s===0&&d(_)))}}}function u(){let e=document.querySelector(`[${a}]`);if(e)return{element:e,generation:c};s=0,c+=1;let t=document.createElement(`div`);return t.setAttribute(`style`,`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);clip-path:inset(50%);white-space:nowrap;border:0`),t.setAttribute(`aria-live`,`assertive`),t.setAttribute(`aria-atomic`,`true`),t.setAttribute(a,``),(document.body??document.documentElement).prepend(t),{element:t,generation:c}}function d(e){e.remove()}function f(e,t,n,r){if(n)try{let t=n(e);if(t)return t}catch(e){console.error(`[real-router] getAnnouncementText threw; falling back to default resolution.`,e)}let i=(r?.textContent??``).trim(),a=e.name.startsWith(`@@`)?``:e.name;return`${t}${i||document.title||a||globalThis.location.pathname}`}function p(e){e&&(e.hasAttribute(`tabindex`)||e.setAttribute(`tabindex`,`-1`),e.focus({preventScroll:!0}))}const m=Object.freeze({destroy:()=>{}});function h(e,t){if(globalThis.window===void 0)return m;let n=t?.mode??`restore`;if(n===`native`)return m;let r=t?.anchorScrolling??!0,i=t?.scrollContainer,a=t?.behavior??`auto`,o=t?.storageKey??`real-router:scroll`,s,c=()=>{if(s!==void 0)return s;try{let e=sessionStorage.getItem(o);s=e?JSON.parse(e):{}}catch{s={}}return s},l=(e,t)=>{try{let n=c();if(n[e]===t)return;n[e]=t,sessionStorage.setItem(o,JSON.stringify(n))}catch{}},u=history.scrollRestoration;try{history.scrollRestoration=`manual`}catch{}let d=()=>{let e=i?.();return e?e.scrollTop:globalThis.scrollY},f=e=>{let t=i?.();t?t.scrollTo({top:e,left:0,behavior:a}):globalThis.scrollTo({top:e,left:0,behavior:a})},p=e=>{if(!i){globalThis.scrollTo({top:e,left:0,behavior:a});return}let t=0,n=()=>{if(g)return;let r=i();if(r){if(r.scrollTo({top:e,left:0,behavior:a}),a!==`smooth`&&Math.abs(r.scrollTop-e)<=1)return}else globalThis.scrollTo({top:e,left:0,behavior:a});t>=10||(t+=1,requestAnimationFrame(n))};n()},h=e=>{let t=e.context?.url?.hash;if(t!==void 0){if(r&&t.length>0){let e=document.getElementById(t);if(e){e.scrollIntoView({behavior:a});return}}f(0);return}let n=globalThis.location.hash;if(r&&n.length>1){let e;try{e=decodeURIComponent(n.slice(1))}catch{e=n.slice(1)}let t=document.getElementById(e);if(t){t.scrollIntoView({behavior:a});return}}f(0)},g=!1,v=!1,y=!0,b=e=>{try{return _(e)}catch{return v||(v=!0,console.error(`[real-router] scroll-restore: route "${e.name}" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`)),null}},x=e.subscribe(({route:e,previousRoute:t})=>{let r=e.context.navigation;if(t&&y){let e=b(t);e!==null&&l(e,d())}y=!1,requestAnimationFrame(()=>{if(!g){if(y=!0,n===`top`){h(e);return}if(e.transition.reload||r?.navigationType===`reload`){let t=b(e);p(t===null?0:c()[t]??0);return}if(r?.direction===`back`||r?.navigationType===`traverse`){let t=b(e);p(t===null?0:c()[t]??0);return}e.transition.replace||r?.navigationType===`replace`||h(e)}})}),S=()=>{let t=e.getState();if(t){let e=b(t);e!==null&&l(e,d())}};return globalThis.addEventListener(`pagehide`,S),{destroy:()=>{g=!0,x(),globalThis.removeEventListener(`pagehide`,S);try{history.scrollRestoration=u}catch{}}}}const g=new WeakMap;function _(e){let t=g.get(e);if(t!==void 0)return t;let n=`${e.name}:${v(e.params)}`;return g.set(e,n),n}function v(e){return JSON.stringify(e,y)}function y(e,t){if(typeof t==`function`)return`<fn>`;if(typeof t==`symbol`)return`<sym>`;if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.create(null),n=Object.keys(t).sort((e,t)=>e.localeCompare(t));for(let r of n)e[r]=t[r];return e}return t}const b=Object.freeze({destroy:()=>{}}),x=e=>e.context?.url,S=e=>{let t=null,n=1/0,r=null,i=-1/0;for(let a of e){if(!a.isIntersecting)continue;let e=a.rootBounds?.top??0,o=a.boundingClientRect.top-e;o>=0?o<n&&(t=a,n=o):o>i&&(r=a,i=o)}return t??r},C=(e,t)=>{let n=null,r=e=>{let n=e.context;n&&n.url===void 0&&(console.warn(`[real-router] scroll-spy: state.context.url is not claimed. Spy requires browser-plugin or navigation-plugin. Disabling.`),t())},i=e.getState();if(i)r(i);else{let t=!1;n=e.subscribe(({route:e})=>{t||(t=!0,r(e),n?.(),n=null)})}return{destroy(){n?.(),n=null}}},w=e=>{let t=!1,n=null,r=null,i=null,a=()=>{n!==null&&(clearTimeout(n),n=null),i&&(r??globalThis).removeEventListener(`scrollend`,i),i=null,r=null,t=!1};return{get active(){return t},start(){a(),t=!0;let o=()=>{a()};i=o,r=e(),(r??globalThis).addEventListener(`scrollend`,o,{once:!0}),n=setTimeout(o,500)},destroy(){a()}}},T=(e,t)=>{let n=null,r=null;return{schedule(){n===null&&(n=requestAnimationFrame(()=>{n=null,r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,e()},t)}))},destroy(){n!==null&&(cancelAnimationFrame(n),n=null),r!==null&&(clearTimeout(r),r=null)}}},E=(e,t,n,r,i,a)=>{let o=new Set,s=new Map,c=!1,l=null,u=e=>{if(!a()){for(let t of e)s.set(t.target,t);r()}},d=e=>new IntersectionObserver(u,{root:e,rootMargin:t,threshold:0}),f=n(),p=d(f),m=()=>{let t=n()??document,r;try{r=t.querySelectorAll(e)}catch{i();return}let a=new Set;for(let e of r){let t=e.id;t&&!c&&(a.has(t)&&(c=!0,console.warn(`[real-router] scroll-spy: duplicate id "${t}" observed. Selection picks the topmost visible match deterministically.`)),a.add(t)),!o.has(e)&&(p.observe(e),o.add(e))}},h={childList:!0,subtree:!0,attributes:!0,attributeFilter:[`id`]},g=null,_=()=>{for(let e of o)e.isConnected||(p.unobserve(e),o.delete(e),s.delete(e));let e=n();e!==f&&(f=e,p.disconnect(),p=d(e),o.clear(),s.clear(),g?.disconnect(),g?.observe(e??document.body,h)),m()};return m(),g=new MutationObserver(()=>{l!==null&&clearTimeout(l),l=setTimeout(()=>{l=null,_()},250)}),g.observe(f??document.body,h),{pending:s,isContainerDetached:()=>f!==null&&!f.isConnected,reconcile:_,destroy(){p.disconnect(),g.disconnect(),l!==null&&(clearTimeout(l),l=null),o.clear(),s.clear()}}};function D(e,t){if(typeof document>`u`||typeof IntersectionObserver>`u`)return b;let{selector:n}=t;if(!n)return b;let r=t.rootMargin??`-20% 0px -60% 0px`,a=t.scrollContainer,o=()=>a?.()??null,s=!1,c=!1,l=!1,u=()=>c||s,d=null,f=(0,i.getTransitionSource)(e),p=C(e,()=>{c=!0}),m=w(o),h=T(()=>{d?.()},150),g=E(n,r,o,()=>{h.schedule()},()=>{c||(c=!0,console.warn(`[real-router] scroll-spy: invalid selector "${n}". Disabling.`))},u);d=()=>{if(s||c){g.pending.clear();return}if(f.getSnapshot().isTransitioning||m.active)return;let t=S(g.pending.values());if(g.pending.clear(),!t)return;let n=t.target.id;if(!n)return;let r=e.getState();if(!r||n===x(r)?.hash)return;let i={hash:n,replace:!0,force:!0,hashChange:!0};l=!0,e.navigate(r.name,r.params,i).catch(()=>{}).finally(()=>{l=!1})};let _=e.subscribe(({route:e})=>{l||(g.isContainerDetached()&&g.reconcile(),x(e)?.hashChanged&&m.start())});return{destroy(){s=!0,_(),g.destroy(),h.destroy(),m.destroy(),p.destroy()}}}const O=Object.freeze({destroy:()=>{}});function k(e){if(typeof document>`u`||typeof document.startViewTransition!=`function`)return O;let t=null,n=null,r=!1,i=()=>{t?.(),t=null},a=e.subscribeLeave(({signal:e})=>{if(!e.aborted)return r=!1,i(),new Promise(a=>{let o=new Promise(e=>{t=e});e.addEventListener(`abort`,()=>{r||(i(),n?.skipTransition?.(),a())},{once:!0});try{n=document.startViewTransition(()=>(a(),o))}catch{i(),a()}})}),o=e.subscribe(()=>{let e=t;if(r=!0,t=null,e===null)n=null;else{let t=n;setTimeout(()=>{e(),n===t&&(n=null)},0)}});return{destroy:()=>{a(),o(),n?.skipTransition?.(),n=null,i()}}}function A(e,n){return e.routeName===n.routeName&&e.className===n.className&&e.activeClassName===n.activeClassName&&e.activeStrict===n.activeStrict&&e.ignoreQueryParams===n.ignoreQueryParams&&e.onClick===n.onClick&&e.target===n.target&&e.style===n.style&&e.children===n.children&&e.hash===n.hash&&t.u(e.routeParams,n.routeParams)&&t.u(e.routeOptions,n.routeOptions)}const j=(0,n.memo)(({routeName:i,routeParams:a,routeOptions:o=e.n,className:s,activeClassName:c=`active`,activeStrict:l=!1,ignoreQueryParams:u=!0,hash:d,onClick:f,target:p,children:m,...h})=>{let g=t.p(),_=t.o(i,a,l,u,d),v=a??e.r,y=t.c(g,i,v,d===void 0?void 0:{hash:d}),b=e=>{f&&(f(e),e.defaultPrevented)||!t.d(e.nativeEvent)||p===`_blank`||(e.preventDefault(),t.l(g,i,v,d,o).catch(()=>{}))},x=(0,n.useMemo)(()=>t.s(_,c,s),[_,c,s]);return(0,r.jsx)(`a`,{...h,href:y,className:x,onClick:b,children:m})},A);j.displayName=`Link`;const M=({router:e,children:i,announceNavigation:a,scrollRestoration:o,scrollSpy:s,viewTransitions:c})=>{let u=a!==void 0&&a!==!1,d=typeof a==`object`?a:void 0,f=d?.prefix;(0,n.useEffect)(()=>{if(!u)return;let t=l(e,d);return()=>{t.destroy()}},[e,u,f]);let p=o?.mode,m=o?.anchorScrolling,g=o?.behavior,_=o?.storageKey,v=o!==void 0;(0,n.useEffect)(()=>{if(!v)return;let t=h(e,{mode:p,anchorScrolling:m,behavior:g,storageKey:_,scrollContainer:o.scrollContainer});return()=>{t.destroy()}},[e,v,p,m,g,_]);let y=s?.selector,b=s?.rootMargin,x=s!==void 0&&y!==void 0&&y!==``;return(0,n.useEffect)(()=>{if(!x)return;let t=D(e,{selector:y,rootMargin:b,scrollContainer:s.scrollContainer});return()=>{t.destroy()}},[e,x,y,b]),(0,n.useEffect)(()=>{if(!c)return;let t=k(e);return()=>{t.destroy()}},[e,c]),(0,r.jsx)(t.t,{router:e,children:i})};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return M}});
2
+ //# sourceMappingURL=RouterProvider-C9eXwr7W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RouterProvider-C9eXwr7W.js","names":["NOOP_INSTANCE","NOOP_INSTANCE","NOOP_INSTANCE","shallowEqual","EMPTY_OPTIONS","useRouter","useIsActiveRoute","EMPTY_PARAMS","buildHref","shouldNavigate","buildActiveClassName","RouterProviderCore"],"sources":["../../../../shared/dom-utils/route-announcer.ts","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/scroll-spy.ts","../../../../shared/dom-utils/view-transitions.ts","../../src/components/Link.tsx","../../src/RouterProvider.tsx"],"sourcesContent":["import type { Router, State } from \"@real-router/core\";\n\nconst CLEAR_DELAY = 7000;\nconst SAFARI_READY_DELAY = 100;\nconst ANNOUNCER_ATTR = \"data-real-router-announcer\";\nconst INTERNAL_ROUTE_PREFIX = \"@@\";\nconst VISUALLY_HIDDEN =\n \"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);clip-path:inset(50%);white-space:nowrap;border:0\";\n\nexport interface RouteAnnouncerOptions {\n prefix?: string;\n getAnnouncementText?: (route: State) => string;\n}\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n// Live (non-NOOP) instances sharing the single `[data-real-router-announcer]`\n// aria-live element. The element is created once by the first instance\n// (`getOrCreateAnnouncer`) and reused by the rest; it must be removed only when\n// the LAST holder is destroyed. Without this count the first provider's\n// destroy() would detach the shared node while sibling providers (micro-\n// frontends — the same multi-provider scenario `scroll-restore`'s `storageKey`\n// exists for) keep writing to the now-orphaned node → silent screen reader (#783).\nlet announcerRefCount = 0;\n// Generation token (#1217): bumped each time a FRESH shared element is created.\n// Each instance captures the generation live at construction; on destroy it\n// touches the shared refcount / element ONLY if its generation is still current.\n// A stale instance — whose element a host wiped without calling destroy() — must\n// not decrement the new generation's refcount (→ negative) or remove its live\n// element (removeAnnouncer used to query by selector = whoever is in the DOM).\nlet announcerGeneration = 0;\n\nexport function createRouteAnnouncer(\n router: Router,\n options?: RouteAnnouncerOptions,\n): { destroy: () => void } {\n // Defensive SSR / non-browser guard: in SSR (Node.js) or non-DOM\n // environments, `document` is undefined and the announcer cannot\n // attach its aria-live region. Return a frozen NOOP_INSTANCE — same\n // pattern as `createDirectionTracker`, `createScrollRestoration`, and\n // `createViewTransitions`. Without this guard, `NavigationAnnouncer`\n // component construction would throw `ReferenceError: document is not\n // defined` under `@angular/ssr` rendering, tearing down the whole SSR\n // bootstrap. Closes review-2026-05-10 §5.10 ⛔ \"NavigationAnnouncer\n // SSR mode\" MED.\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const prefix = options?.prefix ?? \"Navigated to \";\n const getCustomText = options?.getAnnouncementText;\n\n let isInitialNavigation = true;\n let isReady = false;\n let isDestroyed = false;\n let lastAnnouncedText = \"\";\n let pendingText: string | null = null;\n let clearTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const { element: announcer, generation: myGeneration } =\n getOrCreateAnnouncer();\n\n announcerRefCount += 1;\n\n const doAnnounce = (text: string, h1: HTMLElement | null): void => {\n lastAnnouncedText = text;\n clearTimeout(clearTimeoutId);\n announcer.textContent = text;\n clearTimeoutId = setTimeout(() => {\n announcer.textContent = \"\";\n lastAnnouncedText = \"\";\n }, CLEAR_DELAY);\n\n manageFocus(h1);\n };\n\n // Safari-ready delay: announcing before VoiceOver wires up the aria-live region\n // causes the first announcement to be silently dropped. Wait SAFARI_READY_DELAY ms\n // before marking the announcer \"ready\" — any navigation during that window is\n // buffered in pendingText and flushed once the delay expires.\n const safariTimeoutId = setTimeout(() => {\n isReady = true;\n\n if (pendingText !== null && !isDestroyed) {\n const text = pendingText;\n\n pendingText = null;\n doAnnounce(text, document.querySelector<HTMLElement>(\"h1\"));\n }\n }, SAFARI_READY_DELAY);\n\n const unsubscribe = router.subscribe(({ route }) => {\n if (isInitialNavigation) {\n isInitialNavigation = false;\n\n return;\n }\n\n // Double rAF: waits for two paint frames so the incoming route's DOM\n // (including the new <h1>) is fully rendered before resolveText reads it.\n // Single rAF fires before the new route's template has been attached,\n // which would cause resolveText to pick up the OLD h1 or fall back to\n // document.title / route.name prematurely.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n if (isDestroyed) {\n return;\n }\n\n const h1 = document.querySelector<HTMLElement>(\"h1\");\n const text = resolveText(route, prefix, getCustomText, h1);\n\n if (!text || text === lastAnnouncedText) {\n return;\n }\n\n if (!isReady) {\n // Defer announcement until Safari-ready window elapses (see safariTimeoutId).\n pendingText = text;\n\n return;\n }\n\n doAnnounce(text, h1);\n });\n });\n });\n\n return {\n destroy() {\n // Idempotency guard — required so the ref-count is decremented EXACTLY\n // once per instance. A double destroy() must not drop the count below the\n // number of live holders (which would detach a sibling's element, or\n // leave it attached forever).\n if (isDestroyed) {\n return;\n }\n\n isDestroyed = true;\n unsubscribe();\n clearTimeout(clearTimeoutId);\n clearTimeout(safariTimeoutId);\n\n // Ownership guard (#1217): if a host wiped the shared element out from\n // under us, the next getOrCreateAnnouncer bumped the generation for the\n // fresh element. A stale instance must NOT decrement the new generation's\n // refcount (→ negative) or remove its live element — bail if not current.\n if (myGeneration !== announcerGeneration) {\n return;\n }\n\n announcerRefCount -= 1;\n\n // Only the last holder tears down the shared element — via our captured\n // ref, not a selector query (which would delete whoever's element is\n // currently in the DOM, i.e. a newer generation's).\n if (announcerRefCount === 0) {\n removeAnnouncer(announcer);\n }\n },\n };\n}\n\nfunction getOrCreateAnnouncer(): {\n element: HTMLElement;\n generation: number;\n} {\n const existing = document.querySelector<HTMLElement>(`[${ANNOUNCER_ATTR}]`);\n\n if (existing) {\n return { element: existing, generation: announcerGeneration };\n }\n\n // Creating a FRESH element means no live instance is validly sharing one, so\n // the ref-count restarts from zero (the caller increments immediately after).\n // Without this, an element removed out from under live instances — a host\n // wiping the subtree, or a consumer test whose teardown clears the DOM\n // without calling every instance's destroy() — would leave a stale positive\n // count that prevents the new element from ever being torn down (#783).\n // The generation bump (#1217) lets the wiped element's instances recognize\n // themselves as stale so their destroy() does not touch this fresh element.\n announcerRefCount = 0;\n announcerGeneration += 1;\n\n const element = document.createElement(\"div\");\n\n element.setAttribute(\"style\", VISUALLY_HIDDEN);\n element.setAttribute(\"aria-live\", \"assertive\");\n element.setAttribute(\"aria-atomic\", \"true\");\n element.setAttribute(ANNOUNCER_ATTR, \"\");\n\n // Defensive SSR / pre-`<body>` guard: in some environments (early\n // injection, deferred-body documents, certain SSR rehydration paths)\n // `document.body` can be null when the announcer is constructed.\n // `document.body.prepend(...)` would throw `TypeError: Cannot read\n // properties of null`, tearing down the consumer's RouterProvider /\n // NavigationAnnouncer mount. Fallback to `documentElement` keeps the\n // announcer working for SR users; visual-hidden styling means there is\n // no visible artifact regardless of mount point.\n //\n // TS dom lib types `document.body` as `HTMLElement` (non-null), but\n // runtime can return null per spec. The `as` cast narrows the type to\n // include null so the `??` short-circuit is type-safe.\n ((document.body as HTMLElement | null) ?? document.documentElement).prepend(\n element,\n );\n\n return { element, generation: announcerGeneration };\n}\n\nfunction removeAnnouncer(element: HTMLElement): void {\n element.remove();\n}\n\nfunction resolveText(\n route: State,\n prefix: string,\n getCustomText: ((route: State) => string) | undefined,\n h1: HTMLElement | null,\n): string {\n if (getCustomText) {\n try {\n const customText = getCustomText(route);\n\n // Mini-sprint E.4 (audit-5 §4.2 #4) — empty-string fallback.\n // A consumer pattern like\n // getAnnouncementText: (route) => myMap[route.name] ?? \"\"\n // returns `\"\"` for routes outside the map. The subscribe loop\n // then sees an empty text and silently no-announces — screen\n // readers stay quiet without any signal to the developer. Treat\n // a falsy custom result (`\"\"` / `null` / `undefined`) as\n // \"consumer doesn't have a name for this route\" and fall through\n // to the default resolution chain (h1 → title → route name).\n if (customText) {\n return customText;\n }\n } catch (error) {\n // A throwing consumer callback inside the router's subscribe loop\n // would tear down sibling listeners — log and fall through to the\n // built-in resolution chain so the announcer keeps working.\n console.error(\n \"[real-router] getAnnouncementText threw; falling back to default resolution.\",\n error,\n );\n }\n }\n\n const h1Text = (h1?.textContent ?? \"\").trim();\n const routeName = route.name.startsWith(INTERNAL_ROUTE_PREFIX)\n ? \"\"\n : route.name;\n const rawText =\n h1Text || document.title || routeName || globalThis.location.pathname;\n\n return `${prefix}${rawText}`;\n}\n\nfunction manageFocus(h1: HTMLElement | null): void {\n if (!h1) {\n return;\n }\n\n if (!h1.hasAttribute(\"tabindex\")) {\n h1.setAttribute(\"tabindex\", \"-1\");\n }\n\n h1.focus({ preventScroll: true });\n}\n","import type { Router, State } from \"@real-router/core\";\n\nconst DEFAULT_STORAGE_KEY = \"real-router:scroll\";\n\n// Bounded retry budget for resolving a late-mounting scroll container on the\n// restore path. A per-route container (e.g. an `overflow:auto` div rendered\n// only on one route) can be committed to the DOM a few frames after the\n// navigation settles — heavier routes paint later than the subscribe's rAF.\n// ~10 frames (≈160ms at 60fps) comfortably covers a React commit of a large\n// route without being perceptible. See the doc-block on `restorePos`.\nconst RESTORE_RETRY_FRAMES = 10;\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport type ScrollRestorationMode = \"restore\" | \"top\" | \"native\";\n\nexport interface ScrollRestorationOptions {\n mode?: ScrollRestorationMode | undefined;\n anchorScrolling?: boolean | undefined;\n scrollContainer?: (() => HTMLElement | null) | undefined;\n /**\n * Scroll behavior passed to `scrollTo({ behavior })` and\n * `scrollIntoView({ behavior })`.\n *\n * - `\"auto\"` (default) — browser-defined, usually instant.\n * - `\"instant\"` — explicit instant jump (no animation).\n * - `\"smooth\"` — animated transition. Note: smooth restore on back/traverse\n * can feel disorienting if the user expects to land at the saved position\n * immediately. Recommended for `mode: \"top\"` or anchor scroll only.\n *\n * See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior).\n */\n behavior?: ScrollBehavior | undefined;\n /**\n * sessionStorage key used to persist saved scroll positions. Default:\n * `\"real-router:scroll\"`. Override only when multiple independent\n * `RouterProvider` instances share the same document and you need to\n * isolate their scroll stores (e.g. micro-frontends, embedded widgets,\n * or testing). For a single app with one provider the default is fine.\n */\n storageKey?: string | undefined;\n}\n\ninterface NavigationContext {\n direction?: \"forward\" | \"back\" | \"unknown\";\n navigationType?: \"push\" | \"replace\" | \"traverse\" | \"reload\";\n}\n\nexport function createScrollRestoration(\n router: Router,\n options?: ScrollRestorationOptions,\n): { destroy: () => void } {\n if (typeof globalThis.window === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const mode = options?.mode ?? \"restore\";\n\n // mode \"native\" = utility does nothing. Don't flip history.scrollRestoration,\n // don't subscribe, don't register pagehide — `history.scrollRestoration`\n // stays at the browser default (\"auto\") so the browser handles scroll\n // restore natively. (Note: this is the OPPOSITE of `history.scrollRestoration\n // === \"manual\"` — utility's \"native\" leaves the DOM property at \"auto\" so\n // the browser is in charge.)\n if (mode === \"native\") {\n return NOOP_INSTANCE;\n }\n\n const anchorEnabled = options?.anchorScrolling ?? true;\n const getContainer = options?.scrollContainer;\n const behavior: ScrollBehavior = options?.behavior ?? \"auto\";\n const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;\n\n // Write-through in-memory cache: parse sessionStorage once per provider\n // mount, then mutate in-memory. Avoids a JSON.parse + JSON.stringify pair\n // on every subscribeLeave / pagehide event.\n let store: Record<string, number> | undefined;\n\n const loadStore = (): Record<string, number> => {\n if (store !== undefined) {\n return store;\n }\n\n try {\n const raw = sessionStorage.getItem(storageKey);\n\n store = raw ? (JSON.parse(raw) as Record<string, number>) : {};\n } catch {\n store = {};\n }\n\n return store;\n };\n\n const putPos = (key: string, pos: number): void => {\n try {\n const cached = loadStore();\n\n // Skip-same-value: when a route is left at the same scroll position it\n // already holds in the cache (e.g. tab-switching without scrolling),\n // both the in-memory write and the JSON.stringify + setItem pair are\n // no-ops. Eliminates redundant serialization on the navigation hot\n // path for the common \"click tabs without scrolling\" case.\n if (cached[key] === pos) {\n return;\n }\n\n cached[key] = pos;\n sessionStorage.setItem(storageKey, JSON.stringify(cached));\n } catch {\n // Ignore quota / security errors.\n }\n };\n\n const prevScrollRestoration = history.scrollRestoration;\n\n try {\n history.scrollRestoration = \"manual\";\n } catch {\n // Ignore — some embedded contexts may reject the assignment.\n }\n\n // Resolve the container lazily on every event so containers mounted AFTER\n // the provider still get correct scroll handling. Falls back to window when\n // the getter is absent or returns null (pre-mount).\n const readPos = (): number => {\n const element = getContainer?.();\n\n return element ? element.scrollTop : globalThis.scrollY;\n };\n\n const writePos = (top: number): void => {\n const element = getContainer?.();\n\n if (element) {\n element.scrollTo({ top, left: 0, behavior });\n } else {\n globalThis.scrollTo({ top, left: 0, behavior });\n }\n };\n\n // Restore path (back / traverse / reload). Unlike `writePos`, this tolerates a\n // scroll container that both MOUNTS and LAYS OUT a few frames AFTER the\n // navigation settles.\n //\n // The capture-side `readPos` always runs against an already-mounted DOM (the\n // route being left). On restore the target route — and its container — is\n // still being committed by the view layer. The subscribe callback schedules a\n // single rAF; for a heavy route (e.g. a long virtual list) the framework's\n // commit can land AFTER that frame. Two distinct failures follow, each losing\n // the saved position (Scenario 6 e2e, reproduced under CI's slower runner):\n //\n // 1. Container not mounted yet → `getContainer()` is `null`, the scroll\n // silently falls back to `window`, which on a container-only route has\n // nothing to scroll.\n // 2. Container mounted but its content not laid out yet → `scrollHeight`\n // is still small, so a single `scrollTo({ top })` clamps short of the\n // saved position and never re-applies once layout grows.\n //\n // With no `scrollContainer` getter the target is always `window`, present\n // from the first frame — restore in a single shot (unchanged behaviour). When\n // a getter is configured we cannot tell \"this route legitimately uses window\"\n // from \"the container is still mounting\", so re-apply the scroll on every\n // frame for a bounded budget: window as a fallback while the container is\n // absent (harmless clamp on container routes), the container itself once it\n // appears. For instant restores we stop early the moment the position sticks;\n // smooth restores animate asynchronously, so they run the full budget. The\n // frame budget is the hard backstop against an unreachable target (saved\n // position taller than the restored content).\n const restorePos = (top: number): void => {\n if (!getContainer) {\n globalThis.scrollTo({ top, left: 0, behavior });\n\n return;\n }\n\n let frames = 0;\n\n const attempt = (): void => {\n if (destroyed) {\n return;\n }\n\n const element = getContainer();\n\n if (element) {\n element.scrollTo({ top, left: 0, behavior });\n\n // Instant restore landed within rounding tolerance → done; no point\n // re-applying. Smooth restore never matches synchronously, so let it\n // ride the budget.\n if (behavior !== \"smooth\" && Math.abs(element.scrollTop - top) <= 1) {\n return;\n }\n } else {\n globalThis.scrollTo({ top, left: 0, behavior });\n }\n\n if (frames >= RESTORE_RETRY_FRAMES) {\n return;\n }\n\n frames += 1;\n requestAnimationFrame(attempt);\n };\n\n attempt();\n };\n\n const scrollToHashOrTop = (route: State): void => {\n // URL plugin path (#532): `state.context.url.hash` is the source of truth\n // when one of the URL plugins (browser-plugin / navigation-plugin) is\n // installed. The value is already DECODED — feeding it through\n // `decodeURIComponent` again would throw on a bare `%`.\n const ctxHash = (route.context as { url?: { hash?: string } } | undefined)\n ?.url?.hash;\n\n if (ctxHash !== undefined) {\n if (anchorEnabled && ctxHash.length > 0) {\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(ctxHash);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n\n return;\n }\n\n // Fallback path: no URL plugin, read the DOM. `location.hash` is\n // percent-encoded; ids in the DOM are the raw string, so decode for the\n // match. Fall back to the raw slice if the hash contains a malformed\n // escape sequence (decodeURIComponent throws on those).\n const hash = globalThis.location.hash;\n\n if (anchorEnabled && hash.length > 1) {\n let id: string;\n\n try {\n id = decodeURIComponent(hash.slice(1));\n } catch {\n id = hash.slice(1);\n }\n\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(id);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n };\n\n let destroyed = false;\n let unserializableWarned = false;\n // Capture/effect seam guard (#782). previousRoute's position is captured\n // synchronously in `subscribe`, but the snap/restore effect runs a frame\n // later in rAF. Across that window the viewport still shows the route BEFORE\n // previousRoute, so a second navigation landing in the same frame would\n // capture that foreign position under previousRoute's key. `scrollSettled` is\n // false across the window — capture is skipped (previousRoute's own stored\n // value survives the transit). A real user scroll in this <16ms window is\n // physically impossible.\n let scrollSettled = true;\n\n // `keyOf` defers to `canonicalJson` which calls `JSON.stringify`. Two\n // realistic inputs blow up the serializer and would otherwise crash the\n // subscribe callback (taking scroll-restore offline for the whole session):\n // - `BigInt` params → `TypeError: Do not know how to serialize a BigInt`\n // - cyclic params (reactive proxies, DOM-ref back-pointers) → stack\n // overflow.\n // The defensive wrapper drops capture/restore for that specific navigation\n // and warns once per provider — the rest of the cache stays usable.\n const safeKeyOf = (state: State): string | null => {\n try {\n return keyOf(state);\n } catch {\n if (!unserializableWarned) {\n unserializableWarned = true;\n console.error(\n `[real-router] scroll-restore: route \"${state.name}\" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`,\n );\n }\n\n return null;\n }\n };\n\n const unsubscribe = router.subscribe(({ route, previousRoute }) => {\n const nav = (route.context as { navigation?: NavigationContext })\n .navigation;\n\n // Browsers dispatch reload as the initial navigation after refresh, so\n // previousRoute is undefined and capture is naturally skipped. The\n // pre-refresh position was already persisted via pagehide. Capture is also\n // skipped while the scroll is unsettled — a second navigation in the same\n // frame, before the prior nav's rAF snap (see `scrollSettled`, #782).\n if (previousRoute && scrollSettled) {\n const prevKey = safeKeyOf(previousRoute);\n\n if (prevKey !== null) {\n putPos(prevKey, readPos());\n }\n }\n\n // This navigation's scroll effect is now pending: the viewport position no\n // longer belongs to `route` until the rAF below runs and settles it.\n scrollSettled = false;\n\n requestAnimationFrame(() => {\n if (destroyed) {\n return;\n }\n\n // Effect running — the position now belongs to `route`, so the next\n // capture is honest again.\n scrollSettled = true;\n\n if (mode === \"top\") {\n scrollToHashOrTop(route);\n\n return;\n }\n\n // Restore branches (reload, back/traverse) MUST be evaluated before the\n // replace-skip below. Since #657 lifted `replace` into TransitionMeta, a\n // history TRAVERSAL (back/forward) under navigation-plugin carries\n // `transition.replace === true` — a traversal reuses an existing history\n // entry, which is replace-shaped at the history level. If the replace-skip\n // ran first it would swallow every back/forward navigation and restore\n // would never fire (the Scenario 6 e2e regression). Genuine in-place\n // replaces (`router.navigate({ replace: true })`, navigateToNotFound) are\n // not traversals and fall through to the skip below.\n //\n // Both arms of each check are required: `transition.reload` only fires for\n // programmatic `router.navigate({reload:true})`. F5 under navigation-plugin\n // primes `nav.navigationType === \"reload\"` via #531 getActivationType but\n // leaves opts.reload undefined, so dropping the plugin arm would regress F5\n // scroll-restore. Browser-plugin's F5 is not covered (no priming, out of\n // scope).\n if (route.transition.reload || nav?.navigationType === \"reload\") {\n const key = safeKeyOf(route);\n\n restorePos(key === null ? 0 : (loadStore()[key] ?? 0));\n\n return;\n }\n\n if (nav?.direction === \"back\" || nav?.navigationType === \"traverse\") {\n const key = safeKeyOf(route);\n\n restorePos(key === null ? 0 : (loadStore()[key] ?? 0));\n\n return;\n }\n\n // Genuine in-place replace (not a traversal) — leave scroll untouched.\n if (route.transition.replace || nav?.navigationType === \"replace\") {\n return;\n }\n\n scrollToHashOrTop(route);\n });\n });\n\n const onPageHide = (): void => {\n const current = router.getState();\n\n if (current) {\n const key = safeKeyOf(current);\n\n if (key !== null) {\n putPos(key, readPos());\n }\n }\n };\n\n globalThis.addEventListener(\"pagehide\", onPageHide);\n\n return {\n destroy: () => {\n // No `if (destroyed) return` guard: every teardown below is idempotent —\n // `unsubscribe()` is a `set.delete` in the core EventEmitter, DOM\n // `removeEventListener` is spec-idempotent, and the history assignment is\n // a plain re-set. There is no ref-count to protect (unlike\n // route-announcer's shared announcer element), so a double `destroy()` is\n // harmless. `destroyed = true` still gates any pending restore rAF / retry.\n destroyed = true;\n unsubscribe();\n globalThis.removeEventListener(\"pagehide\", onPageHide);\n\n try {\n history.scrollRestoration = prevScrollRestoration;\n } catch {\n // Ignore.\n }\n },\n };\n}\n\n/**\n * Internal cache-key builder for scroll-position storage.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the `(name, canonicalJson(params))` key shape\n * as a regression guard (§8b H20 / audit-2026-05-16 #S3). A change to\n * key format would silently lose scroll positions across an upgrade —\n * the test set is the contract.\n *\n * ## Identity-based memoization (audit-2026-05-17 §8b #2)\n *\n * `State` objects emitted by core are frozen per-navigation: their\n * `name` / `params` are immutable for the lifetime of the snapshot, and\n * any change produces a new `State` reference. A `WeakMap<State, string>`\n * therefore safely caches the canonicalised key by identity — repeat\n * `keyOf(state)` calls on the same snapshot (typical on\n * back/forward/traverse where the same prior `State` is re-emitted)\n * skip the recursive `canonicalJson` pass entirely.\n *\n * The cache key is the `State` reference, so entries auto-release when\n * the snapshot is GC'd — no eviction needed.\n */\nconst KEY_CACHE = new WeakMap<State, string>();\n\nexport function keyOf(state: State): string {\n const cached = KEY_CACHE.get(state);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const key = `${state.name}:${canonicalJson(state.params)}`;\n\n KEY_CACHE.set(state, key);\n\n return key;\n}\n\n/**\n * Stable JSON serializer with sorted object keys.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the key-order-insensitive property\n * (`canonicalJson({a:1,b:2}) === canonicalJson({b:2,a:1})`).\n *\n * ## Divergence from `@real-router/sources/canonicalJson` — by design\n *\n * Two independent implementations live in the monorepo:\n *\n * - **`shared/dom-utils/scroll-restore.canonicalJson`** (this file) — scroll\n * cache key builder. Uses `localeCompare` and a plain-object accumulator;\n * tolerates `__proto__`-keyed inputs only insofar as `JSON.stringify`'s\n * replacer happens to sort them; relies on `JSON.stringify`'s native cycle\n * detector. Designed to be cheap on the navigation hot path. The\n * surrounding [[safeKeyOf]] wrapper catches the two crash inputs (`BigInt`,\n * cyclic) and skips the offending capture/restore.\n *\n * - **`@real-router/sources/canonicalJson`** — sources cache key builder.\n * Uses byte-order compare (`< / >`) for locale-independence, a\n * `Object.create(null)` accumulator to prevent prototype pollution, and a\n * bespoke path-based cycle detector (the native one cannot see the cloned\n * graph). Throws eagerly on `Map`/`Set`/`RegExp`/cycles — the caller falls\n * back to a non-cached source.\n *\n * **They are intentionally NOT interchangeable.** Aligning them would either\n * regress scroll-restore performance (byte-order + recursive clone is heavier\n * per call) or weaken the sources cache (locale dependence breaks\n * deterministic cache keys across machines). No cross-package equivalence\n * test exists or should be added; the relationship is \"different invariants,\n * different costs, different consumers.\" Audit-2 / audit-2026-05-17 §2\n * documents the choice.\n */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(value, canonicalReplacer);\n}\n\nfunction canonicalReplacer(_key: string, val: unknown): unknown {\n // audit-2026-05-17 §5 MEDIUM (Sprint A.3) — function/Symbol marker.\n // `JSON.stringify` silently drops function and symbol values from\n // object output. Two routes that differ ONLY in a function/Symbol\n // value would canonicalize to the same string → silent scroll-cache\n // key collision (positions clobber each other). Replacing the value\n // with a sentinel string breaks the collision while keeping the\n // canonical form deterministic. The sentinels are intentionally\n // ASCII-only and lexically distinct from valid JSON-stringified\n // values; consumers will see `\"<fn>\"` / `\"<sym>\"` if they ever\n // round-trip the cache key, signalling the substitution clearly.\n if (typeof val === \"function\") {\n return \"<fn>\";\n }\n if (typeof val === \"symbol\") {\n return \"<sym>\";\n }\n\n if (val !== null && typeof val === \"object\" && !Array.isArray(val)) {\n // Null-prototype accumulator: a plain `{}` would interpret\n // `sorted[\"__proto__\"] = x` as a prototype assignment (silently dropped\n // from JSON.stringify output AND a prototype-pollution vector). Mirrors\n // the same guard in `@real-router/sources/canonicalJson`. The two\n // implementations are still intentionally divergent (see the doc-block\n // on [[canonicalJson]] above), but prototype-safety is non-negotiable\n // on both. Lock-test: scrollRestoreKey.properties.ts Invariant 11.\n const sorted = Object.create(null) as Record<string, unknown>;\n // eslint-disable-next-line unicorn/no-array-sort -- ng-packagr uses pre-ES2023 lib; toSorted unavailable\n const keys = Object.keys(val).sort((left: string, right: string) =>\n left.localeCompare(right),\n );\n\n for (const key of keys) {\n sorted[key] = (val as Record<string, unknown>)[key];\n }\n\n return sorted;\n }\n\n return val;\n}\n","import { getTransitionSource } from \"@real-router/sources\";\n\nimport type { NavigationOptions, Router } from \"@real-router/core\";\n\n/**\n * Router-coordinated scroll spy (#575).\n *\n * On `IntersectionObserver` notifications the utility picks the topmost\n * visible anchor inside the configured scroll container and emits a forced\n * same-route transition with `{ hash, replace: true, force: true, hashChange:\n * true }` through `router.navigate(...)`. The URL plugin\n * (`@real-router/browser-plugin` or `@real-router/navigation-plugin`) updates\n * `state.context.url.hash` so sibling hash-aware `<Link hash>` re-highlights\n * via the standard `createActiveRouteSource` pipeline.\n *\n * **Anti-flicker gates** (RFC §5.2):\n * 1. `getTransitionSource(router).getSnapshot().isTransitioning` — skip emits\n * while a transition is in-flight (re-entrant lock).\n * 2. `coolingDown` — set on a user-driven hash transition (e.g. `<Link hash>`\n * click + smooth `scrollIntoView`). Cleared on `scrollend` or after a\n * 500ms safety timeout. Spy's own emits are excluded via the synchronous\n * `selfEmitting` flag — required so the spy doesn't rate-limit itself.\n *\n * **Self-healing** (RFC §7.3): if the initial URL contains a hash without a\n * matching `id` (e.g. `/page#nonexistent`), the first IO event emitted right\n * after observe()-ing picks the topmost real anchor and corrects the URL.\n *\n * **Hash-only transition pipeline cost** (RFC §5.3): for same-route same-\n * params hash-only navigations, `getTransitionPath` returns empty\n * `toDeactivate` / `toActivate` arrays, so `runGuards` is a no-op. The only\n * work is the URL plugin's `onTransitionSuccess` write and the\n * `getTransitionSource` flip — cheap.\n *\n * **Architecture**: decomposed into 4 private subsystem closure factories\n * (`createUrlPluginDetector`, `createCooldown`, `createDebouncer`,\n * `createObserverPair`). The main `createScrollSpy` wires them together\n * around the shared `silenced` / `destroyed` / `selfEmitting` flags and the\n * `flush()` emit logic. Each subsystem owns its state + cleanup; `destroy()`\n * delegates to each. See section banners below.\n *\n * @returns A `ScrollSpy` handle whose `destroy()` is idempotent.\n */\nexport interface ScrollSpyOptions {\n /**\n * CSS selector for anchor candidates. Empty string `\"\"` or `undefined`\n * disables the spy (returns a NOOP handle). Common values:\n * `\"[id]\"`, `\"[id]:is(h1,h2,h3)\"`, `\"section[id]\"`.\n */\n selector: string;\n\n /**\n * `IntersectionObserver` `rootMargin`. Default\n * `\"-20% 0px -60% 0px\"` — an anchor is considered \"active\" once it crosses\n * into the top 20 % of the viewport (or scroll container).\n */\n rootMargin?: string | undefined;\n\n /**\n * Lazy getter for the scrollable container. Consulted at creation and\n * re-consulted on every reconcile (DOM mutation), so a container that\n * MOUNTS or CHANGES after the spy is created is honoured: the\n * `IntersectionObserver` root and `MutationObserver` target — both immutable\n * once constructed — are rebuilt to match (#780). `null` (or a missing\n * getter) falls back to the window viewport (`root: null` on the\n * `IntersectionObserver`).\n */\n scrollContainer?: (() => HTMLElement | null) | undefined;\n}\n\nexport interface ScrollSpy {\n /** Tear down observer + listeners. Idempotent. */\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: ScrollSpy = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n// Hardcoded internals (RFC §5.1 — promote only with evidence).\nconst RAF_DEBOUNCE_MS = 150;\nconst MUTATION_DEBOUNCE_MS = 250;\nconst COOLDOWN_TIMEOUT_MS = 500;\nconst DEFAULT_ROOT_MARGIN = \"-20% 0px -60% 0px\";\n\n// Local extension type — browser-plugin / navigation-plugin augment\n// `NavigationOptions` with `hash` and `hashChange`, but `shared/dom-utils`\n// is plugin-agnostic and cannot rely on the augmentation. Mirrors the\n// `HashAwareNavigationOptions` pattern in `link-utils.ts`.\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\n// The `url` namespace contract is owned by browser-env: both URL plugins\n// (browser-plugin, navigation-plugin) write `{ hash: string; hashChanged }` on\n// every transition. This is a local mirror (keeps dom-utils independent of\n// browser-env) and must match that canonical shape — `hash` is always present,\n// never a partial slice.\ninterface UrlContextSlice {\n hash: string;\n hashChanged: boolean;\n}\n\nconst getUrlContext = (state: {\n context?: unknown;\n}): UrlContextSlice | undefined =>\n (state.context as { url?: UrlContextSlice } | undefined)?.url;\n\n// =============================================================================\n// Picker — pure, no state. RFC §5.2 selection rule.\n// =============================================================================\n\n// Pick the anchor closest to the active zone top in viewport coordinates.\n// `entry.rootBounds.top` already reflects `rootMargin` (per W3C IO spec\n// §3.3) — for `rootMargin: \"-20% 0px -60% 0px\"` it returns 20% of root\n// height, for `\"-50% 0px -50% 0px\"` it returns the center, etc. Distance\n// = boundingClientRect.top − zoneTop in viewport pixels: positive = anchor\n// below zone top (just entered), negative = anchor above zone top (body\n// crossing zone from above). We prefer smallest non-negative; fall back to\n// least-negative when no entry has crossed yet.\n// Falls back to zoneTop = 0 when rootBounds is null (cross-origin roots,\n// unit tests). Single pass — handles `Iterable` so flushes can pass\n// `Map.values()` directly without realising the array.\nconst pickTopmost = (\n entries: Iterable<IntersectionObserverEntry>,\n): IntersectionObserverEntry | null => {\n let bestPositive: IntersectionObserverEntry | null = null;\n let bestPositiveDist = Number.POSITIVE_INFINITY;\n let bestNegative: IntersectionObserverEntry | null = null;\n let bestNegativeDist = Number.NEGATIVE_INFINITY;\n\n for (const entry of entries) {\n if (!entry.isIntersecting) {\n continue;\n }\n\n const zoneTop = entry.rootBounds?.top ?? 0;\n const distance = entry.boundingClientRect.top - zoneTop;\n\n if (distance >= 0) {\n if (distance < bestPositiveDist) {\n bestPositive = entry;\n bestPositiveDist = distance;\n }\n } else if (distance > bestNegativeDist) {\n bestNegative = entry;\n bestNegativeDist = distance;\n }\n }\n\n return bestPositive ?? bestNegative;\n};\n\n// =============================================================================\n// Subsystem: URL plugin detector (RFC §5.5)\n// Calls `onMissing` if `state.context` is published but `url` key is missing\n// (i.e. no URL plugin installed). Either synchronous on start, or deferred\n// via a one-shot `router.subscribe` if the router has not started yet.\n// `silenced` flag itself lives in main scope — detector signals via callback\n// (per Oracle Q1 — `silenced` has multiple unrelated triggers; main scope\n// owns the kill switch).\n// =============================================================================\n\ninterface UrlPluginDetector {\n destroy: () => void;\n}\n\nconst createUrlPluginDetector = (\n router: Router,\n onMissing: () => void,\n): UrlPluginDetector => {\n let detectionUnsub: (() => void) | null = null;\n\n const verify = (state: { context?: unknown }): void => {\n const context = state.context as\n (Record<string, unknown> & { url?: unknown }) | undefined;\n\n if (context && context.url === undefined) {\n console.warn(\n \"[real-router] scroll-spy: state.context.url is not claimed. \" +\n \"Spy requires browser-plugin or navigation-plugin. Disabling.\",\n );\n onMissing();\n }\n };\n\n const peekState = router.getState();\n\n if (peekState) {\n verify(peekState);\n } else {\n // Re-entry guard: `router.subscribe` MAY invoke the callback synchronously\n // from inside `.subscribe(...)` before the function returns. In that case\n // `detectionUnsub` is still `null` when the callback fires. Without this\n // boolean, a hypothetical multi-fire would double-warn.\n let detectionConsumed = false;\n\n detectionUnsub = router.subscribe(({ route }) => {\n /* v8 ignore next 3 -- @preserve: the multi-fire is hypothetical (see above) — the real router never invokes a subscriber synchronously twice before unsub; defensive guard, not testable without a contract-violating fake */\n if (detectionConsumed) {\n return;\n }\n\n detectionConsumed = true;\n verify(route);\n\n detectionUnsub?.();\n detectionUnsub = null;\n });\n }\n\n return {\n destroy(): void {\n detectionUnsub?.();\n detectionUnsub = null;\n },\n };\n};\n\n// =============================================================================\n// Subsystem: Cooldown gate (RFC §5.2 — anti-flicker for smooth scrollIntoView)\n// Set on user-driven `<Link hash>` click → smooth scroll. Cleared on\n// `scrollend` (Baseline 2026) or 500ms safety timeout (older Safari).\n// =============================================================================\n\ninterface Cooldown {\n readonly active: boolean;\n start: () => void;\n destroy: () => void;\n}\n\nconst createCooldown = (getContainer: () => HTMLElement | null): Cooldown => {\n let active = false;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let listenerContainer: HTMLElement | null = null;\n let listener: (() => void) | null = null;\n\n const clear = (): void => {\n if (timeout !== null) {\n clearTimeout(timeout);\n timeout = null;\n }\n\n if (listener) {\n const target: EventTarget = listenerContainer ?? globalThis;\n\n target.removeEventListener(\"scrollend\", listener);\n }\n\n listener = null;\n listenerContainer = null;\n active = false;\n };\n\n return {\n get active(): boolean {\n return active;\n },\n start(): void {\n // Reset rather than stack timers if cooldown is already active.\n clear();\n\n active = true;\n\n const lift = (): void => {\n clear();\n };\n\n listener = lift;\n listenerContainer = getContainer();\n\n const target: EventTarget = listenerContainer ?? globalThis;\n\n target.addEventListener(\"scrollend\", lift, { once: true });\n\n timeout = setTimeout(lift, COOLDOWN_TIMEOUT_MS);\n },\n destroy(): void {\n clear();\n },\n };\n};\n\n// =============================================================================\n// Subsystem: rAF + trailing debounce (RFC §5.1)\n// Coalesces a burst of IO events into ≤ 1 callback per debounce window.\n// rAF reduces N setTimeout creations to 1 per animation frame; the trailing\n// 150ms setTimeout waits for the IO stream to quiesce.\n// =============================================================================\n\ninterface Debouncer {\n schedule: () => void;\n destroy: () => void;\n}\n\nconst createDebouncer = (\n callback: () => void,\n trailingMs: number,\n): Debouncer => {\n let raf: number | null = null;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n\n return {\n schedule(): void {\n if (raf !== null) {\n return;\n }\n\n raf = requestAnimationFrame(() => {\n raf = null;\n\n if (timeout !== null) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(() => {\n timeout = null;\n callback();\n }, trailingMs);\n });\n },\n destroy(): void {\n if (raf !== null) {\n cancelAnimationFrame(raf);\n raf = null;\n }\n\n if (timeout !== null) {\n clearTimeout(timeout);\n timeout = null;\n }\n },\n };\n};\n\n// =============================================================================\n// Subsystem: Observer pair (IntersectionObserver + MutationObserver)\n// IO + MO genuinely form one subsystem — both write/read `observed` set and\n// `pending` map, and reconcile flow couples them. Per Oracle Q10, splitting\n// would force cross-subsystem references that re-introduce the wiring\n// problem we're trying to solve.\n//\n// Exposes `pending` directly (per Oracle Q4: hiding behind `consume()` adds\n// boilerplate without isolating the shared mutable state — observers write\n// from IO callbacks while main scope reads in `flush()`).\n// =============================================================================\n\ninterface ObserverPair {\n readonly pending: Map<Element, IntersectionObserverEntry>;\n /** True when a resolved container has since detached from the DOM (#1216). */\n isContainerDetached: () => boolean;\n /** Re-resolve the container + re-observe matches (rebuilds the pair on change). */\n reconcile: () => void;\n destroy: () => void;\n}\n\nconst createObserverPair = (\n selector: string,\n rootMargin: string,\n getContainer: () => HTMLElement | null,\n onIntersection: () => void,\n onInvalidSelector: () => void,\n isStopped: () => boolean,\n): ObserverPair => {\n const observed = new Set<Element>();\n // Latest IO entry per target — accumulated across batches. IO delivers\n // entries only for targets whose intersection state CHANGED (W3C IO\n // §3.2.1), so a fast scroll that lands two callbacks inside the same\n // debounce window must merge by target, not overwrite. Entries are\n // dropped from the map when their target leaves the DOM (see `reconcile`)\n // and on `destroy()`.\n const pending = new Map<Element, IntersectionObserverEntry>();\n\n let duplicateIdWarned = false;\n let mutationTimer: ReturnType<typeof setTimeout> | null = null;\n\n const handleIntersection: IntersectionObserverCallback = (entries) => {\n // Defensive: IO callback may fire AFTER `destroy()` if a queued event\n // was already scheduled by the browser before `disconnect()`. Cheap\n // belt-and-suspenders.\n if (isStopped()) {\n return;\n }\n\n for (const entry of entries) {\n pending.set(entry.target, entry);\n }\n\n onIntersection();\n };\n\n // Build (and rebuild) the IntersectionObserver for a given root. A root is\n // immutable once its IO is constructed, so `reconcile` recreates the IO via\n // this same factory when the resolved container changes (#780) — one\n // definition, two call sites.\n const makeIo = (container: HTMLElement | null): IntersectionObserver =>\n new IntersectionObserver(handleIntersection, {\n root: container,\n rootMargin,\n threshold: 0,\n });\n\n // Container the IntersectionObserver root + MutationObserver target are\n // built with. Both are immutable once the observer is constructed (W3C), so\n // a `scrollContainer` that resolves to a different element after creation —\n // most importantly one that MOUNTS after the spy starts (Angular wires the\n // spy at bootstrap, before any component renders; a docs route's container\n // mounts on navigation) — is only honoured by rebuilding the pair in\n // `reconcile`. Tracked here so `reconcile` can compare on every run (#780).\n let observerContainer = getContainer();\n\n let io = makeIo(observerContainer);\n\n const observeMatches = (): void => {\n const scope = getContainer() ?? document;\n let candidates: NodeListOf<Element>;\n\n try {\n candidates = scope.querySelectorAll(selector);\n } catch {\n onInvalidSelector();\n\n return;\n }\n\n const seenIds = new Set<string>();\n\n for (const element of candidates) {\n // Detect duplicate ids once (RFC §7.7). The DOM permits duplicate ids\n // even though it is a markup bug; the spy keeps working but picks the\n // first one deterministically via the topmost-visible rule.\n const id = (element as HTMLElement).id;\n\n if (id && !duplicateIdWarned) {\n if (seenIds.has(id)) {\n duplicateIdWarned = true;\n\n console.warn(\n `[real-router] scroll-spy: duplicate id \"${id}\" observed. ` +\n \"Selection picks the topmost visible match deterministically.\",\n );\n }\n\n seenIds.add(id);\n }\n\n if (observed.has(element)) {\n continue;\n }\n\n io.observe(element);\n observed.add(element);\n }\n };\n\n // MutationObserver init — reused when the observer is re-pointed at a new\n // container in `reconcile`. `childList: true, subtree: true` catches\n // structural changes; `attributes: true, attributeFilter: [\"id\"]` catches\n // anchor id renames (typical for client-rendered docs). The MO targets the\n // scroll container (or document.body for the window viewport).\n const MUTATION_OBSERVE_INIT: MutationObserverInit = {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [\"id\"],\n };\n\n // Null-then-assigned — the same forward-reference idiom as `flush` in the\n // main scope. `reconcile` re-points it on a container change, so it must be\n // in scope above its assignment; it is non-null by the time any async\n // mutation callback (or `reconcile`) runs.\n let mo: MutationObserver | null = null;\n\n const reconcile = (): void => {\n // Drop observed elements that left the DOM. Avoids observer holding\n // strong refs to detached nodes. Also drop their accumulated entry so\n // stale \"was intersecting\" state for a removed node cannot be picked\n // by `pickTopmost` after the node is gone.\n for (const element of observed) {\n if (element.isConnected) {\n continue;\n }\n\n io.unobserve(element);\n observed.delete(element);\n pending.delete(element);\n }\n\n // Honour a container that mounted (or changed) after construction (#780).\n // The IntersectionObserver root and MutationObserver target cannot be\n // mutated in place, so rebuild the pair under the new container. Clearing\n // `observed` + `pending` makes the rebuild equivalent to constructing the\n // spy with this container from the start: `observeMatches` below\n // re-populates the tracked set from the new container's scope, and the\n // stale merged snapshot (computed against the old root's geometry) is\n // dropped — one empty debounce window, acceptable for a rare event.\n const nextContainer = getContainer();\n\n if (nextContainer !== observerContainer) {\n observerContainer = nextContainer;\n\n io.disconnect();\n io = makeIo(nextContainer);\n observed.clear();\n pending.clear();\n\n mo?.disconnect();\n mo?.observe(nextContainer ?? document.body, MUTATION_OBSERVE_INIT);\n }\n\n observeMatches();\n };\n\n observeMatches();\n\n mo = new MutationObserver(() => {\n if (mutationTimer !== null) {\n clearTimeout(mutationTimer);\n }\n\n mutationTimer = setTimeout(() => {\n mutationTimer = null;\n reconcile();\n }, MUTATION_DEBOUNCE_MS);\n });\n\n mo.observe(observerContainer ?? document.body, MUTATION_OBSERVE_INIT);\n\n return {\n pending,\n // #1216: the MutationObserver is pointed at the container's OWN subtree, so\n // the container's removal (a mutation of its PARENT) is invisible — reconcile\n // never fires on it and a remounted container is never re-observed. Expose a\n // detach check + reconcile so the router.subscribe callback can re-resolve on\n // navigation (exactly when route-tied containers mount/die). When\n // `observerContainer` is null the MO already watches `document.body`, which\n // sees container mounts directly — so only a resolved-then-detached container\n // needs this nav-time nudge.\n isContainerDetached: (): boolean =>\n observerContainer !== null && !observerContainer.isConnected,\n reconcile,\n destroy(): void {\n io.disconnect();\n mo.disconnect();\n\n if (mutationTimer !== null) {\n clearTimeout(mutationTimer);\n mutationTimer = null;\n }\n\n observed.clear();\n pending.clear();\n },\n };\n};\n\n// =============================================================================\n// Main: compositional wiring\n// =============================================================================\n\nexport function createScrollSpy(\n router: Router,\n options: ScrollSpyOptions,\n): ScrollSpy {\n // SSR guard (RFC §7.5) — return early without warnings.\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n // Feature-detect IntersectionObserver — no polyfill ships (RFC §4).\n if (typeof IntersectionObserver === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const { selector } = options;\n\n // Empty selector → disabled. Documented opt-out for conditional enabling\n // (RFC §5.4 `scrollSpy={{ selector: enable ? \"[id]\" : \"\" }}`).\n if (!selector) {\n return NOOP_INSTANCE;\n }\n\n const rootMargin = options.rootMargin ?? DEFAULT_ROOT_MARGIN;\n const getContainer = options.scrollContainer;\n const resolveContainer = (): HTMLElement | null => getContainer?.() ?? null;\n\n // Shared lifecycle flags (Oracle Q1 — `silenced` has multiple unrelated\n // triggers; Oracle Q3 — `selfEmitting` synchronously bracketed around\n // `router.navigate()` cannot cleanly extract). Kept in main scope.\n let destroyed = false;\n let silenced = false;\n let selfEmitting = false;\n\n const isStopped = (): boolean => silenced || destroyed;\n\n // Symmetric late-binding (Oracle Q2): declare `flush` as nullable, wire\n // debouncer + observers, then assign the real implementation. Reads as\n // intentional wiring rather than accidental closure capture ordering.\n // The `flush?.()` call below safely no-ops if a callback somehow fires\n // before assignment (impossible in practice — IO/debounce are async).\n let flush: (() => void) | null = null;\n\n const transitionSource = getTransitionSource(router);\n\n const detector = createUrlPluginDetector(router, () => {\n silenced = true;\n });\n\n const cooldown = createCooldown(resolveContainer);\n\n const debouncer = createDebouncer(() => {\n flush?.();\n }, RAF_DEBOUNCE_MS);\n\n const observers = createObserverPair(\n selector,\n rootMargin,\n resolveContainer,\n () => {\n debouncer.schedule();\n },\n () => {\n if (silenced) {\n return;\n }\n\n silenced = true;\n\n console.warn(\n `[real-router] scroll-spy: invalid selector \"${selector}\". Disabling.`,\n );\n },\n isStopped,\n );\n\n flush = (): void => {\n if (destroyed || silenced) {\n observers.pending.clear();\n\n return;\n }\n\n // Gate-skipped flushes keep `pendingEntries` populated — the merged\n // state is still the best-known snapshot, and the next non-gated flush\n // consumes it. Clearing under a gate would re-introduce the overwrite\n // bug for any anchor whose intersection state did not change during\n // the gate window.\n if (transitionSource.getSnapshot().isTransitioning) {\n return;\n }\n\n if (cooldown.active) {\n return;\n }\n\n // No `if (pending.size === 0) return` fast-path: `pending` is never empty\n // here via any real path (a real IntersectionObserver always delivers ≥1\n // entry, so `handleIntersection` populates `pending` before scheduling; the\n // mutation reconcile that could drop entries runs at MUTATION_DEBOUNCE_MS\n // 250 > RAF_DEBOUNCE_MS 150, i.e. always AFTER the flush). And an empty map\n // is already handled identically below — `pickTopmost(∅)` is `null` → the\n // `if (!picked) return` guard — so the fast-path was both unreachable and\n // redundant.\n\n // Successful flush consumes the merged snapshot. We clear so that the\n // next debounce window starts fresh; an anchor that is still\n // intersecting will only stay observable if IO emits another event for\n // it (which it does whenever the anchor's intersection state actually\n // changes). Skipping the clear here would leak state from one user-\n // perceived \"scroll stop\" into the next.\n const picked = pickTopmost(observers.pending.values());\n\n observers.pending.clear();\n\n if (!picked) {\n // No anchor visible / above zone — preserve last hash (RFC §10 #5).\n return;\n }\n\n const newHash = (picked.target as HTMLElement).id;\n\n if (!newHash) {\n return;\n }\n\n const state = router.getState();\n\n if (!state) {\n return;\n }\n\n // `getUrlContext` is guaranteed present here (the URL-plugin detector\n // silences the spy otherwise), so `?.` only satisfies the `| undefined`\n // slice type. `newHash` is a non-empty id (guarded above), so it can never\n // equal an absent hash — no `?? \"\"` normalization needed for the compare.\n const currentHash = getUrlContext(state)?.hash;\n\n if (newHash === currentHash) {\n return;\n }\n\n // Emit the same-route same-params hash-only transition. URL plugin\n // writes `state.context.url.hash = newHash` + `hashChanged = true` in\n // its `onTransitionSuccess` claim.\n const opts: HashAwareNavigationOptions = {\n hash: newHash,\n replace: true,\n force: true,\n hashChange: true,\n };\n\n // Self-emit guard (RFC §5.2): set synchronously around our own\n // `router.navigate()` so the `router.subscribe` callback skips the\n // cooldown setup for spy-emitted transitions — otherwise spy would\n // rate-limit itself to ≤ 2 emits/s, contradicting the ≤ 10/s benchmark\n // target. Test coupling (Q8): preserve exact `.catch(noop).finally(reset)`\n // chain — migrating to `try/finally` over `await router.navigate(...)`\n // changes microtask schedule and breaks \"spy continues after rejection\".\n selfEmitting = true;\n router\n .navigate(state.name, state.params, opts)\n .catch(() => {\n // Fire-and-forget — suppress expected rejections (concurrent\n // navigate, router stopped, etc.) consistent with `<Link>` adapter\n // patterns.\n })\n .finally(() => {\n selfEmitting = false;\n });\n };\n\n // Cooldown setup on user-driven hash transitions. Spy's own emits are\n // distinguished via the synchronous `selfEmitting` flag (see `flush`).\n const unsubscribeRouter = router.subscribe(({ route }) => {\n if (selfEmitting) {\n return;\n }\n\n // #1216: a route-tied scroll container may have unmounted since the last\n // navigation. The container-scoped MutationObserver can't observe its own\n // removal (a mutation of its parent), so re-resolve + re-observe here —\n // navigation is exactly when such containers mount / die.\n if (observers.isContainerDetached()) {\n observers.reconcile();\n }\n\n if (getUrlContext(route)?.hashChanged) {\n cooldown.start();\n }\n });\n\n return {\n destroy(): void {\n // No `if (destroyed) return` idempotency guard: every subsystem teardown\n // below is itself idempotent (null-guarded timers, `set.delete` on the\n // router unsubscribe, spec-idempotent `IntersectionObserver.disconnect`),\n // and `destroy()` is not a hot path — so a redundant guard would only add\n // an unreachable branch. `destroyed = true` is still set to gate any\n // late-arriving IO/router callback via `isStopped()`.\n destroyed = true;\n\n // Unsubscribe FIRST to prevent late-arriving router transition\n // callback from calling `cooldown.start()` on a half-destroyed\n // instance. Without this ordering, a transition with `hashChanged:\n // true` firing between subsystem teardown and `unsubscribeRouter()`\n // would re-install a 500ms timer that survives `destroy()`. Verified\n // via Oracle review (Q5/Q7).\n unsubscribeRouter();\n\n observers.destroy();\n debouncer.destroy();\n cooldown.destroy();\n detector.destroy();\n },\n };\n}\n","import type { Router } from \"@real-router/core\";\n\nexport interface ViewTransitions {\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: ViewTransitions = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport function createViewTransitions(router: Router): ViewTransitions {\n if (\n typeof document === \"undefined\" ||\n typeof document.startViewTransition !== \"function\"\n ) {\n return NOOP_INSTANCE;\n }\n\n let closeVT: (() => void) | null = null;\n let currentVT: { skipTransition?: () => void } | null = null;\n // Tracks whether TRANSITION_SUCCESS fired for the current leave. Used to\n // distinguish \"benign cleanup abort\" (router's async path aborts its own\n // controller in a finally block after successful navigation) from \"real\n // cancellation\" (concurrent navigate, guard rejection, dispose).\n let successFired = false;\n\n const resolveAndClear = (): void => {\n closeVT?.();\n closeVT = null;\n };\n\n const offLeave = router.subscribeLeave(({ signal }) => {\n // Reentrant abort: signal already aborted when we're called. Open no VT\n // — router will fall through to TRANSITION_CANCELLED via isCurrentNav()\n // after leave resolves. addEventListener(\"abort\", ...) does not re-fire\n // for past events, so skipping startViewTransition is the safe path.\n if (signal.aborted) {\n return;\n }\n\n successFired = false;\n resolveAndClear();\n\n // Return a Promise so the router awaits until the browser invokes\n // updateCallback. This ensures old DOM snapshot is captured BEFORE the\n // router commits the new state — giving correct exit→state→entry\n // ordering (vs fire-and-forget, where URL changes before VT captures).\n return new Promise<void>((resolveLeave) => {\n // Capture the resolver synchronously BEFORE startViewTransition() is\n // called. The browser invokes updateCallback in a later task, but\n // router.subscribe (TRANSITION_SUCCESS) can fire before that. If we\n // captured `resolve` inside the callback, subscribe would see closeVT\n // still null and skip resolving — the deferred would hang for 4s\n // until the VT API aborts with TimeoutError.\n // eslint-disable-next-line unicorn/prefer-promise-with-resolvers -- frozen shared primitive; resolver captured synchronously before startViewTransition() by design (see comment above)\n const deferred = new Promise<void>((resolve) => {\n closeVT = resolve;\n });\n\n signal.addEventListener(\n \"abort\",\n () => {\n if (successFired) {\n // Router's async path (#finishAsyncNavigation) aborts its own\n // controller in a finally block AFTER completeTransition (and\n // thus AFTER subscribe fired). This is cleanup, not\n // cancellation — VT is progressing normally, do nothing.\n return;\n }\n\n // Real cancellation (concurrent navigate, dispose). Resolve the\n // deferred so updateCallback can complete, skip the VT so no\n // stale animation leaks, and unblock the router if the abort\n // fires before updateCallback was invoked.\n resolveAndClear();\n currentVT?.skipTransition?.();\n resolveLeave();\n },\n { once: true },\n );\n\n try {\n currentVT = document.startViewTransition(() => {\n // Resolving here unblocks the router at the moment the browser\n // enters updateCallback — by spec, old DOM snapshot is captured\n // before this callback runs. Router now proceeds through\n // activation guards and setState; the VT animation waits on\n // `deferred`, which is resolved from router.subscribe after a\n // task-queue tick (see NOTE on setTimeout below).\n resolveLeave();\n\n return deferred;\n });\n } catch {\n // Defensive: spec says startViewTransition doesn't throw under\n // normal conditions, but Chromium has had edge cases (detached\n // document, extension interference). Clean up and unblock router.\n resolveAndClear();\n resolveLeave();\n }\n });\n });\n\n const offSuccess = router.subscribe(() => {\n const resolver = closeVT;\n\n successFired = true;\n closeVT = null;\n\n if (resolver === null) {\n currentVT = null;\n } else {\n // The VT this resolver belongs to. If the next navigation opens a new VT\n // in the task-queue window before this setTimeout runs, the stale\n // resolver must NOT null the new `currentVT` — otherwise a later\n // cancellation reads `null` and skips nothing, leaking a stale animation\n // (#781). Same identity-guard technique the navigation-plugin uses to\n // heal its seams.\n const scheduledVT = currentVT;\n\n // CRITICAL: CANNOT use requestAnimationFrame here. When the router\n // takes the async path (leave returned a Promise), subscribe fires\n // AFTER the browser has already transitioned VT into the\n // \"update-callback-called\" phase. In that phase Chromium sets\n // rendering suppression to true, which ALSO blocks rAF callbacks.\n // rAF would never fire → deferred never resolves → browser aborts\n // vt.ready with TimeoutError after 4s (observed in Chromium).\n //\n // setTimeout runs on the task queue independent of the rendering\n // pipeline, so it fires regardless of suppression. React's scheduler\n // uses MessageChannel tasks, which are queued before our setTimeout,\n // so the new DOM is committed by the time our callback runs.\n setTimeout(() => {\n resolver();\n\n if (currentVT === scheduledVT) {\n currentVT = null;\n }\n }, 0);\n }\n });\n\n return {\n destroy: () => {\n offLeave();\n offSuccess();\n currentVT?.skipTransition?.();\n currentVT = null;\n resolveAndClear();\n },\n };\n}\n","import { memo, useMemo } from \"react\";\n\nimport { EMPTY_PARAMS, EMPTY_OPTIONS } from \"../constants\";\nimport {\n shouldNavigate,\n buildHref,\n buildActiveClassName,\n navigateWithHash,\n shallowEqual,\n} from \"../dom-utils\";\nimport { useIsActiveRoute } from \"../hooks/useIsActiveRoute\";\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { LinkProps } from \"../types\";\nimport type { FC, MouseEvent } from \"react\";\n\nfunction areLinkPropsEqual(\n prev: Readonly<LinkProps>,\n next: Readonly<LinkProps>,\n): boolean {\n return (\n prev.routeName === next.routeName &&\n prev.className === next.className &&\n prev.activeClassName === next.activeClassName &&\n prev.activeStrict === next.activeStrict &&\n prev.ignoreQueryParams === next.ignoreQueryParams &&\n prev.onClick === next.onClick &&\n prev.target === next.target &&\n prev.style === next.style &&\n prev.children === next.children &&\n prev.hash === next.hash &&\n shallowEqual(prev.routeParams, next.routeParams) &&\n shallowEqual(prev.routeOptions, next.routeOptions)\n );\n}\n\nconst LinkImpl: FC<LinkProps> = ({\n routeName,\n routeParams,\n routeOptions = EMPTY_OPTIONS,\n className,\n activeClassName = \"active\",\n activeStrict = false,\n ignoreQueryParams = true,\n hash,\n onClick,\n target,\n children,\n ...props\n}) => {\n // memo + areLinkPropsEqual guarantees that on bail-out the component does\n // not render; on render, routeParams/routeOptions either changed reference\n // (true change) or comparator failed (e.g., BigInt fallback to identity),\n // so they're safe to use directly in hook deps.\n\n const router = useRouter();\n\n // Pass `routeParams` straight through (possibly `undefined`) — do NOT default\n // to EMPTY_PARAMS before the active-route call. `createActiveRouteSource` keys\n // params as `params === undefined ? \"\" : canonicalJson(params)`, so a no-params\n // `<Link>` and a manual `useIsActiveRoute(routeName)` both key \"\" and share ONE\n // cached source (one router subscription). Defaulting to EMPTY_PARAMS ({}) here\n // would key \"{}\" and split the same logical question into a second eager\n // subscription (#776). `shallowEqual(undefined, undefined)` keeps the memo\n // fast-path, so the comparison behaviour is unchanged.\n //\n // When `hash` prop is set, active state requires both route AND hash to\n // match (#532). Without this, three tab links sharing routeName=\"settings\"\n // would all be marked active by route-name alone, defeating tab semantics.\n const isActive = useIsActiveRoute(\n routeName,\n routeParams,\n activeStrict,\n ignoreQueryParams,\n hash,\n );\n\n // Navigation/href building need a concrete params object — default here only.\n const paramsForNav = routeParams ?? EMPTY_PARAMS;\n\n // No useMemo: outer memo()+shallowEqual prevents Link re-render unless a\n // prop actually changed. When this body runs, either `hash` differs from\n // last render or another prop changed — in both cases the `{ hash }` alloc\n // is unavoidable. The useMemo wrapper added one closure + deps slot per\n // render without saving an allocation.\n const hashOption = hash === undefined ? undefined : { hash };\n const href = buildHref(router, routeName, paramsForNav, hashOption);\n\n // useCallback was wasteful: 7 deps recreated the closure on every meaningful\n // render anyway, and `<a onClick>` does not benefit from a stable function\n // identity (no child-memo-bail-out chain past it). Inline arrow function is\n // what React Compiler emits automatically for this shape.\n const handleClick = (evt: MouseEvent<HTMLAnchorElement>) => {\n if (onClick) {\n onClick(evt);\n\n if (evt.defaultPrevented) {\n return;\n }\n }\n\n if (!shouldNavigate(evt.nativeEvent) || target === \"_blank\") {\n return;\n }\n\n evt.preventDefault();\n navigateWithHash(router, routeName, paramsForNav, hash, routeOptions).catch(\n () => {},\n );\n };\n\n // Memoize the joined class string. parseTokens + Set + join on every render\n // adds up on pages with N Links navigating frequently; deps cover every\n // input the function reads so cache invalidation is exact.\n const finalClassName = useMemo(\n () => buildActiveClassName(isActive, activeClassName, className),\n [isActive, activeClassName, className],\n );\n\n return (\n <a {...props} href={href} className={finalClassName} onClick={handleClick}>\n {children}\n </a>\n );\n};\n\nexport const Link: FC<LinkProps> = memo(LinkImpl, areLinkPropsEqual);\n\nLink.displayName = \"Link\";\n","import { useEffect } from \"react\";\n\nimport {\n createRouteAnnouncer,\n createScrollRestoration,\n createScrollSpy,\n createViewTransitions,\n} from \"./dom-utils\";\nimport { RouterProviderCore } from \"./RouterProviderCore\";\n\nimport type {\n RouteAnnouncerOptions,\n ScrollRestorationOptions,\n ScrollSpyOptions,\n} from \"./dom-utils\";\nimport type { Router } from \"@real-router/core\";\nimport type { FC, ReactNode } from \"react\";\n\nexport interface RouteProviderProps {\n router: Router;\n children: ReactNode;\n announceNavigation?: boolean | RouteAnnouncerOptions;\n scrollRestoration?: ScrollRestorationOptions;\n scrollSpy?: ScrollSpyOptions;\n viewTransitions?: boolean;\n}\n\n/**\n * DOM-aware router provider: wraps {@link RouterProviderCore} (contexts +\n * subscription wiring) and layers the opt-in DOM-feature effects — announcer,\n * scroll restoration, scroll spy, view transitions — on top. The factory\n * imports live here (not in the core) so terminal targets that compose only the\n * core never pull the dom-utils implementation into their chunk (#800).\n */\nexport const RouterProvider: FC<RouteProviderProps> = ({\n router,\n children,\n announceNavigation,\n scrollRestoration,\n scrollSpy,\n viewTransitions,\n}) => {\n // `announceNavigation` accepts `true` (default announcer) or a\n // `RouteAnnouncerOptions` object (`{ prefix, getAnnouncementText }`) for\n // custom announcement text. `false` / `undefined` disables it.\n const announceEnabled =\n announceNavigation !== undefined && announceNavigation !== false;\n const announceOptions =\n typeof announceNavigation === \"object\" ? announceNavigation : undefined;\n const announcePrefix = announceOptions?.prefix;\n\n useEffect(() => {\n if (!announceEnabled) {\n return;\n }\n\n const announcer = createRouteAnnouncer(router, announceOptions);\n\n return () => {\n announcer.destroy();\n };\n // announceOptions (for getAnnouncementText) omitted — inline-object identity\n // churn shouldn't re-create the announcer; the callback is captured once by\n // the utility (same rationale as scrollContainer below).\n // eslint-disable-next-line @eslint-react/exhaustive-deps\n }, [router, announceEnabled, announcePrefix]);\n\n // Primitive deps so inline `{ mode: \"restore\" }` doesn't thrash on every\n // render. scrollContainer is a getter invoked lazily on every event inside\n // the utility — swapping its reference doesn't change the resolved element,\n // so we intentionally omit it from deps to keep inline getters stable.\n const srMode = scrollRestoration?.mode;\n const srAnchor = scrollRestoration?.anchorScrolling;\n const srBehavior = scrollRestoration?.behavior;\n const srStorageKey = scrollRestoration?.storageKey;\n const srEnabled = scrollRestoration !== undefined;\n\n useEffect(() => {\n if (!srEnabled) {\n return;\n }\n\n const sr = createScrollRestoration(router, {\n mode: srMode,\n anchorScrolling: srAnchor,\n behavior: srBehavior,\n storageKey: srStorageKey,\n // srEnabled check above guarantees scrollRestoration is defined.\n scrollContainer: scrollRestoration.scrollContainer,\n });\n\n return () => {\n sr.destroy();\n };\n // scrollRestoration (for scrollContainer) omitted — see comment above.\n // eslint-disable-next-line @eslint-react/exhaustive-deps\n }, [router, srEnabled, srMode, srAnchor, srBehavior, srStorageKey]);\n\n const spySelector = scrollSpy?.selector;\n const spyRootMargin = scrollSpy?.rootMargin;\n const spyEnabled =\n scrollSpy !== undefined && spySelector !== undefined && spySelector !== \"\";\n\n useEffect(() => {\n if (!spyEnabled) {\n return;\n }\n\n const spy = createScrollSpy(router, {\n selector: spySelector,\n rootMargin: spyRootMargin,\n scrollContainer: scrollSpy.scrollContainer,\n });\n\n return () => {\n spy.destroy();\n };\n // scrollSpy (for scrollContainer) omitted — same rationale as\n // scrollRestoration above: getter is invoked lazily inside the utility,\n // identity changes don't affect resolution.\n // eslint-disable-next-line @eslint-react/exhaustive-deps\n }, [router, spyEnabled, spySelector, spyRootMargin]);\n\n useEffect(() => {\n if (!viewTransitions) {\n return;\n }\n\n const vt = createViewTransitions(router);\n\n return () => {\n vt.destroy();\n };\n }, [router, viewTransitions]);\n\n return <RouterProviderCore router={router}>{children}</RouterProviderCore>;\n};\n"],"mappings":"gLAEA,MAEM,EAAiB,6BAUjBA,EAAyC,OAAO,OAAO,CAC3D,YAAe,CAEf,CACF,CAAC,EASD,IAAI,EAAoB,EAOpB,EAAsB,EAE1B,SAAgB,EACd,EACA,EACyB,CAUzB,GAAI,OAAO,SAAa,IACtB,OAAOA,EAGT,IAAM,EAAS,GAAS,QAAU,gBAC5B,EAAgB,GAAS,oBAE3B,EAAsB,GACtB,EAAU,GACV,EAAc,GACd,EAAoB,GACpB,EAA6B,KAC7B,EAEE,CAAE,QAAS,EAAW,WAAY,GACtC,EAAqB,EAEvB,GAAqB,EAErB,IAAM,GAAc,EAAc,IAAiC,CACjE,EAAoB,EACpB,aAAa,CAAc,EAC3B,EAAU,YAAc,EACxB,EAAiB,eAAiB,CAChC,EAAU,YAAc,GACxB,EAAoB,EACtB,EAAG,GAAW,EAEd,EAAY,CAAE,CAChB,EAMM,EAAkB,eAAiB,CAGvC,GAFA,EAAU,GAEN,IAAgB,MAAQ,CAAC,EAAa,CACxC,IAAM,EAAO,EAEb,EAAc,KACd,EAAW,EAAM,SAAS,cAA2B,IAAI,CAAC,CAC5D,CACF,EAAG,GAAkB,EAEf,EAAc,EAAO,WAAW,CAAE,WAAY,CAClD,GAAI,EAAqB,CACvB,EAAsB,GAEtB,MACF,CAOA,0BAA4B,CAC1B,0BAA4B,CAC1B,GAAI,EACF,OAGF,IAAM,EAAK,SAAS,cAA2B,IAAI,EAC7C,EAAO,EAAY,EAAO,EAAQ,EAAe,CAAE,EAErD,MAAC,GAAQ,IAAS,GAItB,IAAI,CAAC,EAAS,CAEZ,EAAc,EAEd,MACF,CAEA,EAAW,EAAM,CAAE,CAFnB,CAGF,CAAC,CACH,CAAC,CACH,CAAC,E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AG,CAAC,EAAQ,EAAiB,CAAc,CAAC,EAM5C,IAAM,EAAS,GAAmB,KAC5B,EAAW,GAAmB,gBAC9B,EAAa,GAAmB,SAChC,EAAe,GAAmB,WAClC,EAAY,IAAsB,IAAA,IAExC,EAAA,EAAA,UAAA,KAAgB,CACd,GAAI,CAAC,EACH,OAGF,IAAM,EAAK,EAAwB,EAAQ,CACzC,KAAM,EACN,gBAAiB,EACjB,SAAU,EACV,WAAY,EAEZ,gBAAiB,EAAkB,eACrC,CAAC,EAED,UAAa,CACX,EAAG,QAAQ,CACb,CAGF,EAAG,CAAC,EAAQ,EAAW,EAAQ,EAAU,EAAY,CAAY,CAAC,EAElE,IAAM,EAAc,GAAW,SACzB,EAAgB,GAAW,WAC3B,EACJ,IAAc,IAAA,IAAa,IAAgB,IAAA,IAAa,IAAgB,GAkC1E,OAhCA,EAAA,EAAA,UAAA,KAAgB,CACd,GAAI,CAAC,EACH,OAGF,IAAM,EAAM,EAAgB,EAAQ,CAClC,SAAU,EACV,WAAY,EACZ,gBAAiB,EAAU,eAC7B,CAAC,EAED,UAAa,CACX,EAAI,QAAQ,CACd,CAKF,EAAG,CAAC,EAAQ,EAAY,EAAa,CAAa,CAAC,GAEnD,EAAA,EAAA,UAAA,KAAgB,CACd,GAAI,CAAC,EACH,OAGF,IAAM,EAAK,EAAsB,CAAM,EAEvC,UAAa,CACX,EAAG,QAAQ,CACb,CACF,EAAG,CAAC,EAAQ,CAAe,CAAC,GAErB,EAAA,EAAA,IAAA,CAACC,EAAAA,EAAD,CAA4B,SAAS,UAA6B,CAAA,CAC3E"}
package/dist/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./useRoute-D2vAzKWM.js"),t=require("./RouterProviderCore-DE6VCzL6.js"),n=require("./RouterProvider-u98Nbzbg.js");let r=require("react"),i=require("@real-router/core"),a=require("@real-router/route-utils"),o=require("react/jsx-runtime");function s(e){return null}s.displayName=`RouteView.Match`;function c(e){return null}c.displayName=`RouteView.Self`;function l(e){return null}l.displayName=`RouteView.NotFound`;const u=new Set([s,c,l]);function d(e,t,n){return t===``?!1:n?e===t:(0,a.startsWithSegment)(e,t)}function f(e,t){r.Children.forEach(e,e=>{(0,r.isValidElement)(e)&&(u.has(e.type)?t.push(e):f(e.props.children,t))})}function p(e,t,n,i,a){let s=a===void 0?e:(0,o.jsx)(r.Suspense,{fallback:a,children:e});return n?(0,o.jsx)(r.Activity,{mode:i,children:s},t):(0,o.jsx)(r.Fragment,{children:s},t)}function m(e,t){return e.type===l?(t.notFoundChildren=e.props.children,!0):e.type===c?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function h(e,t,n,r,i){let a=e.props,{segment:o,exact:s=!1,keepAlive:c=!1,fallback:l}=a,u=n?`${n}.${o}`:o;return!i&&d(t,u,s)?{rendered:p(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:p(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function g(e,t,n,a){if(a.selfFound&&t===n){e.push(p(a.selfChildren,`__route-view-self__`,!1,`visible`,a.selfFallback));return}t===i.UNKNOWN_ROUTE&&a.notFoundChildren!==null&&e.push((0,o.jsx)(r.Fragment,{children:a.notFoundChildren},`__route-view-not-found__`))}function _(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null},a=null,o=[];for(let s of e){if(m(s,i))continue;let e=h(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&g(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function v({nodeName:e,children:n}){let{route:i}=t.f(e),a=(0,r.useRef)(null);a.current??=new Set;let s=a.current,c=(0,r.useMemo)(()=>{let e=[];return f(n,e),e},[n]),l=i?.name??null,{rendered:u,activatedName:d}=(0,r.useMemo)(()=>{if(l===null)return{rendered:[],activatedName:null};let t=_(c,l,e,s);return{rendered:t.rendered,activatedName:t.activatedName}},[c,l,e,s]);return(0,r.useEffect)(()=>{d!==null&&s.add(d)},[d,s]),u.length>0?(0,o.jsx)(o.Fragment,{children:u}):null}v.displayName=`RouteView`;const y=Object.assign(v,{Match:s,Self:c,NotFound:l});function b(e,n){let i=t.p(),a=(0,r.useRef)(e),o=n?.skipSameRoute??!0;(0,r.useLayoutEffect)(()=>{a.current=e}),(0,r.useEffect)(()=>i.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(o&&e.name===t.name)&&!n.aborted)return a.current({route:e,nextRoute:t,signal:n})}),[i,o])}function x(t,n){let{route:i,previousRoute:a}=e.t(),o=(0,r.useRef)(t),s=(0,r.useRef)(null),c=n?.skipSameRoute??!0;(0,r.useLayoutEffect)(()=>{o.current=t}),(0,r.useEffect)(()=>{i.transition.from&&(c&&i.transition.from===i.name||s.current!==i&&a&&(s.current=i,o.current({route:i,previousRoute:a})))},[i,a,c])}exports.Link=n.n,exports.RouteView=y,exports.RouterErrorBoundary=t.a,exports.RouterProvider=n.t,exports.useNavigator=t.i,exports.useRoute=e.t,exports.useRouteEnter=x,exports.useRouteExit=b,exports.useRouteNode=t.f,exports.useRouteUtils=t.r,exports.useRouter=t.p,exports.useRouterTransition=t.n;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./useRoute-D2vAzKWM.js"),t=require("./RouterProviderCore-DE6VCzL6.js"),n=require("./RouterProvider-C9eXwr7W.js");let r=require("react"),i=require("@real-router/core"),a=require("@real-router/route-utils"),o=require("react/jsx-runtime");function s(e){return null}s.displayName=`RouteView.Match`;function c(e){return null}c.displayName=`RouteView.Self`;function l(e){return null}l.displayName=`RouteView.NotFound`;const u=new Set([s,c,l]);function d(e,t,n){return t===``?!1:n?e===t:(0,a.startsWithSegment)(e,t)}function f(e,t){r.Children.forEach(e,e=>{(0,r.isValidElement)(e)&&(u.has(e.type)?t.push(e):f(e.props.children,t))})}function p(e,t,n,i,a){let s=a===void 0?e:(0,o.jsx)(r.Suspense,{fallback:a,children:e});return n?(0,o.jsx)(r.Activity,{mode:i,children:s},t):(0,o.jsx)(r.Fragment,{children:s},t)}function m(e,t){return e.type===l?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===c?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function h(e,t,n,r,i){let a=e.props,{segment:o,exact:s=!1,keepAlive:c=!1,fallback:l}=a,u=n?`${n}.${o}`:o;return!i&&d(t,u,s)?{rendered:p(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:p(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function g(e,t,n,a){if(a.selfFound&&t===n){e.push(p(a.selfChildren,`__route-view-self__`,!1,`visible`,a.selfFallback));return}t===i.UNKNOWN_ROUTE&&a.notFoundChildren!==null&&e.push((0,o.jsx)(r.Fragment,{children:a.notFoundChildren},`__route-view-not-found__`))}function _(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null,notFoundFound:!1},a=null,o=[];for(let s of e){if(m(s,i))continue;let e=h(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&g(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function v({nodeName:e,children:n}){let{route:i}=t.f(e),a=(0,r.useRef)(null);a.current??=new Set;let s=a.current,c=(0,r.useMemo)(()=>{let e=[];return f(n,e),e},[n]),l=i?.name??null,{rendered:u,activatedName:d}=(0,r.useMemo)(()=>{if(l===null)return{rendered:[],activatedName:null};let t=_(c,l,e,s);return{rendered:t.rendered,activatedName:t.activatedName}},[c,l,e,s]);return(0,r.useEffect)(()=>{d!==null&&s.add(d)},[d,s]),u.length>0?(0,o.jsx)(o.Fragment,{children:u}):null}v.displayName=`RouteView`;const y=Object.assign(v,{Match:s,Self:c,NotFound:l});function b(e,n){let i=t.p(),a=(0,r.useRef)(e),o=n?.skipSameRoute??!0;(0,r.useLayoutEffect)(()=>{a.current=e}),(0,r.useEffect)(()=>i.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(o&&e.name===t.name)&&!n.aborted)return a.current({route:e,nextRoute:t,signal:n})}),[i,o])}function x(t,n){let{route:i,previousRoute:a}=e.t(),o=(0,r.useRef)(t),s=(0,r.useRef)(null),c=n?.skipSameRoute??!0;(0,r.useLayoutEffect)(()=>{o.current=t}),(0,r.useEffect)(()=>{i.transition.from&&(c&&i.transition.from===i.name||s.current!==i&&a&&(s.current=i,o.current({route:i,previousRoute:a})))},[i,a,c])}exports.Link=n.n,exports.RouteView=y,exports.RouterErrorBoundary=t.a,exports.RouterProvider=n.t,exports.useNavigator=t.i,exports.useRoute=e.t,exports.useRouteEnter=x,exports.useRouteExit=b,exports.useRouteNode=t.f,exports.useRouteUtils=t.r,exports.useRouter=t.p,exports.useRouterTransition=t.n;
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Suspense","Activity","Fragment","UNKNOWN_ROUTE","useRouteNode","useRouter","useRoute"],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n}\n\n// Fixed keys used by appendFallback to distinguish the Self / NotFound\n// render slots from user-supplied <Match> children. Match render slots key\n// off `fullSegmentName` instead — these two are the only synthetic keys.\nconst SELF_KEY = \"__route-view-self__\";\nconst NOT_FOUND_KEY = \"__route-view-not-found__\";\n\nfunction isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (fullSegmentName === \"\") {\n return false;\n }\n\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\nexport function collectElements(\n children: ReactNode,\n result: ReactElement[],\n): void {\n // Recurses into Fragment-like wrappers (anything that isn't Match / Self /\n // NotFound) to flatten the slot tree. No explicit depth guard: typical\n // RouteView shape is `<RouteView><Match/>...<NotFound/></RouteView>` —\n // depth ≤ 3 in real apps. A pathological hand-written tree of N Fragments\n // recurses N times; the call stack, not this function, is the bound.\n //\n // `Children.forEach` iterates without `Children.toArray`'s array allocation\n // and per-child clone-with-synthetic-key step. We don't read child.key here\n // (Match/Self/NotFound carry their own segment-derived keys further down),\n // so the cheaper iterator is functionally equivalent.\n // eslint-disable-next-line @eslint-react/no-children-for-each -- intentional: collectElements is a render-hot pipeline; toArray's array+key clone is wasteful here\n Children.forEach(children, (child) => {\n if (!isValidElement(child)) {\n return;\n }\n\n if (MARKER_TYPES.has(child.type)) {\n result.push(child);\n } else {\n collectElements(\n (child.props as { readonly children: ReactNode }).children,\n result,\n );\n }\n });\n}\n\nfunction renderSlotElement(\n slotChildren: ReactNode,\n key: string,\n keepAlive: boolean,\n mode: \"visible\" | \"hidden\",\n fallback?: ReactNode,\n): ReactElement {\n const content =\n fallback === undefined ? (\n slotChildren\n ) : (\n <Suspense fallback={fallback}>{slotChildren}</Suspense>\n );\n\n if (keepAlive) {\n return (\n <Activity mode={mode} key={key}>\n {content}\n </Activity>\n );\n }\n\n return <Fragment key={key}>{content}</Fragment>;\n}\n\nfunction recordFallback(child: ReactElement, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: ReadonlySet<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; activatedName: string | null } {\n const matchProps = child.props as MatchProps;\n const { segment, exact = false, keepAlive = false, fallback } = matchProps;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive =\n !alreadyActive && isSegmentMatch(routeName, fullSegmentName, exact);\n\n if (isActive) {\n // The keepAlive Set is NOT mutated here — RouteView commits the activation\n // in a post-render effect (#1251). Mutating during render coupled the pure\n // winner computation to a side effect (blocking memoization) and, under\n // concurrent rendering, a discarded render would leave a phantom entry that\n // later renders an un-committed match as a hidden keepAlive subtree.\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n activatedName: fullSegmentName,\n };\n }\n\n if (keepAlive && hasBeenActivated.has(fullSegmentName)) {\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"hidden\",\n fallback,\n ),\n activatedName: null,\n };\n }\n\n return { rendered: null, activatedName: null };\n}\n\nfunction appendFallback(\n rendered: ReactElement[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): void {\n if (slots.selfFound && routeName === nodeName) {\n rendered.push(\n renderSlotElement(\n slots.selfChildren,\n SELF_KEY,\n false,\n \"visible\",\n slots.selfFallback,\n ),\n );\n\n return;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {\n rendered.push(\n <Fragment key={NOT_FOUND_KEY}>{slots.notFoundChildren}</Fragment>,\n );\n }\n}\n\nexport function buildRenderList(\n elements: ReactElement[],\n routeName: string,\n nodeName: string,\n hasBeenActivated: ReadonlySet<string>,\n): {\n rendered: ReactElement[];\n activeMatchFound: boolean;\n activatedName: string | null;\n} {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n };\n // The segment that activated this render, or null. Reported to the caller so\n // RouteView can commit it to the keepAlive Set post-render (#1251) — this pure\n // walk no longer mutates the Set. At most one match activates (first-wins via\n // the `alreadyActive` short-circuit), so a single name suffices.\n let activatedName: string | null = null;\n const rendered: ReactElement[] = [];\n\n for (const child of elements) {\n if (recordFallback(child, slots)) {\n continue;\n }\n\n const result = processMatch(\n child,\n routeName,\n nodeName,\n hasBeenActivated,\n activatedName !== null,\n );\n\n if (result.activatedName !== null) {\n activatedName = result.activatedName;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (activatedName === null) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound: activatedName !== null, activatedName };\n}\n","import { useEffect, useMemo, useRef } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport { buildRenderList, collectElements } from \"./helpers\";\nimport { useRouteNode } from \"../../../hooks/useRouteNode\";\n\nimport type { RouteViewProps } from \"./types\";\nimport type { ReactElement } from \"react\";\n\nfunction RouteViewRoot({\n nodeName,\n children,\n}: Readonly<RouteViewProps>): ReactElement | null {\n const { route } = useRouteNode(nodeName);\n const hasBeenActivatedRef = useRef<Set<string> | null>(null);\n\n // eslint-disable-next-line @eslint-react/refs -- lazy init: assign once when null to avoid `new Set()` allocation on every render\n hasBeenActivatedRef.current ??= new Set();\n // eslint-disable-next-line @eslint-react/refs -- stable render cache; the ref is never reassigned after lazy init\n const hasBeenActivated = hasBeenActivatedRef.current;\n\n // Skip the Children.forEach + collectElements traversal when the children\n // reference is unchanged. The common SPA case is a stable JSX tree across\n // re-renders, so the cache hits on every render except the first.\n //\n // Streaming SSR caveat: with `renderToReadableStream`, React may invoke\n // RouteView multiple times across chunks with a fresh `children` reference\n // each time. The useMemo misses on each new render and the traversal runs\n // again — this is the expected SSR cost; the alternative would be build-\n // time codegen of the static route tree, which is out of scope here.\n const elements = useMemo(() => {\n const collected: ReactElement[] = [];\n\n collectElements(children, collected);\n\n return collected;\n }, [children]);\n\n const routeName = route?.name ?? null;\n\n // Memoize the render walk by its pure inputs. Previously `buildRenderList` ran\n // on EVERY render because `processMatch` mutated the keepAlive Set inline —\n // coupling the pure winner/`rendered` computation to a side effect, so a\n // parent re-render with no route change re-walked every Match and re-diffed\n // the identical output (preact, whose `buildRenderList` is a 3-arg pure\n // function, already memoizes here). The Set mutation now lives in the effect\n // below, so the walk memoizes on `[elements, routeName, nodeName]` too. #1251.\n const { rendered, activatedName } = useMemo(() => {\n if (routeName === null) {\n return { rendered: [] as ReactElement[], activatedName: null };\n }\n\n const result = buildRenderList(\n elements,\n routeName,\n nodeName,\n hasBeenActivated,\n );\n\n return { rendered: result.rendered, activatedName: result.activatedName };\n }, [elements, routeName, nodeName, hasBeenActivated]);\n\n // Commit the keepAlive activation AFTER render, not during it. A render that\n // React discards under concurrent rendering must not record an activation\n // that never committed — otherwise a later render would show that\n // never-mounted match as a hidden keepAlive subtree. Adding the same name\n // twice is a no-op, so the effect is safe to re-run.\n useEffect(() => {\n if (activatedName !== null) {\n hasBeenActivated.add(activatedName);\n }\n }, [activatedName, hasBeenActivated]);\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it rejects, the router emits\n * `TRANSITION_CANCELLED` (existing core behavior, no change here).\n *\n * **Reentrancy — no synchronous `navigate()` from the handler.** The handler\n * runs inside the transition's leave-dispatch window, so calling\n * `router.navigate(...)` (or `navigateToDefault` / `navigateToState` /\n * `navigateToNotFound`) **synchronously** in the handler body throws\n * `REENTRANT_NAVIGATION` — core bans reentrant navigation from a transition\n * listener (RFC navigation-cancellation-unification §4). To redirect on exit,\n * defer past the sync dispatch: `await` your exit work first, or\n * `queueMicrotask(() => router.navigate(...))`. A navigate issued after the\n * handler's first `await` runs once the transition settles and is allowed.\n * (Guards — `canDeactivate` — are the intended place to *block* or gate a\n * departure; `useRouteExit` is for side effects, not redirection.)\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Reading rich transition metadata via `nextRoute.transition`\n * ```tsx\n * useRouteExit(({ route, nextRoute }) => {\n * // nextRoute.transition: TransitionMeta — preview of the upcoming nav\n * if (nextRoute.transition.segments.deactivated.includes(\"products\")) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * if (nextRoute.transition.redirected) {\n * // skip animation when navigation arrived via redirect\n * return;\n * }\n * });\n * ```\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n return router.subscribeLeave(({ route, nextRoute, signal }) => {\n if (skipSameRoute && route.name === nextRoute.name) {\n return;\n }\n\n // Reentrant abort: signal is already aborted when listener fires\n // (e.g. a newer navigate superseded this one before subscribeLeave\n // even ran). addEventListener(\"abort\", ...) does not fire\n // retroactively, so we skip the handler entirely — any cleanup the\n // handler would have wired via abort listener must not run because\n // the corresponding `add` work never happened.\n if (signal.aborted) {\n return;\n }\n\n return handlerRef.current({ route, nextRoute, signal });\n });\n }, [router, skipSameRoute]);\n}\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * if (route.transition.redirected) {\n * showToast(`Redirected from ${route.transition.from}`);\n * }\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n const lastHandledRouteRef = useRef<State | null>(null);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // Early-exit guards, top-down:\n //\n // - **Skip-initial**: `state.transition.from` is undefined only\n // for the very first state committed by `router.start()`.\n // - **Skip-same-route**: query-only navigations have\n // `transition.from === route.name`. Opt-out via\n // `skipSameRoute: false`.\n // - **StrictMode dedupe**: same `route` ref between effect\n // cleanup + re-run in dev's strict pass. Not reachable from\n // vitest (`NODE_ENV === \"test\"` disables React's strict-mode\n // double-run), so v8-ignored.\n // - **No previousRoute**: guards the non-nullable\n // `RouteEnterContext.previousRoute` contract — see below.\n if (!route.transition.from) {\n return;\n }\n if (skipSameRoute && route.transition.from === route.name) {\n return;\n }\n /* v8 ignore start -- StrictMode-only (dev double-run); NODE_ENV===\"test\" disables it */\n if (lastHandledRouteRef.current === route) {\n return;\n }\n /* v8 ignore stop */\n // `previousRoute` is `undefined` even when `transition.from` is truthy for the\n // first post-start render — the Provider mounted AFTER a navigation, so the\n // source's initial snapshot carries `previousRoute: undefined` (#1218 PC1) —\n // and after an `<Activity>` catch-up reconcile (#765) resets it (PC2). This is\n // the sole guard against invoking the handler with `previousRoute: undefined`,\n // which `RouteEnterContext.previousRoute` (non-nullable `State`) forbids.\n if (!previousRoute) {\n return;\n }\n\n lastHandledRouteRef.current = route;\n handlerRef.current({ route, previous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C,CAC5B,CClEA,SAAgB,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkBC,EAAAA,EAAS,EACpC,GAAA,EAAA,EAAA,OAAA,CAAoB,CAAO,EAC3B,GAAA,EAAA,EAAA,OAAA,CAA2C,IAAI,EAC/C,EAAgB,GAAS,eAAiB,IAKhD,EAAA,EAAA,gBAAA,KAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,GAED,EAAA,EAAA,UAAA,KAAgB,CAcT,EAAM,WAAW,OAGlB,GAAiB,EAAM,WAAW,OAAS,EAAM,MAIjD,EAAoB,UAAY,GAU/B,IAIL,EAAoB,QAAU,EAC9B,EAAW,QAAQ,CAAE,QAAO,eAAc,CAAC,GAC7C,EAAG,CAAC,EAAO,EAAe,CAAa,CAAC,CAC1C"}
1
+ {"version":3,"file":"index.js","names":["Suspense","Activity","Fragment","UNKNOWN_ROUTE","useRouteNode","useRouter","useRoute"],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n notFoundFound: boolean;\n}\n\n// Fixed keys used by appendFallback to distinguish the Self / NotFound\n// render slots from user-supplied <Match> children. Match render slots key\n// off `fullSegmentName` instead — these two are the only synthetic keys.\nconst SELF_KEY = \"__route-view-self__\";\nconst NOT_FOUND_KEY = \"__route-view-not-found__\";\n\nfunction isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (fullSegmentName === \"\") {\n return false;\n }\n\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\nexport function collectElements(\n children: ReactNode,\n result: ReactElement[],\n): void {\n // Recurses into Fragment-like wrappers (anything that isn't Match / Self /\n // NotFound) to flatten the slot tree. No explicit depth guard: typical\n // RouteView shape is `<RouteView><Match/>...<NotFound/></RouteView>` —\n // depth ≤ 3 in real apps. A pathological hand-written tree of N Fragments\n // recurses N times; the call stack, not this function, is the bound.\n //\n // `Children.forEach` iterates without `Children.toArray`'s array allocation\n // and per-child clone-with-synthetic-key step. We don't read child.key here\n // (Match/Self/NotFound carry their own segment-derived keys further down),\n // so the cheaper iterator is functionally equivalent.\n // eslint-disable-next-line @eslint-react/no-children-for-each -- intentional: collectElements is a render-hot pipeline; toArray's array+key clone is wasteful here\n Children.forEach(children, (child) => {\n if (!isValidElement(child)) {\n return;\n }\n\n if (MARKER_TYPES.has(child.type)) {\n result.push(child);\n } else {\n collectElements(\n (child.props as { readonly children: ReactNode }).children,\n result,\n );\n }\n });\n}\n\nfunction renderSlotElement(\n slotChildren: ReactNode,\n key: string,\n keepAlive: boolean,\n mode: \"visible\" | \"hidden\",\n fallback?: ReactNode,\n): ReactElement {\n const content =\n fallback === undefined ? (\n slotChildren\n ) : (\n <Suspense fallback={fallback}>{slotChildren}</Suspense>\n );\n\n if (keepAlive) {\n return (\n <Activity mode={mode} key={key}>\n {content}\n </Activity>\n );\n }\n\n return <Fragment key={key}>{content}</Fragment>;\n}\n\nfunction recordFallback(child: ReactElement, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n // First-wins: subsequent <NotFound> elements are ignored, symmetric with\n // <Self> below (#1220). Before this guard the assignment was unconditional\n // (last-wins), contradicting the documented Self-symmetric contract.\n if (!slots.notFoundFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n slots.notFoundFound = true;\n }\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: ReadonlySet<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; activatedName: string | null } {\n const matchProps = child.props as MatchProps;\n const { segment, exact = false, keepAlive = false, fallback } = matchProps;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive =\n !alreadyActive && isSegmentMatch(routeName, fullSegmentName, exact);\n\n if (isActive) {\n // The keepAlive Set is NOT mutated here — RouteView commits the activation\n // in a post-render effect (#1251). Mutating during render coupled the pure\n // winner computation to a side effect (blocking memoization) and, under\n // concurrent rendering, a discarded render would leave a phantom entry that\n // later renders an un-committed match as a hidden keepAlive subtree.\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n activatedName: fullSegmentName,\n };\n }\n\n if (keepAlive && hasBeenActivated.has(fullSegmentName)) {\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"hidden\",\n fallback,\n ),\n activatedName: null,\n };\n }\n\n return { rendered: null, activatedName: null };\n}\n\nfunction appendFallback(\n rendered: ReactElement[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): void {\n if (slots.selfFound && routeName === nodeName) {\n rendered.push(\n renderSlotElement(\n slots.selfChildren,\n SELF_KEY,\n false,\n \"visible\",\n slots.selfFallback,\n ),\n );\n\n return;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {\n rendered.push(\n <Fragment key={NOT_FOUND_KEY}>{slots.notFoundChildren}</Fragment>,\n );\n }\n}\n\nexport function buildRenderList(\n elements: ReactElement[],\n routeName: string,\n nodeName: string,\n hasBeenActivated: ReadonlySet<string>,\n): {\n rendered: ReactElement[];\n activeMatchFound: boolean;\n activatedName: string | null;\n} {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n notFoundFound: false,\n };\n // The segment that activated this render, or null. Reported to the caller so\n // RouteView can commit it to the keepAlive Set post-render (#1251) — this pure\n // walk no longer mutates the Set. At most one match activates (first-wins via\n // the `alreadyActive` short-circuit), so a single name suffices.\n let activatedName: string | null = null;\n const rendered: ReactElement[] = [];\n\n for (const child of elements) {\n if (recordFallback(child, slots)) {\n continue;\n }\n\n const result = processMatch(\n child,\n routeName,\n nodeName,\n hasBeenActivated,\n activatedName !== null,\n );\n\n if (result.activatedName !== null) {\n activatedName = result.activatedName;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (activatedName === null) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound: activatedName !== null, activatedName };\n}\n","import { useEffect, useMemo, useRef } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport { buildRenderList, collectElements } from \"./helpers\";\nimport { useRouteNode } from \"../../../hooks/useRouteNode\";\n\nimport type { RouteViewProps } from \"./types\";\nimport type { ReactElement } from \"react\";\n\nfunction RouteViewRoot({\n nodeName,\n children,\n}: Readonly<RouteViewProps>): ReactElement | null {\n const { route } = useRouteNode(nodeName);\n const hasBeenActivatedRef = useRef<Set<string> | null>(null);\n\n // eslint-disable-next-line @eslint-react/refs -- lazy init: assign once when null to avoid `new Set()` allocation on every render\n hasBeenActivatedRef.current ??= new Set();\n // eslint-disable-next-line @eslint-react/refs -- stable render cache; the ref is never reassigned after lazy init\n const hasBeenActivated = hasBeenActivatedRef.current;\n\n // Skip the Children.forEach + collectElements traversal when the children\n // reference is unchanged. The common SPA case is a stable JSX tree across\n // re-renders, so the cache hits on every render except the first.\n //\n // Streaming SSR caveat: with `renderToReadableStream`, React may invoke\n // RouteView multiple times across chunks with a fresh `children` reference\n // each time. The useMemo misses on each new render and the traversal runs\n // again — this is the expected SSR cost; the alternative would be build-\n // time codegen of the static route tree, which is out of scope here.\n const elements = useMemo(() => {\n const collected: ReactElement[] = [];\n\n collectElements(children, collected);\n\n return collected;\n }, [children]);\n\n const routeName = route?.name ?? null;\n\n // Memoize the render walk by its pure inputs. Previously `buildRenderList` ran\n // on EVERY render because `processMatch` mutated the keepAlive Set inline —\n // coupling the pure winner/`rendered` computation to a side effect, so a\n // parent re-render with no route change re-walked every Match and re-diffed\n // the identical output (preact, whose `buildRenderList` is a 3-arg pure\n // function, already memoizes here). The Set mutation now lives in the effect\n // below, so the walk memoizes on `[elements, routeName, nodeName]` too. #1251.\n const { rendered, activatedName } = useMemo(() => {\n if (routeName === null) {\n return { rendered: [] as ReactElement[], activatedName: null };\n }\n\n const result = buildRenderList(\n elements,\n routeName,\n nodeName,\n hasBeenActivated,\n );\n\n return { rendered: result.rendered, activatedName: result.activatedName };\n }, [elements, routeName, nodeName, hasBeenActivated]);\n\n // Commit the keepAlive activation AFTER render, not during it. A render that\n // React discards under concurrent rendering must not record an activation\n // that never committed — otherwise a later render would show that\n // never-mounted match as a hidden keepAlive subtree. Adding the same name\n // twice is a no-op, so the effect is safe to re-run.\n useEffect(() => {\n if (activatedName !== null) {\n hasBeenActivated.add(activatedName);\n }\n }, [activatedName, hasBeenActivated]);\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it rejects, the router emits\n * `TRANSITION_CANCELLED` (existing core behavior, no change here).\n *\n * **Reentrancy — no synchronous `navigate()` from the handler.** The handler\n * runs inside the transition's leave-dispatch window, so calling\n * `router.navigate(...)` (or `navigateToDefault` / `navigateToState` /\n * `navigateToNotFound`) **synchronously** in the handler body throws\n * `REENTRANT_NAVIGATION` — core bans reentrant navigation from a transition\n * listener (RFC navigation-cancellation-unification §4). To redirect on exit,\n * defer past the sync dispatch: `await` your exit work first, or\n * `queueMicrotask(() => router.navigate(...))`. A navigate issued after the\n * handler's first `await` runs once the transition settles and is allowed.\n * (Guards — `canDeactivate` — are the intended place to *block* or gate a\n * departure; `useRouteExit` is for side effects, not redirection.)\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Reading rich transition metadata via `nextRoute.transition`\n * ```tsx\n * useRouteExit(({ route, nextRoute }) => {\n * // nextRoute.transition: TransitionMeta — preview of the upcoming nav\n * if (nextRoute.transition.segments.deactivated.includes(\"products\")) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * if (nextRoute.transition.redirected) {\n * // skip animation when navigation arrived via redirect\n * return;\n * }\n * });\n * ```\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n return router.subscribeLeave(({ route, nextRoute, signal }) => {\n if (skipSameRoute && route.name === nextRoute.name) {\n return;\n }\n\n // Reentrant abort: signal is already aborted when listener fires\n // (e.g. a newer navigate superseded this one before subscribeLeave\n // even ran). addEventListener(\"abort\", ...) does not fire\n // retroactively, so we skip the handler entirely — any cleanup the\n // handler would have wired via abort listener must not run because\n // the corresponding `add` work never happened.\n if (signal.aborted) {\n return;\n }\n\n return handlerRef.current({ route, nextRoute, signal });\n });\n }, [router, skipSameRoute]);\n}\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * if (route.transition.redirected) {\n * showToast(`Redirected from ${route.transition.from}`);\n * }\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n const lastHandledRouteRef = useRef<State | null>(null);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // Early-exit guards, top-down:\n //\n // - **Skip-initial**: `state.transition.from` is undefined only\n // for the very first state committed by `router.start()`.\n // - **Skip-same-route**: query-only navigations have\n // `transition.from === route.name`. Opt-out via\n // `skipSameRoute: false`.\n // - **StrictMode dedupe**: same `route` ref between effect\n // cleanup + re-run in dev's strict pass. Not reachable from\n // vitest (`NODE_ENV === \"test\"` disables React's strict-mode\n // double-run), so v8-ignored.\n // - **No previousRoute**: guards the non-nullable\n // `RouteEnterContext.previousRoute` contract — see below.\n if (!route.transition.from) {\n return;\n }\n if (skipSameRoute && route.transition.from === route.name) {\n return;\n }\n /* v8 ignore start -- StrictMode-only (dev double-run); NODE_ENV===\"test\" disables it */\n if (lastHandledRouteRef.current === route) {\n return;\n }\n /* v8 ignore stop */\n // `previousRoute` is `undefined` even when `transition.from` is truthy for the\n // first post-start render — the Provider mounted AFTER a navigation, so the\n // source's initial snapshot carries `previousRoute: undefined` (#1218 PC1) —\n // and after an `<Activity>` catch-up reconcile (#765) resets it (PC2). This is\n // the sole guard against invoking the handler with `previousRoute: undefined`,\n // which `RouteEnterContext.previousRoute` (non-nullable `State`) forbids.\n if (!previousRoute) {\n return;\n }\n\n lastHandledRouteRef.current = route;\n hand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QAAO,CAAC,CACxD,CAAC,EACA,CAAC,EAAQ,CAAa,CAAC,CAC5B,CClEA,SAAgB,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkBC,EAAAA,EAAS,EACpC,GAAA,EAAA,EAAA,OAAA,CAAoB,CAAO,EAC3B,GAAA,EAAA,EAAA,OAAA,CAA2C,IAAI,EAC/C,EAAgB,GAAS,eAAiB,IAKhD,EAAA,EAAA,gBAAA,KAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,GAED,EAAA,EAAA,UAAA,KAAgB,CAcT,EAAM,WAAW,OAGlB,GAAiB,EAAM,WAAW,OAAS,EAAM,MAIjD,EAAoB,UAAY,GAU/B,IAIL,EAAoB,QAAU,EAC9B,EAAW,QAAQ,CAAE,QAAO,eAAc,CAAC,GAC7C,EAAG,CAAC,EAAO,EAAe,CAAa,CAAC,CAC1C"}
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./useRoute-D2vAzKWM.js"),t=require("./RouterProviderCore-DE6VCzL6.js"),n=require("./RouterProvider-u98Nbzbg.js");exports.Link=n.n,exports.RouterErrorBoundary=t.a,exports.RouterProvider=n.t,exports.useNavigator=t.i,exports.useRoute=e.t,exports.useRouteNode=t.f,exports.useRouteUtils=t.r,exports.useRouter=t.p,exports.useRouterTransition=t.n;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./useRoute-D2vAzKWM.js"),t=require("./RouterProviderCore-DE6VCzL6.js"),n=require("./RouterProvider-C9eXwr7W.js");exports.Link=n.n,exports.RouterErrorBoundary=t.a,exports.RouterProvider=n.t,exports.useNavigator=t.i,exports.useRoute=e.t,exports.useRouteNode=t.f,exports.useRouteUtils=t.r,exports.useRouter=t.p,exports.useRouterTransition=t.n;
@@ -0,0 +1,2 @@
1
+ import{n as e,r as t}from"./useRoute-5MF3j-9P.mjs";import{c as n,d as r,l as i,o as a,p as o,s,t as c,u as l}from"./RouterProviderCore-DOMeY1Ch.mjs";import{memo as u,useEffect as d,useMemo as f}from"react";import{jsx as p}from"react/jsx-runtime";import{getTransitionSource as m}from"@real-router/sources";const h=`data-real-router-announcer`,g=Object.freeze({destroy:()=>{}});let _=0,v=0;function y(e,t){if(typeof document>`u`)return g;let n=t?.prefix??`Navigated to `,r=t?.getAnnouncementText,i=!0,a=!1,o=!1,s=``,c=null,l,{element:u,generation:d}=b();_+=1;let f=(e,t)=>{s=e,clearTimeout(l),u.textContent=e,l=setTimeout(()=>{u.textContent=``,s=``},7e3),C(t)},p=setTimeout(()=>{if(a=!0,c!==null&&!o){let e=c;c=null,f(e,document.querySelector(`h1`))}},100),m=e.subscribe(({route:e})=>{if(i){i=!1;return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(o)return;let t=document.querySelector(`h1`),i=S(e,n,r,t);if(!(!i||i===s)){if(!a){c=i;return}f(i,t)}})})});return{destroy(){o||(o=!0,m(),clearTimeout(l),clearTimeout(p),d===v&&(--_,_===0&&x(u)))}}}function b(){let e=document.querySelector(`[${h}]`);if(e)return{element:e,generation:v};_=0,v+=1;let t=document.createElement(`div`);return t.setAttribute(`style`,`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);clip-path:inset(50%);white-space:nowrap;border:0`),t.setAttribute(`aria-live`,`assertive`),t.setAttribute(`aria-atomic`,`true`),t.setAttribute(h,``),(document.body??document.documentElement).prepend(t),{element:t,generation:v}}function x(e){e.remove()}function S(e,t,n,r){if(n)try{let t=n(e);if(t)return t}catch(e){console.error(`[real-router] getAnnouncementText threw; falling back to default resolution.`,e)}let i=(r?.textContent??``).trim(),a=e.name.startsWith(`@@`)?``:e.name;return`${t}${i||document.title||a||globalThis.location.pathname}`}function C(e){e&&(e.hasAttribute(`tabindex`)||e.setAttribute(`tabindex`,`-1`),e.focus({preventScroll:!0}))}const w=Object.freeze({destroy:()=>{}});function T(e,t){if(globalThis.window===void 0)return w;let n=t?.mode??`restore`;if(n===`native`)return w;let r=t?.anchorScrolling??!0,i=t?.scrollContainer,a=t?.behavior??`auto`,o=t?.storageKey??`real-router:scroll`,s,c=()=>{if(s!==void 0)return s;try{let e=sessionStorage.getItem(o);s=e?JSON.parse(e):{}}catch{s={}}return s},l=(e,t)=>{try{let n=c();if(n[e]===t)return;n[e]=t,sessionStorage.setItem(o,JSON.stringify(n))}catch{}},u=history.scrollRestoration;try{history.scrollRestoration=`manual`}catch{}let d=()=>{let e=i?.();return e?e.scrollTop:globalThis.scrollY},f=e=>{let t=i?.();t?t.scrollTo({top:e,left:0,behavior:a}):globalThis.scrollTo({top:e,left:0,behavior:a})},p=e=>{if(!i){globalThis.scrollTo({top:e,left:0,behavior:a});return}let t=0,n=()=>{if(h)return;let r=i();if(r){if(r.scrollTo({top:e,left:0,behavior:a}),a!==`smooth`&&Math.abs(r.scrollTop-e)<=1)return}else globalThis.scrollTo({top:e,left:0,behavior:a});t>=10||(t+=1,requestAnimationFrame(n))};n()},m=e=>{let t=e.context?.url?.hash;if(t!==void 0){if(r&&t.length>0){let e=document.getElementById(t);if(e){e.scrollIntoView({behavior:a});return}}f(0);return}let n=globalThis.location.hash;if(r&&n.length>1){let e;try{e=decodeURIComponent(n.slice(1))}catch{e=n.slice(1)}let t=document.getElementById(e);if(t){t.scrollIntoView({behavior:a});return}}f(0)},h=!1,g=!1,_=!0,v=e=>{try{return D(e)}catch{return g||(g=!0,console.error(`[real-router] scroll-restore: route "${e.name}" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`)),null}},y=e.subscribe(({route:e,previousRoute:t})=>{let r=e.context.navigation;if(t&&_){let e=v(t);e!==null&&l(e,d())}_=!1,requestAnimationFrame(()=>{if(!h){if(_=!0,n===`top`){m(e);return}if(e.transition.reload||r?.navigationType===`reload`){let t=v(e);p(t===null?0:c()[t]??0);return}if(r?.direction===`back`||r?.navigationType===`traverse`){let t=v(e);p(t===null?0:c()[t]??0);return}e.transition.replace||r?.navigationType===`replace`||m(e)}})}),b=()=>{let t=e.getState();if(t){let e=v(t);e!==null&&l(e,d())}};return globalThis.addEventListener(`pagehide`,b),{destroy:()=>{h=!0,y(),globalThis.removeEventListener(`pagehide`,b);try{history.scrollRestoration=u}catch{}}}}const E=new WeakMap;function D(e){let t=E.get(e);if(t!==void 0)return t;let n=`${e.name}:${O(e.params)}`;return E.set(e,n),n}function O(e){return JSON.stringify(e,k)}function k(e,t){if(typeof t==`function`)return`<fn>`;if(typeof t==`symbol`)return`<sym>`;if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.create(null),n=Object.keys(t).sort((e,t)=>e.localeCompare(t));for(let r of n)e[r]=t[r];return e}return t}const A=Object.freeze({destroy:()=>{}}),j=e=>e.context?.url,M=e=>{let t=null,n=1/0,r=null,i=-1/0;for(let a of e){if(!a.isIntersecting)continue;let e=a.rootBounds?.top??0,o=a.boundingClientRect.top-e;o>=0?o<n&&(t=a,n=o):o>i&&(r=a,i=o)}return t??r},N=(e,t)=>{let n=null,r=e=>{let n=e.context;n&&n.url===void 0&&(console.warn(`[real-router] scroll-spy: state.context.url is not claimed. Spy requires browser-plugin or navigation-plugin. Disabling.`),t())},i=e.getState();if(i)r(i);else{let t=!1;n=e.subscribe(({route:e})=>{t||(t=!0,r(e),n?.(),n=null)})}return{destroy(){n?.(),n=null}}},P=e=>{let t=!1,n=null,r=null,i=null,a=()=>{n!==null&&(clearTimeout(n),n=null),i&&(r??globalThis).removeEventListener(`scrollend`,i),i=null,r=null,t=!1};return{get active(){return t},start(){a(),t=!0;let o=()=>{a()};i=o,r=e(),(r??globalThis).addEventListener(`scrollend`,o,{once:!0}),n=setTimeout(o,500)},destroy(){a()}}},F=(e,t)=>{let n=null,r=null;return{schedule(){n===null&&(n=requestAnimationFrame(()=>{n=null,r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,e()},t)}))},destroy(){n!==null&&(cancelAnimationFrame(n),n=null),r!==null&&(clearTimeout(r),r=null)}}},I=(e,t,n,r,i,a)=>{let o=new Set,s=new Map,c=!1,l=null,u=e=>{if(!a()){for(let t of e)s.set(t.target,t);r()}},d=e=>new IntersectionObserver(u,{root:e,rootMargin:t,threshold:0}),f=n(),p=d(f),m=()=>{let t=n()??document,r;try{r=t.querySelectorAll(e)}catch{i();return}let a=new Set;for(let e of r){let t=e.id;t&&!c&&(a.has(t)&&(c=!0,console.warn(`[real-router] scroll-spy: duplicate id "${t}" observed. Selection picks the topmost visible match deterministically.`)),a.add(t)),!o.has(e)&&(p.observe(e),o.add(e))}},h={childList:!0,subtree:!0,attributes:!0,attributeFilter:[`id`]},g=null,_=()=>{for(let e of o)e.isConnected||(p.unobserve(e),o.delete(e),s.delete(e));let e=n();e!==f&&(f=e,p.disconnect(),p=d(e),o.clear(),s.clear(),g?.disconnect(),g?.observe(e??document.body,h)),m()};return m(),g=new MutationObserver(()=>{l!==null&&clearTimeout(l),l=setTimeout(()=>{l=null,_()},250)}),g.observe(f??document.body,h),{pending:s,isContainerDetached:()=>f!==null&&!f.isConnected,reconcile:_,destroy(){p.disconnect(),g.disconnect(),l!==null&&(clearTimeout(l),l=null),o.clear(),s.clear()}}};function L(e,t){if(typeof document>`u`||typeof IntersectionObserver>`u`)return A;let{selector:n}=t;if(!n)return A;let r=t.rootMargin??`-20% 0px -60% 0px`,i=t.scrollContainer,a=()=>i?.()??null,o=!1,s=!1,c=!1,l=()=>s||o,u=null,d=m(e),f=N(e,()=>{s=!0}),p=P(a),h=F(()=>{u?.()},150),g=I(n,r,a,()=>{h.schedule()},()=>{s||(s=!0,console.warn(`[real-router] scroll-spy: invalid selector "${n}". Disabling.`))},l);u=()=>{if(o||s){g.pending.clear();return}if(d.getSnapshot().isTransitioning||p.active)return;let t=M(g.pending.values());if(g.pending.clear(),!t)return;let n=t.target.id;if(!n)return;let r=e.getState();if(!r||n===j(r)?.hash)return;let i={hash:n,replace:!0,force:!0,hashChange:!0};c=!0,e.navigate(r.name,r.params,i).catch(()=>{}).finally(()=>{c=!1})};let _=e.subscribe(({route:e})=>{c||(g.isContainerDetached()&&g.reconcile(),j(e)?.hashChanged&&p.start())});return{destroy(){o=!0,_(),g.destroy(),h.destroy(),p.destroy(),f.destroy()}}}const R=Object.freeze({destroy:()=>{}});function z(e){if(typeof document>`u`||typeof document.startViewTransition!=`function`)return R;let t=null,n=null,r=!1,i=()=>{t?.(),t=null},a=e.subscribeLeave(({signal:e})=>{if(!e.aborted)return r=!1,i(),new Promise(a=>{let o=new Promise(e=>{t=e});e.addEventListener(`abort`,()=>{r||(i(),n?.skipTransition?.(),a())},{once:!0});try{n=document.startViewTransition(()=>(a(),o))}catch{i(),a()}})}),o=e.subscribe(()=>{let e=t;if(r=!0,t=null,e===null)n=null;else{let t=n;setTimeout(()=>{e(),n===t&&(n=null)},0)}});return{destroy:()=>{a(),o(),n?.skipTransition?.(),n=null,i()}}}function B(e,t){return e.routeName===t.routeName&&e.className===t.className&&e.activeClassName===t.activeClassName&&e.activeStrict===t.activeStrict&&e.ignoreQueryParams===t.ignoreQueryParams&&e.onClick===t.onClick&&e.target===t.target&&e.style===t.style&&e.children===t.children&&e.hash===t.hash&&l(e.routeParams,t.routeParams)&&l(e.routeOptions,t.routeOptions)}const V=u(({routeName:c,routeParams:l,routeOptions:u=e,className:d,activeClassName:m=`active`,activeStrict:h=!1,ignoreQueryParams:g=!0,hash:_,onClick:v,target:y,children:b,...x})=>{let S=o(),C=a(c,l,h,g,_),w=l??t,T=n(S,c,w,_===void 0?void 0:{hash:_}),E=e=>{v&&(v(e),e.defaultPrevented)||!r(e.nativeEvent)||y===`_blank`||(e.preventDefault(),i(S,c,w,_,u).catch(()=>{}))},D=f(()=>s(C,m,d),[C,m,d]);return p(`a`,{...x,href:T,className:D,onClick:E,children:b})},B);V.displayName=`Link`;const H=({router:e,children:t,announceNavigation:n,scrollRestoration:r,scrollSpy:i,viewTransitions:a})=>{let o=n!==void 0&&n!==!1,s=typeof n==`object`?n:void 0,l=s?.prefix;d(()=>{if(!o)return;let t=y(e,s);return()=>{t.destroy()}},[e,o,l]);let u=r?.mode,f=r?.anchorScrolling,m=r?.behavior,h=r?.storageKey,g=r!==void 0;d(()=>{if(!g)return;let t=T(e,{mode:u,anchorScrolling:f,behavior:m,storageKey:h,scrollContainer:r.scrollContainer});return()=>{t.destroy()}},[e,g,u,f,m,h]);let _=i?.selector,v=i?.rootMargin,b=i!==void 0&&_!==void 0&&_!==``;return d(()=>{if(!b)return;let t=L(e,{selector:_,rootMargin:v,scrollContainer:i.scrollContainer});return()=>{t.destroy()}},[e,b,_,v]),d(()=>{if(!a)return;let t=z(e);return()=>{t.destroy()}},[e,a]),p(c,{router:e,children:t})};export{V as n,H as t};
2
+ //# sourceMappingURL=RouterProvider-4SkhC0gT.mjs.map