From 5935ffff7df63de0a68a3c289832410b26e33b9b Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Sat, 20 Jun 2026 19:28:53 -0700 Subject: [PATCH 1/9] feat: per-page chrome like custom actionbars --- .../src/NativeScriptRouterProvider.tsx | 62 ++++++++ packages/tanstack-router/src/PageRenderer.tsx | 141 +++++++++++++++++- 2 files changed, 197 insertions(+), 6 deletions(-) diff --git a/packages/tanstack-router/src/NativeScriptRouterProvider.tsx b/packages/tanstack-router/src/NativeScriptRouterProvider.tsx index 510b7ae..911124a 100644 --- a/packages/tanstack-router/src/NativeScriptRouterProvider.tsx +++ b/packages/tanstack-router/src/NativeScriptRouterProvider.tsx @@ -1,4 +1,5 @@ import { batch, createEffect, createMemo, createSignal, onMount, onCleanup, untrack } from 'solid-js'; +import type { JSX } from 'solid-js'; import type { AnyRouter } from '@tanstack/solid-router'; import { Color, ShowModalOptions, Utils } from '@nativescript/core'; import { renderPage } from './PageRenderer'; @@ -10,6 +11,22 @@ import type { NavigationGuard, NativeScriptModalOptionsResolver, NativeScriptMod import { describeComponentShape, normalizeRenderableComponent } from './component-shape'; import { createNativeScriptRouter } from './router'; import { getSingleModalPathFromSearch, withSingleModalPath } from './modal-state'; +import { subscribeSolidHmrRemount } from './solid-hmr-remount'; + +/** + * Context passed to {@link NativeScriptRouterProviderProps.actionBar} for the route + * whose Page is about to be created. + */ +export interface NativeScriptPageActionBarContext { + /** Resolved pathname for the page being created (e.g. `"/about"`). */ + path: string; + /** Matched leaf route id. */ + routeId: string; + /** The matched route object (`router.routesById[routeId]`). */ + route: any; + /** The route's `staticData` route option, or `{}` when none was declared. */ + staticData: Record; +} export interface NativeScriptRouterProviderProps { router: AnyRouter; @@ -18,6 +35,15 @@ export interface NativeScriptRouterProviderProps { transition?: { name?: string; duration?: number; curve?: any }; debug?: boolean; modalOptions?: NativeScriptModalPresentationOptions | NativeScriptModalOptionsResolver; + /** + * Optional per-page chrome — typically an `` — rendered into each route's + * native Page. Return an `` for the matched route and dominative slots it + * into `page.actionBar`, so iOS/visionOS show a native back button automatically on + * pushed pages; return `null`/`undefined` for no bar. Receives the matched route and + * its `staticData`, so titles/items can be derived per route. With this, the app no + * longer needs a persistent header above the Frame — each page owns its own bar. + */ + actionBar?: (ctx: NativeScriptPageActionBarContext) => JSX.Element | null | undefined; } export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProps) { @@ -500,10 +526,32 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp // Set up back button handling const cleanupBack = setupBackHandler(router, () => frameRef, guard); + // ── Solid HMR remount subscription ── + // After solid-refresh's inline `patchRegistry` has swapped the proxy's + // underlying signal to point at each newly-evaluated component, the + // proxy's memo correctly re-evaluates, but in this universal-renderer + + // nested-context configuration the page-level renderEffect doesn't + // re-fire so the visible Page tree never updates. The NS HMR client + // emits a `__ns_solid_hmr_subscribe` completion event after the solid + // case finishes; we react by re-mounting the Solid tree of every Page + // currently held by the Frame (currentPage + backStack). Re-mounting a + // Page disposes its existing render and then runs `render()` again with + // the fresh route component pulled from `router.routesById`, so the + // user sees the edit without losing their place in the navigation + // history. + const cleanupHmr = subscribeSolidHmrRemount({ + router, + getFrame: () => frameRef, + getActiveModalPage: () => activeModalPage, + getActiveModalPath: () => activeModalPath, + log, + }); + onCleanup(() => { closeModalFromRouterState(); unsub(); cleanupBack(); + cleanupHmr(); unsubLoad(); unsubBeforeLoad(); }); @@ -676,6 +724,19 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp acquireGuard('router_state_forward_or_replace'); + // Build the per-page chrome thunk (e.g. ) for this route, if the + // consumer supplied an `actionBar` render fn. Passed into renderPage so it renders + // inside the page's own reactive scope and slots into page.actionBar. + const pageChrome = props.actionBar + ? () => + props.actionBar!({ + path: curPathname, + routeId: leafMatch.routeId, + route, + staticData: route?.options?.staticData ?? {}, + }) + : undefined; + log('[NSRouter] navigating Frame to', curPathname); frameRef.navigate({ create: () => @@ -729,6 +790,7 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp }, reconcileRouterToVisiblePath, props.debug, + pageChrome, ), animated: prevIndex >= 0 ? (props.animated ?? true) : false, transition: curTransition ?? props.transition, diff --git a/packages/tanstack-router/src/PageRenderer.tsx b/packages/tanstack-router/src/PageRenderer.tsx index c30b634..0dbb7d9 100644 --- a/packages/tanstack-router/src/PageRenderer.tsx +++ b/packages/tanstack-router/src/PageRenderer.tsx @@ -26,6 +26,31 @@ function isExpectedBackstackError(message: string): boolean { ) } +// Unwrap a solid-refresh proxy chain to the underlying user component +// function. See `solid-hmr-remount.ts` for full reasoning — the short +// version is that mounting with the proxy creates a HMRComp createMemo +// subscribed to the M_initial signal, which in our universal-renderer + +// nested context provider configuration is the source of "every other +// save applies". Mounting with the underlying function is a clean, +// single-pass render with no signal-based reactivity for solid-refresh +// to interfere with. +function unwrapSolidRefreshProxyInline(value: any): any { + if (typeof value !== 'function') return value + let current: any = value + let hops = 0 + while (typeof current?.__$ns_resolveSource === 'function' && hops < 8) { + try { + const next = current.__$ns_resolveSource() + if (typeof next !== 'function' || next === current) break + current = next + hops++ + } catch { + break + } + } + return current +} + export function renderPage( router: AnyRouter, RouteComponent: Component, @@ -33,6 +58,13 @@ export function renderPage( onNativeBack?: (sourcePath: string) => void, onVisiblePathChange?: (visiblePath: string) => void, debug?: boolean, + // Optional per-page chrome thunk (e.g. an ). Called inside the page's + // render scope so it participates in the same reactive lifecycle/disposal as the + // route content. Whatever it returns is inserted as a child of the Page alongside + // the route component — dominative's Page slots an ActionBar child into + // `page.actionBar` and the route's root view into `page.content`. See + // `NativeScriptRouterProvider`'s `actionBar` prop. + chrome?: () => any, ): any { const page = document.createElement('Page') as any const log = createDebugLogger(debug) @@ -41,6 +73,10 @@ export function renderPage( const loggedUnexpectedErrors = new Set() let dispose: (() => void) | undefined let nativeBackSyncScheduled = false + // Track the current route component reference. HMR remount swaps this so a + // freshly-imported route module's exported component takes effect on + // subsequent mounts without the consumer needing to re-call renderPage. + let currentRouteComponent: Component = RouteComponent const getPagePath = () => (page as any).__nsRouterPath || routePath @@ -69,17 +105,41 @@ export function renderPage( } const SafeRouteView = () => { - const Comp = normalizeRenderableComponent(RouteComponent) + // Unwrap solid-refresh proxies (M_save_X.proxy → M_initial.proxy → fn) + // ALSO at boot (not just HMR remount). If we mount with the proxy, its + // HMRComp body creates a createMemo subscribed to M_initial.source. + // That subscription survives subsequent unmounts in subtle ways + // (cleanNode unsubscribes, but the cached value held by the renderEffect + // closure still references the previous JSX), and the next HMR cycle's + // patchRegistry causes the previous mount's leftover memo to re-evaluate + // BEFORE our remount fires — producing the visible "every other save + // applies / always one save behind" symptom. By unwrapping here we + // ensure devComponent calls the underlying user function directly with + // no proxy chain at any mount, boot or HMR. + const raw = normalizeRenderableComponent(currentRouteComponent) + const Comp = unwrapSolidRefreshProxyInline(raw) if (!Comp) { console.error( '[NSRouter] Invalid render component for route path:', routePath, 'shape:', - describeComponentShape(RouteComponent), + describeComponentShape(currentRouteComponent), ) return null as any } + // Diagnostic: surface the proxy/component identity SafeRouteView is + // about to render. Pairs with the inline patchRegistry diagnostics in + // `@solid-refresh` ($$refreshESM) — together they make the + // "did patchRegistry actually swap the signal AND did mount actually + // render that swapped proxy?" question answerable from the device + // console without instrumenting solid-js itself. + try { + const compName = (Comp as any).name || 'anonymous' + const compTag = (Comp as any).location || '' + log('[NSRouter] SafeRouteView render — component name=', compName, 'location=', compTag) + } catch {} + try { return createComponent(Comp as any, {}) } catch (err) { @@ -87,7 +147,7 @@ export function renderPage( '[NSRouter] Route component invocation failed for path:', routePath, 'shape:', - describeComponentShape(RouteComponent), + describeComponentShape(currentRouteComponent), err, ) return null as any @@ -97,7 +157,10 @@ export function renderPage( dispose = render( () => ( - {() => ( + {() => [ + // Per-page chrome (e.g. ) rendered as a sibling of the route + // content; dominative routes it to `page.actionBar`. null when no chrome. + chrome ? chrome() : null, void) => { const message = getErrorMessage(err) @@ -114,8 +177,8 @@ export function renderPage( }} > - - )} + , + ]} ), page, @@ -132,6 +195,72 @@ export function renderPage( } } + // Detach every child currently attached to the Page. Solid's `dispose()` + // tears down reactive computations but does NOT remove DOM nodes — so a + // naive unmount + mount leaves the old subtree attached and the new one + // gets appended alongside it. NativeScript Pages can only display one + // root content view at a time, so without this clear the new tree never + // becomes visible (the user keeps seeing the stale render). Used only on + // explicit remount paths (HMR), never during routine navigation. + const clearPageChildren = () => { + try { + let child: any = (page as any).firstChild + while (child) { + const next = child.nextSibling + try { + ;(page as any).removeChild?.(child) + } catch (err) { + log('[NSRouter] removeChild failed during remount clear:', err) + } + child = next + } + // dominative's Page wrapper has no __dominative_onRemoveChild — undom + // clears `page.childNodes` but NS Core's `Page._actionBar` and + // `Page._content` references stay pointing at the previous mount's + // elements. The next mount inserts NEW elements which trigger the + // setters' identity check (different => replace), so this is usually + // a no-op safety. But under HMR remount we've observed cases where the + // NS view tree retains stale visible content even though the new + // dominative tree was correctly built. Explicitly null out the slots + // before the mount inserts fresh elements so the setters always take + // the "first set" path (no comparison against a stale reference). + try { + ;(page as any).actionBar = null + } catch {} + try { + ;(page as any).content = null + } catch {} + } catch (err) { + log('[NSRouter] clearPageChildren failed:', err) + } + } + + // Expose a remount API so HMR-aware code (e.g. + // `NativeScriptRouterProvider`'s solid-hmr subscriber) can swap in a + // freshly-imported route component without going through + // `frame.navigate()` (which would push a new history entry and lose the + // user's place). When `nextComponent` is provided the page picks up that + // reference on the next mount; otherwise it re-mounts with whatever + // reference is currently held (useful when the proxy itself was patched + // in place, e.g. solid-refresh). + ;(page as any).__ns_remount = (nextComponent?: Component) => { + if (typeof nextComponent === 'function') { + // Diagnostic: surface whether nextComponent identity changes from + // call to call. If the same proxy instance is passed across saves + // AND solid-refresh's patchRegistry is functioning, the proxy's + // internal signal source should still produce the latest body. + try { + const sameAsBefore = currentRouteComponent === nextComponent + log('[NSRouter] __ns_remount component identity sameAsBefore=', sameAsBefore, 'name=', (nextComponent as any).name || 'anonymous') + } catch {} + currentRouteComponent = nextComponent + } + unmount() + clearPageChildren() + mount() + log('[NSRouter] page remount:', (page as any).__nsRouterPath || routePath) + } + // Mount immediately for the page being navigated to. mount() From be51072a0385d4755b0a05ed591c19165254dc4b Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Sat, 20 Jun 2026 19:29:08 -0700 Subject: [PATCH 2/9] feat: hmr improvements --- .../tanstack-router/src/solid-hmr-remount.ts | 260 ++++++++++++++++ packages/tanstack-router/src/solid/index.ts | 1 + .../test/solid-hmr-remount.test.ts | 294 ++++++++++++++++++ 3 files changed, 555 insertions(+) create mode 100644 packages/tanstack-router/src/solid-hmr-remount.ts create mode 100644 packages/tanstack-router/test/solid-hmr-remount.test.ts diff --git a/packages/tanstack-router/src/solid-hmr-remount.ts b/packages/tanstack-router/src/solid-hmr-remount.ts new file mode 100644 index 0000000..70a95e1 --- /dev/null +++ b/packages/tanstack-router/src/solid-hmr-remount.ts @@ -0,0 +1,260 @@ +import type { AnyRouter } from '@tanstack/solid-router'; +import { normalizeRenderableComponent } from './component-shape'; + +type NsSolidHmrEvent = { + kind: 'solid'; + changedFiles: string[]; + boundaries: string[]; +}; +type NsSolidHmrUnsubscribe = () => void; +type NsSolidHmrSubscribe = (fn: (ev: NsSolidHmrEvent) => void) => NsSolidHmrUnsubscribe; + +export interface SolidHmrRemountOptions { + router: AnyRouter; + getFrame: () => any; + getActiveModalPage?: () => any; + getActiveModalPath?: () => string | null | undefined; + log: (...args: any[]) => void; +} + +// Translate a TanStack file-based route boundary path +// (e.g. `/src/routes/posts.$postId.tsx`) to its TanStack `fullPath` +// (`/posts/$postId`). Used to look up the route's freshly-patched +// component (set by the NS HMR client during boundary re-import) when a +// route file is the one that changed. +function boundaryToFullPath(bid: string): string | null { + const m = bid.match(/\/src\/routes\/(.+)\.(tsx|jsx|ts|js)$/i); + if (!m) return null; + let p = m[1]; + p = p.replace(/\./g, '/'); + if (p === 'index') return '/'; + if (p.endsWith('/index')) p = p.slice(0, -6); + p = p.replace(/(^|\/)-([\w])/g, '$1$2'); + return '/' + p; +} + +// The root route (`__root__`) shares fullPath '/' with the index route, so +// prefer the non-root (leaf) match — otherwise an `index.tsx` edit would read +// the root layout's component instead of the page's. The NS HMR client patches +// `route.options.component` using the same preference, so patch + read here +// resolve to the same route. +function findRouteByFullPath(router: any, fullPath: string): any | null { + const byId = router?.routesById; + if (!byId) return null; + let rootMatch: any | null = null; + for (const rid of Object.keys(byId)) { + const r = byId[rid]; + if (r?.fullPath !== fullPath) continue; + if (rid === '__root__') { + rootMatch = rootMatch || r; + continue; + } + return r; + } + return rootMatch; +} + +// Resolve a solid-refresh proxy chain down to the underlying user component +// function. solid-refresh wraps every component in a `createProxy`-returned +// Proxy whose `HMRComp` body returns `createMemo(() => source()(props))`. +// On HMR, `patchComponent` rewrites M_save_X.signal.value = M_initial.proxy +// and M_initial.signal.value = newHomeFn, so calling M_save_X.proxy(props) +// goes M_save_X.proxy → OUTER memo → M_initial.proxy → INNER memo → newHomeFn. +// +// The nested memo chain is the source of "every other save applies": each +// remount's INNER memo subscribes to M_initial.source, and on patch the +// previous mount's INNER memos (still subscribed because the disposal +// behavior under universal-renderer + nested context provider isn't fully +// torn down before the next patch) re-evaluate, producing zombie renders +// that fight the fresh mount's renderEffect. +// +// By unwrapping the proxy chain HERE — before passing to `__ns_remount` — +// we hand the page the freshly-evaluated user function directly. The page's +// `createComponent(fn, {})` then runs `fn({})` without any HMRComp memos. +// Each save's mount is a clean, single-pass render with no signal-based +// reactivity to share with previous mounts. solid-refresh's patchRegistry +// still updates the registry (so other consumers that hold the proxy +// reference also see fresh behavior), but our page mount is decoupled. +// +// Each call to source() returns either another solid-refresh proxy +// (recurse) or the underlying user function (terminate). +function unwrapSolidRefreshProxy(value: any, log: (...a: any[]) => void): any { + if (typeof value !== 'function') return value; + let current: any = value; + let hops = 0; + // The escape hatch is `__$ns_resolveSource` (NOT `__$$ns_resolveSource`): + // Vite's plugin patches solid-refresh via String.prototype.replace, where + // `$$` in the replacement is a literal `$`. We use a single `$` to avoid + // that footgun. + while (typeof current?.__$ns_resolveSource === 'function' && hops < 8) { + try { + const next = current.__$ns_resolveSource(); + if (typeof next !== 'function' || next === current) break; + current = next; + hops++; + } catch (err) { + log('[NSRouter][hmr] unwrapSolidRefreshProxy error at hop', hops, err); + break; + } + } + log('[NSRouter][hmr] unwrap', 'name=', (value as any)?.name, 'hops=', hops, 'finalName=', (current as any)?.name); + return current; +} + +// Ask a Page (rendered by `PageRenderer.renderPage`) to dispose its current +// Solid tree and remount with `nextComponent` as the route component. When +// `nextComponent` is undefined, the page reuses its existing component +// reference — which for solid-refresh is the proxy, whose internal signal +// has already been swapped by `patchRegistry` so a fresh render emits the +// updated body. Pages render through the same RouterContextProvider / +// ErrorBoundary chain, so a remount picks up the freshest behavior without +// a Frame.navigate (no backstack churn, no native page transition). +function remountPage(page: any, nextComponent: any, log: (...a: any[]) => void): boolean { + if (!page || typeof page.__ns_remount !== 'function') { + return false; + } + try { + page.__ns_remount(nextComponent); + log('[NSRouter][hmr] remounted page', page.__nsRouterPath || '(unknown path)'); + return true; + } catch (err) { + log('[NSRouter][hmr] remount failed', err); + return false; + } +} + +// Collect every Page currently held by the Frame (currentPage + backStack +// entries). NS Frame's backStack shape varies across runtimes/versions: +// some expose Page directly, others wrap each entry in +// { entry, resolvedPage } or `{ resolvedPage }`. We probe defensively so a +// minor shape change in @nativescript/core doesn't silently break HMR. +function collectFramePages(frame: any): any[] { + if (!frame) return []; + const pages: any[] = []; + if (frame.currentPage) pages.push(frame.currentPage); + const backStack = (frame as any).backStack; + if (Array.isArray(backStack)) { + for (const item of backStack) { + if (!item) continue; + if (item.tagName === 'page' || item.constructor?.name?.toLowerCase().includes('page')) { + pages.push(item); + } else if (item.entry?.resolvedPage) { + pages.push(item.entry.resolvedPage); + } else if (item.resolvedPage) { + pages.push(item.resolvedPage); + } + } + } + return pages; +} + +// Subscribe to the NS HMR client's Solid completion event and trigger a +// page-level remount whenever a Solid HMR cycle finishes. Returns a cleanup +// function that unsubscribes from the HMR event stream. +// +// Strategy: when ANY .tsx file changes (route OR component), every Page held +// by the Frame is remounted. We don't try to map "which file changed" to +// "which page depends on it" — `solid-refresh` already swapped the proxy +// signals globally, so a fresh render of any page automatically picks up the +// latest component bodies. Remounting unaffected pages is a few-millisecond +// no-op cost, and avoiding the dependency analysis means HMR Just Works for +// edits to shared components, hooks, utilities, etc., not just route files. +// +// For route-file edits we do prefer to pass the freshly-patched component +// reference explicitly (rather than reusing the existing proxy ref) so that +// any deep-equality checks downstream see a different identity. +// +// If the NS HMR client is not present (production builds, tests, or older +// runtimes that don't expose `__ns_solid_hmr_subscribe`), this is a no-op +// and returns a no-op cleanup. +// Resolve (or lazily create) the shared globalThis-stored listener Set used +// by the NS HMR client. By using the same Set the HMR client iterates at +// emit time, we sidestep module-instance / realm mismatches that can occur +// in NativeScript when the HMR client and user-app modules load via +// different paths (HTTP loader vs bundled vendor realm). +function resolveSharedListenerSet(): Set<(ev: NsSolidHmrEvent) => void> { + const g = globalThis as any; + let set = g.__ns_solid_hmr_listener_set as Set<(ev: NsSolidHmrEvent) => void> | undefined; + if (!set) { + set = new Set<(ev: NsSolidHmrEvent) => void>(); + g.__ns_solid_hmr_listener_set = set; + } + return set; +} + +export function subscribeSolidHmrRemount(opts: SolidHmrRemountOptions): NsSolidHmrUnsubscribe { + const { router, getFrame, getActiveModalPage, getActiveModalPath, log } = opts; + const g = globalThis as any; + + log('[NSRouter][hmr] subscribeSolidHmrRemount globalSubscribe=', typeof g.__ns_solid_hmr_subscribe, 'listenerSet=', typeof g.__ns_solid_hmr_listener_set); + + const listener = (ev: NsSolidHmrEvent) => { + log('[NSRouter][hmr] event changedFiles=', ev.changedFiles, 'boundaries=', ev.boundaries); + try { + const tsxChanged = ev.changedFiles.filter((id) => /\.(tsx|jsx)$/i.test(id)); + if (tsxChanged.length === 0 && ev.boundaries.length === 0) { + log('[NSRouter][hmr] no .tsx/.jsx changes; skipping remount'); + return; + } + + // Build a routePath → freshly-patched component map for any changed + // route files (under /src/routes/). Used as `nextComponent` hint when + // remounting pages that match those paths. + const routePathToComponent = new Map(); + for (const bid of [...tsxChanged, ...ev.boundaries]) { + const fullPath = boundaryToFullPath(bid); + if (!fullPath) continue; + const route = findRouteByFullPath(router, fullPath); + const rawComp = normalizeRenderableComponent(route?.options?.component); + // Unwrap the solid-refresh proxy chain so the page mount calls the + // freshly-loaded user function directly. See unwrapSolidRefreshProxy + // for full reasoning — this is the fix for "every other save applies". + const Comp = unwrapSolidRefreshProxy(rawComp, log); + if (Comp) routePathToComponent.set(fullPath, Comp); + } + + const frame = getFrame(); + const pages = collectFramePages(frame); + + let remounted = 0; + for (const page of pages) { + const path = page?.__nsRouterPath; + const nextComponent = path ? routePathToComponent.get(path) : undefined; + if (remountPage(page, nextComponent, log)) remounted++; + } + + // Modal pages live outside the Frame. Remount any active modal too so + // its tree picks up the edit. + try { + const modalPage = getActiveModalPage?.(); + const modalPath = getActiveModalPath?.(); + if (modalPage) { + const nextComponent = modalPath ? routePathToComponent.get(modalPath) : undefined; + remountPage(modalPage, nextComponent, log); + } + } catch (err) { + log('[NSRouter][hmr] modal remount failed', err); + } + + log('[NSRouter][hmr] event handled. tsxChanged=', tsxChanged.length, 'pages=', pages.length, 'remounted=', remounted); + } catch (err) { + log('[NSRouter][hmr] handler failed', err); + } + }; + + // Prefer subscribing through the published global API so the HMR client + // can do its own bookkeeping (count logs, etc.). Fall back to writing + // directly into the shared global Set when the API isn't there yet — + // that path still works because the HMR client iterates the same Set + // at emit time. + const subscribe = g.__ns_solid_hmr_subscribe as NsSolidHmrSubscribe | undefined; + if (typeof subscribe === 'function') { + log('[NSRouter][hmr] subscribed via global __ns_solid_hmr_subscribe'); + return subscribe(listener); + } + + const set = resolveSharedListenerSet(); + set.add(listener); + log('[NSRouter][hmr] subscribed via shared listener set (fallback). size=', set.size); + return () => set.delete(listener); +} diff --git a/packages/tanstack-router/src/solid/index.ts b/packages/tanstack-router/src/solid/index.ts index 17cad91..e17bac5 100644 --- a/packages/tanstack-router/src/solid/index.ts +++ b/packages/tanstack-router/src/solid/index.ts @@ -4,6 +4,7 @@ export { createNativeScriptHistory } from '../history'; export { createNativeScriptRouter } from '../router'; export { NativeScriptRouterProvider } from '../NativeScriptRouterProvider'; +export type { NativeScriptRouterProviderProps, NativeScriptPageActionBarContext } from '../NativeScriptRouterProvider'; export { Link } from '../Link'; export type { Register, RegisteredRouter } from '../register'; export { createNativeScriptNavigationState, createNativeScriptTransitionState } from '../transition-state'; diff --git a/packages/tanstack-router/test/solid-hmr-remount.test.ts b/packages/tanstack-router/test/solid-hmr-remount.test.ts new file mode 100644 index 0000000..fa4cb77 --- /dev/null +++ b/packages/tanstack-router/test/solid-hmr-remount.test.ts @@ -0,0 +1,294 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { subscribeSolidHmrRemount } from '../src/solid-hmr-remount'; + +type Listener = (ev: { kind: 'solid'; changedFiles: string[]; boundaries: string[] }) => void; + +class FakePage { + public __nsRouterPath?: string; + public __ns_remount = vi.fn<(next?: any) => void>(); + constructor(path?: string) { + if (path) this.__nsRouterPath = path; + } +} + +class FakeFrame { + public currentPage: FakePage | null = null; + public backStack: any[] = []; +} + +describe('subscribeSolidHmrRemount', () => { + let listener: Listener | null; + const log = vi.fn(); + + beforeEach(() => { + listener = null; + log.mockReset(); + (globalThis as any).__ns_solid_hmr_subscribe = (fn: Listener) => { + listener = fn; + return () => { + listener = null; + }; + }; + delete (globalThis as any).__ns_solid_hmr_listener_set; + }); + + afterEach(() => { + delete (globalThis as any).__ns_solid_hmr_subscribe; + delete (globalThis as any).__ns_solid_hmr_listener_set; + }); + + it('falls back to direct listener set when no subscribe global is present', () => { + delete (globalThis as any).__ns_solid_hmr_subscribe; + const cleanup = subscribeSolidHmrRemount({ + router: {} as any, + getFrame: () => null, + log, + }); + expect(cleanup).toBeTypeOf('function'); + const set = (globalThis as any).__ns_solid_hmr_listener_set as Set; + expect(set).toBeInstanceOf(Set); + expect(set.size).toBe(1); + cleanup(); + expect(set.size).toBe(0); + }); + + it('shared listener set still receives events when emit walks it directly', () => { + delete (globalThis as any).__ns_solid_hmr_subscribe; + const home = new FakePage('/'); + const frame = new FakeFrame(); + frame.currentPage = home; + + subscribeSolidHmrRemount({ + router: { routesById: {} } as any, + getFrame: () => frame, + log, + }); + + const set = (globalThis as any).__ns_solid_hmr_listener_set as Set; + for (const fn of set) { + fn({ kind: 'solid', changedFiles: ['/src/components/home.tsx'], boundaries: [] }); + } + expect(home.__ns_remount).toHaveBeenCalledTimes(1); + }); + + it('remounts every page on the Frame for any tsx change', () => { + const home = new FakePage('/'); + const posts = new FakePage('/posts'); + const frame = new FakeFrame(); + frame.currentPage = posts; + frame.backStack = [home]; + + subscribeSolidHmrRemount({ + router: { routesById: {} } as any, + getFrame: () => frame, + log, + }); + + listener!({ + kind: 'solid', + changedFiles: ['/src/components/home.tsx'], + boundaries: [], + }); + + expect(home.__ns_remount).toHaveBeenCalledTimes(1); + expect(posts.__ns_remount).toHaveBeenCalledTimes(1); + }); + + it('passes the freshly-patched component when a route file changed', () => { + const home = new FakePage('/'); + const frame = new FakeFrame(); + frame.currentPage = home; + + const NewHome = () => null; + const router = { + routesById: { + '/': { fullPath: '/', options: { component: NewHome } }, + }, + } as any; + + subscribeSolidHmrRemount({ + router, + getFrame: () => frame, + log, + }); + + listener!({ + kind: 'solid', + changedFiles: ['/src/routes/index.tsx'], + boundaries: ['/src/routes/index.tsx'], + }); + + expect(home.__ns_remount).toHaveBeenCalledTimes(1); + expect(home.__ns_remount).toHaveBeenCalledWith(NewHome); + }); + + it('passes the freshly-patched component when a component file change propagates to a route file boundary', () => { + // Mirrors the production HMR pipeline: editing + // `/src/components/home.tsx` triggers the HMR client's BFS pass-2, + // which discovers `/src/routes/index.tsx` (the route file that + // imports home.tsx) as a boundary. The HMR client re-imports the + // route file and patches `route.options.component` to the freshly- + // imported reference. The listener then reads that fresh reference + // and passes it through to the page remount — keeping the visible + // tree in sync with the edited source even when solid-refresh's + // proxy patch does not propagate to the page-level renderEffect. + const home = new FakePage('/'); + const frame = new FakeFrame(); + frame.currentPage = home; + + const NewHome = () => null; + const router = { + routesById: { + '/': { fullPath: '/', options: { component: NewHome } }, + }, + } as any; + + subscribeSolidHmrRemount({ + router, + getFrame: () => frame, + log, + }); + + listener!({ + kind: 'solid', + changedFiles: ['/src/components/home.tsx'], + boundaries: ['/src/components/home.tsx', '/src/routes/index.tsx'], + }); + + expect(home.__ns_remount).toHaveBeenCalledTimes(1); + expect(home.__ns_remount).toHaveBeenCalledWith(NewHome); + }); + + it('remounts without a nextComponent for non-route .tsx changes', () => { + const home = new FakePage('/'); + const frame = new FakeFrame(); + frame.currentPage = home; + + subscribeSolidHmrRemount({ + router: { routesById: {} } as any, + getFrame: () => frame, + log, + }); + + listener!({ + kind: 'solid', + changedFiles: ['/src/components/shared.tsx'], + boundaries: [], + }); + + expect(home.__ns_remount).toHaveBeenCalledTimes(1); + expect(home.__ns_remount).toHaveBeenCalledWith(undefined); + }); + + it('skips remount entirely when no .tsx files changed', () => { + const home = new FakePage('/'); + const frame = new FakeFrame(); + frame.currentPage = home; + + subscribeSolidHmrRemount({ + router: { routesById: {} } as any, + getFrame: () => frame, + log, + }); + + listener!({ + kind: 'solid', + changedFiles: ['/src/styles.css'], + boundaries: [], + }); + + expect(home.__ns_remount).not.toHaveBeenCalled(); + }); + + it('also remounts the active modal page when present', () => { + const home = new FakePage('/'); + const modal = new FakePage('/modal/share'); + const frame = new FakeFrame(); + frame.currentPage = home; + + subscribeSolidHmrRemount({ + router: { routesById: {} } as any, + getFrame: () => frame, + getActiveModalPage: () => modal, + getActiveModalPath: () => '/modal/share', + log, + }); + + listener!({ + kind: 'solid', + changedFiles: ['/src/components/modal-content.tsx'], + boundaries: [], + }); + + expect(home.__ns_remount).toHaveBeenCalledTimes(1); + expect(modal.__ns_remount).toHaveBeenCalledTimes(1); + }); + + it('handles backStack entries wrapped in { entry, resolvedPage }', () => { + const home = new FakePage('/'); + const posts = new FakePage('/posts'); + const frame = new FakeFrame(); + frame.currentPage = posts; + frame.backStack = [{ entry: { resolvedPage: home } }]; + + subscribeSolidHmrRemount({ + router: { routesById: {} } as any, + getFrame: () => frame, + log, + }); + + listener!({ + kind: 'solid', + changedFiles: ['/src/components/home.tsx'], + boundaries: [], + }); + + expect(home.__ns_remount).toHaveBeenCalledTimes(1); + expect(posts.__ns_remount).toHaveBeenCalledTimes(1); + }); + + it('cleanup unsubscribes from the HMR client', () => { + const home = new FakePage('/'); + const frame = new FakeFrame(); + frame.currentPage = home; + + const cleanup = subscribeSolidHmrRemount({ + router: { routesById: {} } as any, + getFrame: () => frame, + log, + }); + + cleanup(); + + expect(listener).toBeNull(); + }); + + it('catches handler errors so a flaky page does not break HMR for others', () => { + const broken = new FakePage('/broken'); + broken.__ns_remount = vi.fn(() => { + throw new Error('boom'); + }); + const fine = new FakePage('/fine'); + const frame = new FakeFrame(); + frame.currentPage = broken; + frame.backStack = [fine]; + + subscribeSolidHmrRemount({ + router: { routesById: {} } as any, + getFrame: () => frame, + log, + }); + + expect(() => + listener!({ + kind: 'solid', + changedFiles: ['/src/components/home.tsx'], + boundaries: [], + }), + ).not.toThrow(); + + expect(broken.__ns_remount).toHaveBeenCalledTimes(1); + expect(fine.__ns_remount).toHaveBeenCalledTimes(1); + }); +}); From f5355b4bb6742d5a6093d9924f143d48546e17fd Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Sun, 21 Jun 2026 18:36:03 -0700 Subject: [PATCH 3/9] fix: vite config for hmr --- packages/tanstack-router/nativescript.vite.mjs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/tanstack-router/nativescript.vite.mjs b/packages/tanstack-router/nativescript.vite.mjs index 4677205..e411c40 100644 --- a/packages/tanstack-router/nativescript.vite.mjs +++ b/packages/tanstack-router/nativescript.vite.mjs @@ -87,8 +87,18 @@ export default () => ({ alias: { // Keep Vite behavior aligned with nativescript.webpack.js integration. 'solid-js/web': solidWebShimPath, - 'solid-js/jsx-runtime': jsxRuntimeShimPath, - 'solid-js/jsx-dev-runtime': jsxRuntimeShimPath, + // NOTE: do NOT alias `solid-js/jsx-runtime` / `solid-js/jsx-dev-runtime` to a + // shim file INSIDE this package. @nativescript/vite (solid flavor) already provides + // its own jsx-runtime shim and serves it over HTTP. When this alias pointed at + // `./solid-js-jsx-runtime-shim.js` (a subpath of this vendored runtime plugin), the + // @nativescript/vite device rewriter collapsed that subpath to the vendor-package + // ROOT binding — `jsx = __nsPick("@nativescript/tanstack-router", "jsx")` — and the + // root has no `jsx` export, so `jsx` was `undefined`. Every `jsx(...)` call in the + // bundled router JSX (e.g. renderPage's ``) + // then threw "jsx is not a function", the route Page never rendered, the Frame stayed + // empty, and the app showed a blank screen under HMR. Letting @nativescript/vite's + // HTTP-served shim resolve these keeps `jsx` a real function. (The webpack path still + // aliases them via nativescript.webpack.js, which has its own shim handling.) ...(solidJsHPath ? { 'solid-js/h': solidJsHPath, From 4cb5116ffe353423ebe362406b746cc79f2ae50d Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Mon, 22 Jun 2026 18:07:08 -0700 Subject: [PATCH 4/9] feat: react support --- package-lock.json | 213 +++++++----- package.json | 4 + .../src/react/ErrorBoundary.tsx | 39 +++ packages/tanstack-router/src/react/Link.tsx | 168 ++++++++++ .../src/react/NativeScriptRouterProvider.tsx | 317 ++++++++++++++++++ .../src/react/PageRenderer.tsx | 209 ++++++++++++ .../tanstack-router/src/react/back-handler.ts | 26 ++ packages/tanstack-router/src/react/index.ts | 25 ++ .../src/react/react-hmr-remount.ts | 235 +++++++++++++ packages/tanstack-router/src/react/router.ts | 34 ++ packages/tanstack-router/tsup.config.ts | 3 +- 11 files changed, 1197 insertions(+), 76 deletions(-) create mode 100644 packages/tanstack-router/src/react/ErrorBoundary.tsx create mode 100644 packages/tanstack-router/src/react/Link.tsx create mode 100644 packages/tanstack-router/src/react/NativeScriptRouterProvider.tsx create mode 100644 packages/tanstack-router/src/react/PageRenderer.tsx create mode 100644 packages/tanstack-router/src/react/back-handler.ts create mode 100644 packages/tanstack-router/src/react/index.ts create mode 100644 packages/tanstack-router/src/react/react-hmr-remount.ts create mode 100644 packages/tanstack-router/src/react/router.ts diff --git a/package-lock.json b/package-lock.json index db52c77..ae8c068 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,15 +34,19 @@ "@nativescript/webpack": "~5.0.31", "@ngtools/webpack": "^19.0.0", "@tanstack/history": "^1.161.6", + "@tanstack/react-router": "^1.169.1", "@tanstack/router-core": "^1.169.1", "@tanstack/solid-router": "^1.169.1", "@triniwiz/nativescript-image-cache-it": "^8.0.1", + "@types/react": "^19.0.0", "babel-loader": "^9.1.3", "babel-preset-solid": "^1.8.19", "dominative": "^0.1.3", "husky": "~9.0.0", "jsdom": "^29.1.1", "ng-packagr": "^19.0.0", + "react": "^19.0.0", + "react-reconciler": "^0.32.0", "rxjs": "~7.8.0", "sass": "1.53.0", "solid-js": "^1.9.11", @@ -406,37 +410,6 @@ "tslib": "^2.1.0" } }, - "node_modules/@angular-devkit/schematics": { - "version": "19.2.22", - "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-19.2.22.tgz", - "integrity": "sha512-tvfu5jhem1o8qidVxvXe5KfCij65ioMLCOFA947DD+zb3yTl5pJyDm2dqzbOehuQw0fmH4XPQukRJsCUy+UwaA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@angular-devkit/core": "19.2.22", - "jsonc-parser": "3.3.1", - "magic-string": "0.30.17", - "ora": "5.4.1", - "rxjs": "7.8.1" - }, - "engines": { - "node": "^18.19.1 || ^20.11.1 || >=22.0.0", - "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", - "yarn": ">= 1.13.0" - } - }, - "node_modules/@angular-devkit/schematics/node_modules/rxjs": { - "version": "7.8.1", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", - "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", - "dev": true, - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "tslib": "^2.1.0" - } - }, "node_modules/@angular/animations": { "version": "19.2.19", "resolved": "https://registry.npmjs.org/@angular/animations/-/animations-19.2.19.tgz", @@ -10048,24 +10021,6 @@ } } }, - "node_modules/@schematics/angular": { - "version": "19.2.22", - "resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-19.2.22.tgz", - "integrity": "sha512-ZCyfDHD3dbU/PEr9M4EGGAWxQLlmITKJgJNAvNMLv8aiXkV31SiUCGwvnXh0dVPkufv+hPnqd+5ZpwAso6wkPw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@angular-devkit/core": "19.2.22", - "@angular-devkit/schematics": "19.2.22", - "jsonc-parser": "3.3.1" - }, - "engines": { - "node": "^18.19.1 || ^20.11.1 || >=22.0.0", - "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", - "yarn": ">= 1.13.0" - } - }, "node_modules/@sinclair/typebox": { "version": "0.27.10", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.10.tgz", @@ -10354,6 +10309,83 @@ "url": "https://github.com/sponsors/tannerlinsley" } }, + "node_modules/@tanstack/react-router": { + "version": "1.170.16", + "resolved": "https://registry.npmjs.org/@tanstack/react-router/-/react-router-1.170.16.tgz", + "integrity": "sha512-w6eq1IJklujs1tESazaK/FxH0+H2l8vm/QPuu1cD3oRW/ubgKneQpd7b64ti/8gUyEimzimJQZDmJr6YHfP5+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tanstack/history": "1.162.0", + "@tanstack/react-store": "^0.9.3", + "@tanstack/router-core": "1.171.13", + "isbot": "^5.1.22" + }, + "engines": { + "node": ">=20.19" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": ">=18.0.0 || >=19.0.0", + "react-dom": ">=18.0.0 || >=19.0.0" + } + }, + "node_modules/@tanstack/react-router/node_modules/@tanstack/history": { + "version": "1.162.0", + "resolved": "https://registry.npmjs.org/@tanstack/history/-/history-1.162.0.tgz", + "integrity": "sha512-79pf/RkhteYZTRgcR4F9kbk84P2N8rugQJswxfIqovlbRiT3yI7eBE+5QorIrZaOKktsgzRlXh1l/du/xpl4iA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.19" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-router/node_modules/@tanstack/router-core": { + "version": "1.171.13", + "resolved": "https://registry.npmjs.org/@tanstack/router-core/-/router-core-1.171.13.tgz", + "integrity": "sha512-+NOwEj1kO/6IGmpHRIZHasYxYWpyBQGNIZAST9aNrk9Q3YlU9SgqVnl1pbLa9qAKfeNdXQIRve0RQb/0kyDeDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tanstack/history": "1.162.0", + "cookie-es": "^3.0.0", + "seroval": "^1.5.4", + "seroval-plugins": "^1.5.4" + }, + "engines": { + "node": ">=20.19" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-store": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/@tanstack/react-store/-/react-store-0.9.3.tgz", + "integrity": "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tanstack/store": "0.9.3", + "use-sync-external-store": "^1.6.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/@tanstack/router-core": { "version": "1.169.1", "resolved": "https://registry.npmjs.org/@tanstack/router-core/-/router-core-1.169.1.tgz", @@ -10405,6 +10437,17 @@ "solid-js": "^1.9.10" } }, + "node_modules/@tanstack/store": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/@tanstack/store/-/store-0.9.3.tgz", + "integrity": "sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, "node_modules/@triniwiz/nativescript-image-cache-it": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/@triniwiz/nativescript-image-cache-it/-/nativescript-image-cache-it-8.0.1.tgz", @@ -10720,6 +10763,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/react": { + "version": "19.2.17", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz", + "integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, "node_modules/@types/retry": { "version": "0.12.2", "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.2.tgz", @@ -24437,29 +24490,37 @@ "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } }, - "node_modules/react-dom": { - "version": "19.2.4", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", - "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", + "node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/react-reconciler": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.32.0.tgz", + "integrity": "sha512-2NPMOzgTlG0ZWdIf3qG+dcbLSoAc/uLfOwckc3ofy5sSK0pLJqnQLpUFxvGcN2rlXSjnVtGeeFLNimCQEj5gOQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "scheduler": "^0.27.0" + "scheduler": "^0.26.0" + }, + "engines": { + "node": ">=0.10.0" }, "peerDependencies": { - "react": "^19.2.4" + "react": "^19.1.0" } }, - "node_modules/react-is": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "node_modules/react-reconciler/node_modules/scheduler": { + "version": "0.26.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", + "integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==", "dev": true, "license": "MIT" }, @@ -25585,14 +25646,6 @@ "node": ">=v12.22.7" } }, - "node_modules/scheduler": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", - "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/schema-utils": { "version": "4.3.3", "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz", @@ -25725,9 +25778,9 @@ } }, "node_modules/seroval": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.5.0.tgz", - "integrity": "sha512-OE4cvmJ1uSPrKorFIH9/w/Qwuvi/IMcGbv5RKgcJ/zjA/IohDLU6SVaxFN9FwajbP7nsX0dQqMDes1whk3y+yw==", + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.5.4.tgz", + "integrity": "sha512-46uFvgrXTVxZcUorgSSRZ4y+ieqLLQRMlG4bnCZKW3qI6BZm7Rg4ntMW4p1mILEEBZWrFlcpp0AyIIlM6jD9iw==", "dev": true, "license": "MIT", "engines": { @@ -25735,9 +25788,9 @@ } }, "node_modules/seroval-plugins": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/seroval-plugins/-/seroval-plugins-1.5.0.tgz", - "integrity": "sha512-EAHqADIQondwRZIdeW2I636zgsODzoBDwb3PT/+7TLDWyw1Dy/Xv7iGUIEXXav7usHDE9HVhOU61irI3EnyyHA==", + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/seroval-plugins/-/seroval-plugins-1.5.4.tgz", + "integrity": "sha512-S0xQPhUTefAhNvNWFg0c1J8qJArHt5KdtJ/cFAofo06KD1MVSeFWyl4iiu+ApDIuw0WhjpOfCdgConOfAnLgkw==", "dev": true, "license": "MIT", "engines": { @@ -28760,6 +28813,16 @@ "dev": true, "license": "MIT" }, + "node_modules/use-sync-external-store": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", + "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", diff --git a/package.json b/package.json index ac52df2..62caef1 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,11 @@ "@tanstack/history": "^1.161.6", "@tanstack/router-core": "^1.169.1", "@tanstack/solid-router": "^1.169.1", + "@tanstack/react-router": "^1.169.1", "@triniwiz/nativescript-image-cache-it": "^8.0.1", + "@types/react": "^19.0.0", + "react": "^19.0.0", + "react-reconciler": "^0.32.0", "babel-loader": "^9.1.3", "babel-preset-solid": "^1.8.19", "dominative": "^0.1.3", diff --git a/packages/tanstack-router/src/react/ErrorBoundary.tsx b/packages/tanstack-router/src/react/ErrorBoundary.tsx new file mode 100644 index 0000000..7a308fa --- /dev/null +++ b/packages/tanstack-router/src/react/ErrorBoundary.tsx @@ -0,0 +1,39 @@ +import { Component, createElement } from 'react'; +import type { ReactNode } from 'react'; + +interface RouteErrorBoundaryProps { + // Render fallback for a caught error. Returning null renders nothing (used to + // swallow expected backstack errors on hidden pages — see PageRenderer). + fallback: (error: unknown, reset: () => void) => ReactNode; + // Optional in the type so children can be passed as createElement's variadic + // args; always present at runtime. + children?: ReactNode; +} + +interface RouteErrorBoundaryState { + error: unknown; +} + +/** + * React analog of solid's `` for the per-page route tree. + * Backstack pages can briefly evaluate stale route hooks while hidden; the + * PageRenderer fallback swallows those expected errors by rendering null. + */ +export class RouteErrorBoundary extends Component { + state: RouteErrorBoundaryState = { error: null }; + + static getDerivedStateFromError(error: unknown): RouteErrorBoundaryState { + return { error }; + } + + reset = () => { + this.setState({ error: null }); + }; + + render() { + if (this.state.error != null) { + return this.props.fallback(this.state.error, this.reset); + } + return this.props.children; + } +} diff --git a/packages/tanstack-router/src/react/Link.tsx b/packages/tanstack-router/src/react/Link.tsx new file mode 100644 index 0000000..d4ee2d3 --- /dev/null +++ b/packages/tanstack-router/src/react/Link.tsx @@ -0,0 +1,168 @@ +import { createElement } from 'react'; +import type { ReactNode } from 'react'; +import { useRouter, useMatchRoute } from '@tanstack/react-router'; +import { resolveLinkTapAction, type LinkTapResult } from '../link-action'; +import { MODAL_SEARCH_PARAM_KEY, withSingleModalPath } from '../modal-state'; +import { closeModalFromRouterContext } from '../modal-controller'; + +// Loosely typed on purpose. TanStack's fully-generic `LinkOptions`/`RoutePaths` +// constraints depend on a single resolved `@tanstack/router-core` instance; in a +// dual-flavor (solid + react) package the type graphs collide, and the strong +// link typing buys little for a native tap-driven control. Navigation calls cast +// to `any` against the runtime router anyway. +export interface LinkProps { + to?: string; + params?: Record; + search?: Record | ((prev: unknown) => unknown); + hash?: string; + replace?: boolean; + state?: true | object | ((prev: unknown) => unknown); + back?: boolean; + closeModal?: boolean; + modalTo?: string; + fallbackTo?: string; + onTap?: () => LinkTapResult; + children?: ReactNode; + class?: string; + activeClass?: string; + inactiveClass?: string; + style?: string | Record; + [key: string]: any; +} + +type AnyLinkProps = LinkProps; + +function resolveNextState(prev: unknown, stateInput: AnyLinkProps['state']): unknown { + if (stateInput === undefined || stateInput === true) { + return prev; + } + + const next = typeof stateInput === 'function' ? (stateInput as (previous: unknown) => unknown)(prev) : stateInput; + + if (!next || typeof next !== 'object') { + return next; + } + + if (!prev || typeof prev !== 'object') { + return next; + } + + return { + ...(prev as Record), + ...(next as Record), + }; +} + +function resolveNavigateState(stateInput: AnyLinkProps['state']): true | ((prev: any) => any) | undefined { + if (stateInput === undefined) { + return undefined; + } + + if (stateInput === true) { + return true; + } + + return (prev: any) => resolveNextState(prev, stateInput); +} + +/** + * Native ``: renders a tap-driven `` that navigates the shared + * NativeScript router. Mirrors the Solid Link, but as a plain React component — + * the reconciler creates the `contentview` host node and wires `onTap` → the + * native `tap` gesture via the renderer's prop translation. + */ +export function Link(props: LinkProps) { + const router = useRouter() as any; + const matchRoute = useMatchRoute() as any; + + const isActive = props.to + ? !!matchRoute({ + to: props.to as any, + params: props.params as any, + fuzzy: false, + }) + : false; + + const handleTap = () => { + const action = resolveLinkTapAction({ + onTapResult: props.onTap?.(), + back: props.back, + closeModal: props.closeModal, + canGoBack: router.history.canGoBack(), + fallbackTo: props.fallbackTo, + to: props.to, + }); + + if (action.type === 'none') { + return; + } + + if (action.type === 'back') { + router.history.back(); + return; + } + + if (action.type === 'close_modal') { + if (closeModalFromRouterContext(router)) { + return; + } + + router.navigate({ + to: '.', + search: (prev: unknown) => withSingleModalPath(prev, null), + replace: props.replace ?? true, + } as any); + return; + } + + if (props.modalTo) { + const modalTo = props.modalTo; + router.navigate({ + to: (props.to || '.') as any, + params: props.params as any, + state: resolveNavigateState(props.state), + hash: props.hash as any, + replace: props.replace, + search: (prev: unknown) => { + const base = + typeof props.search === 'function' + ? (props.search as (old: unknown) => unknown)(prev) + : ({ + ...(prev as Record), + ...(props.search as Record | undefined), + } as unknown); + + return withSingleModalPath(base, modalTo, MODAL_SEARCH_PARAM_KEY); + }, + } as any); + return; + } + + if (typeof action.to !== 'string') { + return; + } + + router.navigate({ + to: action.to, + params: props.params as any, + state: resolveNavigateState(props.state), + search: props.search as any, + hash: props.hash as any, + replace: props.replace, + }); + }; + + const base = props.class || ''; + const active = isActive ? props.activeClass || '' : props.inactiveClass || ''; + const className = [base, active].filter(Boolean).join(' '); + + return createElement( + 'contentview', + { + class: className || undefined, + style: props.style, + onTap: handleTap, + }, + props.children, + ); +} diff --git a/packages/tanstack-router/src/react/NativeScriptRouterProvider.tsx b/packages/tanstack-router/src/react/NativeScriptRouterProvider.tsx new file mode 100644 index 0000000..fae6fc3 --- /dev/null +++ b/packages/tanstack-router/src/react/NativeScriptRouterProvider.tsx @@ -0,0 +1,317 @@ +import { createElement, useEffect, useRef } from 'react'; +import type { ReactNode } from 'react'; +import type { AnyRouter } from '@tanstack/react-router'; +import { renderPage } from './PageRenderer'; +import { setupBackHandler } from './back-handler'; +import { doesRouteIdMatchPathname, getHistoryIndex, getNativeScriptNavigationTransition, getNavigationKind, shouldSkipPathNavigation } from '../navigation-state'; +import { getNativeBackCallbackDecision } from '../native-back-sync'; +import { createDebugLogger } from '../debug-log'; +import { describeComponentShape, normalizeRenderableComponent } from '../component-shape'; +import { subscribeReactHmrRemount } from './react-hmr-remount'; +import type { NavigationGuard } from '../types'; + +const h = createElement; + +/** + * Context passed to {@link NativeScriptRouterProviderProps.actionBar} for the route + * whose Page is about to be created. + */ +export interface NativeScriptPageActionBarContext { + path: string; + routeId: string; + route: any; + staticData: Record; +} + +export interface NativeScriptRouterProviderProps { + router: AnyRouter; + actionBarVisibility?: 'auto' | 'never' | 'always'; + animated?: boolean; + transition?: { name?: string; duration?: number; curve?: any }; + debug?: boolean; + /** + * Optional per-page chrome — typically an `` — rendered into each + * route's native Page. Return a React element (e.g. an ``) for the + * matched route, or `null`/`undefined` for none. + */ + actionBar?: (ctx: NativeScriptPageActionBarContext) => ReactNode; +} + +/** + * Native router host. Renders a `` and drives `Frame.navigate()` from the + * shared NativeScript router's state. + * + * NOTE: This React port covers forward/replace/back navigation, native back-pop + * sync, and per-page chrome. The modal state machine and the queued-native-back + * drain from the Solid provider are intentionally deferred (not needed by the + * base template) — see `@nativescript/tanstack-router/solid` for the full version. + */ +export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProps) { + const router = props.router; + const frameRef = useRef(null); + + // Mutable navigation bookkeeping (persists across renders / the effect). + const stateRef = useRef({ + prevIndex: -1, + prevPathname: '', + suppressedNativeBackCallbacks: 0, + skipNextFrameBackNavigation: false, + nativeBackSyncInFlight: false, + nativeBackSyncFromPath: null as string | null, + }); + + // Shared guard preventing circular updates between router and Frame. + const guardRef = useRef({ isNavigating: false }); + + useEffect(() => { + const frame = frameRef.current; + if (!frame) { + console.error('[NSRouter] frame ref not set; cannot drive navigation'); + return; + } + + const log = createDebugLogger(props.debug); + const guard = guardRef.current; + const s = stateRef.current; + + // Ensure router stores are initialized (mirrors RouterContextProvider). + try { + router.update({ + ...router.options, + context: { ...router.options.context }, + }); + } catch {} + + // Synchronous startTransition — no Suspense/concurrent transition needed; we + // render Pages through Frame.navigate(), not a single mounted tree. + (router as any).startTransition = (fn: () => void) => { + fn(); + }; + + const releaseGuard = () => { + guard.isNavigating = false; + guard.lockReason = undefined; + if (guard.lockTimeoutId) { + clearTimeout(guard.lockTimeoutId); + guard.lockTimeoutId = undefined; + } + }; + + const acquireGuard = (reason: string) => { + guard.isNavigating = true; + guard.lockReason = reason; + if (guard.lockTimeoutId) clearTimeout(guard.lockTimeoutId); + // Failsafe: never let the navigation lock remain active indefinitely. + guard.lockTimeoutId = setTimeout(() => { + log('[NSRouter] force releasing stale guard:', guard.lockReason); + releaseGuard(); + }, 250) as any; + }; + + const runNativeBackSync = () => { + if (!router.history.canGoBack()) return; + s.nativeBackSyncInFlight = true; + s.nativeBackSyncFromPath = router.state.location.pathname; + // Native UI has already popped the page. Reflect it in router history + // without issuing a second Frame.goBack from the sync effect. + s.skipNextFrameBackNavigation = true; + acquireGuard('native_back_callback'); + log('[NSRouter] native back pop -> router.history.back()'); + router.history.back(); + }; + + // ── Drive the Frame from current router state (forward / replace / back) ── + const syncFrameToRouter = () => { + if (!frame) return; + const state = router.state; + const matches = state.matches; + if (!matches.length) return; + + // Release native-back sync lock once the router settles out of pending. + if (s.nativeBackSyncInFlight && (state.status !== 'pending' || (s.nativeBackSyncFromPath != null && state.location.pathname !== s.nativeBackSyncFromPath))) { + s.nativeBackSyncInFlight = false; + s.nativeBackSyncFromPath = null; + if (guard.lockReason === 'native_back_callback') { + log('[NSRouter] native back callback releasing guard'); + releaseGuard(); + } + } + + if (s.nativeBackSyncInFlight || guard.isNavigating) { + return; + } + + const curIndex = getHistoryIndex(router.history.location.state as any); + const curTransition = getNativeScriptNavigationTransition(router.history.location.state); + const curPathname = state.location.pathname; + const hasPathChanged = !shouldSkipPathNavigation(curPathname, s.prevPathname, s.prevIndex); + + if (!hasPathChanged) { + s.prevIndex = curIndex; + return; + } + + const navigationKind = getNavigationKind(s.prevIndex, curIndex); + const isBack = navigationKind === 'back'; + const isReplace = navigationKind === 'replace'; + + if (isBack) { + if (s.skipNextFrameBackNavigation) { + s.skipNextFrameBackNavigation = false; + log('[NSRouter] skipping Frame.goBack for native-originated back sync'); + s.prevIndex = curIndex; + s.prevPathname = curPathname; + return; + } + + acquireGuard('router_state_back'); + if (frame.canGoBack()) { + // Router-initiated goBack causes a native navigatingFrom(back) event. + // Suppress exactly one sync callback for this controlled pop. + s.suppressedNativeBackCallbacks += 1; + frame.goBack(); + } + s.prevIndex = curIndex; + s.prevPathname = curPathname; + setTimeout(releaseGuard, 0); + return; + } + + // Forward or replace navigation: resolve the leaf route -> component. + let leafMatch = matches[matches.length - 1]; + + if (!doesRouteIdMatchPathname(leafMatch.routeId, curPathname)) { + const routesById = (router as any).routesById || {}; + let resolvedRouteId: string | null = null; + for (const routeId of Object.keys(routesById)) { + if (routeId === '__root__') continue; + if (doesRouteIdMatchPathname(routeId, curPathname)) { + if (!resolvedRouteId || routeId.length > resolvedRouteId.length) { + resolvedRouteId = routeId; + } + } + } + if (resolvedRouteId) { + log('[NSRouter] match/path mismatch resolved:', leafMatch.routeId, '->', resolvedRouteId); + leafMatch = { ...leafMatch, routeId: resolvedRouteId }; + } else { + log('[NSRouter] deferring Frame navigation due to pending match/path mismatch:', leafMatch.routeId, curPathname); + return; + } + } + + const route = (router as any).routesById[leafMatch.routeId]; + const rawComponent = route?.options?.component; + const Component = normalizeRenderableComponent(rawComponent); + + if (!Component) { + console.error('[NSRouter] Invalid route component for route:', leafMatch.routeId, 'shape:', describeComponentShape(rawComponent)); + s.prevIndex = curIndex; + s.prevPathname = curPathname; + return; + } + + acquireGuard('router_state_forward_or_replace'); + + const pageChrome = props.actionBar + ? () => + props.actionBar!({ + path: curPathname, + routeId: leafMatch.routeId, + route, + staticData: route?.options?.staticData ?? {}, + }) + : undefined; + + log('[NSRouter] navigating Frame to', curPathname); + frame.navigate({ + create: () => + renderPage( + router, + Component as any, + curPathname, + (sourcePath: string) => { + if (s.suppressedNativeBackCallbacks > 0) { + s.suppressedNativeBackCallbacks -= 1; + log('[NSRouter] native back callback suppressed (router-initiated goBack)'); + return; + } + const decision = getNativeBackCallbackDecision({ + guardActive: guard.isNavigating, + canGoBack: router.history.canGoBack(), + }); + if (decision === 'ignore_guard_active') { + log('[NSRouter] native back callback ignored (guard active)'); + return; + } + if (decision === 'ignore_cannot_go_back') { + log('[NSRouter] native back callback ignored (cannot go back)'); + return; + } + runNativeBackSync(); + }, + (visiblePath: string) => { + // Visible-path change: keep prev-tracking aligned with what's on screen. + s.prevPathname = visiblePath; + }, + props.debug, + pageChrome, + ), + animated: s.prevIndex >= 0 ? (props.animated ?? true) : false, + transition: curTransition ?? props.transition, + backstackVisible: !isReplace, + clearHistory: false, + }); + + s.prevIndex = curIndex; + s.prevPathname = curPathname; + releaseGuard(); + }; + + // ── Wire it up ── + const unsubHistory = router.history.subscribe(() => { + log('[NSRouter] history.subscribe fired, pathname:', router.state.location.pathname); + const loadPromise = router.load(); + if (loadPromise && typeof loadPromise.then === 'function') { + loadPromise.then(() => syncFrameToRouter()).catch((err: any) => log('[NSRouter] history load error:', err?.message || err)); + } else { + syncFrameToRouter(); + } + }); + + const unsubResolved = router.subscribe('onResolved' as any, () => syncFrameToRouter()); + const unsubBeforeMount = router.subscribe('onBeforeRouteMount' as any, () => syncFrameToRouter()); + + const cleanupBack = setupBackHandler(router, () => frame, guard); + + // HMR: when a route file changes, re-import it and remount the matching Page + // in place (no Frame.navigate, so the user keeps their place). Shell/non-route + // edits are handled by the app-runtime's re-import. No-op in production. + const cleanupHmr = subscribeReactHmrRemount({ router, getFrame: () => frame, log }); + + // Initial load -> render the initial route's Page. + Promise.resolve(router.load()) + .then(() => { + log('[NSRouter] initial load resolved. status:', router.state.status, 'matches:', router.state.matches.length); + syncFrameToRouter(); + }) + .catch((err: any) => console.error('[NSRouter] initial load rejected:', err)); + + return () => { + unsubHistory(); + unsubResolved(); + unsubBeforeMount(); + cleanupBack(); + cleanupHmr(); + if (guard.lockTimeoutId) clearTimeout(guard.lockTimeoutId); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + return h('frame', { + ref: (el: any) => { + frameRef.current = el; + }, + actionBarVisibility: props.actionBarVisibility || 'never', + }); +} diff --git a/packages/tanstack-router/src/react/PageRenderer.tsx b/packages/tanstack-router/src/react/PageRenderer.tsx new file mode 100644 index 0000000..4f2a1de --- /dev/null +++ b/packages/tanstack-router/src/react/PageRenderer.tsx @@ -0,0 +1,209 @@ +import { createElement } from 'react'; +import type { ComponentType, ReactNode } from 'react'; +import { render } from '@nativescript-community/react'; +import { RouterContextProvider, type AnyRouter } from '@tanstack/react-router'; +import { resetNativeBackSyncScheduled, shouldScheduleNativeBackSync } from '../native-back-sync'; +import { createDebugLogger } from '../debug-log'; +import { describeComponentShape, normalizeRenderableComponent } from '../component-shape'; +import { shouldUnmountPageOnNavigatingFrom } from '../page-lifecycle'; +import { NavigatedData } from '@nativescript/core'; +import { RouteErrorBoundary } from './ErrorBoundary'; + +const h = createElement; + +function getErrorMessage(err: unknown): string { + if (err instanceof Error) { + return err.message; + } + return String(err); +} + +function isExpectedBackstackError(message: string): boolean { + return message.includes('Cannot read properties of undefined') || message.includes('Could not find an active match'); +} + +export function renderPage( + router: AnyRouter, + RouteComponent: ComponentType, + routePath: string, + onNativeBack?: (sourcePath: string) => void, + onVisiblePathChange?: (visiblePath: string) => void, + debug?: boolean, + // Optional per-page chrome thunk (e.g. an ). Returns a React element + // that's rendered as a sibling of the route content; dominative's Page routes an + // ActionBar child into `page.actionBar` and the route root into `page.content`. + chrome?: () => ReactNode, +): any { + const page = document.createElement('Page') as any; + const log = createDebugLogger(debug); + + let resetErrorBoundary: (() => void) | undefined; + const loggedUnexpectedErrors = new Set(); + let dispose: (() => void) | undefined; + let nativeBackSyncScheduled = false; + // Track the current route component reference. HMR remount swaps this so a + // freshly-imported route module's exported component takes effect on + // subsequent mounts without the consumer needing to re-call renderPage. + let currentRouteComponent: ComponentType = RouteComponent; + + const getPagePath = () => (page as any).__nsRouterPath || routePath; + + // Reset error boundary when Page comes back from backstack. + page.on('loaded', () => { + if (resetErrorBoundary) { + resetErrorBoundary(); + resetErrorBoundary = undefined; + } + }); + + // Keep a stable path tag on the page for native navigation reconciliation. + (page as any).__nsRouterPath = routePath; + + const mount = () => { + if (dispose) return; + + if (typeof RouterContextProvider !== 'function') { + console.error('[NSRouter] Invalid RouterContextProvider export:', describeComponentShape(RouterContextProvider)); + return; + } + + const SafeRouteView = () => { + const Comp = normalizeRenderableComponent(currentRouteComponent); + if (!Comp) { + console.error('[NSRouter] Invalid render component for route path:', routePath, 'shape:', describeComponentShape(currentRouteComponent)); + return null; + } + try { + return h(Comp as ComponentType); + } catch (err) { + console.error('[NSRouter] Route component invocation failed for path:', routePath, 'shape:', describeComponentShape(currentRouteComponent), err); + return null; + } + }; + + const tree = h( + RouterContextProvider as any, + { router }, + // Per-page chrome (e.g. ) — dominative routes it to page.actionBar. + chrome ? chrome() : null, + h( + RouteErrorBoundary, + { + fallback: (err: unknown, reset: () => void) => { + const message = getErrorMessage(err); + // Backstack pages can briefly evaluate stale route hooks while hidden. + // This is expected and intentionally swallowed by rendering nothing. + if (!isExpectedBackstackError(message) && !loggedUnexpectedErrors.has(message)) { + loggedUnexpectedErrors.add(message); + console.error('[NSRouter] ErrorBoundary caught:', err); + } + resetErrorBoundary = reset; + return null; + }, + }, + h(SafeRouteView), + ), + ); + + dispose = render(tree, page); + log('[NSRouter] page mount:', (page as any).__nsRouterPath || routePath); + }; + + const unmount = () => { + if (dispose) { + dispose(); + dispose = undefined; + log('[NSRouter] page unmount:', (page as any).__nsRouterPath || routePath); + } + }; + + // Detach every child currently attached to the Page. `dispose()` tears down the + // React tree but a naive unmount+mount could leave the old subtree attached and + // the new one appended alongside it; a NativeScript Page shows only one root + // content view, so clear the slots before re-mounting. Used only on explicit + // remount paths (HMR), never during routine navigation. + const clearPageChildren = () => { + try { + let child: any = (page as any).firstChild; + while (child) { + const next = child.nextSibling; + try { + (page as any).removeChild?.(child); + } catch (err) { + log('[NSRouter] removeChild failed during remount clear:', err); + } + child = next; + } + try { + (page as any).actionBar = null; + } catch {} + try { + (page as any).content = null; + } catch {} + } catch (err) { + log('[NSRouter] clearPageChildren failed:', err); + } + }; + + // Expose a remount API so HMR-aware code can swap in a freshly-imported route + // component without going through frame.navigate() (which would push history). + (page as any).__ns_remount = (nextComponent?: ComponentType) => { + if (typeof nextComponent === 'function') { + currentRouteComponent = nextComponent; + } + unmount(); + clearPageChildren(); + mount(); + log('[NSRouter] page remount:', (page as any).__nsRouterPath || routePath); + }; + + // Mount immediately for the page being navigated to. + mount(); + + // Re-mount when this page becomes visible again after back navigation. + page.on('navigatedTo', () => { + nativeBackSyncScheduled = resetNativeBackSyncScheduled(); + onVisiblePathChange?.(getPagePath()); + // Deterministic lifecycle: once a Page is visible it must have an active view + // tree regardless of router pending/transient state. + mount(); + log('[NSRouter] page navigatedTo:', getPagePath()); + }); + + // Sync router when this page is popped by native UI back controls + // (iOS ActionBar/UINavigationController back, swipe-back, Android native pop). + page.on('navigatingFrom', (args: NavigatedData) => { + const isBack = !!args?.isBackNavigation; + + if (shouldUnmountPageOnNavigatingFrom(args)) { + unmount(); + } + + if ( + shouldScheduleNativeBackSync({ + isBackNavigation: isBack, + alreadyScheduled: nativeBackSyncScheduled, + }) + ) { + nativeBackSyncScheduled = true; + log('[NSRouter] schedule native back sync from:', getPagePath()); + setTimeout(() => { + const sourcePath = getPagePath(); + log('[NSRouter] run native back sync from:', sourcePath); + onNativeBack?.(sourcePath); + }, 0); + } else if (isBack) { + log('[NSRouter] native back sync already scheduled for:', getPagePath()); + } + + log('[NSRouter] page navigatingFrom:', getPagePath(), 'isBack:', isBack); + }); + + // Clean up the React tree when the native Page is destroyed. + page.on('disposeNativeView', () => { + nativeBackSyncScheduled = resetNativeBackSyncScheduled(); + unmount(); + }); + + return page; +} diff --git a/packages/tanstack-router/src/react/back-handler.ts b/packages/tanstack-router/src/react/back-handler.ts new file mode 100644 index 0000000..9a6f5a2 --- /dev/null +++ b/packages/tanstack-router/src/react/back-handler.ts @@ -0,0 +1,26 @@ +import { Application, isAndroid } from '@nativescript/core'; +import type { AnyRouter } from '@tanstack/react-router'; +import type { NavigationGuard } from '../types'; + +export function setupBackHandler(router: AnyRouter, _getFrame: () => any, _guard: NavigationGuard): () => void { + const cleanups: Array<() => void> = []; + + if (isAndroid) { + const handler = (args: any) => { + if (router.history.canGoBack()) { + args.cancel = true; + router.history.back(); + } + }; + Application.android?.on('activityBackPressed', handler); + cleanups.push(() => { + Application.android?.off('activityBackPressed', handler); + }); + } + + // iOS/native page-pop sync is handled by PageRenderer's per-page navigatedTo(isBackNavigation) callback. + + return () => { + cleanups.forEach((fn) => fn()); + }; +} diff --git a/packages/tanstack-router/src/react/index.ts b/packages/tanstack-router/src/react/index.ts new file mode 100644 index 0000000..0019c5f --- /dev/null +++ b/packages/tanstack-router/src/react/index.ts @@ -0,0 +1,25 @@ +// React entrypoint for @nativescript/tanstack-router + +// === NativeScript-specific exports === +export { createNativeScriptHistory } from '../history'; +export { createNativeScriptRouter } from './router'; +export { NativeScriptRouterProvider } from './NativeScriptRouterProvider'; +export type { NativeScriptRouterProviderProps, NativeScriptPageActionBarContext } from './NativeScriptRouterProvider'; +export { Link } from './Link'; +export type { Register, RegisteredRouter } from '../register'; +export { createNativeScriptNavigationState, createNativeScriptTransitionState } from '../transition-state'; +export { MODAL_SEARCH_PARAM_KEY, withSingleModalPath } from '../modal-state'; +export type { NativeScriptNavigationOptions, NativeScriptNavigationState, NativeScriptNavigationTransition, NativeScriptModalDetent, NativeScriptModalIOSPresentationOptions, NativeScriptModalPresentationOptions, NativeScriptModalOptionsResolver, NativeScriptModalOptionsResolverContext } from '../types'; + +// === Re-exports from @tanstack/react-router === +// Route definition +export { createRootRoute, createRootRouteWithContext, createRoute, createFileRoute, createLazyRoute, rootRouteId, RouteApi, getRouteApi } from '@tanstack/react-router'; + +// Router creation (for users who want full control over history) +export { createRouter } from '@tanstack/react-router'; + +// Hooks +export { useRouter, useRouterState, useNavigate, useMatch, useMatches, useParentMatches, useChildMatches, useParams, useSearch, useLoaderData, useLoaderDeps, useLocation, useRouteContext, useMatchRoute, useBlocker, useCanGoBack } from '@tanstack/react-router'; + +// Components (that work in NativeScript context) +export { Navigate, MatchRoute, Await } from '@tanstack/react-router'; diff --git a/packages/tanstack-router/src/react/react-hmr-remount.ts b/packages/tanstack-router/src/react/react-hmr-remount.ts new file mode 100644 index 0000000..9c5c2fc --- /dev/null +++ b/packages/tanstack-router/src/react/react-hmr-remount.ts @@ -0,0 +1,235 @@ +import type { AnyRouter } from '@tanstack/react-router'; +import { normalizeRenderableComponent } from '../component-shape'; + +// React HMR per-page remount for NativeScript. +// +// React has no Fast Refresh / global component patching (unlike solid-refresh). +// So when a route file changes we must RE-IMPORT it ourselves, read the fresh +// `Route.options.component`, patch it onto the live router, and remount the +// matching Page(s) in place — no Frame.navigate (so no backstack churn / native +// transition, and the user keeps their place). +// +// Shell / non-route edits are handled by the app-runtime (`startReactApp`), which +// re-imports the app entry and re-renders the whole tree; this module deliberately +// ignores them. + +export interface ReactHmrRemountOptions { + router: AnyRouter; + getFrame: () => any; + log: (...args: any[]) => void; +} + +type NsHmrUpdatePayload = { type?: string; version?: number; changedIds?: string[]; raw?: any }; + +const ROUTE_FILE_RE = /\/routes\/.+\.(?:tsx|jsx)$/i; +// `__root` is a layout route with no page component, and on device the web root +// (which `import`s app CSS) isn't a loadable ESM — exclude it from remount. +const ROOT_FILE_RE = /(^|[\\/])__root\.[a-z0-9]+$/i; + +// `/src/routes/posts.$postId.tsx` → TanStack `fullPath` `/posts/$postId`. +function boundaryToFullPath(bid: string): string | null { + const m = bid.match(/\/routes\/(.+)\.(?:tsx|jsx|ts|js)$/i); + if (!m) return null; + let p = m[1]; + p = p.replace(/\./g, '/'); + if (p === 'index') return '/'; + if (p.endsWith('/index')) p = p.slice(0, -6); + p = p.replace(/(^|\/)-([\w])/g, '$1$2'); + return '/' + p; +} + +// The root route (`__root__`) shares fullPath '/' with the index route; prefer the +// non-root (leaf) match so an `index.tsx` edit patches the page, not the layout. +function findRouteByFullPath(router: any, fullPath: string): any | null { + const byId = router?.routesById; + if (!byId) return null; + let rootMatch: any | null = null; + for (const rid of Object.keys(byId)) { + const r = byId[rid]; + if (r?.fullPath !== fullPath) continue; + if (rid === '__root__') { + rootMatch = rootMatch || r; + continue; + } + return r; + } + return rootMatch; +} + +// Every Page currently held by the Frame (currentPage + backStack). The backStack +// shape varies across @nativescript/core versions, so probe defensively. +function collectFramePages(frame: any): any[] { + if (!frame) return []; + const pages: any[] = []; + if (frame.currentPage) pages.push(frame.currentPage); + const backStack = (frame as any).backStack; + if (Array.isArray(backStack)) { + for (const item of backStack) { + if (!item) continue; + if (item.tagName === 'page' || item.constructor?.name?.toLowerCase().includes('page')) { + pages.push(item); + } else if (item.entry?.resolvedPage) { + pages.push(item.entry.resolvedPage); + } else if (item.resolvedPage) { + pages.push(item.resolvedPage); + } + } + } + return pages; +} + +function remountPage(page: any, nextComponent: any, log: (...a: any[]) => void): boolean { + if (!page || typeof page.__ns_remount !== 'function') return false; + try { + page.__ns_remount(nextComponent); + log('[NSRouter][hmr] remounted page', page.__nsRouterPath || '(unknown path)'); + return true; + } catch (err) { + log('[NSRouter][hmr] remount failed', err); + return false; + } +} + +// Dev-server HTTP origin used to fetch app modules over the wire (mirrors the +// solid app-runtime's resolver). +function resolveOrigin(): string { + try { + const m = String(import.meta.url).match(/^https?:\/\/[^/]+/); + if (m) return m[0]; + } catch {} + const g = globalThis as any; + if (typeof g.__NS_HTTP_ORIGIN__ === 'string' && /^https?:\/\//.test(g.__NS_HTTP_ORIGIN__)) return g.__NS_HTTP_ORIGIN__; + if (typeof g.__NS_HMR_WS_URL__ === 'string') { + const m = String(g.__NS_HMR_WS_URL__).match(/^wss?:\/\/([^/]+)/); + if (m) return 'http://' + m[1]; + } + return ''; +} + +const SCRIPT_EXT = /\.(?:tsx|ts|jsx|js|mjs)$/i; + +// Monotonic per-save counter for cache-bust tags (see reimportRouteModule). +let importNonce = 0; + +// Re-import a changed route file fresh (evicting its cached module first so any +// changed in-graph dependency is re-evaluated too), returning its module +// namespace (with the freshly-built `Route`). Returns null if it can't load. +async function reimportRouteModule(origin: string, changedIds: string[], fileId: string): Promise { + const spec = fileId.startsWith('/') ? fileId : '/' + fileId; + const canonical = spec.replace(SCRIPT_EXT, ''); + // Cache-bust exactly as the proven solid app-runtime does (its + // `installHmrRemount`), since both target the SAME native runtime: + // 1. EVICT every URL form the module may be cached under (ext-less canonical, + // the original spec, and each script-extension variant) via + // `__nsInvalidateModules`, so V8 drops it from the module registry. + // 2. RE-IMPORT through a `__ns_hmr__//…?t=` URL whose tag is + // `Date.now()_` — UNIQUE PER SAVE. This is the crux: a repeated + // tag hits the dev server's per-URL transform cache and serves the + // PREVIOUS save's output ("one edit behind"); a unique tag forces a fresh + // transform AND (after the runtime canonicalizes the tag away to the + // evicted canonical) a fresh V8 evaluation. + const evict = new Set(); + for (const raw of [spec, ...changedIds]) { + if (!raw) continue; + let s = String(raw).split('?')[0]; + if (!s.startsWith('/')) s = '/' + s; + if (/(^|\/)node_modules\//.test(s)) continue; + const c = s.replace(SCRIPT_EXT, ''); + evict.add(origin + '/ns/m' + c); + if (s !== c) evict.add(origin + '/ns/m' + s); + for (const ext of ['.tsx', '.ts', '.jsx', '.js']) evict.add(origin + '/ns/m' + c + ext); + } + const g = globalThis as any; + const invalidate = g.__nsInvalidateModules; + if (typeof invalidate === 'function') { + try { + invalidate(Array.from(evict)); + } catch {} + } + const t = `${Date.now()}_${++importNonce}`; + const candidates = [`${origin}/ns/m/__ns_hmr__/r-${t}${canonical}?t=${t}`, `${origin}/ns/m${canonical}?t=${t}`, `${origin}/ns/m${spec}?t=${t}`]; + for (const url of candidates) { + try { + const mod: any = await import(/* @vite-ignore */ url); + if (mod && mod.Route) return mod; + } catch (err) { + // try next candidate + } + } + return null; +} + +/** + * Subscribe to the NS HMR client's app-level update hook and remount route Pages + * in place when their files change. Returns an unsubscribe function. + * + * Wraps `globalThis.__NS_HMR_ON_UPDATE__` (the framework-agnostic hook the HMR + * client invokes after each applied batch — see `@nativescript/vite`'s + * `hmr/shared/runtime/hooks`), preserving any previously-installed hook. + */ +export function subscribeReactHmrRemount(opts: ReactHmrRemountOptions): () => void { + const { router, getFrame, log } = opts; + const g = globalThis as any; + + let running = false; + const onUpdate = async (payload: NsHmrUpdatePayload) => { + if (running) return; + const changed = (payload?.changedIds || []).filter((id) => typeof id === 'string'); + const routeFiles = changed.filter((id) => ROUTE_FILE_RE.test(id) && !ROOT_FILE_RE.test(id)); + if (!routeFiles.length) { + log('[NSRouter][hmr] no route-file changes; leaving to app-runtime'); + return; + } + const origin = resolveOrigin(); + if (!origin) { + log('[NSRouter][hmr] no HTTP origin; cannot re-import route module'); + return; + } + running = true; + try { + const frame = getFrame(); + for (const fileId of routeFiles) { + // Per-route isolation: one route's re-import failure must not abort the rest. + try { + const fullPath = boundaryToFullPath(fileId); + if (!fullPath) continue; + const mod = await reimportRouteModule(origin, changed, fileId); + const nextComponent = normalizeRenderableComponent(mod?.Route?.options?.component); + if (!nextComponent) { + log('[NSRouter][hmr] re-import yielded no component for', fileId); + continue; + } + // Patch the live router so future navigations use the fresh component. + const route = findRouteByFullPath(router, fullPath); + if (route?.options) route.options.component = nextComponent; + // Remount any visible/backstack Page on that route in place. + let remounted = 0; + for (const page of collectFramePages(frame)) { + if (page?.__nsRouterPath === fullPath && remountPage(page, nextComponent, log)) remounted++; + } + log('[NSRouter][hmr] route updated', fullPath, 'remounted=', remounted); + } catch (err) { + log('[NSRouter][hmr] route remount failed for', fileId, err); + } + } + } catch (err) { + log('[NSRouter][hmr] update handler failed', err); + } finally { + running = false; + } + }; + + const prev = g.__NS_HMR_ON_UPDATE__; + const hook = (payload: NsHmrUpdatePayload) => { + try { + if (typeof prev === 'function') prev(payload); + } catch {} + void onUpdate(payload); + }; + g.__NS_HMR_ON_UPDATE__ = hook; + log('[NSRouter][hmr] react HMR remount subscribed'); + + return () => { + if (g.__NS_HMR_ON_UPDATE__ === hook) g.__NS_HMR_ON_UPDATE__ = prev; + }; +} diff --git a/packages/tanstack-router/src/react/router.ts b/packages/tanstack-router/src/react/router.ts new file mode 100644 index 0000000..4f18c4f --- /dev/null +++ b/packages/tanstack-router/src/react/router.ts @@ -0,0 +1,34 @@ +import { createRouter, type AnyRoute } from '@tanstack/react-router'; +import { AbortController as NativeScriptAbortController, AbortSignal as NativeScriptAbortSignal } from '@nativescript/core/abortcontroller'; +import { createNativeScriptHistory } from '../history'; + +// NativeScript polyfills — TanStack Router requires these globals. +// Runs at module load time, after imports resolve but before any router is created. +if (typeof self === 'undefined') { + (globalThis as any).self = globalThis; +} +if (typeof AbortController === 'undefined') { + (globalThis as any).AbortController = NativeScriptAbortController; + (globalThis as any).AbortSignal = NativeScriptAbortSignal; +} + +type RouterOptions = Parameters>[0]; + +export function createNativeScriptRouter( + opts: Omit, 'history'> & { + initialPath?: string; + }, +) { + const { initialPath, ...routerOpts } = opts; + const router = createRouter({ + ...(routerOpts as RouterOptions), + history: createNativeScriptHistory({ initialPath }), + }); + // Dev-only: expose router for HMR client to patch route loaders + // when non-component utility modules change (standard pattern: + // React uses __REACT_DEVTOOLS_GLOBAL_HOOK__, Vue uses __VUE_HMR_RUNTIME__). + try { + (globalThis as any).__ns_router = router; + } catch {} + return router; +} diff --git a/packages/tanstack-router/tsup.config.ts b/packages/tanstack-router/tsup.config.ts index 1ddc57c..dbc761f 100644 --- a/packages/tanstack-router/tsup.config.ts +++ b/packages/tanstack-router/tsup.config.ts @@ -4,6 +4,7 @@ export default defineConfig({ entry: { index: 'packages/tanstack-router/src/index.ts', 'solid/index': 'packages/tanstack-router/src/solid/index.ts', + 'react/index': 'packages/tanstack-router/src/react/index.ts', }, format: ['esm', 'cjs'], dts: true, @@ -12,7 +13,7 @@ export default defineConfig({ clean: false, target: 'es2018', outDir: 'dist/packages/tanstack-router', - external: ['@tanstack/solid-router', '@tanstack/history', '@nativescript/core', '@nativescript/core/abortcontroller', '@nativescript-community/solid-js', 'solid-js', 'solid-js/web', 'solid-js/jsx-runtime'], + external: ['@tanstack/solid-router', '@tanstack/react-router', '@tanstack/history', '@nativescript/core', '@nativescript/core/abortcontroller', '@nativescript-community/solid-js', '@nativescript-community/react', 'solid-js', 'solid-js/web', 'solid-js/jsx-runtime', 'react', 'react-dom', 'react/jsx-runtime', 'react-reconciler'], esbuildOptions(options) { options.jsx = 'automatic'; options.jsxImportSource = 'solid-js'; From fc40d7b201fd58429e7056320495da61251bd89c Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Mon, 22 Jun 2026 18:09:26 -0700 Subject: [PATCH 5/9] release: 0.1.5 --- packages/tanstack-router/package.json | 33 +++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/packages/tanstack-router/package.json b/packages/tanstack-router/package.json index 92eeb7c..5d11a74 100644 --- a/packages/tanstack-router/package.json +++ b/packages/tanstack-router/package.json @@ -1,6 +1,6 @@ { "name": "@nativescript/tanstack-router", - "version": "0.1.2", + "version": "0.1.5", "description": "TanStack Router for NativeScript", "main": "index.cjs", "types": "index.d.ts", @@ -9,6 +9,7 @@ "index.mjs", "index.d.ts", "solid", + "react", "nativescript.vite.mjs", "nativescript.webpack.js", "solid-web-shim.js", @@ -29,6 +30,12 @@ "require": "./solid/index.cjs", "default": "./solid/index.mjs" }, + "./react": { + "types": "./react/index.d.ts", + "import": "./react/index.mjs", + "require": "./react/index.cjs", + "default": "./react/index.mjs" + }, "./package.json": "./package.json" }, "nativescript": { @@ -70,16 +77,34 @@ "dependencies": { "@tanstack/router-plugin": "~1.167.0", "@tanstack/history": "~1.161.0", - "@tanstack/solid-router": "~1.169.0" + "@tanstack/solid-router": "~1.169.0", + "@tanstack/react-router": "~1.169.0" }, "peerDependencies": { "@nativescript-community/solid-js": ">=0.1.0", + "@nativescript-community/react": ">=0.1.0", "@nativescript/core": ">=9.0.0", - "solid-js": ">=1.9.0" + "solid-js": ">=1.9.0", + "react": ">=19.0.0" + }, + "peerDependenciesMeta": { + "@nativescript-community/solid-js": { + "optional": true + }, + "@nativescript-community/react": { + "optional": true + }, + "solid-js": { + "optional": true + }, + "react": { + "optional": true + } }, "devDependencies": { "tsup": "^8.3.5", "typescript": "~5.9.0", - "vitest": "^4.1.5" + "vitest": "^4.1.5", + "@types/react": "^19.0.0" } } From 842fec3fc282209569aa9bc6c926ca6e5213a0dc Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Mon, 22 Jun 2026 20:10:01 -0700 Subject: [PATCH 6/9] fix: react hmr remount --- .../tanstack-router/src/react/react-hmr-remount.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/tanstack-router/src/react/react-hmr-remount.ts b/packages/tanstack-router/src/react/react-hmr-remount.ts index 9c5c2fc..a601093 100644 --- a/packages/tanstack-router/src/react/react-hmr-remount.ts +++ b/packages/tanstack-router/src/react/react-hmr-remount.ts @@ -174,6 +174,17 @@ export function subscribeReactHmrRemount(opts: ReactHmrRemountOptions): () => vo let running = false; const onUpdate = async (payload: NsHmrUpdatePayload) => { if (running) return; + // Only react to DELTA updates (actual file edits). The HMR client also fires + // this hook with `type: 'full-graph'` on boot and on reconnect/resync, where + // `changedIds` lists EVERY module in the graph — including all route files. + // Treating that as "every route changed" would remount the just-mounted page + // on boot, churning its s; the native bar buttons hold only a + // WeakRef to each item, so the originals get GC'd and taps silently no-op. + // Real edits always arrive as 'delta', so restrict to that. + if (payload?.type && payload.type !== 'delta') { + log('[NSRouter][hmr] ignoring non-delta update', payload.type); + return; + } const changed = (payload?.changedIds || []).filter((id) => typeof id === 'string'); const routeFiles = changed.filter((id) => ROUTE_FILE_RE.test(id) && !ROOT_FILE_RE.test(id)); if (!routeFiles.length) { From 1f3534ef74089878837dcf2cebbc7625d9840ffd Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Mon, 22 Jun 2026 20:10:42 -0700 Subject: [PATCH 7/9] release: 0.1.6 --- packages/tanstack-router/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/tanstack-router/package.json b/packages/tanstack-router/package.json index 5d11a74..d4f69b0 100644 --- a/packages/tanstack-router/package.json +++ b/packages/tanstack-router/package.json @@ -1,6 +1,6 @@ { "name": "@nativescript/tanstack-router", - "version": "0.1.5", + "version": "0.1.6", "description": "TanStack Router for NativeScript", "main": "index.cjs", "types": "index.d.ts", From cb5159d8629f7dbb12ca70764947612efcfa9631 Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Mon, 22 Jun 2026 22:13:58 -0700 Subject: [PATCH 8/9] chore: clearify comment for reach hmr remount --- .../src/react/react-hmr-remount.ts | 47 ++++++++++--------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/packages/tanstack-router/src/react/react-hmr-remount.ts b/packages/tanstack-router/src/react/react-hmr-remount.ts index a601093..b016a7c 100644 --- a/packages/tanstack-router/src/react/react-hmr-remount.ts +++ b/packages/tanstack-router/src/react/react-hmr-remount.ts @@ -12,6 +12,14 @@ import { normalizeRenderableComponent } from '../component-shape'; // Shell / non-route edits are handled by the app-runtime (`startReactApp`), which // re-imports the app entry and re-renders the whole tree; this module deliberately // ignores them. +// +// This works in-place (no restart) PROVIDED the dev server purges its transform +// caches BEFORE broadcasting the delta — otherwise the client's re-import here races +// the server and re-fetches the previous save's transform ("one save behind"). That +// server-side contract lives in `@nativescript/vite`'s react server strategy +// (`deferDeltaBroadcast: true` + a cache-purging `handleHotUpdate`, mirroring Solid). +// Without it the device returns the BOOT-evaluated module on re-import; with it the +// re-import evaluates fresh. The runtime itself re-evaluates fine on eviction. export interface ReactHmrRemountOptions { router: AnyRouter; @@ -111,23 +119,17 @@ const SCRIPT_EXT = /\.(?:tsx|ts|jsx|js|mjs)$/i; // Monotonic per-save counter for cache-bust tags (see reimportRouteModule). let importNonce = 0; -// Re-import a changed route file fresh (evicting its cached module first so any -// changed in-graph dependency is re-evaluated too), returning its module -// namespace (with the freshly-built `Route`). Returns null if it can't load. +// Re-import a changed route file and return its module namespace (with the freshly +// built `Route`). Returns null if it can't load. +// +// Evicts the route's cached module via `__nsInvalidateModules` then re-imports it +// through a unique `__ns_hmr__//…?t=` URL (the tag is `Date.now()_`, +// unique per save). On runtimes that honour the eviction this yields fresh code; see +// the file header for the known NS 9.1.0-alpha limitation where re-evaluation is not +// guaranteed. async function reimportRouteModule(origin: string, changedIds: string[], fileId: string): Promise { const spec = fileId.startsWith('/') ? fileId : '/' + fileId; const canonical = spec.replace(SCRIPT_EXT, ''); - // Cache-bust exactly as the proven solid app-runtime does (its - // `installHmrRemount`), since both target the SAME native runtime: - // 1. EVICT every URL form the module may be cached under (ext-less canonical, - // the original spec, and each script-extension variant) via - // `__nsInvalidateModules`, so V8 drops it from the module registry. - // 2. RE-IMPORT through a `__ns_hmr__//…?t=` URL whose tag is - // `Date.now()_` — UNIQUE PER SAVE. This is the crux: a repeated - // tag hits the dev server's per-URL transform cache and serves the - // PREVIOUS save's output ("one edit behind"); a unique tag forces a fresh - // transform AND (after the runtime canonicalizes the tag away to the - // evicted canonical) a fresh V8 evaluation. const evict = new Set(); for (const raw of [spec, ...changedIds]) { if (!raw) continue; @@ -139,8 +141,7 @@ async function reimportRouteModule(origin: string, changedIds: string[], fileId: if (s !== c) evict.add(origin + '/ns/m' + s); for (const ext of ['.tsx', '.ts', '.jsx', '.js']) evict.add(origin + '/ns/m' + c + ext); } - const g = globalThis as any; - const invalidate = g.__nsInvalidateModules; + const invalidate = (globalThis as any).__nsInvalidateModules; if (typeof invalidate === 'function') { try { invalidate(Array.from(evict)); @@ -174,13 +175,13 @@ export function subscribeReactHmrRemount(opts: ReactHmrRemountOptions): () => vo let running = false; const onUpdate = async (payload: NsHmrUpdatePayload) => { if (running) return; - // Only react to DELTA updates (actual file edits). The HMR client also fires - // this hook with `type: 'full-graph'` on boot and on reconnect/resync, where - // `changedIds` lists EVERY module in the graph — including all route files. - // Treating that as "every route changed" would remount the just-mounted page - // on boot, churning its s; the native bar buttons hold only a - // WeakRef to each item, so the originals get GC'd and taps silently no-op. - // Real edits always arrive as 'delta', so restrict to that. + // Only act on DELTA updates (real file edits). The HMR client also fires this + // hook with `type: 'full-graph'` on boot and on reconnect/resync, where + // `changedIds` lists EVERY module (incl. all route files). Treating that as + // "every route changed" would remount the just-mounted page on boot, churning + // its s; the native bar buttons hold only a WeakRef to each item, so + // the originals get GC'd and taps silently no-op. Real edits always arrive as + // 'delta', so restrict to that. if (payload?.type && payload.type !== 'delta') { log('[NSRouter][hmr] ignoring non-delta update', payload.type); return; From eb0fb3f9e042ee037d4f63b406afd9e9c014b1d0 Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Tue, 23 Jun 2026 19:41:17 -0700 Subject: [PATCH 9/9] release: 0.1.7 --- packages/tanstack-router/package.json | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/packages/tanstack-router/package.json b/packages/tanstack-router/package.json index d4f69b0..1a1feea 100644 --- a/packages/tanstack-router/package.json +++ b/packages/tanstack-router/package.json @@ -1,6 +1,6 @@ { "name": "@nativescript/tanstack-router", - "version": "0.1.6", + "version": "0.1.7", "description": "TanStack Router for NativeScript", "main": "index.cjs", "types": "index.d.ts", @@ -75,17 +75,17 @@ "homepage": "https://github.com/NativeScript/tanstack", "readmeFilename": "README.md", "dependencies": { - "@tanstack/router-plugin": "~1.167.0", - "@tanstack/history": "~1.161.0", - "@tanstack/solid-router": "~1.169.0", - "@tanstack/react-router": "~1.169.0" + "@tanstack/router-plugin": "~1.167.0" }, "peerDependencies": { "@nativescript-community/solid-js": ">=0.1.0", "@nativescript-community/react": ">=0.1.0", "@nativescript/core": ">=9.0.0", "solid-js": ">=1.9.0", - "react": ">=19.0.0" + "react": ">=19.0.0", + "@tanstack/solid-router": ">=1.169.0", + "@tanstack/react-router": ">=1.169.0", + "@tanstack/history": ">=1.161.0" }, "peerDependenciesMeta": { "@nativescript-community/solid-js": { @@ -99,12 +99,22 @@ }, "react": { "optional": true + }, + "@tanstack/solid-router": { + "optional": true + }, + "@tanstack/react-router": { + "optional": true } }, "devDependencies": { "tsup": "^8.3.5", "typescript": "~5.9.0", "vitest": "^4.1.5", - "@types/react": "^19.0.0" + "@types/react": "^19.0.0", + "@tanstack/solid-router": "~1.169.0", + "@tanstack/react-router": "~1.169.0", + "@tanstack/history": "~1.161.0", + "@tanstack/router-core": "~1.169.0" } }