Skip to content

Commit 35281e5

Browse files
authored
fix(react-router): keep pages in back history mounted after a replace (#31827)
Issue number: resolves #31815 --------- <!-- Please do not submit updates to dependencies unless it fixes an issue. --> <!-- Please try to limit your pull request to one type (bugfix, feature, etc). Submit multiple pull requests if needed. --> ## What is the current behavior? <!-- Please describe the current behavior that you are modifying. --> Currently, a replace to a sibling route unmounts every sibling page in the outlet, including the page that pushed the one being replaced. Going back remounts that page, so its state is lost and swipe back can't start. A redirect through `<Navigate replace>` unmounts the page behind it the same way. ## What is the new behavior? <!-- Please describe the behavior or changes that are being added by this PR. --> A replace now only unmounts the page it replaces. Before the outlet removes any other view, it checks the location history and keeps every view that back can still reach, which matches React Router since a replace only swaps one history entry. When the leaving view is a redirect with no page of its own, we transition out the page that was showing before it, and unmount that page only once it's out of history. ## Does this introduce a breaking change? - [ ] Yes - [X] No <!-- If this introduces a breaking change: 1. Describe the impact and migration path for existing applications below. 2. Update the BREAKING.md file with the breaking change. 3. Add "BREAKING CHANGE: [...]" to the commit description when merging. See https://github.com/ionic-team/ionic-framework/blob/main/docs/CONTRIBUTING.md#footer for more information. --> ## Other information <!-- Any other information that is important to this PR such as screenshots of how the component looks before and after the change. --> The sibling cleanup came in with the React Router 6 migration to get rid of root-level siblings that never unmounted. Views that are out of history still get cleaned up, so that case still works. The "Home with redirect" and "Home with router" routing tests now expect Favorites to be hidden instead of removed, because it's still in the back history. The `replace-params` test page also pops back to step 1 now, which is what its description says it does. It only worked before because of the old cleanup.
1 parent 33b8c7e commit 35281e5

12 files changed

Lines changed: 702 additions & 65 deletions

File tree

‎packages/react-router/src/ReactRouter/IonRouter.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,7 @@ export const IonRouter = ({ children, registerHistoryListener }: PropsWithChildr
690690
findViewItemByPathname: viewStack.current.findViewItemByPathname,
691691
getChildrenToRender: viewStack.current.getChildrenToRender,
692692
getViewItemsForOutlet: viewStack.current.getViewItemsForOutlet.bind(viewStack.current),
693+
getLocationHistoryPathnames: () => locationHistory.current.getPathnames(),
693694
goBack: () => handleNavigateBack(),
694695
createViewItem: viewStack.current.createViewItem,
695696
findViewItemByRouteInfo: viewStack.current.findViewItemByRouteInfo,

‎packages/react-router/src/ReactRouter/StackManager.tsx‎

Lines changed: 128 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -629,9 +629,18 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
629629

630630
this.lastTransition = currentTransition;
631631

632-
const shouldSkipAnimation = this.applySkipAnimationIfNeeded(enteringViewItem, leavingViewItem);
632+
// A page-less leaving view (e.g. a redirect) has nothing to animate out,
633+
// so transition the page shown before it instead. Look it up once and reuse
634+
// it for cleanup: applySkipAnimationIfNeeded may hide it, and the fallback
635+
// lookup only matches visible pages.
636+
const pageBehindPagelessView = this.findPageBehindPagelessView(routeInfo, enteringViewItem, leavingViewItem);
637+
const pageBehindIsVisible =
638+
pageBehindPagelessView?.ionPageElement && isViewVisible(pageBehindPagelessView.ionPageElement);
639+
const transitionLeavingViewItem = pageBehindIsVisible ? pageBehindPagelessView : leavingViewItem;
633640

634-
this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, undefined, false, shouldSkipAnimation);
641+
const shouldSkipAnimation = this.applySkipAnimationIfNeeded(enteringViewItem, transitionLeavingViewItem);
642+
643+
this.transitionPage(routeInfo, enteringViewItem, transitionLeavingViewItem, undefined, false, shouldSkipAnimation);
635644

636645
if (shouldUnmountLeavingViewItem && leavingViewItem && enteringViewItem !== leavingViewItem) {
637646
// For replace actions, skip setting mount=false here. handleLeavingViewUnmount
@@ -654,7 +663,9 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
654663
this.handleLeavingViewUnmount(routeInfo, enteringViewItem, leavingViewItem);
655664
}
656665

657-
// Clean up orphaned sibling views after replace actions (redirects)
666+
this.cleanupPageBehindPagelessView(routeInfo, pageBehindPagelessView);
667+
668+
// Clean up orphaned sibling views after replace actions or push-to-container navigations
658669
this.cleanupOrphanedSiblingViews(routeInfo, enteringViewItem, leavingViewItem);
659670

660671
// On a fresh push, browser forward history is invalidated. Any views we
@@ -691,17 +702,8 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
691702
this.preservedViewItems.delete(viewItem);
692703
continue;
693704
}
694-
viewItem.mount = false;
695705
this.preservedViewItems.delete(viewItem);
696-
const viewToUnmount = viewItem;
697-
setTimeout(() => {
698-
// Skip if a follow-up transition re-entered the view (mount flipped back to true).
699-
if (viewToUnmount.mount) {
700-
return;
701-
}
702-
this.context.unMountViewItem(viewToUnmount);
703-
this.forceUpdate();
704-
}, VIEW_UNMOUNT_DELAY_MS);
706+
this.scheduleViewUnmount(viewItem);
705707
}
706708
}
707709

