diff --git a/packages/tanstack-router/CHANGELOG.md b/packages/tanstack-router/CHANGELOG.md index 2fcf6d1..a2daec7 100644 --- a/packages/tanstack-router/CHANGELOG.md +++ b/packages/tanstack-router/CHANGELOG.md @@ -1,3 +1,14 @@ +## 0.2.2 (2026-11-24) + +### 🩹 Fixes + +- Links that only navigated on the first tap: router changes that arrived while the Frame sync was locked were dropped, so re-opening a modal after closing it (or navigating during a back transition) did nothing. +- Android hardware back after closing a modal route: closing a modal (Close link, Android back, iOS sheet swipe) now pops its history entry when it was pushed over the same page, instead of leaving a duplicate entry that swallowed the next Back. +- A modal route linked from another page (e.g. `/posts?@modal=/users/3` from `/`) opened twice on Android. Modals now open once their page is visible, and cancelled opens never present. +- Android back while a modal is presented is handled by the dialog, so it closes the modal like the iOS sheet swipe-down. +- `replace` navigations now drop the replaced page from the Frame backstack, and router back targets the matching backstack page even across several history entries. +- A tap made while a page was still animating in is no longer reverted when that page's transition finishes. + ## 0.2.1 (2026-11-23) The 0.2.0 tarball on npm was built before the following changes landed; 0.2.1 publishes them. diff --git a/packages/tanstack-router/package.json b/packages/tanstack-router/package.json index 10d336a..c3a20a9 100644 --- a/packages/tanstack-router/package.json +++ b/packages/tanstack-router/package.json @@ -1,6 +1,6 @@ { "name": "@nativescript/tanstack-router", - "version": "0.2.1", + "version": "0.2.2", "description": "TanStack Router for NativeScript", "main": "index.cjs", "types": "index.d.ts", diff --git a/packages/tanstack-router/src/NativeScriptRouterProvider.ts b/packages/tanstack-router/src/NativeScriptRouterProvider.ts index 693a001..b7dc717 100644 --- a/packages/tanstack-router/src/NativeScriptRouterProvider.ts +++ b/packages/tanstack-router/src/NativeScriptRouterProvider.ts @@ -4,7 +4,7 @@ import type { AnyRouter } from '@tanstack/solid-router'; import { Color, ShowModalOptions, Utils } from '@nativescript/core'; import { renderPage } from './PageRenderer'; import { setupBackHandler } from './back-handler'; -import { doesRouteIdMatchPathname, getHistoryIndex, getNativeScriptNavigationTransition, getNavigationSignalFromRouterState, getNavigationKind, shouldSkipPathNavigation } from './navigation-state'; +import { doesRouteIdMatchPathname, getHistoryIndex, getHistoryKey, getNativeScriptNavigationTransition, getNavigationSignalFromRouterState, getNavigationKind, shouldSkipPathNavigation } from './navigation-state'; import { getNativeBackCallbackDecision, shouldCompleteNativeBackSyncOnVisiblePath } from './native-back-sync'; import { createDebugLogger } from './debug-log'; import type { NavigationGuard, NativeScriptModalOptionsResolver, NativeScriptModalPresentationOptions } from './types'; @@ -47,6 +47,8 @@ export interface NativeScriptRouterProviderProps { actionBar?: (ctx: NativeScriptPageActionBarContext) => SolidElement; } +const MAX_MISMATCH_RETRIES = 20; + export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProps) { const router = props.router; @@ -65,19 +67,44 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp let frameRef: any; let prevIndex = -1; let prevPathname = ''; - let prevModalPath: string | null = null; + // Modal the provider is opening or presenting; null when none is wanted. + let modalTargetPath: string | null = null; let activeModalPath: string | null = null; let activeModalPage: any; - let modalLifecycleLock = false; let modalRequestId = 0; + // History key of the entry whose modal the user just dismissed natively, so the + // modal is not reopened before the router has dropped it from that entry. + let dismissedModalHistoryKey: string | null = null; + // History entries seen so far, by index. Memory history exposes no entry list, + // and closing a modal needs to know whether the entry below it is its own page. + const seenHistoryEntries: Array<{ pathname: string; modalPath: string | null } | undefined> = []; let suppressedNativeBackCallbacks = 0; let nativeBackSyncInFlight = false; let nativeBackSyncFromPath: string | null = null; let queuedNativeBackCount = 0; let skipNextFrameBackNavigation = false; + let routerGoBackPending = false; + let syncQueued = false; + let resyncWhenUnlocked = false; + let mismatchRetries = 0; + let mismatchRetryPath: string | null = null; + let disposed = false; // Shared guard to prevent circular updates between router and Frame const guard: NavigationGuard = { isNavigating: false }; + // Router state is reconciled against the Frame as a whole, so coalescing and + // re-running a sync is always safe. + const scheduleSync = () => { + if (syncQueued || disposed) { + return; + } + syncQueued = true; + queueMicrotask(() => { + syncQueued = false; + syncFrameToRouterState(); + }); + }; + const releaseGuard = () => { guard.isNavigating = false; guard.lockReason = undefined; @@ -85,6 +112,11 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp clearTimeout(guard.lockTimeoutId); guard.lockTimeoutId = undefined; } + // Router changes that arrived while locked were not applied to the Frame. + if (resyncWhenUnlocked) { + resyncWhenUnlocked = false; + scheduleSync(); + } }; const acquireGuard = (reason: string) => { @@ -104,10 +136,11 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp installNativeScriptStartTransition(router); // Includes pathname so child-route swaps inside a layout (e.g. /virtual → - // /virtual/inspector) register even when the match ids lag behind. + // /virtual/inspector) register even when the match ids lag behind, and the + // history entry key so moving between entries that look alike still syncs. const readNavigationKey = () => { const state = router.state; - return `${getNavigationSignalFromRouterState(state)}:${state.location?.pathname || ''}`; + return `${getNavigationSignalFromRouterState(state)}:${state.location?.pathname || ''}:${getHistoryKey(state.location?.state)}`; }; // Seeded once, then driven only by the router subscriptions below so Frame @@ -132,43 +165,59 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp updateSignal(); }); + // The modal page's close callback ignores closes started here: it only syncs + // the router for the presented page, which this clears first. const closeModalFromRouterState = () => { - if (!activeModalPage) { - activeModalPath = null; - return; - } - - modalLifecycleLock = true; + // Also cancels an open that is still loading. + modalRequestId += 1; + modalTargetPath = null; const page = activeModalPage; activeModalPage = undefined; activeModalPath = null; + if (!page) { + return; + } + try { page.closeModal?.(); - } finally { - setTimeout(() => { - modalLifecycleLock = false; - }, 0); + } catch (err) { + console.error('[NSRouter] Failed to close modal:', err); } }; - const syncRouterOnNativeModalClose = () => { - if (modalLifecycleLock) { + // The user dismissed the modal natively (Close link, Android back, iOS swipe), + // or it could not be shown. Drop it from router state: pop its history entry + // when that entry was pushed over the same page, so Back is not spent on a + // duplicate; otherwise remove the search param in place. + const syncRouterOnNativeModalClose = (modalPath: string) => { + const location = router.state.location; + if (getSingleModalPathFromSearch(location.search) !== modalPath) { return; } - const currentModalPath = getSingleModalPathFromSearch(router.state.location.search); - if (!currentModalPath) { + dismissedModalHistoryKey = getHistoryKey(location.state); + const entryBelow = seenHistoryEntries[getHistoryIndex(location.state) - 1]; + + if (entryBelow && entryBelow.pathname === location.pathname && !entryBelow.modalPath && router.history.canGoBack()) { + log('[NSRouter] native modal close -> popping modal history entry'); + router.history.back(); return; } - acquireGuard('native_modal_close'); + log('[NSRouter] native modal close -> removing modal search param'); router.navigate({ to: '.', search: (prev: unknown) => withSingleModalPath(prev, null), replace: true, } as any); - setTimeout(releaseGuard, 0); + }; + + const abandonModalOpen = (modalPath: string) => { + if (modalTargetPath === modalPath) { + modalTargetPath = null; + } + syncRouterOnNativeModalClose(modalPath); }; const openModalFromRouterState = async (modalPath: string) => { @@ -179,6 +228,7 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp } const requestId = ++modalRequestId; + const isCurrentRequest = () => requestId === modalRequestId && !disposed; let modalPageRef: any; const parentContext = (router as any).options?.context; const modalContext = parentContext && typeof parentContext === 'object' ? { ...parentContext } : {}; @@ -200,11 +250,11 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp await modalRouter.load(); } catch (err) { console.error('[NSRouter] Modal router load failed for path:', modalPath, err); - syncRouterOnNativeModalClose(); + if (isCurrentRequest()) abandonModalOpen(modalPath); return; } - if (requestId !== modalRequestId) { + if (!isCurrentRequest()) { return; } @@ -212,7 +262,7 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp const leafMatch = modalMatches[modalMatches.length - 1]; if (!leafMatch) { console.error('[NSRouter] No modal match found for path:', modalPath); - syncRouterOnNativeModalClose(); + abandonModalOpen(modalPath); return; } @@ -222,7 +272,7 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp if (!Component) { console.error('[NSRouter] Invalid modal route component for route:', leafMatch.routeId, 'shape:', describeComponentShape(rawComponent), 'value:', rawComponent); - syncRouterOnNativeModalClose(); + abandonModalOpen(modalPath); return; } @@ -295,11 +345,14 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp animated: resolvedModalOptions?.animated ?? props.animated ?? true, fullscreen: resolvedModalOptions?.fullscreen ?? __ANDROID__, closeCallback: () => { - if (activeModalPage === modalPage) { - activeModalPage = undefined; - activeModalPath = null; + // Closes started by the router already cleared activeModalPage. + if (activeModalPage !== modalPage) { + return; } - syncRouterOnNativeModalClose(); + activeModalPage = undefined; + activeModalPath = null; + modalTargetPath = null; + syncRouterOnNativeModalClose(modalPath); }, }; @@ -310,6 +363,11 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp } const attemptShowModal = (hostPage: any) => { + // The router may have moved on, or a newer open started, while this waited. + if (!isCurrentRequest() || activeModalPage) { + return; + } + try { log('[NSRouter] showModal attempt:', 'path=', modalPath, 'hostLoaded=', !!hostPage?.isLoaded, 'frameLoaded=', !!hostPage?.frame?.isLoaded); @@ -320,7 +378,7 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp activeModalPage = undefined; activeModalPath = null; console.error('[NSRouter] Failed to show modal for path:', modalPath, err); - syncRouterOnNativeModalClose(); + abandonModalOpen(modalPath); } }; @@ -332,16 +390,6 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp const onHostLoaded = () => { currentPage.removeEventListener?.('loaded', onHostLoaded); - - if (requestId !== modalRequestId) { - return; - } - - const latestModalPath = getSingleModalPathFromSearch(router.state.location.search); - if (!latestModalPath || latestModalPath !== modalPath || activeModalPath) { - return; - } - setTimeout(() => attemptShowModal(currentPage), 0); }; @@ -352,6 +400,9 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp } else { attemptShowModal(currentPage); setTimeout(() => { + if (activeModalPage !== modalPage) { + return; + } try { configureIOSModalSheet(); } catch (err) { @@ -377,8 +428,15 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp router.history.back(); }; - const reconcileRouterToVisiblePath = (visiblePath: string) => { + const reconcileRouterToVisiblePath = (visiblePath: string, isBackNavigation: boolean) => { const activePath = router.state.location.pathname; + const isRouterInitiatedBack = isBackNavigation && routerGoBackPending; + if (isBackNavigation) { + routerGoBackPending = false; + } + // A page that finished appearing may host a deferred modal. + scheduleSync(); + if (visiblePath === activePath) { // Native visibility has aligned with router path, so any in-flight native // back sync can be deterministically completed from this event. @@ -400,6 +458,13 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp return; } + // Only a native pop the router did not start can leave the router behind the + // Frame. Pages the router itself pushed or popped report a stale path when + // the router moved on during their transition; the Frame catches up instead. + if (!isBackNavigation || isRouterInitiatedBack) { + return; + } + log('[NSRouter] reconciling router to visible native page:', 'visible=', visiblePath, 'active=', activePath); nativeBackSyncInFlight = false; @@ -476,7 +541,7 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp log('[NSRouter] initial load:', JSON.stringify(router.latestLocation?.pathname)); loadRouter('initial'); - const cleanupBack = setupBackHandler(router, () => frameRef, guard); + const cleanupBack = setupBackHandler(router, () => !!activeModalPage); // Route-file edits are hot-swapped per Page (see solid-hmr-remount.ts) so the // navigation stack survives the edit. @@ -490,6 +555,7 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp return () => { closeModalFromRouterState(); + disposed = true; unsubHistory(); cleanupBack(); cleanupHmr(); @@ -499,7 +565,64 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp }; }); + // Opens/closes the native modal so it matches `?@modal=`. Opening waits until + // the route's own Page is the visible one; its navigatedTo schedules a resync. + const reconcileModal = (curModalPath: string | null) => { + const historyKey = getHistoryKey(router.state.location.state); + if (dismissedModalHistoryKey && dismissedModalHistoryKey !== historyKey) { + dismissedModalHistoryKey = null; + } + + if (curModalPath === modalTargetPath) { + return; + } + + if (modalTargetPath) { + closeModalFromRouterState(); + } + + if (!curModalPath) { + return; + } + + if (dismissedModalHistoryKey) { + return; + } + + const hostPath = frameRef?.currentPage?.__nsRouterPath; + if (hostPath !== router.state.location.pathname) { + log('[NSRouter] deferring modal open until its page is visible:', curModalPath, 'visible=', hostPath); + return; + } + + modalTargetPath = curModalPath; + void openModalFromRouterState(curModalPath); + }; + + const recordHistoryEntry = (index: number, kind: 'forward' | 'back' | 'replace', pathname: string, modalPath: string | null) => { + if (kind !== 'back') { + // A push or replace discards every entry above it. + seenHistoryEntries.length = Math.min(seenHistoryEntries.length, index + 1); + } + seenHistoryEntries[index] = { pathname, modalPath }; + }; + + // Nearest backstack entry showing `pathname`; router back can span several + // entries (history.go(-n)), so popping just the top page is not enough. + const findBackstackEntryForPath = (pathname: string) => { + const backStack: any[] = frameRef?.backStack || []; + for (let i = backStack.length - 1; i >= 0; i--) { + if (backStack[i]?.resolvedPage?.__nsRouterPath === pathname) { + return backStack[i]; + } + } + return undefined; + }; + const syncFrameToRouterState = () => { + if (disposed) { + return; + } if (!frameRef) { log('[NSRouter] no frameRef'); return; @@ -524,77 +647,85 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp tryDrainQueuedNativeBack(); } + const curModalPath = getSingleModalPathFromSearch(state.location.search); + if (nativeBackSyncInFlight || guard.isNavigating) { + // Dropping a modal never has to wait for the Frame. + if (!curModalPath) { + reconcileModal(null); + } + log('[NSRouter] Frame sync deferred until unlocked. reason:', guard.lockReason || 'native_back_in_flight'); + resyncWhenUnlocked = true; return; } - const curIndex = getHistoryIndex(router.history.location.state as any); - const curTransition = getNativeScriptNavigationTransition(router.history.location.state); + syncFramePath(state, matches); + reconcileModal(curModalPath); + }; + + const syncFramePath = (state: AnyRouter['state'], matches: AnyRouter['state']['matches']) => { + // Index, key and pathname all come from the router's parsed location so they + // describe the same entry even while history is ahead of a pending load. + const curIndex = getHistoryIndex(state.location.state); + const curTransition = getNativeScriptNavigationTransition(state.location.state); const curPathname = state.location.pathname; const curModalPath = getSingleModalPathFromSearch(state.location.search); const hasPathChanged = !shouldSkipPathNavigation(curPathname, prevPathname, prevIndex); - - if (curModalPath !== prevModalPath) { - if (!curModalPath) { - closeModalFromRouterState(); - prevModalPath = curModalPath; - } else if (!activeModalPath) { - // Defer opening modal until the base path is settled on the active page. - if (hasPathChanged && prevPathname) { - log('[NSRouter] deferring modal open until pathname settles:', curModalPath); - } else { - void openModalFromRouterState(curModalPath); - prevModalPath = curModalPath; - } - } else if (activeModalPath !== curModalPath) { - closeModalFromRouterState(); - void openModalFromRouterState(curModalPath); - prevModalPath = curModalPath; - } - } - - if (guard.isNavigating) { - log('[NSRouter] guard active; syncing prev tracking only. reason:', guard.lockReason); - prevIndex = curIndex; - prevPathname = curPathname; - return; - } + const navigationKind = getNavigationKind(prevIndex, curIndex); log('[NSRouter] curPathname:', curPathname, 'prevPathname:', prevPathname, 'curIndex:', curIndex, 'prevIndex:', prevIndex); // Skip if the pathname hasn't changed (e.g., only search params changed) if (!hasPathChanged) { + recordHistoryEntry(curIndex, navigationKind, curPathname, curModalPath); prevIndex = curIndex; return; } - const navigationKind = getNavigationKind(prevIndex, curIndex); - const isBack = navigationKind === 'back'; - const isReplace = navigationKind === 'replace'; - - if (isBack) { + if (navigationKind === 'back') { if (skipNextFrameBackNavigation) { skipNextFrameBackNavigation = false; log('[NSRouter] skipping Frame.goBack for native-originated back sync'); + recordHistoryEntry(curIndex, navigationKind, curPathname, curModalPath); prevIndex = curIndex; prevPathname = curPathname; return; } - acquireGuard('router_state_back'); - if (frameRef.canGoBack()) { + const target = findBackstackEntryForPath(curPathname); + if (target) { + recordHistoryEntry(curIndex, navigationKind, curPathname, curModalPath); + prevIndex = curIndex; + prevPathname = curPathname; + acquireGuard('router_state_back'); // Router-initiated goBack causes a native navigatingFrom(back) event. // Suppress exactly one sync callback for this controlled pop. suppressedNativeBackCallbacks += 1; - frameRef.goBack(); + routerGoBackPending = true; + frameRef.goBack(target); + setTimeout(releaseGuard, 0); + return; + } + + // The Frame holds no page for this entry; show it in place of the current one. + log('[NSRouter] no backstack page for', curPathname, '- replacing current page'); + if (navigateFrameTo(state, matches, curPathname, curTransition, true)) { + recordHistoryEntry(curIndex, navigationKind, curPathname, curModalPath); + prevIndex = curIndex; + prevPathname = curPathname; } + return; + } + + if (navigateFrameTo(state, matches, curPathname, curTransition, navigationKind === 'replace')) { + recordHistoryEntry(curIndex, navigationKind, curPathname, curModalPath); prevIndex = curIndex; prevPathname = curPathname; - setTimeout(releaseGuard, 0); - return; } + }; - // Forward or replace navigation + // Pushes the route's Page; returns false when it must retry once matches settle. + const navigateFrameTo = (state: AnyRouter['state'], matches: AnyRouter['state']['matches'], curPathname: string, curTransition: ReturnType, isReplace: boolean): boolean => { let leafMatch = matches[matches.length - 1]; // If the leaf match's routeId doesn't match the current pathname, the matches @@ -619,16 +750,22 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp if (resolvedRouteId) { log('[NSRouter] match/path mismatch resolved:', leafMatch.routeId, '->', resolvedRouteId, 'for pathname:', curPathname); leafMatch = { ...leafMatch, routeId: resolvedRouteId }; - // Schedule a delayed signal update so the match stores settle and - // useParams/useMatch can read correct data when the component renders. - setTimeout(() => updateSignal(), 16); } else { + if (mismatchRetryPath !== curPathname) { + mismatchRetryPath = curPathname; + mismatchRetries = 0; + } log('[NSRouter] deferring Frame navigation due to pending match/path mismatch:', 'routeId=', leafMatch.routeId, 'pathname=', curPathname, 'status=', state.status); - // Schedule retry — stores may settle on next tick - setTimeout(() => updateSignal(), 16); - return; + // Stores may settle on the next tick; router load events also resync. + if (mismatchRetries < MAX_MISMATCH_RETRIES) { + mismatchRetries += 1; + setTimeout(scheduleSync, 16); + } + return false; } } + mismatchRetries = 0; + mismatchRetryPath = null; const route = (router as any).routesById[leafMatch.routeId]; const rawComponent = route?.options?.component; @@ -638,9 +775,7 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp if (!Component) { console.error('[NSRouter] Invalid route component for route:', leafMatch.routeId, 'shape:', describeComponentShape(rawComponent), 'value:', rawComponent); - prevIndex = curIndex; - prevPathname = curPathname; - return; + return true; } acquireGuard('router_state_forward_or_replace'); @@ -658,10 +793,18 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp }) : undefined; - log('[NSRouter] navigating Frame to', curPathname); - frameRef.navigate({ - create: () => - renderPage( + // The Frame drops a page from its backstack based on that page's own entry + // when navigating away, so a replace flags the outgoing entry. + if (isReplace) { + const outgoingEntry = frameRef.currentPage?.__nsRouterNavigationEntry; + if (outgoingEntry) { + outgoingEntry.backstackVisible = false; + } + } + + const navigationEntry: any = { + create: () => { + const page = renderPage( router, Component, curPathname, @@ -712,31 +855,21 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp reconcileRouterToVisiblePath, props.debug, pageChrome, - ), + ); + page.__nsRouterNavigationEntry = navigationEntry; + return page; + }, animated: prevIndex >= 0 ? (props.animated ?? true) : false, transition: curTransition ?? props.transition, - backstackVisible: !isReplace, + backstackVisible: true, clearHistory: false, - }); - - prevIndex = curIndex; - prevPathname = curPathname; - - // If a modal path is present on a path transition, open it after the - // new page has a chance to become current. - if (curModalPath && !activeModalPath) { - setTimeout(() => { - const latestModalPath = getSingleModalPathFromSearch(router.state.location.search); - if (!latestModalPath || latestModalPath !== curModalPath || activeModalPath) { - return; - } + }; - void openModalFromRouterState(latestModalPath); - prevModalPath = latestModalPath; - }, 0); - } + log('[NSRouter] navigating Frame to', curPathname, isReplace ? '(replace)' : ''); + frameRef.navigate(navigationEntry); releaseGuard(); + return true; }; createEffect( @@ -745,7 +878,7 @@ export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProp log('[NSRouter] effect fired, navigationSignal:', signal, 'frameRef:', !!frameRef); // Frame navigation renders a new Page root, and Solid forbids creating // ownerless roots inside an effect callback, so the sync runs right after it. - queueMicrotask(syncFrameToRouterState); + scheduleSync(); }, ); diff --git a/packages/tanstack-router/src/PageRenderer.ts b/packages/tanstack-router/src/PageRenderer.ts index dac31e0..31cd318 100644 --- a/packages/tanstack-router/src/PageRenderer.ts +++ b/packages/tanstack-router/src/PageRenderer.ts @@ -41,7 +41,7 @@ export function renderPage( RouteComponent: Component, routePath: string, onNativeBack?: (sourcePath: string) => void, - onVisiblePathChange?: (visiblePath: string) => void, + onVisiblePathChange?: (visiblePath: string, isBackNavigation: boolean) => 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 @@ -196,9 +196,9 @@ export function renderPage( mount(); // Re-mount when this page becomes visible again after back navigation. - page.on('navigatedTo', () => { + page.on('navigatedTo', (args: NavigatedData) => { nativeBackSyncScheduled = resetNativeBackSyncScheduled(); - onVisiblePathChange?.(getPagePath()); + onVisiblePathChange?.(getPagePath(), !!args?.isBackNavigation); // Deterministic lifecycle handling: once a Page is visible, it must have // an active view tree regardless of router pending/transient state. mount(); diff --git a/packages/tanstack-router/src/back-handler.ts b/packages/tanstack-router/src/back-handler.ts index 43fd151..58223d6 100644 --- a/packages/tanstack-router/src/back-handler.ts +++ b/packages/tanstack-router/src/back-handler.ts @@ -1,12 +1,22 @@ import { Application, isAndroid } from '@nativescript/core'; import type { AnyRouter } from '@tanstack/solid-router'; -import type { NavigationGuard } from './types'; -export function setupBackHandler(router: AnyRouter, _getFrame: () => any, _guard: NavigationGuard): () => void { +/** + * Routes Android hardware back through router history. + * + * A presented modal dialog also emits `activityBackPressed`. While one is up the + * event is left alone so the dialog dismisses itself; its close callback then + * syncs the router, exactly like the iOS sheet swipe-down. + */ +export function setupBackHandler(router: AnyRouter, hasPresentedModal: () => boolean = () => false): () => void { const cleanups: Array<() => void> = []; if (isAndroid) { const handler = (args: any) => { + if (hasPresentedModal()) { + return; + } + if (router.history.canGoBack()) { args.cancel = true; router.history.back(); diff --git a/packages/tanstack-router/src/navigation-state.ts b/packages/tanstack-router/src/navigation-state.ts index f45fdc3..cb95f42 100644 --- a/packages/tanstack-router/src/navigation-state.ts +++ b/packages/tanstack-router/src/navigation-state.ts @@ -13,6 +13,16 @@ export function getHistoryIndex(historyState: unknown): number { return typeof raw === 'number' ? raw : 0; } +export function getHistoryKey(historyState: unknown): string { + if (!historyState || typeof historyState !== 'object') { + return ''; + } + + const state = historyState as Record; + const raw = state.__TSR_key ?? state.key; + return typeof raw === 'string' ? raw : ''; +} + export function getNativeScriptNavigationTransition(historyState: unknown): NativeScriptNavigationTransition | undefined { if (!historyState || typeof historyState !== 'object') { return undefined; diff --git a/packages/tanstack-router/test/page-renderer.test.ts b/packages/tanstack-router/test/page-renderer.test.ts index 0e0eaa8..d9c9527 100644 --- a/packages/tanstack-router/test/page-renderer.test.ts +++ b/packages/tanstack-router/test/page-renderer.test.ts @@ -63,9 +63,9 @@ describe('renderPage', () => { // Router path is still stale ("/posts/1") while the visible native page is "/". // navigatedTo must still re-mount deterministically. - page.emit('navigatedTo'); + page.emit('navigatedTo', { isBackNavigation: true }); - expect(onVisiblePathChange).toHaveBeenCalledWith('/'); + expect(onVisiblePathChange).toHaveBeenCalledWith('/', true); expect(insertSpy).toHaveBeenCalledTimes(2); }); diff --git a/packages/tanstack-router/test/router-provider-modal.test.ts b/packages/tanstack-router/test/router-provider-modal.test.ts new file mode 100644 index 0000000..40fed73 --- /dev/null +++ b/packages/tanstack-router/test/router-provider-modal.test.ts @@ -0,0 +1,260 @@ +// @vitest-environment jsdom +// +// Modal routes (`?@modal=`) and Android hardware back, driven through +// NativeScriptRouterProvider against a fake Frame/Page that models +// NativeScript's backstack rules and asynchronous dialog dismissal. + +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { createComponent } from 'solid-js'; +import { createMemoryHistory, createRootRoute, createRoute, createRouter } from '@tanstack/solid-router'; +import { FakeNode } from './support/fake-native-renderer'; +import { FakeFrame, FakePage, createFakeElementFactory, presentedModals } from './support/fake-frame'; + +const backListeners: Array<(args: any) => void> = []; + +vi.mock('@nativescript-community/solid-js', async () => { + const { createFakeCommunitySolid } = await import('./support/fake-native-renderer'); + return createFakeCommunitySolid(); +}); + +vi.mock('@solidjs/web', async () => { + return await import('../solid-web-shim.js'); +}); + +vi.mock('@nativescript/core', () => ({ + Application: { + android: { + on: (_event: string, fn: (args: any) => void) => backListeners.push(fn), + off: (_event: string, fn: (args: any) => void) => { + const idx = backListeners.indexOf(fn); + if (idx >= 0) backListeners.splice(idx, 1); + }, + }, + }, + isAndroid: true, + Color: class {}, + Utils: {}, +})); + +vi.mock('@nativescript/core/abortcontroller', () => ({ + AbortController: globalThis.AbortController, + AbortSignal: globalThis.AbortSignal, +})); + +(globalThis as any).__ANDROID__ = true; +(globalThis as any).__IOS__ = false; + +const community = await import('@nativescript-community/solid-js'); +const { NativeScriptRouterProvider } = await import('../src/NativeScriptRouterProvider'); + +const originalCreateElement = document.createElement; + +beforeAll(() => { + (document as any).createElement = createFakeElementFactory(); +}); + +afterAll(() => { + (document as any).createElement = originalCreateElement; +}); + +afterEach(() => { + presentedModals.length = 0; +}); + +const settle = () => new Promise((r) => setTimeout(r, 40)); + +function label(text: string) { + return () => { + const node = community.createElement('label'); + community.setProp(node, 'text', text); + return node; + }; +} + +function setup() { + const rootRoute = createRootRoute(); + const routeTree = rootRoute.addChildren([createRoute({ getParentRoute: () => rootRoute, path: '/', component: label('home') }), createRoute({ getParentRoute: () => rootRoute, path: '/posts', component: label('posts') }), createRoute({ getParentRoute: () => rootRoute, path: '/about', component: label('about') }), createRoute({ getParentRoute: () => rootRoute, path: '/users/$userId', component: label('user') })]); + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + }); + const host = new FakeNode('page'); + const dispose = community.render(() => createComponent(NativeScriptRouterProvider, { router, debug: !!process.env.NSR_DEBUG }), host); + const frame = host.content as unknown as FakeFrame; + return { router, frame, dispose }; +} + +const historyIndex = (router: any) => router.history.location.state.__TSR_index; +const modalOf = (router: any) => router.state.location.search['@modal']; + +function pressHardwareBack() { + const args = { cancel: false }; + for (const fn of [...backListeners]) fn(args); + return args; +} + +async function openAuthorModal(router: any, userId: string) { + await router.navigate({ to: '/posts', search: { '@modal': `/users/${userId}` } }); + await settle(); +} + +describe('NativeScriptRouterProvider modal routes', () => { + it('reopens the same modal after it was closed from inside the modal', async () => { + const { router, dispose } = setup(); + await settle(); + await router.navigate({ to: '/posts' }); + await settle(); + + await openAuthorModal(router, '1'); + expect(presentedModals).toHaveLength(1); + + presentedModals[0].closeModal(); + await settle(); + expect(presentedModals).toHaveLength(0); + expect(modalOf(router)).toBeUndefined(); + + await openAuthorModal(router, '1'); + expect(presentedModals).toHaveLength(1); + + dispose(); + }); + + it('pops the modal history entry on close so the next back leaves the page', async () => { + const { router, frame, dispose } = setup(); + await settle(); + await router.navigate({ to: '/posts' }); + await settle(); + await openAuthorModal(router, '1'); + expect(historyIndex(router)).toBe(2); + + presentedModals[0].closeModal(); + await settle(); + expect(historyIndex(router)).toBe(1); + expect(router.state.location.pathname).toBe('/posts'); + + const args = pressHardwareBack(); + expect(args.cancel).toBe(true); + await settle(); + expect(router.state.location.pathname).toBe('/'); + expect(frame.pagePaths()).toEqual(['/']); + + dispose(); + }); + + it('opens a modal deep-linked from another page exactly once, on the new page', async () => { + const { router, frame, dispose } = setup(); + await settle(); + + await router.navigate({ to: '/posts', search: { '@modal': '/users/3' } }); + await settle(); + await settle(); + + expect(presentedModals).toHaveLength(1); + expect(presentedModals[0].modalHost).toBe(frame.currentPage); + expect((frame.currentPage as any).__nsRouterPath).toBe('/posts'); + expect((frame.currentPage as FakePage).showModalCalls).toBe(1); + + // Its entry was not pushed on top of /posts, so closing keeps the page. + presentedModals[0].closeModal(); + await settle(); + expect(router.state.location.pathname).toBe('/posts'); + expect(modalOf(router)).toBeUndefined(); + expect(frame.pagePaths()).toEqual(['/', '/posts']); + + dispose(); + }); + + it('lets the dialog handle hardware back while a modal is presented', async () => { + const { router, dispose } = setup(); + await settle(); + await router.navigate({ to: '/posts' }); + await settle(); + await openAuthorModal(router, '2'); + + const args = pressHardwareBack(); + expect(args.cancel).toBe(false); + expect(historyIndex(router)).toBe(2); + + // The dialog's default back handling dismisses it. + presentedModals[0].closeModal(); + await settle(); + expect(router.state.location.pathname).toBe('/posts'); + expect(historyIndex(router)).toBe(1); + + dispose(); + }); + + it('closes the modal when router history leaves the modal entry', async () => { + const { router, dispose } = setup(); + await settle(); + await router.navigate({ to: '/posts' }); + await settle(); + await openAuthorModal(router, '1'); + expect(presentedModals).toHaveLength(1); + + router.history.back(); + await settle(); + expect(presentedModals).toHaveLength(0); + expect(router.state.location.pathname).toBe('/posts'); + expect(historyIndex(router)).toBe(1); + + dispose(); + }); + + it('never presents a modal whose route was left before it finished loading', async () => { + const { router, dispose } = setup(); + await settle(); + await router.navigate({ to: '/posts' }); + await settle(); + + void router.navigate({ to: '/posts', search: { '@modal': '/users/1' } }); + router.history.back(); + await settle(); + await settle(); + + expect(presentedModals).toHaveLength(0); + expect(modalOf(router)).toBeUndefined(); + + dispose(); + }); +}); + +describe('NativeScriptRouterProvider navigation while the Frame is locked', () => { + it('applies a navigation that lands during a router back', async () => { + const { router, frame, dispose } = setup(); + await settle(); + await router.navigate({ to: '/posts' }); + await settle(); + + router.history.back(); + await new Promise((r) => queueMicrotask(() => r(undefined))); + await Promise.resolve(); + void router.navigate({ to: '/about' }); + await settle(); + await settle(); + + expect(router.state.location.pathname).toBe('/about'); + expect(frame.pagePaths()).toEqual(['/', '/about']); + + dispose(); + }); +}); + +describe('NativeScriptRouterProvider replace navigation', () => { + it('drops the replaced page from the Frame backstack', async () => { + const { router, frame, dispose } = setup(); + await settle(); + await router.navigate({ to: '/posts' }); + await settle(); + await router.navigate({ to: '/about', replace: true }); + await settle(); + expect(frame.pagePaths()).toEqual(['/', '/about']); + + pressHardwareBack(); + await settle(); + expect(router.state.location.pathname).toBe('/'); + expect(frame.pagePaths()).toEqual(['/']); + + dispose(); + }); +}); diff --git a/packages/tanstack-router/test/router-provider.test.ts b/packages/tanstack-router/test/router-provider.test.ts index 619cb7e..d5b256d 100644 --- a/packages/tanstack-router/test/router-provider.test.ts +++ b/packages/tanstack-router/test/router-provider.test.ts @@ -8,6 +8,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { createComponent } from 'solid-js'; import { createMemoryHistory, createRootRoute, createRoute, createRouter } from '@tanstack/solid-router'; import { FakeNode } from './support/fake-native-renderer'; +import { FakeFrame, createFakeElementFactory } from './support/fake-frame'; vi.mock('@nativescript-community/solid-js', async () => { const { createFakeCommunitySolid } = await import('./support/fake-native-renderer'); @@ -33,36 +34,10 @@ vi.mock('@nativescript/core/abortcontroller', () => ({ const community = await import('@nativescript-community/solid-js'); const { NativeScriptRouterProvider } = await import('../src/NativeScriptRouterProvider'); -class FakeFrame extends FakeNode { - currentPage?: FakeNode; - backStack: FakeNode[] = []; - navigations: Array<{ animated?: boolean; backstackVisible?: boolean }> = []; - - navigate(entry: { create: () => FakeNode; animated?: boolean; backstackVisible?: boolean }) { - this.navigations.push({ animated: entry.animated, backstackVisible: entry.backstackVisible }); - const page = entry.create(); - if (this.currentPage && entry.backstackVisible !== false) this.backStack.push(this.currentPage); - this.currentPage = page; - page.emit('navigatedTo', { isBackNavigation: false }); - } - - canGoBack() { - return this.backStack.length > 0; - } - - goBack() { - const page = this.backStack.pop(); - if (!page) return; - this.currentPage?.emit('navigatingFrom', { isBackNavigation: true }); - this.currentPage = page; - page.emit('navigatedTo', { isBackNavigation: true }); - } -} - const originalCreateElement = document.createElement; beforeAll(() => { - (document as any).createElement = (tag: string) => (tag.toLowerCase() === 'frame' ? new FakeFrame('frame') : new FakeNode(tag.toLowerCase())); + (document as any).createElement = createFakeElementFactory(); }); afterAll(() => { diff --git a/packages/tanstack-router/test/support/fake-frame.ts b/packages/tanstack-router/test/support/fake-frame.ts new file mode 100644 index 0000000..b7b3dcb --- /dev/null +++ b/packages/tanstack-router/test/support/fake-frame.ts @@ -0,0 +1,96 @@ +import { FakeNode } from './fake-native-renderer'; + +interface FakeNavigationEntry { + create: () => FakeNode; + animated?: boolean; + backstackVisible?: boolean; +} + +interface FakeBackstackEntry { + entry: FakeNavigationEntry; + resolvedPage: FakePage; +} + +/** Every modal currently presented by any FakePage, in presentation order. */ +export const presentedModals: FakePage[] = []; + +/** + * Page with NativeScript's modal surface. Android dismisses dialogs + * asynchronously, so the close callback fires on a later macrotask. + */ +export class FakePage extends FakeNode { + isLoaded = true; + modalHost?: FakePage; + showModalCalls = 0; + private closeCallback?: () => void; + + showModal(modalPage: FakePage, options: { closeCallback?: () => void }) { + this.showModalCalls += 1; + modalPage.modalHost = this; + modalPage.closeCallback = options?.closeCallback; + presentedModals.push(modalPage); + } + + closeModal() { + const idx = presentedModals.indexOf(this); + if (idx < 0) return; + presentedModals.splice(idx, 1); + this.modalHost = undefined; + const cb = this.closeCallback; + this.closeCallback = undefined; + setTimeout(() => cb?.(), 0); + } +} + +/** + * Frame with NativeScript's backstack rule: when navigating away, the outgoing + * entry is kept only if *its own* `backstackVisible` is not false. + */ +export class FakeFrame extends FakeNode { + currentPage?: FakePage; + private currentEntry?: FakeBackstackEntry; + backStack: FakeBackstackEntry[] = []; + navigations: Array<{ animated?: boolean; backstackVisible?: boolean }> = []; + + navigate(entry: FakeNavigationEntry) { + this.navigations.push({ animated: entry.animated, backstackVisible: entry.backstackVisible }); + const page = entry.create() as FakePage; + const outgoing = this.currentEntry; + if (outgoing) { + outgoing.resolvedPage.emit('navigatingFrom', { isBackNavigation: false }); + if (outgoing.entry.backstackVisible !== false) this.backStack.push(outgoing); + } + this.currentEntry = { entry, resolvedPage: page }; + this.currentPage = page; + page.emit('navigatedTo', { isBackNavigation: false }); + } + + canGoBack() { + return this.backStack.length > 0; + } + + goBack(to?: FakeBackstackEntry) { + const idx = to ? this.backStack.indexOf(to) : this.backStack.length - 1; + if (idx < 0) return; + const target = this.backStack[idx]; + this.backStack.length = idx; + this.currentPage?.emit('navigatingFrom', { isBackNavigation: true }); + this.currentEntry = target; + this.currentPage = target.resolvedPage; + target.resolvedPage.emit('navigatedTo', { isBackNavigation: true }); + } + + /** Pages from the bottom of the stack to the visible one. */ + pagePaths(): string[] { + return [...this.backStack.map((e) => (e.resolvedPage as any).__nsRouterPath), (this.currentPage as any)?.__nsRouterPath]; + } +} + +export function createFakeElementFactory() { + return (tag: string) => { + const t = tag.toLowerCase(); + if (t === 'frame') return new FakeFrame('frame'); + if (t === 'page') return new FakePage('page'); + return new FakeNode(t); + }; +}