Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useSidePanelActions from '@hooks/useSidePanelActions';
import useSidePanelState from '@hooks/useSidePanelState';

import {asCustomHistory, isModalHistorySentinel} from '@libs/Navigation/AppNavigator/routerExtensions/addRootHistoryRouterExtensionUtils';
import {isModalHistorySentinel} from '@libs/Navigation/AppNavigator/routerExtensions/addRootHistoryRouterExtensionUtils';
import Navigation from '@libs/Navigation/Navigation';
import navigationRef from '@libs/Navigation/navigationRef';

Expand All @@ -27,7 +27,7 @@ export default function useSyncSidePanelWithHistory() {
const {isExtraLargeScreenWidth} = useResponsiveLayout();
// Modals with `shouldHandleNavigationBack` push their own back-guard entry after the Side Panel's, so skip those:
// a modal opened from the panel must not read as the panel having been closed.
const lastHistoryEntry = useNavigationState((state) => asCustomHistory(state?.history)?.findLast((entry) => !isModalHistorySentinel(entry)));
const lastHistoryEntry = useNavigationState((state) => state?.history?.findLast((entry) => !isModalHistorySentinel(entry)));
const previousLastHistoryEntry = usePrevious(lastHistoryEntry);

useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,22 @@ import compoundParamsKey from '@libs/compoundParamsKey';
import type {PlatformStackNavigationState, PlatformStackRouterFactory, PlatformStackRouterOptions} from '@libs/Navigation/PlatformStackNavigation/types';
import type {GoBackAction, SetParamsAction} from '@libs/Navigation/types';
import {cancelPendingFocusRestore, notifyPushParamsBackward, notifyPushParamsForward} from '@libs/NavigationFocusReturn';
import {isRecord} from '@libs/ObjectUtils';

import CONST from '@src/CONST';

import type {NavigationRoute, ParamListBase, PartialState, Router, RouterConfigOptions, StackActionType} from '@react-navigation/native';
import type {ParamListBase, PartialState, Router, RouterConfigOptions, StackActionType} from '@react-navigation/native';

import {CommonActions} from '@react-navigation/native';

import type {CustomHistoryEntry, PushParamsActionType, PushParamsRouterAction} from './types';
import type {PushParamsActionType, PushParamsRouterAction} from './types';

import {enhanceStateWithHistory} from './utils';

function preserveHistoryForRoutes(oldHistory: CustomHistoryEntry[], routes: Array<{key?: string}>): CustomHistoryEntry[] {
function preserveHistoryForRoutes(oldHistory: unknown[], routes: Array<{key?: string}>): unknown[] {
const remainingKeys = new Set(routes.map((r) => r.key));
return oldHistory.filter((entry) => typeof entry === 'string' || remainingKeys.has(entry.key));
// Keep string history markers and anything else that is not a route snapshot; drop only route snapshots whose route is gone.
return oldHistory.filter((entry) => !isRecord(entry) || typeof entry.key !== 'string' || remainingKeys.has(entry.key));
}

// noop=match at cursor; backward/forward=move cursor to match; ambiguous=same compound at cursor±1 (see ambiguous branch); unknown=target not in history.
Expand All @@ -25,7 +27,7 @@ type ResetOutcome = {type: 'noop'; cursor: number} | {type: 'backward'; cursor:
* Classifies a RESET's target against our PUSH_PARAMS history + cursor so the caller fires the right focus-return notification and updates the cursor.
* Without the 'noop' branch, `useNavigationResetOnLayoutChange`'s reflexive `reset(getState())` on window resize would be treated as a real navigation — cancelling any pending Esc-triggered focus restore so focus never returns to the trigger.
*/
function resolveCursorForReset(history: CustomHistoryEntry[], currentCursor: number, newFocused: {key: string; params: unknown}): ResetOutcome {
function resolveCursorForReset(history: unknown[], currentCursor: number, newFocused: {key: string; params: unknown}): ResetOutcome {
const inRange = currentCursor >= 0 && currentCursor < history.length;
// Snapped cursor drives direction inference only; adjacent probes are gated on inRange.
const cursor = inRange ? currentCursor : history.length - 1;
Expand All @@ -36,7 +38,7 @@ function resolveCursorForReset(history: CustomHistoryEntry[], currentCursor: num
return false;
}
const entry = history.at(index);
if (typeof entry === 'string' || !entry || entry.key !== newFocused.key) {
if (!isRecord(entry) || entry.key !== newFocused.key) {
return false;
}
return compoundParamsKey(entry.key, entry.params) === newCompound;
Expand Down Expand Up @@ -134,7 +136,10 @@ function addPushParamsRouterExtension<RouterOptions extends PlatformStackRouterO
return seedCursor(enhanceStateWithHistory(state));
};

const getRehydratedState = (partialState: PartialState<PlatformStackNavigationState<ParamListBase>>, configOptions: RouterConfigOptions) => {
const getRehydratedState = (
partialState: PartialState<PlatformStackNavigationState<ParamListBase>> | PlatformStackNavigationState<ParamListBase>,
configOptions: RouterConfigOptions,
) => {
const state = router.getRehydratedState(partialState, configOptions);
return seedCursor(enhanceStateWithHistory(state));
};
Expand Down Expand Up @@ -178,29 +183,30 @@ function addPushParamsRouterExtension<RouterOptions extends PlatformStackRouterO

// No browser history on native — intercept GO_BACK/POP to revert params to the prior snapshot (what the browser does via popstate on web).
if ((isGoBackAction(action) || isPopAction(action)) && state.history) {
const routeHistoryEntries = state.history.filter((entry): entry is NavigationRoute<ParamListBase, string> => typeof entry !== 'string');
const routeHistoryEntries = state.history.filter((entry) => typeof entry !== 'string');

if (routeHistoryEntries.length > state.routes.length) {
// Index-based, not at(-1) — must match the key PUSH_PARAMS captured under.
const focusedRoute = state.routes.at(state.index) ?? state.routes.at(-1);
if (focusedRoute) {
// Cursor-relative, not last-two: last-two drifts out of sync after a mid-cursor browser-back RESET.
const history = state.history as CustomHistoryEntry[];
const history = state.history;
const currentIdx = pushParamsHistoryPosition >= 0 && pushParamsHistoryPosition < history.length ? pushParamsHistoryPosition : history.length - 1;
const currentEntry = history.at(currentIdx);

if (currentEntry && typeof currentEntry !== 'string' && currentEntry.key === focusedRoute.key) {
if (isRecord(currentEntry) && currentEntry.key === focusedRoute.key) {
let prevIdx = -1;
for (let i = currentIdx - 1; i >= 0; i -= 1) {
const e = history.at(i);
if (e && typeof e !== 'string' && e.key === focusedRoute.key) {
if (isRecord(e) && e.key === focusedRoute.key) {
prevIdx = i;
break;
}
}

if (prevIdx >= 0) {
const prevEntry = history.at(prevIdx) as NavigationRoute<ParamListBase, string>;
const prevEntry = history.at(prevIdx);
// React Navigation types history entries as unknown, so check that the snapshot's params are valid route params before restoring them.
if (prevIdx >= 0 && isRecord(prevEntry) && (prevEntry.params === undefined || isRecord(prevEntry.params))) {
const targetParams = prevEntry.params;
const routes = [...state.routes];
routes[state.index] = {
Expand Down Expand Up @@ -232,7 +238,7 @@ function addPushParamsRouterExtension<RouterOptions extends PlatformStackRouterO
if (!newState) {
return null;
}
const preservedHistory = preserveHistoryForRoutes(state.history as CustomHistoryEntry[], newState.routes);
const preservedHistory = preserveHistoryForRoutes(state.history, newState.routes);
// Sync cursor to the focused entry of the filtered history — same invariant as the fall-through path.
pushParamsHistoryPosition = preservedHistory.length > 0 ? preservedHistory.length - 1 : -1;
return {
Expand All @@ -254,14 +260,13 @@ function addPushParamsRouterExtension<RouterOptions extends PlatformStackRouterO
};
}

// @ts-expect-error newState may be partial, but getRehydratedState handles both partial and full states correctly.
const rehydratedState = getRehydratedState(newState, configOptions);

// RESET (e.g. web URL sync) would wipe PUSH_PARAMS snapshots via 1:1 rehydration — preserve entries for surviving routes.
if (action.type === CONST.NAVIGATION.ACTION_TYPE.RESET && state.history) {
// CommonActions.reset can install any index — pick the focused route, not routes.at(-1).
const newFocused = rehydratedState.routes.at(rehydratedState.index) ?? rehydratedState.routes.at(-1);
const history = state.history as CustomHistoryEntry[];
const history = state.history;
if (newFocused?.key) {
const outcome = resolveCursorForReset(history, pushParamsHistoryPosition, {key: newFocused.key, params: newFocused.params});
if (outcome.type === 'backward' || outcome.type === 'ambiguous') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import type {PendingReveal, RootHistoryState} from './addRootHistoryRouterExtens

import {
applyRevealPaddingOffset,
asCustomHistory,
getFrozenHistoryStateForRemoveFullscreenUnderRHP,
getFrozenHistoryStateForReplaceFullscreenUnderRHP,
getRevealDismissState,
Expand Down Expand Up @@ -39,7 +38,7 @@ function addRootHistoryRouterExtension<RouterOptions extends PlatformStackRouter
return enhanceStateWithHistory(state);
};

const getRehydratedState = (partialState: PartialState<PlatformStackNavigationState<ParamListBase>>, configOptions: RouterConfigOptions) => {
const getRehydratedState = (partialState: PartialState<RootHistoryState> | RootHistoryState, configOptions: RouterConfigOptions) => {
const state = router.getRehydratedState(partialState, configOptions);
const stateWithInitialHistory = enhanceStateWithHistory(state);

Expand All @@ -49,17 +48,12 @@ function addRootHistoryRouterExtension<RouterOptions extends PlatformStackRouter
// getStateForAction is what intentionally drops a modal back-guard entry.
const trailingSentinels = getTrailingStringSentinels(state.history);
if (trailingSentinels.length > 0) {
stateWithInitialHistory.history = [...(asCustomHistory(stateWithInitialHistory.history) ?? []), ...trailingSentinels];
stateWithInitialHistory.history = [...(stateWithInitialHistory.history ?? []), ...trailingSentinels];
}

return stateWithInitialHistory;
};

// Centralizes the `PartialState | FullState` cast to `getRehydratedState`'s input shape.
function rehydrate(newState: PartialState<RootHistoryState> | RootHistoryState, configOptions: RouterConfigOptions) {
return getRehydratedState(newState as PartialState<RootHistoryState>, configOptions);
}

const getStateForAction = (state: RootHistoryState, action: RootStackNavigatorAction, configOptions: RouterConfigOptions) => {
// Snapshot is stale if its RHP key vanished via a non-DISMISS path.
if (pendingReveal && !state.routes.some((r) => r.key === pendingReveal?.rhpKey)) {
Expand All @@ -75,14 +69,14 @@ function addRootHistoryRouterExtension<RouterOptions extends PlatformStackRouter

// REPLACE: capture pending reveal + freeze history (intermediate frame; useLinking historyDelta=0).
if (isReplaceFullscreenUnderRHPAction(action)) {
const result = getFrozenHistoryStateForReplaceFullscreenUnderRHP(state, newState, configOptions, pendingReveal, rehydrate);
const result = getFrozenHistoryStateForReplaceFullscreenUnderRHP(state, newState, configOptions, pendingReveal, getRehydratedState);
pendingReveal = result.pendingReveal;
return result.state;
}

// REMOVE: cancel path; clear snapshot + freeze history (same rationale as REPLACE).
if (isRemoveFullscreenUnderRHPAction(action)) {
const result = getFrozenHistoryStateForRemoveFullscreenUnderRHP(state, newState, configOptions, rehydrate);
const result = getFrozenHistoryStateForRemoveFullscreenUnderRHP(state, newState, configOptions, getRehydratedState);
if (state.history) {
pendingReveal = null;
}
Expand All @@ -93,17 +87,17 @@ function addRootHistoryRouterExtension<RouterOptions extends PlatformStackRouter
// useLinking sees historyDelta=0 and just `history.replace`s the current entry,
// preserving the prior fullscreen browser entry. (RN 7.x useLinking semantics.)
if (isDismissModalAction(action) && pendingReveal && state.history) {
const result = getRevealDismissState(state, newState, configOptions, pendingReveal, rehydrate);
const result = getRevealDismissState(state, newState, configOptions, pendingReveal, getRehydratedState);
pendingReveal = result.pendingReveal;
if (result.state) {
return result.state;
}
}

const rehydrated = rehydrate(newState, configOptions);
const rehydrated = getRehydratedState(newState, configOptions);

// forward navigation out of a `shouldHandleNavigationBack` Modal. The previous state
// had a trailing modal back-guard entry; rehydrate() re-appends it on top of the freshly
// had a trailing modal back-guard entry; getRehydratedState() re-appends it on top of the freshly
// pushed route, which would strand a phantom browser entry (Back needing two presses). Drop only
// the top modal entry so the new history length matches the previous one and useLinking
// sees historyDelta === 0 → history.replace, letting the new screen consume the guard entry.
Expand All @@ -112,8 +106,8 @@ function addRootHistoryRouterExtension<RouterOptions extends PlatformStackRouter
// unaffected. Either ordering works: if the Modal's own toggle(false) ran first, the trailing
// entry is already a route and this is a no-op.
const isForwardNavigation = action.type === CONST.NAVIGATION.ACTION_TYPE.PUSH || action.type === CONST.NAVIGATION.ACTION_TYPE.NAVIGATE;
if (isForwardNavigation && isModalHistorySentinel(asCustomHistory(state.history)?.at(-1))) {
const consumedHistory = stripTrailingModalSentinels(asCustomHistory(rehydrated.history) ?? []);
if (isForwardNavigation && isModalHistorySentinel(state.history?.at(-1))) {
const consumedHistory = stripTrailingModalSentinels(rehydrated.history ?? []);
return applyRevealPaddingOffset(state, {...rehydrated, history: consumedHistory});
}

Expand Down
Loading
Loading