@@ -715,16 +717,7 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
715717
}
716718

717719
if (!leavingViewItem.ionPageElement) {
718-
leavingViewItem.mount = false;
719-
const viewToUnmount = leavingViewItem;
720-
setTimeout(() => {
721-
// Skip if a follow-up transition re-entered the view (mount flipped back to true).
722-
if (viewToUnmount.mount) {
723-
return;
724-
}
725-
this.context.unMountViewItem(viewToUnmount);
726-
this.forceUpdate();
727-
}, VIEW_UNMOUNT_DELAY_MS);
720+
this.scheduleViewUnmount(leavingViewItem);
728721
return;
729722
}
730723

@@ -744,21 +737,111 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
744737
return;
745738
}
746739

747-
leavingViewItem.mount = false;
740+
this.scheduleViewUnmount(leavingViewItem);
741+
}
748742

749-
const viewToUnmount = leavingViewItem;
743+
/**
744+
* Marks a view unmounted and removes it after VIEW_UNMOUNT_DELAY_MS, unless a
745+
* follow-up transition re-enters it first (mount flips back to true).
746+
*/
747+
private scheduleViewUnmount(viewItem: ViewItem): void {
748+
viewItem.mount = false;
750749
setTimeout(() => {
751-
// Skip if a follow-up transition re-entered the view (mount flipped back to true).
752-
if (viewToUnmount.mount) {
750+
if (viewItem.mount) {
753751
return;
754752
}
755-
this.context.unMountViewItem(viewToUnmount);
753+
this.context.unMountViewItem(viewItem);
756754
this.forceUpdate();
757755
}, VIEW_UNMOUNT_DELAY_MS);
758756
}
759757

760758
/**
761-
* Cleans up orphaned sibling views after replace actions or push-to-container navigations.
759+
* Returns the ids of this outlet's views that a location history entry still
760+
* resolves to. Those views are reachable with back.
761+
*/
762+
private getViewIdsInHistory(): Set<string> {
763+
const viewIds = new Set<string>();
764+
for (const pathname of this.context.getLocationHistoryPathnames()) {
765+
const viewItem = this.context.findViewItemByPathname(pathname, this.id);
766+
if (viewItem) {
767+
viewIds.add(viewItem.id);
768+
}
769+
}
770+
return viewIds;
771+
}
772+
773+
/**
774+
* When the leaving view renders no IonPage (a redirect, or a component that
775+
* navigates on mount), returns the page shown before it.
776+
*/
777+
private findPageBehindPagelessView(
778+
routeInfo: RouteInfo,
779+
enteringViewItem: ViewItem,
780+
leavingViewItem: ViewItem | undefined
781+
): ViewItem | undefined {
782+
if (
783+
!leavingViewItem ||
784+
leavingViewItem.ionPageElement ||
785+
!routeInfo.prevRouteLastPathname ||
786+
(routeInfo.routeAction !== 'push' && routeInfo.routeAction !== 'replace')
787+
) {
788+
return undefined;
789+
}
790+
791+
const isCandidate = (viewItem: ViewItem | undefined): viewItem is ViewItem =>
792+
!!viewItem &&
793+
viewItem !== enteringViewItem &&
794+
viewItem !== leavingViewItem &&
795+
viewItem.mount &&
796+
!!viewItem.ionPageElement;
797+
798+
const pageBehind = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
799+
if (isCandidate(pageBehind)) {
800+
return pageBehind;
801+
}
802+
803+
// In a chain of page-less redirects the previous pathname is another hop,
804+
// often already unmounted. The page the user was on is the one still
805+
// showing in this outlet.
806+
return this.context
807+
.getViewItemsForOutlet(this.id)
808+
.find(
809+
(viewItem) =>
810+
isCandidate(viewItem) &&
811+
isViewVisible(viewItem.ionPageElement!) &&
812+
!(viewItem.reactElement?.props?.path as string | undefined)?.endsWith('/*')
813+
);
814+
}
815+
816+
/**
817+
* Unmounts the page shown before a page-less view (a redirect, or a component
818+
* that navigates on mount) unless back can still reach it, since the replace
819+
* only unmounts the page-less view itself.
820+
*/
821+
private cleanupPageBehindPagelessView(routeInfo: RouteInfo, pageBehindPagelessView: ViewItem | undefined): void {
822+
if (routeInfo.routeAction !== 'replace') {
823+
return;
824+
}
825+
826+
if (!pageBehindPagelessView || this.getViewIdsInHistory().has(pageBehindPagelessView.id)) {
827+
return;
828+
}
829+
830+
// Container views (e.g. /tabs/*) host their own nested outlets; leave them alone.
831+
const pageBehindPagelessViewPath = pageBehindPagelessView.reactElement?.props?.path as string | undefined;
832+
if (pageBehindPagelessViewPath?.endsWith('/*')) {
833+
return;
834+
}
835+
836+
// No explicit hide: the transition already animates this page out, and
837+
// hiding it now would cut that animation short.
838+
this.scheduleViewUnmount(pageBehindPagelessView);
839+
}
840+
841+
/**
842+
* Cleans up orphaned sibling views after replace actions or push-to-container
843+
* navigations. A view that the location history still resolves to is
844+
* reachable with back, so it is kept.
762845
*/
763846
private cleanupOrphanedSiblingViews(
764847
routeInfo: RouteInfo,
@@ -770,20 +853,19 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
770853
return;
771854
}
772855

773-
const leavingRoutePath = leavingViewItem?.reactElement?.props?.path as string | undefined;
774-
const isContainerRoute = (path: string | undefined) => path?.endsWith('/*');
775-
776-
const isReplaceAction = routeInfo.routeAction === 'replace';
856+
// A push into a container (e.g. a menu link to /tabs/*) can leave behind
857+
// siblings that an earlier pop already took out of history
777858
const isPushToContainer =
778-
routeInfo.routeAction === 'push' && routeInfo.routeDirection === 'none' && isContainerRoute(enteringRoutePath);
779-
780-
if (!isReplaceAction && !isPushToContainer) {
859+
routeInfo.routeAction === 'push' && routeInfo.routeDirection === 'none' && enteringRoutePath.endsWith('/*');
860+
if (routeInfo.routeAction !== 'replace' && !isPushToContainer) {
781861
return;
782862
}
783863

864+
const leavingRoutePath = leavingViewItem?.reactElement?.props?.path as string | undefined;
865+
784866
// Skip cleanup for tab switches
785867
const isSameView = enteringViewItem === leavingViewItem;
786-
const isSameContainerRoute = isContainerRoute(enteringRoutePath) && leavingRoutePath === enteringRoutePath;
868+
const isSameContainerRoute = enteringRoutePath.endsWith('/*') && leavingRoutePath === enteringRoutePath;
787869
const isNavigatingWithinContainer =
788870
isPushToContainer &&
789871
!leavingViewItem &&
@@ -794,6 +876,11 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
794876
}
795877

796878
const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
879+
880+
// Views still in history are reachable with back, so they are not orphaned
881+
// even when they are siblings of the entering route.
882+
const viewIdsInHistory = this.getViewIdsInHistory();
883+
797884
const areSiblingRoutes = (path1: string, path2: string): boolean => {
798885
const path1IsRelative = !path1.startsWith('/');
799886
const path2IsRelative = !path2.startsWith('/');
@@ -835,6 +922,7 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
835922
(leavingViewItem && viewItem.id === leavingViewItem.id) ||
836923
!viewItem.mount ||
837924
!viewRoutePath ||
925+
viewIdsInHistory.has(viewItem.id) ||
838926
// Don't clean up container routes when entering a container route
839927
// (e.g., /tabs/* and /settings/* coexist for tab switching)
840928
(viewRoutePath.endsWith('/*') && enteringRoutePath.endsWith('/*'));
@@ -843,27 +931,11 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
843931
continue;
844932
}
845933

846-
const isOrphanedSpecificRoute = !viewRoutePath.endsWith('/*');
847-
848934
// Clean up sibling non-container routes that are no longer reachable.
849-
let shouldCleanup = false;
850-
if ((isReplaceAction || isPushToContainer) && isOrphanedSpecificRoute) {
851-
shouldCleanup = areSiblingRoutes(enteringRoutePath, viewRoutePath);
852-
}
853-
854-
if (shouldCleanup) {
935+
const isSpecificRoute = !viewRoutePath.endsWith('/*');
936+
if (isSpecificRoute && areSiblingRoutes(enteringRoutePath, viewRoutePath)) {
855937
hideIonPageElement(viewItem.ionPageElement);
856-
viewItem.mount = false;
857-
858-
const viewToRemove = viewItem;
859-
setTimeout(() => {
860-
// Skip if a follow-up transition re-entered the view (mount flipped back to true).
861-
if (viewToRemove.mount) {
862-
return;
863-
}
864-
this.context.unMountViewItem(viewToRemove);
865-
this.forceUpdate();
866-
}, VIEW_UNMOUNT_DELAY_MS);
938+
this.scheduleViewUnmount(viewItem);
867939
}
868940
}
869941
}

‎packages/react-router/test/base/src/App.tsx‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,16 @@ import DisabledButton from './pages/disabled-button/DisabledButton';
6363
import SplatSibling from './pages/splat-sibling/SplatSibling';
6464
import StaleRegister from './pages/stale-register/StaleRegister';
6565
import { EmptyPathSibling, IndexSibling } from './pages/index-sibling/IndexSibling';
66+
import {
67+
ReplaceSiblingDetail,
68+
ReplaceSiblingGateTarget,
69+
ReplaceSiblingHome,
70+
ReplaceSiblingHop,
71+
ReplaceSiblingLessonContent,
72+
ReplaceSiblingLessonQuiz,
73+
ReplaceSiblingList,
74+
ReplaceSiblingNew,
75+
} from './pages/replace-sibling/ReplaceSibling';
6676

6777
const App: React.FC = () => {
6878
return (
@@ -141,6 +151,18 @@ const App: React.FC = () => {
141151
/>
142152
<Route path="/index-sibling/*" element={<IndexSibling />} />
143153
<Route path="/empty-path-sibling/*" element={<EmptyPathSibling />} />
154+
<Route path="/replace-sibling/home" element={<ReplaceSiblingHome />} />
155+
<Route path="/replace-sibling/detail" element={<ReplaceSiblingDetail />} />
156+
<Route path="/replace-sibling/new" element={<ReplaceSiblingNew />} />
157+
<Route path="/replace-sibling/list" element={<ReplaceSiblingList />} />
158+
<Route path="/replace-sibling-redirect" element={<Navigate to="/replace-sibling/list" replace />} />
159+
<Route path="/replace-sibling/hop1" element={<ReplaceSiblingHop to="/replace-sibling/hop2" />} />
160+
<Route path="/replace-sibling/hop2" element={<ReplaceSiblingHop to="/replace-sibling/list" />} />
161+
{/* Outside /replace-sibling so Home isn't a sibling of the target and only the page-less view cleanup can unmount it */}
162+
<Route path="/replace-sibling-gate" element={<ReplaceSiblingHop to="/replace-sibling-gate/target" />} />
163+
<Route path="/replace-sibling-gate/target" element={<ReplaceSiblingGateTarget />} />
164+
<Route path="/replace-sibling/lesson/:lessonId/content" element={<ReplaceSiblingLessonContent />} />
165+
<Route path="/replace-sibling/lesson/:lessonId/quiz/:questionId" element={<ReplaceSiblingLessonQuiz />} />
144166
</IonRouterOutlet>
145167
</IonReactRouter>
146168
</IonApp>

‎packages/react-router/test/base/src/pages/Main.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,9 @@ const Main: React.FC = () => {
175175
<IonItem routerLink="/empty-path-sibling">
176176
<IonLabel>Empty Path Sibling</IonLabel>
177177
</IonItem>
178+
<IonItem routerLink="/replace-sibling/home">
179+
<IonLabel>Replace Sibling</IonLabel>
180+
</IonItem>
178181
{/* A separate React root, so a plain href rather than a routerLink. */}
179182
<IonItem href={`${ROOT_SPLAT_SIBLING_BASENAME}/feed`}>
180183
<IonLabel>Root Splat Sibling</IonLabel>

‎packages/react-router/test/base/src/pages/replace-params/ReplaceParams.tsx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
IonButton,
88
IonButtons,
99
IonBackButton,
10+
useIonRouter,
1011
} from '@ionic/react';
1112
import React, { useState } from 'react';
1213
import { useNavigate, useParams } from 'react-router-dom';
@@ -47,7 +48,7 @@ const Step1: React.FC = () => {
4748
>
4849
Replace to Step 2 (second)
4950
</IonButton>
50-
<TestDescription>Tap "Replace to Step 2 (first)" -&gt; "Replace to Step 3" -&gt; "Push to Step 4" -&gt; go back to Step 1. Then repeat with "second". On the second visit to Step 3, it should show the "second" param and a different mount ID, confirming the old view was cleaned up from the DOM (issue #25640).</TestDescription>
51+
<TestDescription>Tap "Replace to Step 2 (first)" -&gt; "Replace to Step 3" -&gt; "Push to Step 4" -&gt; go back to Step 1. Then repeat with "second". On the second visit to Step 3, it should show the "second" param and a different mount ID, confirming the old view was cleaned up from the DOM (issue #25640). With "Push to Step 1" instead, the first Step 3 stays in history, so it should stay hidden while the new one shows "second".</TestDescription>
5152
</IonContent>
5253
</IonPage>
5354
);
@@ -104,6 +105,7 @@ const Step3: React.FC = () => {
104105
};
105106

106107
const Step4: React.FC = () => {
108+
const router = useIonRouter();
107109
const navigate = useNavigate();
108110
const { id } = useParams<{ id: string }>();
109111

@@ -121,10 +123,14 @@ const Step4: React.FC = () => {
121123
<p data-testid="step4-param">{id}</p>
122124
<IonButton
123125
id="go-to-step1"
124-
onClick={() => navigate('/replace-params/step1')}
126+
// Pop back to step1, as the header's flow describes
127+
onClick={() => router.push('/replace-params/step1', 'back', 'pop')}
125128
>
126129
Go to Step 1
127130
</IonButton>
131+
<IonButton id="push-to-step1" onClick={() => navigate('/replace-params/step1')}>
132+
Push to Step 1
133+
</IonButton>
128134
</IonContent>
129135
</IonPage>
130136
);

0 commit comments

Comments
 (0)