@ionic/react-router 8.7.12 → 8.7.13-dev.11765426479.16a61ecf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,176 +1,1074 @@
1
1
  import { __rest } from 'tslib';
2
- import { createBrowserHistory, createHashHistory } from 'history';
3
- import React from 'react';
4
- import { withRouter, Router } from 'react-router-dom';
5
- import { ViewStacks, generateId, IonRoute, ViewLifeCycleManager, StackContext, RouteManagerContext, getConfig, LocationHistory, NavManager } from '@ionic/react';
6
- import { Route, matchPath as matchPath$1, Router as Router$1 } from 'react-router';
2
+ import React, { useRef, useState, useEffect, useCallback } from 'react';
3
+ import { Route, matchPath as matchPath$1, Routes, Navigate, UNSAFE_RouteContext, useLocation, useNavigate, BrowserRouter, useNavigationType, HashRouter } from 'react-router-dom';
4
+ import { ViewStacks, IonRoute, ViewLifeCycleManager, generateId, StackContext, RouteManagerContext, getConfig, LocationHistory, NavManager } from '@ionic/react';
5
+ import { MemoryRouter, useLocation as useLocation$1, useNavigationType as useNavigationType$1 } from 'react-router';
7
6
 
8
- class IonRouteInner extends React.PureComponent {
9
- render() {
10
- return (React.createElement(Route, Object.assign({ path: this.props.path, exact: this.props.exact, render: this.props.render }, (this.props.computedMatch !== undefined
11
- ? {
12
- computedMatch: this.props.computedMatch,
7
+ const IonRouteInner = ({ path, element }) => {
8
+ return React.createElement(Route, { path: path, element: element });
9
+ };
10
+
11
+ /**
12
+ * The matchPath function is used only for matching paths, not rendering components or elements.
13
+ * @see https://reactrouter.com/v6/utils/match-path
14
+ */
15
+ const matchPath = ({ pathname, componentProps }) => {
16
+ const { path, index } = componentProps, restProps = __rest(componentProps, ["path", "index"]);
17
+ // Handle index routes
18
+ if (index && !path) {
19
+ // Index routes match when there's no additional path after the parent route
20
+ // For example, in a nested outlet at /routing/*, the index route matches
21
+ // when the relative path is empty (i.e., we're exactly at /routing)
22
+ // If pathname is empty or just "/", it should match the index route
23
+ if (pathname === '' || pathname === '/') {
24
+ return {
25
+ params: {},
26
+ pathname: pathname,
27
+ pathnameBase: pathname || '/',
28
+ pattern: {
29
+ path: '',
30
+ caseSensitive: false,
31
+ end: true,
32
+ },
33
+ };
34
+ }
35
+ // Otherwise, index routes don't match when there's additional path
36
+ return null;
37
+ }
38
+ if (!path) {
39
+ return null;
40
+ }
41
+ // For relative paths in nested routes (those that don't start with '/'),
42
+ // use React Router's matcher against a normalized path.
43
+ if (!path.startsWith('/')) {
44
+ const matchOptions = Object.assign({ path: `/${path}` }, restProps);
45
+ if ((matchOptions === null || matchOptions === void 0 ? void 0 : matchOptions.end) === undefined) {
46
+ matchOptions.end = !path.endsWith('*');
47
+ }
48
+ const normalizedPathname = pathname.startsWith('/') ? pathname : `/${pathname}`;
49
+ const match = matchPath$1(matchOptions, normalizedPathname);
50
+ if (match) {
51
+ // Adjust the match to remove the leading '/' we added
52
+ return Object.assign(Object.assign({}, match), { pathname: pathname, pathnameBase: match.pathnameBase === '/' ? '' : match.pathnameBase.slice(1), pattern: Object.assign(Object.assign({}, match.pattern), { path: path }) });
53
+ }
54
+ // No match found
55
+ return null;
56
+ }
57
+ // For absolute paths, use React Router's matcher directly.
58
+ // React Router v6 routes default to `end: true` unless the pattern
59
+ // explicitly opts into wildcards with `*`. Mirror that behaviour so
60
+ // matching parity stays aligned with <Route>.
61
+ const matchOptions = Object.assign({ path }, restProps);
62
+ if ((matchOptions === null || matchOptions === void 0 ? void 0 : matchOptions.end) === undefined) {
63
+ matchOptions.end = !path.endsWith('*');
64
+ }
65
+ return matchPath$1(matchOptions, pathname);
66
+ };
67
+ /**
68
+ * Determines the portion of a pathname that a given route pattern should match against.
69
+ * For absolute route patterns we return the full pathname. For relative patterns we
70
+ * strip off the already-matched parent segments so React Router receives the remainder.
71
+ */
72
+ const derivePathnameToMatch = (fullPathname, routePath) => {
73
+ var _a;
74
+ if (!routePath || routePath === '' || routePath.startsWith('/')) {
75
+ return fullPathname;
76
+ }
77
+ const trimmedPath = fullPathname.startsWith('/') ? fullPathname.slice(1) : fullPathname;
78
+ if (!trimmedPath) {
79
+ return '';
80
+ }
81
+ const fullSegments = trimmedPath.split('/').filter(Boolean);
82
+ if (fullSegments.length === 0) {
83
+ return '';
84
+ }
85
+ const routeSegments = routePath.split('/').filter(Boolean);
86
+ if (routeSegments.length === 0) {
87
+ return trimmedPath;
88
+ }
89
+ const wildcardIndex = routeSegments.findIndex((segment) => segment === '*' || segment === '**');
90
+ if (wildcardIndex >= 0) {
91
+ const baseSegments = routeSegments.slice(0, wildcardIndex);
92
+ if (baseSegments.length === 0) {
93
+ return trimmedPath;
94
+ }
95
+ const startIndex = fullSegments.findIndex((_, idx) => baseSegments.every((seg, segIdx) => {
96
+ const target = fullSegments[idx + segIdx];
97
+ if (!target) {
98
+ return false;
13
99
  }
14
- : {}))));
100
+ if (seg.startsWith(':')) {
101
+ return true;
102
+ }
103
+ return target === seg;
104
+ }));
105
+ if (startIndex >= 0) {
106
+ return fullSegments.slice(startIndex).join('/');
107
+ }
15
108
  }
16
- }
109
+ if (routeSegments.length <= fullSegments.length) {
110
+ return fullSegments.slice(fullSegments.length - routeSegments.length).join('/');
111
+ }
112
+ return (_a = fullSegments[fullSegments.length - 1]) !== null && _a !== void 0 ? _a : trimmedPath;
113
+ };
17
114
 
18
115
  /**
19
- * @see https://v5.reactrouter.com/web/api/matchPath
116
+ * Finds the longest common prefix among an array of paths.
117
+ * Used to determine the scope of an outlet with absolute routes.
118
+ *
119
+ * @param paths An array of absolute path strings.
120
+ * @returns The common prefix shared by all paths.
20
121
  */
21
- const matchPath = ({ pathname, componentProps, }) => {
22
- const { exact, component } = componentProps;
23
- const path = componentProps.path || componentProps.from;
24
- /***
25
- * The props to match against, they are identical
26
- * to the matching props `Route` accepts. It could also be a string
27
- * or an array of strings as shortcut for `{ path }`.
28
- */
29
- const matchProps = {
30
- exact,
31
- path,
32
- component,
33
- };
34
- const match = matchPath$1(pathname, matchProps);
35
- if (!match) {
122
+ const computeCommonPrefix = (paths) => {
123
+ if (paths.length === 0)
124
+ return '';
125
+ if (paths.length === 1) {
126
+ // For a single path, extract the directory-like prefix
127
+ // e.g., /dynamic-routes/home -> /dynamic-routes
128
+ const segments = paths[0].split('/').filter(Boolean);
129
+ if (segments.length > 1) {
130
+ return '/' + segments.slice(0, -1).join('/');
131
+ }
132
+ return '/' + segments[0];
133
+ }
134
+ // Split all paths into segments
135
+ const segmentArrays = paths.map((p) => p.split('/').filter(Boolean));
136
+ const minLength = Math.min(...segmentArrays.map((s) => s.length));
137
+ const commonSegments = [];
138
+ for (let i = 0; i < minLength; i++) {
139
+ const segment = segmentArrays[0][i];
140
+ // Skip segments with route parameters or wildcards
141
+ if (segment.includes(':') || segment.includes('*')) {
142
+ break;
143
+ }
144
+ const allMatch = segmentArrays.every((s) => s[i] === segment);
145
+ if (allMatch) {
146
+ commonSegments.push(segment);
147
+ }
148
+ else {
149
+ break;
150
+ }
151
+ }
152
+ return commonSegments.length > 0 ? '/' + commonSegments.join('/') : '';
153
+ };
154
+ /**
155
+ * Checks if a route is a specific match (not wildcard or index).
156
+ *
157
+ * @param route The route element to check.
158
+ * @param remainingPath The remaining path to match against.
159
+ * @returns True if the route specifically matches the remaining path.
160
+ */
161
+ const isSpecificRouteMatch = (route, remainingPath) => {
162
+ const routePath = route.props.path;
163
+ const isWildcardOnly = routePath === '*' || routePath === '/*';
164
+ const isIndex = route.props.index;
165
+ // Skip wildcards and index routes
166
+ if (isIndex || isWildcardOnly) {
36
167
  return false;
37
168
  }
38
- return match;
169
+ return !!matchPath({
170
+ pathname: remainingPath,
171
+ componentProps: route.props,
172
+ });
173
+ };
174
+ /**
175
+ * Analyzes route children to determine their characteristics.
176
+ *
177
+ * @param routeChildren The route children to analyze.
178
+ * @returns Analysis of the route characteristics.
179
+ */
180
+ const analyzeRouteChildren = (routeChildren) => {
181
+ const hasRelativeRoutes = routeChildren.some((route) => {
182
+ const path = route.props.path;
183
+ return path && !path.startsWith('/') && path !== '*';
184
+ });
185
+ const hasIndexRoute = routeChildren.some((route) => route.props.index);
186
+ const hasWildcardRoute = routeChildren.some((route) => {
187
+ const routePath = route.props.path;
188
+ return routePath === '*' || routePath === '/*';
189
+ });
190
+ return { hasRelativeRoutes, hasIndexRoute, hasWildcardRoute, routeChildren };
191
+ };
192
+ /**
193
+ * Computes the parent path for a nested outlet based on the current pathname
194
+ * and the outlet's route configuration.
195
+ *
196
+ * The algorithm finds the shortest parent path where a route matches the remaining path.
197
+ * Priority: specific routes > wildcard routes > index routes (only at mount point)
198
+ *
199
+ * @param options The options for computing the parent path.
200
+ * @returns The computed parent path result.
201
+ */
202
+ const computeParentPath = (options) => {
203
+ const { currentPathname, outletMountPath, routeChildren, hasRelativeRoutes, hasIndexRoute, hasWildcardRoute } = options;
204
+ // If this outlet previously established a mount path and the current
205
+ // pathname is outside of that scope, do not attempt to re-compute a new
206
+ // parent path.
207
+ if (outletMountPath && !currentPathname.startsWith(outletMountPath)) {
208
+ return { parentPath: undefined, outletMountPath };
209
+ }
210
+ if ((hasRelativeRoutes || hasIndexRoute) && currentPathname.includes('/')) {
211
+ const segments = currentPathname.split('/').filter(Boolean);
212
+ if (segments.length >= 1) {
213
+ // Find matches at each level, keeping track of the FIRST (shortest) match
214
+ let firstSpecificMatch = undefined;
215
+ let firstWildcardMatch = undefined;
216
+ let indexMatchAtMount = undefined;
217
+ for (let i = 1; i <= segments.length; i++) {
218
+ const parentPath = '/' + segments.slice(0, i).join('/');
219
+ const remainingPath = segments.slice(i).join('/');
220
+ // Check for specific (non-wildcard, non-index) route matches
221
+ const hasSpecificMatch = routeChildren.some((route) => isSpecificRouteMatch(route, remainingPath));
222
+ if (hasSpecificMatch && !firstSpecificMatch) {
223
+ firstSpecificMatch = parentPath;
224
+ // Found a specific match - this is our answer for non-index routes
225
+ break;
226
+ }
227
+ // Check if wildcard would match this remaining path
228
+ // Only if remaining is non-empty (wildcard needs something to match)
229
+ if (remainingPath !== '' && remainingPath !== '/' && hasWildcardRoute && !firstWildcardMatch) {
230
+ // Check if any specific route could plausibly match this remaining path
231
+ const remainingFirstSegment = remainingPath.split('/')[0];
232
+ const couldAnyRouteMatch = routeChildren.some((route) => {
233
+ const routePath = route.props.path;
234
+ if (!routePath || routePath === '*' || routePath === '/*')
235
+ return false;
236
+ if (route.props.index)
237
+ return false;
238
+ const routeFirstSegment = routePath.split('/')[0].replace(/[*:]/g, '');
239
+ if (!routeFirstSegment)
240
+ return false;
241
+ // Check for prefix overlap (either direction)
242
+ return (routeFirstSegment.startsWith(remainingFirstSegment.slice(0, 3)) ||
243
+ remainingFirstSegment.startsWith(routeFirstSegment.slice(0, 3)));
244
+ });
245
+ // Only save wildcard match if no specific route could match
246
+ if (!couldAnyRouteMatch) {
247
+ firstWildcardMatch = parentPath;
248
+ // Continue looking - might find a specific match at a longer path
249
+ }
250
+ }
251
+ // Check for index route match when remaining path is empty
252
+ // BUT only at the outlet's mount path level
253
+ if ((remainingPath === '' || remainingPath === '/') && hasIndexRoute) {
254
+ // Index route matches when current path exactly matches the mount path
255
+ // If we already have an outletMountPath, index should only match there
256
+ if (outletMountPath) {
257
+ if (parentPath === outletMountPath) {
258
+ indexMatchAtMount = parentPath;
259
+ }
260
+ }
261
+ else {
262
+ // No mount path set yet - index would establish this as mount path
263
+ // But only if we haven't found a better match
264
+ indexMatchAtMount = parentPath;
265
+ }
266
+ }
267
+ }
268
+ // Determine the best parent path:
269
+ // 1. Specific match (routes like tabs/*, favorites) - highest priority
270
+ // 2. Wildcard match (route path="*") - catches unmatched segments
271
+ // 3. Index match - only valid at the outlet's mount point, not deeper
272
+ let bestPath = undefined;
273
+ if (firstSpecificMatch) {
274
+ bestPath = firstSpecificMatch;
275
+ }
276
+ else if (firstWildcardMatch) {
277
+ bestPath = firstWildcardMatch;
278
+ }
279
+ else if (indexMatchAtMount) {
280
+ // Only use index match if no specific or wildcard matched
281
+ // This handles the case where pathname exactly matches the mount path
282
+ bestPath = indexMatchAtMount;
283
+ }
284
+ // Store the mount path when we first successfully match a route
285
+ let newOutletMountPath = outletMountPath;
286
+ if (!outletMountPath && bestPath) {
287
+ newOutletMountPath = bestPath;
288
+ }
289
+ // If we have a mount path, verify the current pathname is within scope
290
+ if (newOutletMountPath && !currentPathname.startsWith(newOutletMountPath)) {
291
+ return { parentPath: undefined, outletMountPath: newOutletMountPath };
292
+ }
293
+ return { parentPath: bestPath, outletMountPath: newOutletMountPath };
294
+ }
295
+ }
296
+ // Handle outlets with ONLY absolute routes (no relative routes or index routes)
297
+ // Compute the common prefix of all absolute routes to determine the outlet's scope
298
+ if (!hasRelativeRoutes && !hasIndexRoute) {
299
+ const absolutePathRoutes = routeChildren.filter((route) => {
300
+ const path = route.props.path;
301
+ return path && path.startsWith('/');
302
+ });
303
+ if (absolutePathRoutes.length > 0) {
304
+ const absolutePaths = absolutePathRoutes.map((r) => r.props.path);
305
+ const commonPrefix = computeCommonPrefix(absolutePaths);
306
+ if (commonPrefix && commonPrefix !== '/') {
307
+ // Set the mount path based on common prefix of absolute routes
308
+ const newOutletMountPath = outletMountPath || commonPrefix;
309
+ // Check if current pathname is within scope
310
+ if (!currentPathname.startsWith(commonPrefix)) {
311
+ return { parentPath: undefined, outletMountPath: newOutletMountPath };
312
+ }
313
+ return { parentPath: commonPrefix, outletMountPath: newOutletMountPath };
314
+ }
315
+ }
316
+ }
317
+ return { parentPath: outletMountPath, outletMountPath };
318
+ };
319
+
320
+ /**
321
+ * Ensures the given path has a leading slash.
322
+ *
323
+ * @param value The path string to normalize.
324
+ * @returns The path with a leading slash.
325
+ */
326
+ const ensureLeadingSlash = (value) => {
327
+ if (value === '') {
328
+ return '/';
329
+ }
330
+ return value.startsWith('/') ? value : `/${value}`;
331
+ };
332
+ /**
333
+ * Strips the trailing slash from a path, unless it's the root path.
334
+ *
335
+ * @param value The path string to normalize.
336
+ * @returns The path without a trailing slash.
337
+ */
338
+ const stripTrailingSlash = (value) => {
339
+ return value.length > 1 && value.endsWith('/') ? value.slice(0, -1) : value;
340
+ };
341
+ /**
342
+ * Normalizes a pathname for comparison by ensuring a leading slash
343
+ * and removing trailing slashes.
344
+ *
345
+ * @param value The pathname to normalize, can be undefined.
346
+ * @returns A normalized pathname string.
347
+ */
348
+ const normalizePathnameForComparison = (value) => {
349
+ if (!value || value === '') {
350
+ return '/';
351
+ }
352
+ const withLeadingSlash = ensureLeadingSlash(value);
353
+ return stripTrailingSlash(withLeadingSlash);
354
+ };
355
+
356
+ /**
357
+ * Extracts the children from a Routes wrapper component.
358
+ * The use of `<Routes />` is encouraged with React Router v6.
359
+ *
360
+ * @param node The React node to extract Routes children from.
361
+ * @returns The children of the Routes component, or undefined if not found.
362
+ */
363
+ const getRoutesChildren = (node) => {
364
+ let routesNode;
365
+ React.Children.forEach(node, (child) => {
366
+ if (child.type === Routes) {
367
+ routesNode = child;
368
+ }
369
+ });
370
+ if (routesNode) {
371
+ // The children of the `<Routes />` component are most likely
372
+ // (and should be) the `<Route />` components.
373
+ return routesNode.props.children;
374
+ }
375
+ return undefined;
376
+ };
377
+ /**
378
+ * Extracts Route children from a node (either directly or from a Routes wrapper).
379
+ *
380
+ * @param children The children to extract routes from.
381
+ * @returns An array of Route elements.
382
+ */
383
+ const extractRouteChildren = (children) => {
384
+ var _a;
385
+ const routesChildren = (_a = getRoutesChildren(children)) !== null && _a !== void 0 ? _a : children;
386
+ return React.Children.toArray(routesChildren).filter((child) => React.isValidElement(child) && child.type === Route);
387
+ };
388
+ /**
389
+ * Checks if a React element is a Navigate component (redirect).
390
+ *
391
+ * @param element The element to check.
392
+ * @returns True if the element is a Navigate component.
393
+ */
394
+ const isNavigateElement = (element) => {
395
+ return (React.isValidElement(element) &&
396
+ (element.type === Navigate || (typeof element.type === 'function' && element.type.name === 'Navigate')));
397
+ };
398
+
399
+ /**
400
+ * Sorts view items by route specificity (most specific first).
401
+ * - Exact matches (no wildcards/params) come first
402
+ * - Among wildcard routes, longer paths are more specific
403
+ *
404
+ * @param views The view items to sort.
405
+ * @returns A new sorted array of view items.
406
+ */
407
+ const sortViewsBySpecificity = (views) => {
408
+ return [...views].sort((a, b) => {
409
+ var _a, _b, _c, _d;
410
+ const pathA = ((_b = (_a = a.routeData) === null || _a === void 0 ? void 0 : _a.childProps) === null || _b === void 0 ? void 0 : _b.path) || '';
411
+ const pathB = ((_d = (_c = b.routeData) === null || _c === void 0 ? void 0 : _c.childProps) === null || _d === void 0 ? void 0 : _d.path) || '';
412
+ // Exact matches (no wildcards/params) come first
413
+ const aHasWildcard = pathA.includes('*') || pathA.includes(':');
414
+ const bHasWildcard = pathB.includes('*') || pathB.includes(':');
415
+ if (!aHasWildcard && bHasWildcard)
416
+ return -1;
417
+ if (aHasWildcard && !bHasWildcard)
418
+ return 1;
419
+ // Among wildcard routes, longer paths are more specific
420
+ return pathB.length - pathA.length;
421
+ });
39
422
  };
40
423
 
424
+ /**
425
+ * `ReactRouterViewStack` is a custom navigation manager used in Ionic React
426
+ * apps to map React Router route elements (such as `<IonRoute>`) to "view
427
+ * items" that Ionic can manage in a view stack. This is critical to maintain
428
+ * Ionic’s animation, lifecycle, and history behavior across views.
429
+ */
430
+ /**
431
+ * Delay in milliseconds before removing a Navigate view item after a redirect.
432
+ * This ensures the redirect navigation completes before the view is removed.
433
+ */
434
+ const NAVIGATE_REDIRECT_DELAY_MS = 100;
435
+ /**
436
+ * Delay in milliseconds before cleaning up a view without an IonPage element.
437
+ * This double-checks that the view is truly not needed before removal.
438
+ */
439
+ const VIEW_CLEANUP_DELAY_MS = 200;
440
+ const createDefaultMatch = (fullPathname, routeProps) => {
441
+ var _a, _b;
442
+ const isIndexRoute = !!routeProps.index;
443
+ const patternPath = (_a = routeProps.path) !== null && _a !== void 0 ? _a : '';
444
+ const pathnameBase = fullPathname === '' ? '/' : fullPathname;
445
+ const computedEnd = routeProps.end !== undefined ? routeProps.end : patternPath !== '' ? !patternPath.endsWith('*') : true;
446
+ return {
447
+ params: {},
448
+ pathname: isIndexRoute ? '' : fullPathname,
449
+ pathnameBase,
450
+ pattern: {
451
+ path: patternPath,
452
+ caseSensitive: (_b = routeProps.caseSensitive) !== null && _b !== void 0 ? _b : false,
453
+ end: isIndexRoute ? true : computedEnd,
454
+ },
455
+ };
456
+ };
457
+ const computeRelativeToParent = (pathname, parentPath) => {
458
+ if (!parentPath)
459
+ return null;
460
+ const normalizedParent = normalizePathnameForComparison(parentPath);
461
+ const normalizedPathname = normalizePathnameForComparison(pathname);
462
+ if (normalizedPathname === normalizedParent) {
463
+ return '';
464
+ }
465
+ const withSlash = normalizedParent === '/' ? '/' : normalizedParent + '/';
466
+ if (normalizedPathname.startsWith(withSlash)) {
467
+ return normalizedPathname.slice(withSlash.length);
468
+ }
469
+ return null;
470
+ };
471
+ const resolveIndexRouteMatch = (viewItem, pathname, parentPath) => {
472
+ var _a, _b, _c;
473
+ if (!((_b = (_a = viewItem.routeData) === null || _a === void 0 ? void 0 : _a.childProps) === null || _b === void 0 ? void 0 : _b.index)) {
474
+ return null;
475
+ }
476
+ // Prefer computing against the parent path when available to align with RRv6 semantics
477
+ const relative = computeRelativeToParent(pathname, parentPath);
478
+ if (relative !== null) {
479
+ // Index routes match only when there is no remaining path
480
+ if (relative === '' || relative === '/') {
481
+ return createDefaultMatch(parentPath || pathname, viewItem.routeData.childProps);
482
+ }
483
+ return null;
484
+ }
485
+ // Fallback: use previously computed match base for equality check
486
+ const previousMatch = (_c = viewItem.routeData) === null || _c === void 0 ? void 0 : _c.match;
487
+ if (!previousMatch) {
488
+ return null;
489
+ }
490
+ const normalizedPathname = normalizePathnameForComparison(pathname);
491
+ const normalizedBase = normalizePathnameForComparison(previousMatch.pathnameBase || previousMatch.pathname || '');
492
+ return normalizedPathname === normalizedBase ? previousMatch : null;
493
+ };
41
494
  class ReactRouterViewStack extends ViewStacks {
42
495
  constructor() {
43
496
  super();
44
- this.createViewItem = this.createViewItem.bind(this);
45
- this.findViewItemByRouteInfo = this.findViewItemByRouteInfo.bind(this);
46
- this.findLeavingViewItemByRouteInfo = this.findLeavingViewItemByRouteInfo.bind(this);
47
- this.getChildrenToRender = this.getChildrenToRender.bind(this);
48
- this.findViewItemByPathname = this.findViewItemByPathname.bind(this);
49
- }
50
- createViewItem(outletId, reactElement, routeInfo, page) {
51
- const viewItem = {
52
- id: generateId('viewItem'),
53
- outletId,
54
- ionPageElement: page,
55
- reactElement,
56
- mount: true,
57
- ionRoute: false,
58
- };
59
- if (reactElement.type === IonRoute) {
60
- viewItem.ionRoute = true;
61
- viewItem.disableIonPageManagement = reactElement.props.disableIonPageManagement;
62
- }
63
- viewItem.routeData = {
64
- match: matchPath({
65
- pathname: routeInfo.pathname,
66
- componentProps: reactElement.props,
67
- }),
68
- childProps: reactElement.props,
69
- };
70
- return viewItem;
71
- }
72
- getChildrenToRender(outletId, ionRouterOutlet, routeInfo) {
73
- const viewItems = this.getViewItemsForOutlet(outletId);
74
- // Sync latest routes with viewItems
75
- React.Children.forEach(ionRouterOutlet.props.children, (child) => {
76
- const viewItem = viewItems.find((v) => {
77
- return matchComponent$1(child, v.routeData.childProps.path || v.routeData.childProps.from);
497
+ this.viewItemCounter = 0;
498
+ /**
499
+ * Creates a new view item for the given outlet and react route element.
500
+ * Associates route props with the matched route path for further lookups.
501
+ */
502
+ this.createViewItem = (outletId, reactElement, routeInfo, page) => {
503
+ var _a, _b;
504
+ const routePath = reactElement.props.path || '';
505
+ // Check if we already have a view item for this exact route that we can reuse
506
+ // Include wildcard routes like tabs/* since they should be reused
507
+ // Also check unmounted items that might have been preserved for browser navigation
508
+ const existingViewItem = this.getViewItemsForOutlet(outletId).find((v) => {
509
+ var _a, _b, _c, _d, _e, _f, _g, _h;
510
+ const existingRouteProps = (_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) !== null && _b !== void 0 ? _b : {};
511
+ const existingPath = existingRouteProps.path || '';
512
+ const existingElement = existingRouteProps.element;
513
+ const newElement = reactElement.props.element;
514
+ const existingIsIndexRoute = !!existingRouteProps.index;
515
+ const newIsIndexRoute = !!reactElement.props.index;
516
+ // For Navigate components, match by destination
517
+ const existingIsNavigate = React.isValidElement(existingElement) && existingElement.type === Navigate;
518
+ const newIsNavigate = React.isValidElement(newElement) && newElement.type === Navigate;
519
+ if (existingIsNavigate && newIsNavigate) {
520
+ const existingTo = (_c = existingElement.props) === null || _c === void 0 ? void 0 : _c.to;
521
+ const newTo = (_d = newElement.props) === null || _d === void 0 ? void 0 : _d.to;
522
+ if (existingTo === newTo) {
523
+ return true;
524
+ }
525
+ }
526
+ if (existingIsIndexRoute && newIsIndexRoute) {
527
+ return true;
528
+ }
529
+ // Reuse view items with the same path
530
+ // Special case: reuse tabs/* and other specific wildcard routes
531
+ // Don't reuse index routes (empty path) or generic catch-all wildcards (*)
532
+ if (existingPath === routePath && existingPath !== '' && existingPath !== '*') {
533
+ // Parameterized routes need pathname matching to ensure /details/1 and /details/2
534
+ // get separate view items. For wildcard routes (e.g., user/:userId/*), compare
535
+ // pathnameBase to allow child path changes while preserving the parent view.
536
+ const hasParams = routePath.includes(':');
537
+ const isWildcard = routePath.includes('*');
538
+ if (hasParams) {
539
+ if (isWildcard) {
540
+ const existingPathnameBase = (_f = (_e = v.routeData) === null || _e === void 0 ? void 0 : _e.match) === null || _f === void 0 ? void 0 : _f.pathnameBase;
541
+ const newMatch = matchComponent$1(reactElement, routeInfo.pathname, false);
542
+ const newPathnameBase = newMatch === null || newMatch === void 0 ? void 0 : newMatch.pathnameBase;
543
+ if (existingPathnameBase !== newPathnameBase) {
544
+ return false;
545
+ }
546
+ }
547
+ else {
548
+ const existingPathname = (_h = (_g = v.routeData) === null || _g === void 0 ? void 0 : _g.match) === null || _h === void 0 ? void 0 : _h.pathname;
549
+ if (existingPathname !== routeInfo.pathname) {
550
+ return false;
551
+ }
552
+ }
553
+ }
554
+ return true;
555
+ }
556
+ // Also reuse specific wildcard routes like tabs/*
557
+ if (existingPath === routePath && existingPath.endsWith('/*') && existingPath !== '/*') {
558
+ return true;
559
+ }
560
+ return false;
78
561
  });
79
- if (viewItem) {
80
- viewItem.reactElement = child;
562
+ if (existingViewItem) {
563
+ // Update and ensure the existing view item is properly configured
564
+ existingViewItem.reactElement = reactElement;
565
+ existingViewItem.mount = true;
566
+ existingViewItem.ionPageElement = page || existingViewItem.ionPageElement;
567
+ const updatedMatch = matchComponent$1(reactElement, routeInfo.pathname, false) ||
568
+ ((_a = existingViewItem.routeData) === null || _a === void 0 ? void 0 : _a.match) ||
569
+ createDefaultMatch(routeInfo.pathname, reactElement.props);
570
+ existingViewItem.routeData = {
571
+ match: updatedMatch,
572
+ childProps: reactElement.props,
573
+ lastPathname: (_b = existingViewItem.routeData) === null || _b === void 0 ? void 0 : _b.lastPathname, // Preserve navigation history
574
+ };
575
+ return existingViewItem;
81
576
  }
82
- });
83
- const children = viewItems.map((viewItem) => {
84
- let clonedChild;
85
- if (viewItem.ionRoute && !viewItem.disableIonPageManagement) {
86
- clonedChild = (React.createElement(ViewLifeCycleManager, { key: `view-${viewItem.id}`, mount: viewItem.mount, removeView: () => this.remove(viewItem) }, React.cloneElement(viewItem.reactElement, {
87
- computedMatch: viewItem.routeData.match,
88
- })));
577
+ this.viewItemCounter++;
578
+ const id = `${outletId}-${this.viewItemCounter}`;
579
+ const viewItem = {
580
+ id,
581
+ outletId,
582
+ ionPageElement: page,
583
+ reactElement,
584
+ mount: true,
585
+ ionRoute: true,
586
+ };
587
+ if (reactElement.type === IonRoute) {
588
+ viewItem.disableIonPageManagement = reactElement.props.disableIonPageManagement;
89
589
  }
90
- else {
91
- const match = matchComponent$1(viewItem.reactElement, routeInfo.pathname);
92
- clonedChild = (React.createElement(ViewLifeCycleManager, { key: `view-${viewItem.id}`, mount: viewItem.mount, removeView: () => this.remove(viewItem) }, React.cloneElement(viewItem.reactElement, {
93
- computedMatch: viewItem.routeData.match,
94
- })));
95
- if (!match && viewItem.routeData.match) {
96
- viewItem.routeData.match = undefined;
590
+ const initialMatch = matchComponent$1(reactElement, routeInfo.pathname, true) ||
591
+ createDefaultMatch(routeInfo.pathname, reactElement.props);
592
+ viewItem.routeData = {
593
+ match: initialMatch,
594
+ childProps: reactElement.props,
595
+ };
596
+ this.add(viewItem);
597
+ return viewItem;
598
+ };
599
+ /**
600
+ * Renders a ViewLifeCycleManager for the given view item.
601
+ * Handles cleanup if the view no longer matches.
602
+ *
603
+ * - Deactivates view if it no longer matches the current route
604
+ * - Wraps the route element in <Routes> to support nested routing and ensure remounting
605
+ * - Adds a unique key to <Routes> so React Router remounts routes when switching
606
+ */
607
+ this.renderViewItem = (viewItem, routeInfo, parentPath) => {
608
+ var _a, _b, _c, _d, _e, _f, _g, _h;
609
+ const routePath = viewItem.reactElement.props.path || '';
610
+ let match = matchComponent$1(viewItem.reactElement, routeInfo.pathname);
611
+ if (!match) {
612
+ const indexMatch = resolveIndexRouteMatch(viewItem, routeInfo.pathname, parentPath);
613
+ if (indexMatch) {
614
+ match = indexMatch;
615
+ }
616
+ }
617
+ // For parameterized routes, check if this is a navigation to a different path instance
618
+ // In that case, we should NOT reuse this view - a new view should be created
619
+ const isParameterRoute = routePath.includes(':');
620
+ const previousMatch = (_a = viewItem.routeData) === null || _a === void 0 ? void 0 : _a.match;
621
+ const isSamePath = (match === null || match === void 0 ? void 0 : match.pathname) === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathname);
622
+ // Flag to indicate this view should not be reused for this different parameterized path
623
+ const shouldSkipForDifferentParam = isParameterRoute && match && previousMatch && !isSamePath;
624
+ // Don't deactivate views automatically - let the StackManager handle view lifecycle
625
+ // This preserves views in the stack for navigation history like native apps
626
+ // Views will be hidden/shown by the StackManager's transition logic instead of being unmounted
627
+ // Special handling for Navigate components - they should unmount after redirecting
628
+ const elementComponent = (_c = (_b = viewItem.reactElement) === null || _b === void 0 ? void 0 : _b.props) === null || _c === void 0 ? void 0 : _c.element;
629
+ const isNavigateComponent = isNavigateElement(elementComponent);
630
+ if (isNavigateComponent) {
631
+ // Navigate components should only be mounted when they match
632
+ // Once they redirect (no longer match), they should be removed completely
633
+ // IMPORTANT: For index routes, we need to check indexMatch too since matchComponent
634
+ // may not properly match index routes without explicit parent path context
635
+ const indexMatch = ((_e = (_d = viewItem.routeData) === null || _d === void 0 ? void 0 : _d.childProps) === null || _e === void 0 ? void 0 : _e.index)
636
+ ? resolveIndexRouteMatch(viewItem, routeInfo.pathname, parentPath)
637
+ : null;
638
+ const hasValidMatch = match || indexMatch;
639
+ if (!hasValidMatch && viewItem.mount) {
97
640
  viewItem.mount = false;
641
+ // Schedule removal of the Navigate view item after a short delay
642
+ // This ensures the redirect completes before removal
643
+ setTimeout(() => {
644
+ this.remove(viewItem);
645
+ }, NAVIGATE_REDIRECT_DELAY_MS);
98
646
  }
99
647
  }
100
- return clonedChild;
101
- });
102
- return children;
103
- }
104
- findViewItemByRouteInfo(routeInfo, outletId, updateMatch) {
105
- const { viewItem, match } = this.findViewItemByPath(routeInfo.pathname, outletId);
106
- const shouldUpdateMatch = updateMatch === undefined || updateMatch === true;
107
- if (shouldUpdateMatch && viewItem && match) {
108
- viewItem.routeData.match = match;
109
- }
110
- return viewItem;
111
- }
112
- findLeavingViewItemByRouteInfo(routeInfo, outletId, mustBeIonRoute = true) {
113
- const { viewItem } = this.findViewItemByPath(routeInfo.lastPathname, outletId, mustBeIonRoute);
114
- return viewItem;
115
- }
116
- findViewItemByPathname(pathname, outletId) {
117
- const { viewItem } = this.findViewItemByPath(pathname, outletId);
118
- return viewItem;
648
+ // Components that don't have IonPage elements and no longer match should be cleaned up
649
+ // BUT we need to be careful not to remove them if they're part of browser navigation history
650
+ // This handles components that perform immediate actions like programmatic navigation
651
+ // EXCEPTION: Navigate components should ALWAYS remain mounted until they redirect
652
+ // since they need to be rendered to trigger the navigation
653
+ if (!match && viewItem.mount && !viewItem.ionPageElement && !isNavigateComponent) {
654
+ // Check if this view item should be preserved for browser navigation
655
+ // We'll keep it if it was recently active (within the last navigation)
656
+ const shouldPreserve = viewItem.routeData.lastPathname === routeInfo.pathname ||
657
+ ((_f = viewItem.routeData.match) === null || _f === void 0 ? void 0 : _f.pathname) === routeInfo.lastPathname;
658
+ if (!shouldPreserve) {
659
+ // This view item doesn't match and doesn't have an IonPage
660
+ // It's likely a utility component that performs an action and navigates away
661
+ viewItem.mount = false;
662
+ // Schedule removal to allow it to be recreated on next navigation
663
+ setTimeout(() => {
664
+ // Double-check before removing - the view might be needed again
665
+ const stillNotNeeded = !viewItem.mount && !viewItem.ionPageElement;
666
+ if (stillNotNeeded) {
667
+ this.remove(viewItem);
668
+ }
669
+ }, VIEW_CLEANUP_DELAY_MS);
670
+ }
671
+ else {
672
+ // Preserve it but unmount it for now
673
+ viewItem.mount = false;
674
+ }
675
+ }
676
+ // Reactivate view if it matches but was previously deactivated
677
+ // Don't reactivate if this is a parameterized route navigating to a different path instance
678
+ if (match && !viewItem.mount && !shouldSkipForDifferentParam) {
679
+ viewItem.mount = true;
680
+ viewItem.routeData.match = match;
681
+ }
682
+ // Deactivate wildcard routes and catch-all routes (empty path) when we have specific route matches
683
+ // This prevents "Not found" or fallback pages from showing alongside valid routes
684
+ if (routePath === '*' || routePath === '') {
685
+ // Check if any other view in this outlet has a match for the current route
686
+ const hasSpecificMatch = this.getViewItemsForOutlet(viewItem.outletId).some((v) => {
687
+ var _a, _b;
688
+ if (v.id === viewItem.id)
689
+ return false; // Skip self
690
+ const vRoutePath = ((_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path) || '';
691
+ if (vRoutePath === '*' || vRoutePath === '')
692
+ return false; // Skip other wildcard/empty routes
693
+ // Check if this view item would match the current route
694
+ const vMatch = v.reactElement ? matchComponent$1(v.reactElement, routeInfo.pathname) : null;
695
+ return !!vMatch;
696
+ });
697
+ if (hasSpecificMatch) {
698
+ viewItem.mount = false;
699
+ // Also hide the ion-page element immediately to prevent visual overlap
700
+ if (viewItem.ionPageElement) {
701
+ viewItem.ionPageElement.classList.add('ion-page-hidden');
702
+ viewItem.ionPageElement.setAttribute('aria-hidden', 'true');
703
+ }
704
+ }
705
+ }
706
+ const routeElement = React.cloneElement(viewItem.reactElement);
707
+ const componentElement = routeElement.props.element;
708
+ // Don't update match for parameterized routes navigating to different path instances
709
+ // This preserves the original match so that findViewItemByPath can correctly skip this view
710
+ if (match && viewItem.routeData.match !== match && !shouldSkipForDifferentParam) {
711
+ viewItem.routeData.match = match;
712
+ }
713
+ const routeMatch = shouldSkipForDifferentParam ? (_g = viewItem.routeData) === null || _g === void 0 ? void 0 : _g.match : match || ((_h = viewItem.routeData) === null || _h === void 0 ? void 0 : _h.match);
714
+ return (React.createElement(UNSAFE_RouteContext.Consumer, { key: `view-context-${viewItem.id}` }, (parentContext) => {
715
+ var _a, _b, _c;
716
+ const parentMatches = (_a = parentContext === null || parentContext === void 0 ? void 0 : parentContext.matches) !== null && _a !== void 0 ? _a : [];
717
+ let accumulatedParentParams = parentMatches.reduce((acc, match) => {
718
+ return Object.assign(Object.assign({}, acc), match.params);
719
+ }, {});
720
+ // If parentMatches is empty, try to extract params from view items in other outlets.
721
+ // This handles cases where React context propagation doesn't work as expected
722
+ // for nested router outlets.
723
+ if (parentMatches.length === 0 && Object.keys(accumulatedParentParams).length === 0) {
724
+ const allViewItems = this.getAllViewItems();
725
+ for (const otherViewItem of allViewItems) {
726
+ // Skip view items from the same outlet
727
+ if (otherViewItem.outletId === viewItem.outletId)
728
+ continue;
729
+ // Check if this view item's route could match the current pathname
730
+ const otherMatch = (_b = otherViewItem.routeData) === null || _b === void 0 ? void 0 : _b.match;
731
+ if (otherMatch && otherMatch.params && Object.keys(otherMatch.params).length > 0) {
732
+ // Check if the current pathname starts with this view item's matched pathname
733
+ const matchedPathname = otherMatch.pathnameBase || otherMatch.pathname;
734
+ if (matchedPathname && routeInfo.pathname.startsWith(matchedPathname)) {
735
+ accumulatedParentParams = Object.assign(Object.assign({}, accumulatedParentParams), otherMatch.params);
736
+ }
737
+ }
738
+ }
739
+ }
740
+ const combinedParams = Object.assign(Object.assign({}, accumulatedParentParams), ((_c = routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.params) !== null && _c !== void 0 ? _c : {}));
741
+ // For relative route paths, we need to compute an absolute pathnameBase
742
+ // by combining the parent's pathnameBase with the matched portion
743
+ let absolutePathnameBase = (routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.pathnameBase) || routeInfo.pathname;
744
+ const routePath = routeElement.props.path;
745
+ const isRelativePath = routePath && !routePath.startsWith('/');
746
+ const isIndexRoute = !!routeElement.props.index;
747
+ if (isRelativePath || isIndexRoute) {
748
+ // Get the parent's pathnameBase to build the absolute path
749
+ const parentPathnameBase = parentMatches.length > 0 ? parentMatches[parentMatches.length - 1].pathnameBase : '/';
750
+ // For relative paths, the matchPath returns a relative pathnameBase
751
+ // We need to make it absolute by prepending the parent's base
752
+ if ((routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.pathnameBase) && isRelativePath) {
753
+ // Strip leading slash if present in the relative match
754
+ const relativeBase = routeMatch.pathnameBase.startsWith('/')
755
+ ? routeMatch.pathnameBase.slice(1)
756
+ : routeMatch.pathnameBase;
757
+ absolutePathnameBase =
758
+ parentPathnameBase === '/' ? `/${relativeBase}` : `${parentPathnameBase}/${relativeBase}`;
759
+ }
760
+ else if (isIndexRoute) {
761
+ // Index routes should use the parent's base as their base
762
+ absolutePathnameBase = parentPathnameBase;
763
+ }
764
+ }
765
+ const contextMatches = [
766
+ ...parentMatches,
767
+ {
768
+ params: combinedParams,
769
+ pathname: (routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.pathname) || routeInfo.pathname,
770
+ pathnameBase: absolutePathnameBase,
771
+ route: {
772
+ id: viewItem.id,
773
+ path: routeElement.props.path,
774
+ element: componentElement,
775
+ index: !!routeElement.props.index,
776
+ caseSensitive: routeElement.props.caseSensitive,
777
+ hasErrorBoundary: false,
778
+ },
779
+ },
780
+ ];
781
+ const routeContextValue = parentContext
782
+ ? Object.assign(Object.assign({}, parentContext), { matches: contextMatches }) : {
783
+ outlet: null,
784
+ matches: contextMatches,
785
+ isDataRoute: false,
786
+ };
787
+ return (React.createElement(ViewLifeCycleManager, { key: `view-${viewItem.id}`, mount: viewItem.mount, removeView: () => this.remove(viewItem) },
788
+ React.createElement(UNSAFE_RouteContext.Provider, { value: routeContextValue }, componentElement)));
789
+ }));
790
+ };
791
+ /**
792
+ * Re-renders all active view items for the specified outlet.
793
+ * Ensures React elements are updated with the latest match.
794
+ *
795
+ * 1. Iterates through children of IonRouterOutlet
796
+ * 2. Updates each matching viewItem with the current child React element
797
+ * (important for updating props or changes to elements)
798
+ * 3. Returns a list of React components that will be rendered inside the outlet
799
+ * Each view is wrapped in <ViewLifeCycleManager> to manage lifecycle and rendering
800
+ */
801
+ this.getChildrenToRender = (outletId, ionRouterOutlet, routeInfo) => {
802
+ const viewItems = this.getViewItemsForOutlet(outletId);
803
+ // Determine parentPath for nested outlets to properly evaluate index routes
804
+ let parentPath = undefined;
805
+ try {
806
+ // Only attempt parent path computation for non-root outlets
807
+ if (outletId !== 'routerOutlet') {
808
+ const routeChildren = extractRouteChildren(ionRouterOutlet.props.children);
809
+ const { hasRelativeRoutes, hasIndexRoute, hasWildcardRoute } = analyzeRouteChildren(routeChildren);
810
+ if (hasRelativeRoutes || hasIndexRoute) {
811
+ const result = computeParentPath({
812
+ currentPathname: routeInfo.pathname,
813
+ outletMountPath: undefined,
814
+ routeChildren,
815
+ hasRelativeRoutes,
816
+ hasIndexRoute,
817
+ hasWildcardRoute,
818
+ });
819
+ parentPath = result.parentPath;
820
+ }
821
+ }
822
+ }
823
+ catch (e) {
824
+ // Non-fatal: if we fail to compute parentPath, fall back to previous behavior
825
+ }
826
+ // Sync child elements with stored viewItems (e.g. to reflect new props)
827
+ React.Children.forEach(ionRouterOutlet.props.children, (child) => {
828
+ // Ensure the child is a valid React element since we
829
+ // might have whitespace strings or other non-element children
830
+ if (React.isValidElement(child)) {
831
+ // Find view item by exact path match to avoid wildcard routes overwriting specific routes
832
+ const childPath = child.props.path;
833
+ const viewItem = viewItems.find((v) => {
834
+ var _a, _b;
835
+ const viewItemPath = (_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
836
+ // Only update if paths match exactly (prevents wildcard routes from overwriting specific routes)
837
+ return viewItemPath === childPath;
838
+ });
839
+ if (viewItem) {
840
+ viewItem.reactElement = child;
841
+ }
842
+ }
843
+ });
844
+ // Filter out duplicate view items by ID (but keep all mounted items)
845
+ const uniqueViewItems = viewItems.filter((viewItem, index, array) => {
846
+ // Remove duplicates by ID (keep first occurrence)
847
+ const isFirstOccurrence = array.findIndex((v) => v.id === viewItem.id) === index;
848
+ return isFirstOccurrence;
849
+ });
850
+ // Filter out unmounted Navigate components to prevent them from being rendered
851
+ // and triggering unwanted redirects
852
+ const renderableViewItems = uniqueViewItems.filter((viewItem) => {
853
+ var _a, _b, _c, _d;
854
+ const elementComponent = (_b = (_a = viewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.element;
855
+ const isNavigateComponent = isNavigateElement(elementComponent);
856
+ // Exclude unmounted Navigate components from rendering
857
+ if (isNavigateComponent && !viewItem.mount) {
858
+ return false;
859
+ }
860
+ // Filter out views that are unmounted, have no ionPageElement, and don't match the current route.
861
+ // These are "stale" views from previous routes that should not be rendered.
862
+ // Views WITH ionPageElement are handled by the normal lifecycle events.
863
+ // Views that MATCH the current route should be kept (they might be transitioning).
864
+ if (!viewItem.mount && !viewItem.ionPageElement) {
865
+ // Check if this view's route path matches the current pathname
866
+ const viewRoutePath = (_d = (_c = viewItem.reactElement) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.path;
867
+ if (viewRoutePath) {
868
+ // First try exact match using matchComponent
869
+ const routeMatch = matchComponent$1(viewItem.reactElement, routeInfo.pathname);
870
+ if (routeMatch) {
871
+ // View matches current route, keep it
872
+ return true;
873
+ }
874
+ // For parent routes (like /multiple-tabs or /routing), check if current pathname
875
+ // starts with this route's path. This handles views with IonSplitPane/IonTabs
876
+ // that don't have IonPage but should remain mounted while navigating within their children.
877
+ const normalizedViewPath = normalizePathnameForComparison(viewRoutePath.replace(/\/?\*$/, '')); // Remove trailing wildcard
878
+ const normalizedCurrentPath = normalizePathnameForComparison(routeInfo.pathname);
879
+ // Check if current pathname is within this view's route hierarchy
880
+ const isWithinRouteHierarchy = normalizedCurrentPath === normalizedViewPath || normalizedCurrentPath.startsWith(normalizedViewPath + '/');
881
+ if (!isWithinRouteHierarchy) {
882
+ // View is outside current route hierarchy, remove it
883
+ setTimeout(() => {
884
+ this.remove(viewItem);
885
+ }, 0);
886
+ return false;
887
+ }
888
+ }
889
+ }
890
+ return true;
891
+ });
892
+ const renderedItems = renderableViewItems.map((viewItem) => this.renderViewItem(viewItem, routeInfo, parentPath));
893
+ return renderedItems;
894
+ };
895
+ /**
896
+ * Finds a view item matching the current route, optionally updating its match state.
897
+ */
898
+ this.findViewItemByRouteInfo = (routeInfo, outletId, updateMatch) => {
899
+ const { viewItem, match } = this.findViewItemByPath(routeInfo.pathname, outletId);
900
+ const shouldUpdateMatch = updateMatch === undefined || updateMatch === true;
901
+ if (shouldUpdateMatch && viewItem && match) {
902
+ viewItem.routeData.match = match;
903
+ }
904
+ return viewItem;
905
+ };
906
+ /**
907
+ * Finds the view item that was previously active before a route change.
908
+ */
909
+ this.findLeavingViewItemByRouteInfo = (routeInfo, outletId, mustBeIonRoute = true) => {
910
+ // If the lastPathname is not set, we cannot find a leaving view item
911
+ if (!routeInfo.lastPathname) {
912
+ return undefined;
913
+ }
914
+ const { viewItem } = this.findViewItemByPath(routeInfo.lastPathname, outletId, mustBeIonRoute);
915
+ return viewItem;
916
+ };
917
+ /**
918
+ * Finds a view item by pathname only, used in simpler queries.
919
+ */
920
+ this.findViewItemByPathname = (pathname, outletId) => {
921
+ const { viewItem } = this.findViewItemByPath(pathname, outletId);
922
+ return viewItem;
923
+ };
924
+ /**
925
+ * Clean up old, unmounted view items to prevent memory leaks
926
+ */
927
+ this.cleanupStaleViewItems = (outletId) => {
928
+ const viewItems = this.getViewItemsForOutlet(outletId);
929
+ // Keep only the most recent mounted views and a few unmounted ones for history
930
+ const maxUnmountedItems = 3;
931
+ const unmountedItems = viewItems.filter((v) => !v.mount);
932
+ if (unmountedItems.length > maxUnmountedItems) {
933
+ // Remove oldest unmounted items
934
+ const itemsToRemove = unmountedItems.slice(0, unmountedItems.length - maxUnmountedItems);
935
+ itemsToRemove.forEach((item) => {
936
+ this.remove(item);
937
+ });
938
+ }
939
+ };
940
+ /**
941
+ * Override add to prevent duplicate view items with the same ID in the same outlet
942
+ * But allow multiple view items for the same route path (for navigation history)
943
+ */
944
+ this.add = (viewItem) => {
945
+ const existingViewItem = this.getViewItemsForOutlet(viewItem.outletId).find((v) => v.id === viewItem.id);
946
+ if (existingViewItem) {
947
+ return;
948
+ }
949
+ super.add(viewItem);
950
+ this.cleanupStaleViewItems(viewItem.outletId);
951
+ };
952
+ /**
953
+ * Override remove
954
+ */
955
+ this.remove = (viewItem) => {
956
+ super.remove(viewItem);
957
+ };
119
958
  }
120
959
  /**
121
- * Returns the matching view item and the match result for a given pathname.
960
+ * Core function that matches a given pathname against all view items.
961
+ * Returns both the matched view item and match metadata.
122
962
  */
123
- findViewItemByPath(pathname, outletId, mustBeIonRoute) {
963
+ findViewItemByPath(pathname, outletId, mustBeIonRoute, allowDefaultMatch = true) {
124
964
  let viewItem;
125
- let match;
965
+ let match = null;
126
966
  let viewStack;
127
967
  if (outletId) {
128
- viewStack = this.getViewItemsForOutlet(outletId);
968
+ viewStack = sortViewsBySpecificity(this.getViewItemsForOutlet(outletId));
129
969
  viewStack.some(matchView);
130
- if (!viewItem) {
970
+ if (!viewItem && allowDefaultMatch)
131
971
  viewStack.some(matchDefaultRoute);
132
- }
133
972
  }
134
973
  else {
135
- const viewItems = this.getAllViewItems();
974
+ const viewItems = sortViewsBySpecificity(this.getAllViewItems());
136
975
  viewItems.some(matchView);
137
- if (!viewItem) {
976
+ if (!viewItem && allowDefaultMatch)
138
977
  viewItems.some(matchDefaultRoute);
139
- }
140
978
  }
979
+ // If we still have not found a view item for this outlet, try to find a matching
980
+ // view item across all outlets and adopt it into the current outlet. This helps
981
+ // recover when an outlet remounts and receives a new id, leaving views associated
982
+ // with the previous outlet id.
983
+ // Do not adopt across outlets; if we didn't find a view for this outlet,
984
+ // defer to route matching to create a new one.
141
985
  return { viewItem, match };
986
+ /**
987
+ * Matches a route path with dynamic parameters (e.g. /tabs/:id)
988
+ */
142
989
  function matchView(v) {
143
- var _a, _b;
144
- if (mustBeIonRoute && !v.ionRoute) {
990
+ var _a;
991
+ if (mustBeIonRoute && !v.ionRoute)
145
992
  return false;
993
+ const viewItemPath = v.routeData.childProps.path || '';
994
+ const isIndexRoute = !!v.routeData.childProps.index;
995
+ const previousMatch = (_a = v.routeData) === null || _a === void 0 ? void 0 : _a.match;
996
+ const result = v.reactElement ? matchComponent$1(v.reactElement, pathname) : null;
997
+ if (!result) {
998
+ const indexMatch = resolveIndexRouteMatch(v, pathname, undefined);
999
+ if (indexMatch) {
1000
+ match = indexMatch;
1001
+ viewItem = v;
1002
+ return true;
1003
+ }
146
1004
  }
147
- match = matchPath({
148
- pathname,
149
- componentProps: v.routeData.childProps,
150
- });
151
- if (match) {
152
- /**
153
- * Even though we have a match from react-router, we do not know if the match
154
- * is for this specific view item.
155
- *
156
- * To validate this, we need to check if the path and url match the view item's route data.
157
- */
158
- const hasParameter = match.path.includes(':');
159
- if (!hasParameter || (hasParameter && match.url === ((_b = (_a = v.routeData) === null || _a === void 0 ? void 0 : _a.match) === null || _b === void 0 ? void 0 : _b.url))) {
1005
+ if (result) {
1006
+ const hasParams = result.params && Object.keys(result.params).length > 0;
1007
+ const isSamePath = result.pathname === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathname);
1008
+ const isWildcardRoute = viewItemPath.includes('*');
1009
+ const isParameterRoute = viewItemPath.includes(':');
1010
+ // Don't allow view items with undefined paths to match specific routes
1011
+ // This prevents broken index route view items from interfering with navigation
1012
+ if (!viewItemPath && !isIndexRoute && pathname !== '/' && pathname !== '') {
1013
+ return false;
1014
+ }
1015
+ // For parameterized routes, check if we should reuse the view item.
1016
+ // Wildcard routes (e.g., user/:userId/*) compare pathnameBase to allow
1017
+ // child path changes while preserving the parent view.
1018
+ if (isParameterRoute && !isSamePath) {
1019
+ if (isWildcardRoute) {
1020
+ const isSameBase = result.pathnameBase === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathnameBase);
1021
+ if (isSameBase) {
1022
+ match = result;
1023
+ viewItem = v;
1024
+ return true;
1025
+ }
1026
+ }
1027
+ return false;
1028
+ }
1029
+ // For routes without params, or when navigating to the exact same path,
1030
+ // or when there's no previous match, reuse the view item
1031
+ if (!hasParams || isSamePath || !previousMatch) {
1032
+ match = result;
1033
+ viewItem = v;
1034
+ return true;
1035
+ }
1036
+ // For wildcard routes (without params), only reuse if the pathname exactly matches
1037
+ if (isWildcardRoute && isSamePath) {
1038
+ match = result;
160
1039
  viewItem = v;
161
1040
  return true;
162
1041
  }
163
1042
  }
164
1043
  return false;
165
1044
  }
1045
+ /**
1046
+ * Matches a view with no path prop (default fallback route) or index route.
1047
+ */
166
1048
  function matchDefaultRoute(v) {
167
- // try to find a route that doesn't have a path or from prop, that will be our default route
168
- if (!v.routeData.childProps.path && !v.routeData.childProps.from) {
1049
+ var _a;
1050
+ const childProps = v.routeData.childProps;
1051
+ const isDefaultRoute = childProps.path === undefined || childProps.path === '';
1052
+ const isIndexRoute = !!childProps.index;
1053
+ if (isIndexRoute) {
1054
+ const indexMatch = resolveIndexRouteMatch(v, pathname, undefined);
1055
+ if (indexMatch) {
1056
+ match = indexMatch;
1057
+ viewItem = v;
1058
+ return true;
1059
+ }
1060
+ return false;
1061
+ }
1062
+ if (isDefaultRoute) {
169
1063
  match = {
170
- path: pathname,
171
- url: pathname,
172
- isExact: true,
173
1064
  params: {},
1065
+ pathname,
1066
+ pathnameBase: pathname === '' ? '/' : pathname,
1067
+ pattern: {
1068
+ path: '',
1069
+ caseSensitive: (_a = childProps.caseSensitive) !== null && _a !== void 0 ? _a : false,
1070
+ end: true,
1071
+ },
174
1072
  };
175
1073
  viewItem = v;
176
1074
  return true;
@@ -179,11 +1077,29 @@ class ReactRouterViewStack extends ViewStacks {
179
1077
  }
180
1078
  }
181
1079
  }
182
- function matchComponent$1(node, pathname) {
183
- return matchPath({
184
- pathname,
185
- componentProps: node.props,
1080
+ /**
1081
+ * Utility to apply matchPath to a React element and return its match state.
1082
+ */
1083
+ function matchComponent$1(node, pathname, allowFallback = false) {
1084
+ var _a;
1085
+ const routeProps = (_a = node === null || node === void 0 ? void 0 : node.props) !== null && _a !== void 0 ? _a : {};
1086
+ const routePath = routeProps.path;
1087
+ const pathnameToMatch = derivePathnameToMatch(pathname, routePath);
1088
+ const match = matchPath({
1089
+ pathname: pathnameToMatch,
1090
+ componentProps: routeProps,
186
1091
  });
1092
+ if (match || !allowFallback) {
1093
+ return match;
1094
+ }
1095
+ const isIndexRoute = !!routeProps.index;
1096
+ if (isIndexRoute) {
1097
+ return createDefaultMatch(pathname, routeProps);
1098
+ }
1099
+ if (!routePath || routePath === '') {
1100
+ return createDefaultMatch(pathname, routeProps);
1101
+ }
1102
+ return null;
187
1103
  }
188
1104
 
189
1105
  function clonePageElement(leavingViewHtml) {
@@ -208,7 +1124,40 @@ function clonePageElement(leavingViewHtml) {
208
1124
  return undefined;
209
1125
  }
210
1126
 
1127
+ /**
1128
+ * `StackManager` is responsible for managing page transitions, keeping track
1129
+ * of views (pages), and ensuring that navigation behaves like native apps —
1130
+ * particularly with animations and swipe gestures.
1131
+ */
1132
+ /**
1133
+ * Delay in milliseconds before unmounting a view after a transition completes.
1134
+ * This ensures the page transition animation finishes before the view is removed.
1135
+ */
1136
+ const VIEW_UNMOUNT_DELAY_MS = 250;
1137
+ /**
1138
+ * Delay in milliseconds to wait for an IonPage element to be mounted before
1139
+ * proceeding with a page transition.
1140
+ */
1141
+ const ION_PAGE_WAIT_TIMEOUT_MS = 50;
211
1142
  const isViewVisible = (el) => !el.classList.contains('ion-page-invisible') && !el.classList.contains('ion-page-hidden');
1143
+ /**
1144
+ * Hides an ion-page element by adding hidden class and aria attribute.
1145
+ */
1146
+ const hideIonPageElement = (element) => {
1147
+ if (element) {
1148
+ element.classList.add('ion-page-hidden');
1149
+ element.setAttribute('aria-hidden', 'true');
1150
+ }
1151
+ };
1152
+ /**
1153
+ * Shows an ion-page element by removing hidden class and aria attribute.
1154
+ */
1155
+ const showIonPageElement = (element) => {
1156
+ if (element) {
1157
+ element.classList.remove('ion-page-hidden');
1158
+ element.removeAttribute('aria-hidden');
1159
+ }
1160
+ };
212
1161
  class StackManager extends React.PureComponent {
213
1162
  constructor(props) {
214
1163
  super(props);
@@ -217,13 +1166,315 @@ class StackManager extends React.PureComponent {
217
1166
  isInOutlet: () => true,
218
1167
  };
219
1168
  this.pendingPageTransition = false;
1169
+ this.waitingForIonPage = false;
1170
+ this.outletMountPath = undefined;
220
1171
  this.registerIonPage = this.registerIonPage.bind(this);
221
1172
  this.transitionPage = this.transitionPage.bind(this);
222
1173
  this.handlePageTransition = this.handlePageTransition.bind(this);
223
- this.id = generateId('routerOutlet');
1174
+ this.id = props.id || `routerOutlet-${generateId('routerOutlet')}`;
224
1175
  this.prevProps = undefined;
225
1176
  this.skipTransition = false;
226
1177
  }
1178
+ /**
1179
+ * Determines the parent path that was matched to reach this outlet.
1180
+ * This helps with nested routing in React Router 6.
1181
+ *
1182
+ * The algorithm finds the shortest parent path where a route matches the remaining path.
1183
+ * Priority: specific routes > wildcard routes > index routes (only at mount point)
1184
+ */
1185
+ getParentPath() {
1186
+ const currentPathname = this.props.routeInfo.pathname;
1187
+ // If this outlet previously established a mount path and the current
1188
+ // pathname is outside of that scope, do not attempt to re-compute a new
1189
+ // parent path. This prevents out-of-scope outlets from "adopting"
1190
+ // unrelated routes (e.g., matching their index route under /overlays).
1191
+ if (this.outletMountPath && !currentPathname.startsWith(this.outletMountPath)) {
1192
+ return undefined;
1193
+ }
1194
+ // If this is a nested outlet (has an explicit ID like "main"),
1195
+ // we need to figure out what part of the path was already matched
1196
+ if (this.id !== 'routerOutlet' && this.ionRouterOutlet) {
1197
+ const routeChildren = extractRouteChildren(this.ionRouterOutlet.props.children);
1198
+ const { hasRelativeRoutes, hasIndexRoute, hasWildcardRoute } = analyzeRouteChildren(routeChildren);
1199
+ const result = computeParentPath({
1200
+ currentPathname,
1201
+ outletMountPath: this.outletMountPath,
1202
+ routeChildren,
1203
+ hasRelativeRoutes,
1204
+ hasIndexRoute,
1205
+ hasWildcardRoute,
1206
+ });
1207
+ // Update the outlet mount path if it was set
1208
+ if (result.outletMountPath && !this.outletMountPath) {
1209
+ this.outletMountPath = result.outletMountPath;
1210
+ }
1211
+ return result.parentPath;
1212
+ }
1213
+ return this.outletMountPath;
1214
+ }
1215
+ /**
1216
+ * Finds the entering and leaving view items for a route transition,
1217
+ * handling special redirect cases.
1218
+ */
1219
+ findViewItems(routeInfo) {
1220
+ const enteringViewItem = this.context.findViewItemByRouteInfo(routeInfo, this.id);
1221
+ let leavingViewItem = this.context.findLeavingViewItemByRouteInfo(routeInfo, this.id);
1222
+ // If we don't have a leaving view item, but the route info indicates
1223
+ // that the user has routed from a previous path, then the leaving view
1224
+ // can be found by the last known pathname.
1225
+ if (!leavingViewItem && routeInfo.prevRouteLastPathname) {
1226
+ leavingViewItem = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1227
+ }
1228
+ // Special case for redirects: When a redirect happens inside a nested route,
1229
+ // the entering and leaving view might be the same (the container route like tabs/*).
1230
+ // In this case, we need to look at prevRouteLastPathname to find the actual
1231
+ // view we're transitioning away from.
1232
+ if (enteringViewItem &&
1233
+ leavingViewItem &&
1234
+ enteringViewItem === leavingViewItem &&
1235
+ routeInfo.routeAction === 'replace' &&
1236
+ routeInfo.prevRouteLastPathname) {
1237
+ const actualLeavingView = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1238
+ if (actualLeavingView && actualLeavingView !== enteringViewItem) {
1239
+ leavingViewItem = actualLeavingView;
1240
+ }
1241
+ }
1242
+ // Also check if we're in a redirect scenario where entering and leaving are different
1243
+ // but we still need to handle the actual previous view.
1244
+ if (enteringViewItem &&
1245
+ !leavingViewItem &&
1246
+ routeInfo.routeAction === 'replace' &&
1247
+ routeInfo.prevRouteLastPathname) {
1248
+ const actualLeavingView = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1249
+ if (actualLeavingView && actualLeavingView !== enteringViewItem) {
1250
+ leavingViewItem = actualLeavingView;
1251
+ }
1252
+ }
1253
+ return { enteringViewItem, leavingViewItem };
1254
+ }
1255
+ /**
1256
+ * Determines if the leaving view item should be unmounted after a transition.
1257
+ */
1258
+ shouldUnmountLeavingView(routeInfo, enteringViewItem, leavingViewItem) {
1259
+ if (!leavingViewItem) {
1260
+ return false;
1261
+ }
1262
+ if (routeInfo.routeAction === 'replace') {
1263
+ return true;
1264
+ }
1265
+ const isForwardPush = routeInfo.routeAction === 'push' && routeInfo.routeDirection === 'forward';
1266
+ if (!isForwardPush && routeInfo.routeDirection !== 'none' && enteringViewItem !== leavingViewItem) {
1267
+ return true;
1268
+ }
1269
+ return false;
1270
+ }
1271
+ /**
1272
+ * Handles the case when the outlet is out of scope (current route is outside mount path).
1273
+ * Returns true if the transition should be aborted.
1274
+ */
1275
+ handleOutOfScopeOutlet(routeInfo) {
1276
+ if (!this.outletMountPath || routeInfo.pathname.startsWith(this.outletMountPath)) {
1277
+ return false;
1278
+ }
1279
+ // Clear any pending unmount timeout to avoid conflicts
1280
+ if (this.outOfScopeUnmountTimeout) {
1281
+ clearTimeout(this.outOfScopeUnmountTimeout);
1282
+ this.outOfScopeUnmountTimeout = undefined;
1283
+ }
1284
+ // When an outlet is out of scope, unmount its views immediately
1285
+ const allViewsInOutlet = this.context.getViewItemsForOutlet ? this.context.getViewItemsForOutlet(this.id) : [];
1286
+ // Unmount and remove all views in this outlet immediately to avoid leftover content
1287
+ allViewsInOutlet.forEach((viewItem) => {
1288
+ hideIonPageElement(viewItem.ionPageElement);
1289
+ this.context.unMountViewItem(viewItem);
1290
+ });
1291
+ this.forceUpdate();
1292
+ return true;
1293
+ }
1294
+ /**
1295
+ * Handles the case when this is a nested outlet with relative routes but no valid parent path.
1296
+ * Returns true if the transition should be aborted.
1297
+ */
1298
+ handleOutOfContextNestedOutlet(parentPath, leavingViewItem) {
1299
+ var _a;
1300
+ if (this.id === 'routerOutlet' || parentPath !== undefined || !this.ionRouterOutlet) {
1301
+ return false;
1302
+ }
1303
+ const routesChildren = (_a = getRoutesChildren(this.ionRouterOutlet.props.children)) !== null && _a !== void 0 ? _a : this.ionRouterOutlet.props.children;
1304
+ const routeChildren = React.Children.toArray(routesChildren).filter((child) => React.isValidElement(child) && child.type === Route);
1305
+ const hasRelativeRoutes = routeChildren.some((route) => {
1306
+ const path = route.props.path;
1307
+ return path && !path.startsWith('/') && path !== '*';
1308
+ });
1309
+ if (hasRelativeRoutes) {
1310
+ // Hide any visible views in this outlet since it's out of scope
1311
+ hideIonPageElement(leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement);
1312
+ if (leavingViewItem) {
1313
+ leavingViewItem.mount = false;
1314
+ }
1315
+ this.forceUpdate();
1316
+ return true;
1317
+ }
1318
+ return false;
1319
+ }
1320
+ /**
1321
+ * Handles the case when a nested outlet has no matching route.
1322
+ * Returns true if the transition should be aborted.
1323
+ */
1324
+ handleNoMatchingRoute(enteringRoute, enteringViewItem, leavingViewItem) {
1325
+ if (this.id === 'routerOutlet' || enteringRoute || enteringViewItem) {
1326
+ return false;
1327
+ }
1328
+ // Hide any visible views in this outlet since it has no matching route
1329
+ hideIonPageElement(leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement);
1330
+ if (leavingViewItem) {
1331
+ leavingViewItem.mount = false;
1332
+ }
1333
+ this.forceUpdate();
1334
+ return true;
1335
+ }
1336
+ /**
1337
+ * Handles the transition when entering view item has an ion-page element ready.
1338
+ */
1339
+ handleReadyEnteringView(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem) {
1340
+ var _a, _b;
1341
+ // Ensure the entering view is not hidden from previous navigations
1342
+ showIonPageElement(enteringViewItem.ionPageElement);
1343
+ // Handle same view item case (e.g., parameterized route changes)
1344
+ if (enteringViewItem === leavingViewItem) {
1345
+ const routePath = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1346
+ const isParameterizedRoute = routePath ? routePath.includes(':') : false;
1347
+ if (isParameterizedRoute) {
1348
+ // Refresh match metadata so the component receives updated params
1349
+ const updatedMatch = matchComponent(enteringViewItem.reactElement, routeInfo.pathname, true);
1350
+ if (updatedMatch) {
1351
+ enteringViewItem.routeData.match = updatedMatch;
1352
+ }
1353
+ const enteringEl = enteringViewItem.ionPageElement;
1354
+ if (enteringEl) {
1355
+ enteringEl.classList.remove('ion-page-hidden', 'ion-page-invisible');
1356
+ enteringEl.removeAttribute('aria-hidden');
1357
+ }
1358
+ this.forceUpdate();
1359
+ return;
1360
+ }
1361
+ }
1362
+ // Try to find leaving view using prev route info if still not found
1363
+ if (!leavingViewItem && this.props.routeInfo.prevRouteLastPathname) {
1364
+ leavingViewItem = this.context.findViewItemByPathname(this.props.routeInfo.prevRouteLastPathname, this.id);
1365
+ }
1366
+ // Skip transition if entering view is visible and leaving view is not
1367
+ if (enteringViewItem.ionPageElement &&
1368
+ isViewVisible(enteringViewItem.ionPageElement) &&
1369
+ leavingViewItem !== undefined &&
1370
+ leavingViewItem.ionPageElement &&
1371
+ !isViewVisible(leavingViewItem.ionPageElement)) {
1372
+ return;
1373
+ }
1374
+ // Check for duplicate transition
1375
+ const currentTransition = {
1376
+ enteringId: enteringViewItem.id,
1377
+ leavingId: leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.id,
1378
+ };
1379
+ if (leavingViewItem &&
1380
+ this.lastTransition &&
1381
+ this.lastTransition.leavingId &&
1382
+ this.lastTransition.enteringId === currentTransition.enteringId &&
1383
+ this.lastTransition.leavingId === currentTransition.leavingId) {
1384
+ return;
1385
+ }
1386
+ this.lastTransition = currentTransition;
1387
+ this.transitionPage(routeInfo, enteringViewItem, leavingViewItem);
1388
+ // Handle unmounting the leaving view
1389
+ if (shouldUnmountLeavingViewItem && leavingViewItem && enteringViewItem !== leavingViewItem) {
1390
+ leavingViewItem.mount = false;
1391
+ this.handleLeavingViewUnmount(routeInfo, enteringViewItem, leavingViewItem);
1392
+ }
1393
+ }
1394
+ /**
1395
+ * Handles the delayed unmount of the leaving view item after a replace action.
1396
+ */
1397
+ handleLeavingViewUnmount(routeInfo, enteringViewItem, leavingViewItem) {
1398
+ var _a, _b, _c, _d, _e, _f;
1399
+ if (routeInfo.routeAction !== 'replace' || !leavingViewItem.ionPageElement) {
1400
+ return;
1401
+ }
1402
+ // Check if we should skip removal for nested outlet redirects
1403
+ const enteringRoutePath = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1404
+ const leavingRoutePath = (_d = (_c = leavingViewItem.reactElement) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.path;
1405
+ const isEnteringContainerRoute = enteringRoutePath && enteringRoutePath.endsWith('/*');
1406
+ const isLeavingSpecificRoute = leavingRoutePath &&
1407
+ leavingRoutePath !== '' &&
1408
+ leavingRoutePath !== '*' &&
1409
+ !leavingRoutePath.endsWith('/*') &&
1410
+ !((_f = (_e = leavingViewItem.reactElement) === null || _e === void 0 ? void 0 : _e.props) === null || _f === void 0 ? void 0 : _f.index);
1411
+ // Skip removal only for container-to-container transitions
1412
+ if (isEnteringContainerRoute && !isLeavingSpecificRoute) {
1413
+ return;
1414
+ }
1415
+ const viewToUnmount = leavingViewItem;
1416
+ setTimeout(() => {
1417
+ this.context.unMountViewItem(viewToUnmount);
1418
+ }, VIEW_UNMOUNT_DELAY_MS);
1419
+ }
1420
+ /**
1421
+ * Handles the case when entering view has no ion-page element yet (waiting for render).
1422
+ */
1423
+ handleWaitingForIonPage(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem) {
1424
+ var _a, _b;
1425
+ const enteringRouteElement = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.element;
1426
+ // Handle Navigate components (they never render an IonPage)
1427
+ if (isNavigateElement(enteringRouteElement)) {
1428
+ this.waitingForIonPage = false;
1429
+ if (this.ionPageWaitTimeout) {
1430
+ clearTimeout(this.ionPageWaitTimeout);
1431
+ this.ionPageWaitTimeout = undefined;
1432
+ }
1433
+ this.pendingPageTransition = false;
1434
+ // Hide the leaving view immediately for Navigate redirects
1435
+ hideIonPageElement(leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement);
1436
+ // Don't unmount if entering and leaving are the same view item
1437
+ if (shouldUnmountLeavingViewItem && leavingViewItem && enteringViewItem !== leavingViewItem) {
1438
+ leavingViewItem.mount = false;
1439
+ }
1440
+ this.forceUpdate();
1441
+ return;
1442
+ }
1443
+ // Hide leaving view while we wait for the entering view's IonPage to mount
1444
+ hideIonPageElement(leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement);
1445
+ this.waitingForIonPage = true;
1446
+ if (this.ionPageWaitTimeout) {
1447
+ clearTimeout(this.ionPageWaitTimeout);
1448
+ }
1449
+ this.ionPageWaitTimeout = setTimeout(() => {
1450
+ var _a, _b;
1451
+ this.ionPageWaitTimeout = undefined;
1452
+ if (!this.waitingForIonPage) {
1453
+ return;
1454
+ }
1455
+ this.waitingForIonPage = false;
1456
+ const latestEnteringView = (_a = this.context.findViewItemByRouteInfo(routeInfo, this.id)) !== null && _a !== void 0 ? _a : enteringViewItem;
1457
+ const latestLeavingView = (_b = this.context.findLeavingViewItemByRouteInfo(routeInfo, this.id)) !== null && _b !== void 0 ? _b : leavingViewItem;
1458
+ if (latestEnteringView === null || latestEnteringView === void 0 ? void 0 : latestEnteringView.ionPageElement) {
1459
+ this.transitionPage(routeInfo, latestEnteringView, latestLeavingView !== null && latestLeavingView !== void 0 ? latestLeavingView : undefined);
1460
+ if (shouldUnmountLeavingViewItem && latestLeavingView && latestEnteringView !== latestLeavingView) {
1461
+ latestLeavingView.mount = false;
1462
+ }
1463
+ this.forceUpdate();
1464
+ }
1465
+ }, ION_PAGE_WAIT_TIMEOUT_MS);
1466
+ this.forceUpdate();
1467
+ }
1468
+ /**
1469
+ * Gets the route info to use for finding views during swipe-to-go-back gestures.
1470
+ * This pattern is used in multiple places in setupRouterOutlet.
1471
+ */
1472
+ getSwipeBackRouteInfo() {
1473
+ const { routeInfo } = this.props;
1474
+ return this.prevProps && this.prevProps.routeInfo.pathname === routeInfo.pushedByRoute
1475
+ ? this.prevProps.routeInfo
1476
+ : { pathname: routeInfo.pushedByRoute || '' };
1477
+ }
227
1478
  componentDidMount() {
228
1479
  if (this.clearOutletTimeout) {
229
1480
  /**
@@ -255,114 +1506,123 @@ class StackManager extends React.PureComponent {
255
1506
  }
256
1507
  }
257
1508
  componentWillUnmount() {
1509
+ if (this.ionPageWaitTimeout) {
1510
+ clearTimeout(this.ionPageWaitTimeout);
1511
+ this.ionPageWaitTimeout = undefined;
1512
+ }
1513
+ if (this.outOfScopeUnmountTimeout) {
1514
+ clearTimeout(this.outOfScopeUnmountTimeout);
1515
+ this.outOfScopeUnmountTimeout = undefined;
1516
+ }
1517
+ this.waitingForIonPage = false;
1518
+ // Hide all views in this outlet before clearing.
1519
+ // This is critical for nested outlets - when the parent component unmounts,
1520
+ // the nested outlet's componentDidUpdate won't be called, so we must hide
1521
+ // the ion-page elements here to prevent them from remaining visible on top
1522
+ // of other content after navigation to a different route.
1523
+ const allViewsInOutlet = this.context.getViewItemsForOutlet ? this.context.getViewItemsForOutlet(this.id) : [];
1524
+ allViewsInOutlet.forEach((viewItem) => {
1525
+ hideIonPageElement(viewItem.ionPageElement);
1526
+ });
258
1527
  this.clearOutletTimeout = this.context.clearOutlet(this.id);
259
1528
  }
1529
+ /**
1530
+ * Sets the transition between pages within this router outlet.
1531
+ * This function determines the entering and leaving views based on the
1532
+ * provided route information and triggers the appropriate animation.
1533
+ * It also handles scenarios like initial loads, back navigation, and
1534
+ * navigation to the same view with different parameters.
1535
+ *
1536
+ * @param routeInfo It contains info about the current route,
1537
+ * the previous route, and the action taken (e.g., push, replace).
1538
+ *
1539
+ * @returns A promise that resolves when the transition is complete.
1540
+ * If no transition is needed or if the router outlet isn't ready,
1541
+ * the Promise may resolve immediately.
1542
+ */
260
1543
  async handlePageTransition(routeInfo) {
261
- var _a, _b;
1544
+ var _a;
1545
+ // Wait for router outlet to mount
262
1546
  if (!this.routerOutletElement || !this.routerOutletElement.commit) {
263
- /**
264
- * The route outlet has not mounted yet. We need to wait for it to render
265
- * before we can transition the page.
266
- *
267
- * Set a flag to indicate that we should transition the page after
268
- * the component has updated.
269
- */
270
1547
  this.pendingPageTransition = true;
1548
+ return;
271
1549
  }
272
- else {
273
- let enteringViewItem = this.context.findViewItemByRouteInfo(routeInfo, this.id);
274
- let leavingViewItem = this.context.findLeavingViewItemByRouteInfo(routeInfo, this.id);
275
- if (!leavingViewItem && routeInfo.prevRouteLastPathname) {
276
- leavingViewItem = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1550
+ // Find entering and leaving view items
1551
+ const viewItems = this.findViewItems(routeInfo);
1552
+ let enteringViewItem = viewItems.enteringViewItem;
1553
+ const leavingViewItem = viewItems.leavingViewItem;
1554
+ const shouldUnmountLeavingViewItem = this.shouldUnmountLeavingView(routeInfo, enteringViewItem, leavingViewItem);
1555
+ // Get parent path for nested outlets
1556
+ const parentPath = this.getParentPath();
1557
+ // Handle out-of-scope outlet (route outside mount path)
1558
+ if (this.handleOutOfScopeOutlet(routeInfo)) {
1559
+ return;
1560
+ }
1561
+ // Clear any pending out-of-scope unmount timeout
1562
+ if (this.outOfScopeUnmountTimeout) {
1563
+ clearTimeout(this.outOfScopeUnmountTimeout);
1564
+ this.outOfScopeUnmountTimeout = undefined;
1565
+ }
1566
+ // Handle nested outlet with relative routes but no valid parent path
1567
+ if (this.handleOutOfContextNestedOutlet(parentPath, leavingViewItem)) {
1568
+ return;
1569
+ }
1570
+ // Find the matching route element
1571
+ const enteringRoute = findRouteByRouteInfo((_a = this.ionRouterOutlet) === null || _a === void 0 ? void 0 : _a.props.children, routeInfo, parentPath);
1572
+ // Handle nested outlet with no matching route
1573
+ if (this.handleNoMatchingRoute(enteringRoute, enteringViewItem, leavingViewItem)) {
1574
+ return;
1575
+ }
1576
+ // Create or update the entering view item
1577
+ if (enteringViewItem && enteringRoute) {
1578
+ enteringViewItem.reactElement = enteringRoute;
1579
+ }
1580
+ else if (enteringRoute) {
1581
+ enteringViewItem = this.context.createViewItem(this.id, enteringRoute, routeInfo);
1582
+ this.context.addViewItem(enteringViewItem);
1583
+ }
1584
+ // Handle transition based on ion-page element availability
1585
+ if (enteringViewItem && enteringViewItem.ionPageElement) {
1586
+ // Clear waiting state
1587
+ if (this.waitingForIonPage) {
1588
+ this.waitingForIonPage = false;
1589
+ }
1590
+ if (this.ionPageWaitTimeout) {
1591
+ clearTimeout(this.ionPageWaitTimeout);
1592
+ this.ionPageWaitTimeout = undefined;
277
1593
  }
278
- // Check if leavingViewItem should be unmounted
1594
+ this.handleReadyEnteringView(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem);
1595
+ }
1596
+ else if (enteringViewItem && !enteringViewItem.ionPageElement) {
1597
+ // Wait for ion-page to mount
1598
+ this.handleWaitingForIonPage(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem);
1599
+ return;
1600
+ }
1601
+ else if (!enteringViewItem && !enteringRoute) {
1602
+ // No view or route found - likely leaving to another outlet
279
1603
  if (leavingViewItem) {
280
- if (routeInfo.routeAction === 'replace') {
281
- leavingViewItem.mount = false;
282
- }
283
- else if (!(routeInfo.routeAction === 'push' && routeInfo.routeDirection === 'forward')) {
284
- if (routeInfo.routeDirection !== 'none' && enteringViewItem !== leavingViewItem) {
285
- leavingViewItem.mount = false;
286
- }
287
- }
288
- else if ((_a = routeInfo.routeOptions) === null || _a === void 0 ? void 0 : _a.unmount) {
1604
+ hideIonPageElement(leavingViewItem.ionPageElement);
1605
+ if (shouldUnmountLeavingViewItem) {
289
1606
  leavingViewItem.mount = false;
290
1607
  }
291
1608
  }
292
- const enteringRoute = matchRoute((_b = this.ionRouterOutlet) === null || _b === void 0 ? void 0 : _b.props.children, routeInfo);
293
- if (enteringViewItem) {
294
- enteringViewItem.reactElement = enteringRoute;
295
- }
296
- else if (enteringRoute) {
297
- enteringViewItem = this.context.createViewItem(this.id, enteringRoute, routeInfo);
298
- this.context.addViewItem(enteringViewItem);
299
- }
300
- if (enteringViewItem && enteringViewItem.ionPageElement) {
301
- /**
302
- * If the entering view item is the same as the leaving view item,
303
- * then we don't need to transition.
304
- */
305
- if (enteringViewItem === leavingViewItem) {
306
- /**
307
- * If the entering view item is the same as the leaving view item,
308
- * we are either transitioning using parameterized routes to the same view
309
- * or a parent router outlet is re-rendering as a result of React props changing.
310
- *
311
- * If the route data does not match the current path, the parent router outlet
312
- * is attempting to transition and we cancel the operation.
313
- */
314
- if (enteringViewItem.routeData.match.url !== routeInfo.pathname) {
315
- return;
316
- }
317
- }
318
- /**
319
- * If there isn't a leaving view item, but the route info indicates
320
- * that the user has routed from a previous path, then we need
321
- * to find the leaving view item to transition between.
322
- */
323
- if (!leavingViewItem && this.props.routeInfo.prevRouteLastPathname) {
324
- leavingViewItem = this.context.findViewItemByPathname(this.props.routeInfo.prevRouteLastPathname, this.id);
325
- }
326
- /**
327
- * If the entering view is already visible and the leaving view is not, the transition does not need to occur.
328
- */
329
- if (isViewVisible(enteringViewItem.ionPageElement) &&
330
- leavingViewItem !== undefined &&
331
- !isViewVisible(leavingViewItem.ionPageElement)) {
332
- return;
333
- }
334
- /**
335
- * The view should only be transitioned in the following cases:
336
- * 1. Performing a replace or pop action, such as a swipe to go back gesture
337
- * to animation the leaving view off the screen.
338
- *
339
- * 2. Navigating between top-level router outlets, such as /page-1 to /page-2;
340
- * or navigating within a nested outlet, such as /tabs/tab-1 to /tabs/tab-2.
341
- *
342
- * 3. The entering view is an ion-router-outlet containing a page
343
- * matching the current route and that hasn't already transitioned in.
344
- *
345
- * This should only happen when navigating directly to a nested router outlet
346
- * route or on an initial page load (i.e. refreshing). In cases when loading
347
- * /tabs/tab-1, we need to transition the /tabs page element into the view.
348
- */
349
- this.transitionPage(routeInfo, enteringViewItem, leavingViewItem);
350
- }
351
- else if (leavingViewItem && !enteringRoute && !enteringViewItem) {
352
- // If we have a leavingView but no entering view/route, we are probably leaving to
353
- // another outlet, so hide this leavingView. We do it in a timeout to give time for a
354
- // transition to finish.
355
- // setTimeout(() => {
356
- if (leavingViewItem.ionPageElement) {
357
- leavingViewItem.ionPageElement.classList.add('ion-page-hidden');
358
- leavingViewItem.ionPageElement.setAttribute('aria-hidden', 'true');
359
- }
360
- // }, 250);
361
- }
362
- this.forceUpdate();
363
1609
  }
1610
+ this.forceUpdate();
364
1611
  }
1612
+ /**
1613
+ * Registers an `<IonPage>` DOM element with the `StackManager`.
1614
+ * This is called when `<IonPage>` has been mounted.
1615
+ *
1616
+ * @param page The element of the rendered `<IonPage>`.
1617
+ * @param routeInfo The route information that associates with `<IonPage>`.
1618
+ */
365
1619
  registerIonPage(page, routeInfo) {
1620
+ this.waitingForIonPage = false;
1621
+ if (this.ionPageWaitTimeout) {
1622
+ clearTimeout(this.ionPageWaitTimeout);
1623
+ this.ionPageWaitTimeout = undefined;
1624
+ }
1625
+ this.pendingPageTransition = false;
366
1626
  const foundView = this.context.findViewItemByRouteInfo(routeInfo, this.id);
367
1627
  if (foundView) {
368
1628
  const oldPageElement = foundView.ionPageElement;
@@ -379,48 +1639,38 @@ class StackManager extends React.PureComponent {
379
1639
  }
380
1640
  this.handlePageTransition(routeInfo);
381
1641
  }
1642
+ /**
1643
+ * Configures the router outlet for the swipe-to-go-back gesture.
1644
+ *
1645
+ * @param routerOutlet The Ionic router outlet component: `<IonRouterOutlet>`.
1646
+ */
382
1647
  async setupRouterOutlet(routerOutlet) {
383
1648
  const canStart = () => {
384
1649
  const config = getConfig();
1650
+ // Check if swipe back is enabled in config (default to true for iOS mode)
385
1651
  const swipeEnabled = config && config.get('swipeBackEnabled', routerOutlet.mode === 'ios');
386
1652
  if (!swipeEnabled) {
387
1653
  return false;
388
1654
  }
389
1655
  const { routeInfo } = this.props;
390
- const propsToUse = this.prevProps && this.prevProps.routeInfo.pathname === routeInfo.pushedByRoute
391
- ? this.prevProps.routeInfo
392
- : { pathname: routeInfo.pushedByRoute || '' };
393
- const enteringViewItem = this.context.findViewItemByRouteInfo(propsToUse, this.id, false);
394
- return (!!enteringViewItem &&
395
- /**
396
- * The root url '/' is treated as
397
- * the first view item (but is never mounted),
398
- * so we do not want to swipe back to the
399
- * root url.
400
- */
1656
+ const swipeBackRouteInfo = this.getSwipeBackRouteInfo();
1657
+ const enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, this.id, false);
1658
+ const canStartSwipe = !!enteringViewItem &&
1659
+ // The root url '/' is treated as the first view item (but is never mounted),
1660
+ // so we do not want to swipe back to the root url.
401
1661
  enteringViewItem.mount &&
402
- /**
403
- * When on the first page (whatever view
404
- * you land on after the root url) it
405
- * is possible for findViewItemByRouteInfo to
406
- * return the exact same view you are currently on.
407
- * Make sure that we are not swiping back to the same
408
- * instances of a view.
409
- */
410
- enteringViewItem.routeData.match.path !== routeInfo.pathname);
1662
+ // When on the first page it is possible for findViewItemByRouteInfo to
1663
+ // return the exact same view you are currently on.
1664
+ // Make sure that we are not swiping back to the same instances of a view.
1665
+ enteringViewItem.routeData.match.pattern.path !== routeInfo.pathname;
1666
+ return canStartSwipe;
411
1667
  };
412
1668
  const onStart = async () => {
413
1669
  const { routeInfo } = this.props;
414
- const propsToUse = this.prevProps && this.prevProps.routeInfo.pathname === routeInfo.pushedByRoute
415
- ? this.prevProps.routeInfo
416
- : { pathname: routeInfo.pushedByRoute || '' };
417
- const enteringViewItem = this.context.findViewItemByRouteInfo(propsToUse, this.id, false);
1670
+ const swipeBackRouteInfo = this.getSwipeBackRouteInfo();
1671
+ const enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, this.id, false);
418
1672
  const leavingViewItem = this.context.findViewItemByRouteInfo(routeInfo, this.id, false);
419
- /**
420
- * When the gesture starts, kick off
421
- * a transition that is controlled
422
- * via a swipe gesture.
423
- */
1673
+ // When the gesture starts, kick off a transition controlled via swipe gesture
424
1674
  if (enteringViewItem && leavingViewItem) {
425
1675
  await this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, 'back', true);
426
1676
  }
@@ -428,34 +1678,19 @@ class StackManager extends React.PureComponent {
428
1678
  };
429
1679
  const onEnd = (shouldContinue) => {
430
1680
  if (shouldContinue) {
1681
+ // User finished the swipe gesture, so complete the back navigation
431
1682
  this.skipTransition = true;
432
1683
  this.context.goBack();
433
1684
  }
434
1685
  else {
435
- /**
436
- * In the event that the swipe
437
- * gesture was aborted, we should
438
- * re-hide the page that was going to enter.
439
- */
1686
+ // Swipe gesture was aborted - re-hide the page that was going to enter
440
1687
  const { routeInfo } = this.props;
441
- const propsToUse = this.prevProps && this.prevProps.routeInfo.pathname === routeInfo.pushedByRoute
442
- ? this.prevProps.routeInfo
443
- : { pathname: routeInfo.pushedByRoute || '' };
444
- const enteringViewItem = this.context.findViewItemByRouteInfo(propsToUse, this.id, false);
1688
+ const swipeBackRouteInfo = this.getSwipeBackRouteInfo();
1689
+ const enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, this.id, false);
445
1690
  const leavingViewItem = this.context.findViewItemByRouteInfo(routeInfo, this.id, false);
446
- /**
447
- * Ionic React has a design defect where it
448
- * a) Unmounts the leaving view item when using parameterized routes
449
- * b) Considers the current view to be the entering view when using
450
- * parameterized routes
451
- *
452
- * As a result, we should not hide the view item here
453
- * as it will cause the current view to be hidden.
454
- */
1691
+ // Don't hide if entering and leaving are the same (parameterized route edge case)
455
1692
  if (enteringViewItem !== leavingViewItem && (enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement) !== undefined) {
456
- const { ionPageElement } = enteringViewItem;
457
- ionPageElement.setAttribute('aria-hidden', 'true');
458
- ionPageElement.classList.add('ion-page-hidden');
1693
+ hideIonPageElement(enteringViewItem.ionPageElement);
459
1694
  }
460
1695
  }
461
1696
  };
@@ -465,6 +1700,18 @@ class StackManager extends React.PureComponent {
465
1700
  onEnd,
466
1701
  };
467
1702
  }
1703
+ /**
1704
+ * Animates the transition between the entering and leaving pages within the
1705
+ * router outlet.
1706
+ *
1707
+ * @param routeInfo Info about the current route.
1708
+ * @param enteringViewItem The view item that is entering.
1709
+ * @param leavingViewItem The view item that is leaving.
1710
+ * @param direction The direction of the transition.
1711
+ * @param progressAnimation Indicates if the transition is part of a
1712
+ * gesture controlled animation (e.g., swipe to go back).
1713
+ * Defaults to `false`.
1714
+ */
468
1715
  async transitionPage(routeInfo, enteringViewItem, leavingViewItem, direction, progressAnimation = false) {
469
1716
  const runCommit = async (enteringEl, leavingEl) => {
470
1717
  const skipTransition = this.skipTransition;
@@ -510,7 +1757,8 @@ class StackManager extends React.PureComponent {
510
1757
  if (leavingViewItem && leavingViewItem.ionPageElement && enteringViewItem === leavingViewItem) {
511
1758
  // If a page is transitioning to another version of itself
512
1759
  // we clone it so we can have an animation to show
513
- const match = matchComponent(leavingViewItem.reactElement, routeInfo.pathname, true);
1760
+ // (e.g., `/user/1` → `/user/2`)
1761
+ const match = matchComponent(leavingViewItem.reactElement, routeInfo.pathname);
514
1762
  if (match) {
515
1763
  const newLeavingElement = clonePageElement(leavingViewItem.ionPageElement.outerHTML);
516
1764
  if (newLeavingElement) {
@@ -520,6 +1768,15 @@ class StackManager extends React.PureComponent {
520
1768
  }
521
1769
  }
522
1770
  else {
1771
+ /**
1772
+ * The route no longer matches the component type of the leaving view.
1773
+ * (e.g., `/user/1` → `/settings`)
1774
+ *
1775
+ * This can also occur in edge cases like rapid navigation
1776
+ * or during parent component re-renders that briefly cause
1777
+ * the view items to be the same instance before the final
1778
+ * route component is determined.
1779
+ */
523
1780
  await runCommit(enteringViewItem.ionPageElement, undefined);
524
1781
  }
525
1782
  }
@@ -535,20 +1792,25 @@ class StackManager extends React.PureComponent {
535
1792
  render() {
536
1793
  const { children } = this.props;
537
1794
  const ionRouterOutlet = React.Children.only(children);
1795
+ // Store reference for use in getParentPath() and handlePageTransition()
538
1796
  this.ionRouterOutlet = ionRouterOutlet;
539
1797
  const components = this.context.getChildrenToRender(this.id, this.ionRouterOutlet, this.props.routeInfo, () => {
1798
+ // Callback triggers re-render when view items are modified during getChildrenToRender
540
1799
  this.forceUpdate();
541
1800
  });
542
1801
  return (React.createElement(StackContext.Provider, { value: this.stackContextValue }, React.cloneElement(ionRouterOutlet, {
543
1802
  ref: (node) => {
544
1803
  if (ionRouterOutlet.props.setRef) {
1804
+ // Needed to handle external refs from devs.
545
1805
  ionRouterOutlet.props.setRef(node);
546
1806
  }
547
1807
  if (ionRouterOutlet.props.forwardedRef) {
1808
+ // Needed to handle external refs from devs.
548
1809
  ionRouterOutlet.props.forwardedRef.current = node;
549
1810
  }
550
1811
  this.routerOutletElement = node;
551
1812
  const { ref } = ionRouterOutlet;
1813
+ // Check for legacy refs.
552
1814
  if (typeof ref === 'function') {
553
1815
  ref(node);
554
1816
  }
@@ -559,169 +1821,357 @@ class StackManager extends React.PureComponent {
559
1821
  return RouteManagerContext;
560
1822
  }
561
1823
  }
562
- function matchRoute(node, routeInfo) {
1824
+ /**
1825
+ * Finds the `<Route />` node matching the current route info.
1826
+ * If no `<Route />` can be matched, a fallback node is returned.
1827
+ * Routes are prioritized by specificity (most specific first).
1828
+ *
1829
+ * @param node The root node to search for `<Route />` nodes.
1830
+ * @param routeInfo The route information to match against.
1831
+ * @param parentPath The parent path that was matched by the parent outlet (for nested routing)
1832
+ */
1833
+ function findRouteByRouteInfo(node, routeInfo, parentPath) {
1834
+ var _a;
563
1835
  let matchedNode;
564
- React.Children.forEach(node, (child) => {
1836
+ let fallbackNode;
1837
+ // `<Route />` nodes are rendered inside of a <Routes /> node
1838
+ const routesChildren = (_a = getRoutesChildren(node)) !== null && _a !== void 0 ? _a : node;
1839
+ // Collect all route children
1840
+ const routeChildren = React.Children.toArray(routesChildren).filter((child) => React.isValidElement(child) && child.type === Route);
1841
+ // Sort routes by specificity (most specific first)
1842
+ const sortedRoutes = routeChildren.sort((a, b) => {
1843
+ const pathA = a.props.path || '';
1844
+ const pathB = b.props.path || '';
1845
+ // Index routes come first
1846
+ if (a.props.index && !b.props.index)
1847
+ return -1;
1848
+ if (!a.props.index && b.props.index)
1849
+ return 1;
1850
+ // Wildcard-only routes (*) should come LAST
1851
+ const aIsWildcardOnly = pathA === '*';
1852
+ const bIsWildcardOnly = pathB === '*';
1853
+ if (!aIsWildcardOnly && bIsWildcardOnly)
1854
+ return -1;
1855
+ if (aIsWildcardOnly && !bIsWildcardOnly)
1856
+ return 1;
1857
+ // Exact matches (no wildcards/params) come before wildcard/param routes
1858
+ const aHasWildcard = pathA.includes('*') || pathA.includes(':');
1859
+ const bHasWildcard = pathB.includes('*') || pathB.includes(':');
1860
+ if (!aHasWildcard && bHasWildcard)
1861
+ return -1;
1862
+ if (aHasWildcard && !bHasWildcard)
1863
+ return 1;
1864
+ // Among routes with same wildcard status, longer paths are more specific
1865
+ if (pathA.length !== pathB.length) {
1866
+ return pathB.length - pathA.length;
1867
+ }
1868
+ return 0;
1869
+ });
1870
+ // For nested routes in React Router 6, we need to extract the relative path
1871
+ // that this outlet should be responsible for matching
1872
+ let pathnameToMatch = routeInfo.pathname;
1873
+ // Check if we have relative routes (routes that don't start with '/')
1874
+ const hasRelativeRoutes = sortedRoutes.some((r) => r.props.path && !r.props.path.startsWith('/'));
1875
+ const hasIndexRoute = sortedRoutes.some((r) => r.props.index);
1876
+ // SIMPLIFIED: Trust React Router 6's matching more, compute relative path when parent is known
1877
+ if ((hasRelativeRoutes || hasIndexRoute) && parentPath) {
1878
+ const parentPrefix = parentPath.replace('/*', '');
1879
+ const normalizedParent = stripTrailingSlash(parentPrefix);
1880
+ const normalizedPathname = stripTrailingSlash(routeInfo.pathname);
1881
+ // Only compute relative path if pathname is within parent scope
1882
+ if (normalizedPathname.startsWith(normalizedParent + '/') || normalizedPathname === normalizedParent) {
1883
+ const pathSegments = routeInfo.pathname.split('/').filter(Boolean);
1884
+ const parentSegments = normalizedParent.split('/').filter(Boolean);
1885
+ const relativeSegments = pathSegments.slice(parentSegments.length);
1886
+ pathnameToMatch = relativeSegments.join('/'); // Empty string is valid for index routes
1887
+ }
1888
+ }
1889
+ // Find the first matching route
1890
+ for (const child of sortedRoutes) {
565
1891
  const match = matchPath({
566
- pathname: routeInfo.pathname,
1892
+ pathname: pathnameToMatch,
567
1893
  componentProps: child.props,
568
1894
  });
569
1895
  if (match) {
570
1896
  matchedNode = child;
1897
+ break;
571
1898
  }
572
- });
1899
+ }
573
1900
  if (matchedNode) {
574
1901
  return matchedNode;
575
1902
  }
576
- // If we haven't found a node
577
- // try to find one that doesn't have a path or from prop, that will be our not found route
578
- React.Children.forEach(node, (child) => {
579
- if (!(child.props.path || child.props.from)) {
580
- matchedNode = child;
1903
+ // If we haven't found a node, try to find one that doesn't have a path prop (fallback route)
1904
+ // BUT only return the fallback if the current pathname is within the outlet's scope.
1905
+ // For outlets with absolute paths, compute the common prefix to determine scope.
1906
+ const absolutePathRoutes = routeChildren.filter((r) => r.props.path && r.props.path.startsWith('/'));
1907
+ // Determine if pathname is within scope before returning fallback
1908
+ let isPathnameInScope = true;
1909
+ if (absolutePathRoutes.length > 0) {
1910
+ // Find common prefix of all absolute paths to determine outlet scope
1911
+ const absolutePaths = absolutePathRoutes.map((r) => r.props.path);
1912
+ const commonPrefix = computeCommonPrefix(absolutePaths);
1913
+ // If we have a common prefix, check if the current pathname is within that scope
1914
+ if (commonPrefix && commonPrefix !== '/') {
1915
+ isPathnameInScope = routeInfo.pathname.startsWith(commonPrefix);
581
1916
  }
582
- });
583
- return matchedNode;
1917
+ }
1918
+ // Only look for fallback route if pathname is within scope
1919
+ if (isPathnameInScope) {
1920
+ for (const child of routeChildren) {
1921
+ if (!child.props.path) {
1922
+ fallbackNode = child;
1923
+ break;
1924
+ }
1925
+ }
1926
+ }
1927
+ return matchedNode !== null && matchedNode !== void 0 ? matchedNode : fallbackNode;
584
1928
  }
585
1929
  function matchComponent(node, pathname, forceExact) {
1930
+ var _a;
1931
+ const routePath = (_a = node === null || node === void 0 ? void 0 : node.props) === null || _a === void 0 ? void 0 : _a.path;
1932
+ const pathnameToMatch = derivePathnameToMatch(pathname, routePath);
586
1933
  return matchPath({
587
- pathname,
588
- componentProps: Object.assign(Object.assign({}, node.props), { exact: forceExact }),
1934
+ pathname: pathnameToMatch,
1935
+ componentProps: Object.assign(Object.assign({}, node.props), { end: forceExact }),
589
1936
  });
590
1937
  }
591
1938
 
592
- class IonRouterInner extends React.PureComponent {
593
- constructor(props) {
594
- super(props);
595
- this.exitViewFromOtherOutletHandlers = [];
596
- this.locationHistory = new LocationHistory();
597
- this.viewStack = new ReactRouterViewStack();
598
- this.routeMangerContextState = {
599
- canGoBack: () => this.locationHistory.canGoBack(),
600
- clearOutlet: this.viewStack.clear,
601
- findViewItemByPathname: this.viewStack.findViewItemByPathname,
602
- getChildrenToRender: this.viewStack.getChildrenToRender,
603
- goBack: () => this.handleNavigateBack(),
604
- createViewItem: this.viewStack.createViewItem,
605
- findViewItemByRouteInfo: this.viewStack.findViewItemByRouteInfo,
606
- findLeavingViewItemByRouteInfo: this.viewStack.findLeavingViewItemByRouteInfo,
607
- addViewItem: this.viewStack.add,
608
- unMountViewItem: this.viewStack.remove,
609
- };
610
- const routeInfo = {
611
- id: generateId('routeInfo'),
612
- pathname: this.props.location.pathname,
613
- search: this.props.location.search,
614
- };
615
- this.locationHistory.add(routeInfo);
616
- this.handleChangeTab = this.handleChangeTab.bind(this);
617
- this.handleResetTab = this.handleResetTab.bind(this);
618
- this.handleNativeBack = this.handleNativeBack.bind(this);
619
- this.handleNavigate = this.handleNavigate.bind(this);
620
- this.handleNavigateBack = this.handleNavigateBack.bind(this);
621
- this.props.registerHistoryListener(this.handleHistoryChange.bind(this));
622
- this.handleSetCurrentTab = this.handleSetCurrentTab.bind(this);
623
- this.state = {
624
- routeInfo,
625
- };
1939
+ /**
1940
+ * `IonRouter` is responsible for managing the application's navigation
1941
+ * state, tracking the history of visited routes, and coordinating
1942
+ * transitions between different views. It intercepts route changes from
1943
+ * React Router and translates them into actions that Ionic can understand
1944
+ * and animate.
1945
+ */
1946
+ const filterUndefinedParams = (params) => {
1947
+ const result = {};
1948
+ for (const key of Object.keys(params)) {
1949
+ const value = params[key];
1950
+ if (value !== undefined) {
1951
+ result[key] = value;
1952
+ }
626
1953
  }
627
- handleChangeTab(tab, path, routeOptions) {
628
- if (!path) {
1954
+ return result;
1955
+ };
1956
+ const areParamsEqual = (a, b) => {
1957
+ const paramsA = a || {};
1958
+ const paramsB = b || {};
1959
+ const keysA = Object.keys(paramsA);
1960
+ const keysB = Object.keys(paramsB);
1961
+ if (keysA.length !== keysB.length) {
1962
+ return false;
1963
+ }
1964
+ return keysA.every((key) => {
1965
+ const valueA = paramsA[key];
1966
+ const valueB = paramsB[key];
1967
+ if (Array.isArray(valueA) && Array.isArray(valueB)) {
1968
+ if (valueA.length !== valueB.length) {
1969
+ return false;
1970
+ }
1971
+ return valueA.every((entry, idx) => entry === valueB[idx]);
1972
+ }
1973
+ return valueA === valueB;
1974
+ });
1975
+ };
1976
+ const IonRouter = ({ children, registerHistoryListener }) => {
1977
+ const location = useLocation();
1978
+ const navigate = useNavigate();
1979
+ const didMountRef = useRef(false);
1980
+ const locationHistory = useRef(new LocationHistory());
1981
+ const currentTab = useRef(undefined);
1982
+ const viewStack = useRef(new ReactRouterViewStack());
1983
+ const incomingRouteParams = useRef(null);
1984
+ const [routeInfo, setRouteInfo] = useState({
1985
+ id: generateId('routeInfo'),
1986
+ pathname: location.pathname,
1987
+ search: location.search,
1988
+ params: {},
1989
+ });
1990
+ useEffect(() => {
1991
+ if (didMountRef.current) {
629
1992
  return;
630
1993
  }
631
- const routeInfo = this.locationHistory.getCurrentRouteInfoForTab(tab);
632
- const [pathname, search] = path.split('?');
633
- if (routeInfo) {
634
- this.incomingRouteParams = Object.assign(Object.assign({}, routeInfo), { routeAction: 'push', routeDirection: 'none' });
635
- if (routeInfo.pathname === pathname) {
636
- this.incomingRouteParams.routeOptions = routeOptions;
637
- this.props.history.push(routeInfo.pathname + (routeInfo.search || ''));
638
- }
639
- else {
640
- this.incomingRouteParams.pathname = pathname;
641
- this.incomingRouteParams.search = search ? '?' + search : undefined;
642
- this.incomingRouteParams.routeOptions = routeOptions;
643
- this.props.history.push(pathname + (search ? '?' + search : ''));
1994
+ // Seed the history stack with the initial location and begin listening
1995
+ // for future navigations once React has committed the mount. This avoids
1996
+ // duplicate entries when React StrictMode runs an extra render pre-commit.
1997
+ locationHistory.current.add(routeInfo);
1998
+ registerHistoryListener(handleHistoryChange);
1999
+ didMountRef.current = true;
2000
+ }, []);
2001
+ useEffect(() => {
2002
+ var _a;
2003
+ const activeView = viewStack.current.findViewItemByRouteInfo(routeInfo, undefined, true);
2004
+ const matchedParams = (_a = activeView === null || activeView === void 0 ? void 0 : activeView.routeData.match) === null || _a === void 0 ? void 0 : _a.params;
2005
+ if (matchedParams) {
2006
+ const paramsCopy = filterUndefinedParams(Object.assign({}, matchedParams));
2007
+ if (areParamsEqual(routeInfo.params, paramsCopy)) {
2008
+ return;
644
2009
  }
2010
+ const updatedRouteInfo = Object.assign(Object.assign({}, routeInfo), { params: paramsCopy });
2011
+ locationHistory.current.update(updatedRouteInfo);
2012
+ setRouteInfo(updatedRouteInfo);
645
2013
  }
646
- else {
647
- this.handleNavigate(pathname, 'push', 'none', undefined, routeOptions, tab);
648
- }
649
- }
650
- handleHistoryChange(location, action) {
651
- var _a, _b, _c;
2014
+ }, [routeInfo]);
2015
+ /**
2016
+ * Triggered whenever the history changes, either through user navigation
2017
+ * or programmatic changes. It transforms the raw browser history changes
2018
+ * into `RouteInfo` objects, which are needed Ionic's animations and
2019
+ * navigation patterns.
2020
+ *
2021
+ * @param location The current location object from the history.
2022
+ * @param action The action that triggered the history change.
2023
+ */
2024
+ const handleHistoryChange = (location, action) => {
2025
+ var _a, _b, _c, _d, _e;
652
2026
  let leavingLocationInfo;
653
- if (this.incomingRouteParams) {
654
- if (this.incomingRouteParams.routeAction === 'replace') {
655
- leavingLocationInfo = this.locationHistory.previous();
2027
+ /**
2028
+ * A programmatic navigation was triggered.
2029
+ * e.g., `<Redirect />`, `history.push()`, or `handleNavigate()`
2030
+ */
2031
+ if (incomingRouteParams.current) {
2032
+ /**
2033
+ * The current history entry is overwritten, so the previous entry
2034
+ * is the one we are leaving.
2035
+ */
2036
+ if (((_a = incomingRouteParams.current) === null || _a === void 0 ? void 0 : _a.routeAction) === 'replace') {
2037
+ leavingLocationInfo = locationHistory.current.previous();
656
2038
  }
657
2039
  else {
658
- leavingLocationInfo = this.locationHistory.current();
2040
+ // If the action is 'push' or 'pop', we want to use the current route.
2041
+ leavingLocationInfo = locationHistory.current.current();
659
2042
  }
660
2043
  }
661
2044
  else {
662
- leavingLocationInfo = this.locationHistory.current();
2045
+ /**
2046
+ * An external navigation was triggered
2047
+ * e.g., browser back/forward button or direct link
2048
+ *
2049
+ * The leaving location is the current route.
2050
+ */
2051
+ leavingLocationInfo = locationHistory.current.current();
663
2052
  }
664
2053
  const leavingUrl = leavingLocationInfo.pathname + leavingLocationInfo.search;
665
2054
  if (leavingUrl !== location.pathname) {
666
- if (!this.incomingRouteParams) {
2055
+ if (!incomingRouteParams.current) {
2056
+ // Determine if the destination is a tab route by checking if it matches
2057
+ // the pattern of tab routes (containing /tabs/ in the path)
2058
+ const isTabRoute = /\/tabs(\/|$)/.test(location.pathname);
2059
+ const tabToUse = isTabRoute ? currentTab.current : undefined;
2060
+ // If we're leaving tabs entirely, clear the current tab
2061
+ if (!isTabRoute && currentTab.current) {
2062
+ currentTab.current = undefined;
2063
+ }
2064
+ /**
2065
+ * A `REPLACE` action can be triggered by React Router's
2066
+ * `<Redirect />` component.
2067
+ */
667
2068
  if (action === 'REPLACE') {
668
- this.incomingRouteParams = {
2069
+ incomingRouteParams.current = {
669
2070
  routeAction: 'replace',
670
2071
  routeDirection: 'none',
671
- tab: this.currentTab,
2072
+ tab: tabToUse,
672
2073
  };
673
2074
  }
2075
+ /**
2076
+ * A `POP` action can be triggered by the browser's back/forward
2077
+ * button.
2078
+ */
674
2079
  if (action === 'POP') {
675
- const currentRoute = this.locationHistory.current();
2080
+ const currentRoute = locationHistory.current.current();
2081
+ /**
2082
+ * Check if the current route was "pushed" by a previous route
2083
+ * (indicates a linear history path).
2084
+ */
676
2085
  if (currentRoute && currentRoute.pushedByRoute) {
677
- const prevInfo = this.locationHistory.findLastLocation(currentRoute);
678
- this.incomingRouteParams = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back' });
2086
+ const prevInfo = locationHistory.current.findLastLocation(currentRoute);
2087
+ incomingRouteParams.current = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back' });
2088
+ // It's a non-linear history path like a direct link.
679
2089
  }
680
2090
  else {
681
- this.incomingRouteParams = {
2091
+ incomingRouteParams.current = {
682
2092
  routeAction: 'pop',
683
2093
  routeDirection: 'none',
684
- tab: this.currentTab,
2094
+ tab: tabToUse,
685
2095
  };
686
2096
  }
687
2097
  }
688
- if (!this.incomingRouteParams) {
689
- this.incomingRouteParams = {
2098
+ if (!incomingRouteParams.current) {
2099
+ const state = location.state;
2100
+ incomingRouteParams.current = {
690
2101
  routeAction: 'push',
691
- routeDirection: ((_a = location.state) === null || _a === void 0 ? void 0 : _a.direction) || 'forward',
692
- routeOptions: (_b = location.state) === null || _b === void 0 ? void 0 : _b.routerOptions,
693
- tab: this.currentTab,
2102
+ routeDirection: (state === null || state === void 0 ? void 0 : state.direction) || 'forward',
2103
+ routeOptions: state === null || state === void 0 ? void 0 : state.routerOptions,
2104
+ tab: tabToUse,
694
2105
  };
695
2106
  }
696
2107
  }
697
2108
  let routeInfo;
698
- if ((_c = this.incomingRouteParams) === null || _c === void 0 ? void 0 : _c.id) {
699
- routeInfo = Object.assign(Object.assign({}, this.incomingRouteParams), { lastPathname: leavingLocationInfo.pathname });
700
- this.locationHistory.add(routeInfo);
2109
+ // If we're navigating away from tabs to a non-tab route, clear the current tab
2110
+ if (!/\/tabs(\/|$)/.test(location.pathname) && currentTab.current) {
2111
+ currentTab.current = undefined;
2112
+ }
2113
+ /**
2114
+ * An existing id indicates that it's re-activating an existing route.
2115
+ * e.g., tab switching or navigating back to a previous route
2116
+ */
2117
+ if ((_b = incomingRouteParams.current) === null || _b === void 0 ? void 0 : _b.id) {
2118
+ routeInfo = Object.assign(Object.assign({}, incomingRouteParams.current), { lastPathname: leavingLocationInfo.pathname });
2119
+ locationHistory.current.add(routeInfo);
2120
+ /**
2121
+ * A new route is being created since it's not re-activating
2122
+ * an existing route.
2123
+ */
701
2124
  }
702
2125
  else {
703
- const isPushed = this.incomingRouteParams.routeAction === 'push' && this.incomingRouteParams.routeDirection === 'forward';
704
- routeInfo = Object.assign(Object.assign({ id: generateId('routeInfo') }, this.incomingRouteParams), { lastPathname: leavingLocationInfo.pathname, pathname: location.pathname, search: location.search, params: this.props.match.params, prevRouteLastPathname: leavingLocationInfo.lastPathname });
2126
+ const isPushed = ((_c = incomingRouteParams.current) === null || _c === void 0 ? void 0 : _c.routeAction) === 'push' &&
2127
+ incomingRouteParams.current.routeDirection === 'forward';
2128
+ routeInfo = Object.assign(Object.assign({ id: generateId('routeInfo') }, incomingRouteParams.current), { lastPathname: leavingLocationInfo.pathname, pathname: location.pathname, search: location.search, params: ((_d = incomingRouteParams.current) === null || _d === void 0 ? void 0 : _d.params)
2129
+ ? filterUndefinedParams(incomingRouteParams.current.params)
2130
+ : {}, prevRouteLastPathname: leavingLocationInfo.lastPathname });
705
2131
  if (isPushed) {
706
- routeInfo.tab = leavingLocationInfo.tab;
2132
+ // Only inherit tab from leaving route if we don't already have one.
2133
+ // This preserves tab context for same-tab navigation while allowing cross-tab navigation.
2134
+ routeInfo.tab = routeInfo.tab || leavingLocationInfo.tab;
707
2135
  routeInfo.pushedByRoute = leavingLocationInfo.pathname;
2136
+ // Triggered by a browser back button or handleNavigateBack.
708
2137
  }
709
2138
  else if (routeInfo.routeAction === 'pop') {
710
- const r = this.locationHistory.findLastLocation(routeInfo);
2139
+ // Find the route that pushed this one.
2140
+ const r = locationHistory.current.findLastLocation(routeInfo);
711
2141
  routeInfo.pushedByRoute = r === null || r === void 0 ? void 0 : r.pushedByRoute;
2142
+ // Navigating to a new tab.
712
2143
  }
713
2144
  else if (routeInfo.routeAction === 'push' && routeInfo.tab !== leavingLocationInfo.tab) {
714
- // If we are switching tabs grab the last route info for the tab and use its pushedByRoute
715
- const lastRoute = this.locationHistory.getCurrentRouteInfoForTab(routeInfo.tab);
716
- routeInfo.pushedByRoute = lastRoute === null || lastRoute === void 0 ? void 0 : lastRoute.pushedByRoute;
2145
+ /**
2146
+ * If we are switching tabs grab the last route info for the
2147
+ * tab and use its `pushedByRoute`.
2148
+ */
2149
+ const lastRoute = locationHistory.current.getCurrentRouteInfoForTab(routeInfo.tab);
2150
+ /**
2151
+ * Tab bar switches (direction 'none') should not create cross-tab back
2152
+ * navigation. Only inherit pushedByRoute from the tab's own history.
2153
+ */
2154
+ if (routeInfo.routeDirection === 'none') {
2155
+ routeInfo.pushedByRoute = lastRoute === null || lastRoute === void 0 ? void 0 : lastRoute.pushedByRoute;
2156
+ }
2157
+ else {
2158
+ routeInfo.pushedByRoute = (_e = lastRoute === null || lastRoute === void 0 ? void 0 : lastRoute.pushedByRoute) !== null && _e !== void 0 ? _e : leavingLocationInfo.pathname;
2159
+ }
2160
+ // Triggered by `history.replace()` or a `<Redirect />` component, etc.
717
2161
  }
718
2162
  else if (routeInfo.routeAction === 'replace') {
719
- // Make sure to set the lastPathname, etc.. to the current route so the page transitions out
720
- const currentRouteInfo = this.locationHistory.current();
721
2163
  /**
722
- * If going from /home to /child, then replacing from
723
- * /child to /home, we don't want the route info to
724
- * say that /home was pushed by /home which is not correct.
2164
+ * Make sure to set the `lastPathname`, etc.. to the current route
2165
+ * so the page transitions out.
2166
+ */
2167
+ const currentRouteInfo = locationHistory.current.current();
2168
+ /**
2169
+ * Special handling for `replace` to ensure correct `pushedByRoute`
2170
+ * and `lastPathname`.
2171
+ *
2172
+ * If going from `/home` to `/child`, then replacing from
2173
+ * `/child` to `/home`, we don't want the route info to
2174
+ * say that `/home` was pushed by `/home` which is not correct.
725
2175
  */
726
2176
  const currentPushedBy = currentRouteInfo === null || currentRouteInfo === void 0 ? void 0 : currentRouteInfo.pushedByRoute;
727
2177
  const pushedByRoute = currentPushedBy !== undefined && currentPushedBy !== routeInfo.pathname
@@ -739,46 +2189,107 @@ class IonRouterInner extends React.PureComponent {
739
2189
  routeInfo.routeDirection = routeInfo.routeDirection || (currentRouteInfo === null || currentRouteInfo === void 0 ? void 0 : currentRouteInfo.routeDirection);
740
2190
  routeInfo.routeAnimation = routeInfo.routeAnimation || (currentRouteInfo === null || currentRouteInfo === void 0 ? void 0 : currentRouteInfo.routeAnimation);
741
2191
  }
742
- this.locationHistory.add(routeInfo);
2192
+ locationHistory.current.add(routeInfo);
743
2193
  }
744
- this.setState({
745
- routeInfo,
746
- });
2194
+ setRouteInfo(routeInfo);
747
2195
  }
748
- this.incomingRouteParams = undefined;
749
- }
2196
+ incomingRouteParams.current = null;
2197
+ };
750
2198
  /**
751
- * history@4.x uses goBack(), history@5.x uses back()
752
- * TODO: If support for React Router <=5 is dropped
753
- * this logic is no longer needed. We can just
754
- * assume back() is available.
2199
+ * Resets the specified tab to its initial, root route.
2200
+ *
2201
+ * @param tab The tab to reset.
2202
+ * @param originalHref The original href for the tab.
2203
+ * @param originalRouteOptions The original route options for the tab.
755
2204
  */
756
- handleNativeBack() {
757
- const history = this.props.history;
758
- const goBack = history.goBack || history.back;
759
- goBack();
760
- }
761
- handleNavigate(path, routeAction, routeDirection, routeAnimation, routeOptions, tab) {
762
- this.incomingRouteParams = Object.assign(this.incomingRouteParams || {}, {
763
- routeAction,
764
- routeDirection,
765
- routeOptions,
766
- routeAnimation,
767
- tab,
768
- });
769
- if (routeAction === 'push') {
770
- this.props.history.push(path);
2205
+ const handleResetTab = (tab, originalHref, originalRouteOptions) => {
2206
+ const routeInfo = locationHistory.current.getFirstRouteInfoForTab(tab);
2207
+ if (routeInfo) {
2208
+ const newRouteInfo = Object.assign({}, routeInfo);
2209
+ newRouteInfo.pathname = originalHref;
2210
+ newRouteInfo.routeOptions = originalRouteOptions;
2211
+ incomingRouteParams.current = Object.assign(Object.assign({}, newRouteInfo), { routeAction: 'pop', routeDirection: 'back' });
2212
+ navigate(newRouteInfo.pathname + (newRouteInfo.search || ''));
2213
+ }
2214
+ };
2215
+ /**
2216
+ * Handles tab changes.
2217
+ *
2218
+ * @param tab The tab to switch to.
2219
+ * @param path The new path for the tab.
2220
+ * @param routeOptions Additional route options.
2221
+ */
2222
+ const handleChangeTab = (tab, path, routeOptions) => {
2223
+ if (!path) {
2224
+ return;
2225
+ }
2226
+ const routeInfo = locationHistory.current.getCurrentRouteInfoForTab(tab);
2227
+ const [pathname, search] = path.split('?');
2228
+ // User has navigated to the current tab before.
2229
+ if (routeInfo) {
2230
+ const routeParams = Object.assign(Object.assign({}, routeInfo), { routeAction: 'push', routeDirection: 'none' });
2231
+ /**
2232
+ * User is navigating to the same tab.
2233
+ * e.g., `/tabs/home` → `/tabs/home`
2234
+ */
2235
+ if (routeInfo.pathname === pathname) {
2236
+ incomingRouteParams.current = Object.assign(Object.assign({}, routeParams), { routeOptions });
2237
+ navigate(routeInfo.pathname + (routeInfo.search || ''));
2238
+ /**
2239
+ * User is navigating to a different tab.
2240
+ * e.g., `/tabs/home` → `/tabs/settings`
2241
+ */
2242
+ }
2243
+ else {
2244
+ incomingRouteParams.current = Object.assign(Object.assign({}, routeParams), { pathname, search: search ? '?' + search : undefined, routeOptions });
2245
+ navigate(pathname + (search ? '?' + search : ''));
2246
+ }
2247
+ // User has not navigated to this tab before.
771
2248
  }
772
2249
  else {
773
- this.props.history.replace(path);
2250
+ handleNavigate(pathname, 'push', 'none', undefined, routeOptions, tab);
774
2251
  }
775
- }
776
- handleNavigateBack(defaultHref = '/', routeAnimation) {
2252
+ };
2253
+ /**
2254
+ * Set the current active tab in `locationHistory`.
2255
+ * This is crucial for maintaining tab history since each tab has
2256
+ * its own navigation stack.
2257
+ *
2258
+ * @param tab The tab to set as active.
2259
+ */
2260
+ const handleSetCurrentTab = (tab) => {
2261
+ currentTab.current = tab;
2262
+ const ri = Object.assign({}, locationHistory.current.current());
2263
+ if (ri.tab !== tab) {
2264
+ ri.tab = tab;
2265
+ locationHistory.current.update(ri);
2266
+ }
2267
+ };
2268
+ /**
2269
+ * Handles the native back button press.
2270
+ * It's usually called when a user presses the platform-native back action.
2271
+ */
2272
+ const handleNativeBack = () => {
2273
+ navigate(-1);
2274
+ };
2275
+ /**
2276
+ * Used to manage the back navigation within the Ionic React's routing
2277
+ * system. It's deeply integrated with Ionic's view lifecycle, animations,
2278
+ * and its custom history tracking (`locationHistory`) to provide a
2279
+ * native-like transition and maintain correct application state.
2280
+ *
2281
+ * @param defaultHref The fallback URL to navigate to if there's no
2282
+ * previous entry in the `locationHistory` stack.
2283
+ * @param routeAnimation A custom animation builder to override the
2284
+ * default "back" animation.
2285
+ */
2286
+ const handleNavigateBack = (defaultHref = '/', routeAnimation) => {
777
2287
  const config = getConfig();
778
2288
  defaultHref = defaultHref ? defaultHref : config && config.get('backButtonDefaultHref');
779
- const routeInfo = this.locationHistory.current();
2289
+ const routeInfo = locationHistory.current.current();
2290
+ // It's a linear navigation.
780
2291
  if (routeInfo && routeInfo.pushedByRoute) {
781
- const prevInfo = this.locationHistory.findLastLocation(routeInfo);
2292
+ const prevInfo = locationHistory.current.findLastLocation(routeInfo);
782
2293
  if (prevInfo) {
783
2294
  /**
784
2295
  * This needs to be passed to handleNavigate
@@ -786,160 +2297,235 @@ class IonRouterInner extends React.PureComponent {
786
2297
  * will be overridden.
787
2298
  */
788
2299
  const incomingAnimation = routeAnimation || routeInfo.routeAnimation;
789
- this.incomingRouteParams = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back', routeAnimation: incomingAnimation });
790
- if (routeInfo.lastPathname === routeInfo.pushedByRoute ||
791
- /**
792
- * We need to exclude tab switches/tab
793
- * context changes here because tabbed
794
- * navigation is not linear, but router.back()
795
- * will go back in a linear fashion.
796
- */
797
- (prevInfo.pathname === routeInfo.pushedByRoute && routeInfo.tab === '' && prevInfo.tab === '')) {
798
- /**
799
- * history@4.x uses goBack(), history@5.x uses back()
800
- * TODO: If support for React Router <=5 is dropped
801
- * this logic is no longer needed. We can just
802
- * assume back() is available.
803
- */
804
- const history = this.props.history;
805
- const goBack = history.goBack || history.back;
806
- goBack();
2300
+ incomingRouteParams.current = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back', routeAnimation: incomingAnimation });
2301
+ /**
2302
+ * Check if it's a simple linear back navigation (not tabbed).
2303
+ * e.g., `/home` `/settings` back to `/home`
2304
+ */
2305
+ const condition1 = routeInfo.lastPathname === routeInfo.pushedByRoute;
2306
+ const condition2 = prevInfo.pathname === routeInfo.pushedByRoute && routeInfo.tab === '' && prevInfo.tab === '';
2307
+ if (condition1 || condition2) {
2308
+ navigate(-1);
807
2309
  }
808
2310
  else {
809
- this.handleNavigate(prevInfo.pathname + (prevInfo.search || ''), 'pop', 'back', incomingAnimation);
2311
+ /**
2312
+ * It's a non-linear back navigation.
2313
+ * e.g., direct link or tab switch or nested navigation with redirects
2314
+ */
2315
+ handleNavigate(prevInfo.pathname + (prevInfo.search || ''), 'pop', 'back', incomingAnimation);
810
2316
  }
2317
+ /**
2318
+ * `pushedByRoute` exists, but no corresponding previous entry in
2319
+ * the history stack.
2320
+ */
811
2321
  }
812
2322
  else {
813
- this.handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
2323
+ handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
814
2324
  }
2325
+ /**
2326
+ * No `pushedByRoute` (e.g., initial page load or tab root).
2327
+ * Tabs with no back history should not navigate.
2328
+ */
815
2329
  }
816
2330
  else {
817
- this.handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
818
- }
819
- }
820
- handleResetTab(tab, originalHref, originalRouteOptions) {
821
- const routeInfo = this.locationHistory.getFirstRouteInfoForTab(tab);
822
- if (routeInfo) {
823
- const newRouteInfo = Object.assign({}, routeInfo);
824
- newRouteInfo.pathname = originalHref;
825
- newRouteInfo.routeOptions = originalRouteOptions;
826
- this.incomingRouteParams = Object.assign(Object.assign({}, newRouteInfo), { routeAction: 'pop', routeDirection: 'back' });
827
- this.props.history.push(newRouteInfo.pathname + (newRouteInfo.search || ''));
2331
+ if (routeInfo && routeInfo.tab) {
2332
+ return;
2333
+ }
2334
+ handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
828
2335
  }
829
- }
830
- handleSetCurrentTab(tab) {
831
- this.currentTab = tab;
832
- const ri = Object.assign({}, this.locationHistory.current());
833
- if (ri.tab !== tab) {
834
- ri.tab = tab;
835
- this.locationHistory.update(ri);
2336
+ };
2337
+ /**
2338
+ * Used to programmatically navigate through the app.
2339
+ *
2340
+ * @param path The path to navigate to.
2341
+ * @param routeAction The action to take (push, replace, etc.).
2342
+ * @param routeDirection The direction of the navigation (forward,
2343
+ * back, etc.).
2344
+ * @param routeAnimation The animation to use for the transition.
2345
+ * @param routeOptions Additional options for the route.
2346
+ * @param tab The tab to navigate to, if applicable.
2347
+ */
2348
+ const handleNavigate = (path, routeAction, routeDirection, routeAnimation, routeOptions, tab) => {
2349
+ var _a;
2350
+ const normalizedRouteDirection = routeAction === 'push' && routeDirection === undefined ? 'forward' : routeDirection;
2351
+ // When navigating from tabs context, we need to determine if the destination
2352
+ // is also within tabs. If not, we should clear the tab context.
2353
+ let navigationTab = tab;
2354
+ // If no explicit tab is provided and we're in a tab context,
2355
+ // check if the destination path is outside of the current tab context
2356
+ if (!tab && currentTab.current && path) {
2357
+ // Get the current route info to understand where we are
2358
+ const currentRoute = locationHistory.current.current();
2359
+ // If we're navigating from a tab route to a completely different path structure,
2360
+ // we should clear the tab context. This is a simplified check that assumes
2361
+ // tab routes share a common parent path.
2362
+ if (currentRoute && currentRoute.pathname) {
2363
+ // Extract the base tab path (e.g., /routing/tabs from /routing/tabs/home)
2364
+ const tabBaseMatch = currentRoute.pathname.match(/^(.*\/tabs)/);
2365
+ if (tabBaseMatch) {
2366
+ const tabBasePath = tabBaseMatch[1];
2367
+ // If the new path doesn't start with the tab base path, we're leaving tabs
2368
+ if (!path.startsWith(tabBasePath)) {
2369
+ currentTab.current = undefined;
2370
+ navigationTab = undefined;
2371
+ }
2372
+ else {
2373
+ // Still within tabs, preserve the tab context
2374
+ navigationTab = currentTab.current;
2375
+ }
2376
+ }
2377
+ }
836
2378
  }
837
- }
838
- render() {
839
- return (React.createElement(RouteManagerContext.Provider, { value: this.routeMangerContextState },
840
- React.createElement(NavManager, { ionRoute: IonRouteInner, ionRedirect: {}, stackManager: StackManager, routeInfo: this.state.routeInfo, onNativeBack: this.handleNativeBack, onNavigateBack: this.handleNavigateBack, onNavigate: this.handleNavigate, onSetCurrentTab: this.handleSetCurrentTab, onChangeTab: this.handleChangeTab, onResetTab: this.handleResetTab, locationHistory: this.locationHistory }, this.props.children)));
841
- }
842
- }
843
- const IonRouter = withRouter(IonRouterInner);
2379
+ const baseParams = (_a = incomingRouteParams.current) !== null && _a !== void 0 ? _a : {};
2380
+ incomingRouteParams.current = Object.assign(Object.assign({}, baseParams), { routeAction, routeDirection: normalizedRouteDirection, routeOptions,
2381
+ routeAnimation, tab: navigationTab });
2382
+ navigate(path, { replace: routeAction !== 'push' });
2383
+ };
2384
+ const routeMangerContextValue = {
2385
+ canGoBack: () => locationHistory.current.canGoBack(),
2386
+ clearOutlet: viewStack.current.clear,
2387
+ findViewItemByPathname: viewStack.current.findViewItemByPathname,
2388
+ getChildrenToRender: viewStack.current.getChildrenToRender,
2389
+ getViewItemsForOutlet: viewStack.current.getViewItemsForOutlet.bind(viewStack.current),
2390
+ goBack: () => handleNavigateBack(),
2391
+ createViewItem: viewStack.current.createViewItem,
2392
+ findViewItemByRouteInfo: viewStack.current.findViewItemByRouteInfo,
2393
+ findLeavingViewItemByRouteInfo: viewStack.current.findLeavingViewItemByRouteInfo,
2394
+ addViewItem: viewStack.current.add,
2395
+ unMountViewItem: viewStack.current.remove,
2396
+ };
2397
+ return (React.createElement(RouteManagerContext.Provider, { value: routeMangerContextValue },
2398
+ React.createElement(NavManager, { ionRoute: IonRouteInner, ionRedirect: {}, stackManager: StackManager, routeInfo: routeInfo, onNativeBack: handleNativeBack, onNavigateBack: handleNavigateBack, onNavigate: handleNavigate, onSetCurrentTab: handleSetCurrentTab, onChangeTab: handleChangeTab, onResetTab: handleResetTab, locationHistory: locationHistory.current }, children)));
2399
+ };
844
2400
  IonRouter.displayName = 'IonRouter';
845
2401
 
846
- class IonReactRouter extends React.Component {
847
- constructor(props) {
848
- super(props);
849
- const { history } = props, rest = __rest(props, ["history"]);
850
- this.history = history || createBrowserHistory(rest);
851
- this.history.listen(this.handleHistoryChange.bind(this));
852
- this.registerHistoryListener = this.registerHistoryListener.bind(this);
853
- }
2402
+ /**
2403
+ * `IonReactRouter` facilitates the integration of Ionic's specific
2404
+ * navigation and UI management with the standard React Router mechanisms,
2405
+ * allowing an inner Ionic-specific router (`IonRouter`) to react to
2406
+ * navigation events.
2407
+ */
2408
+ /**
2409
+ * This component acts as a bridge to ensure React Router hooks like
2410
+ * `useLocation` and `useNavigationType` are called within the valid
2411
+ * context of a `<BrowserRouter>`.
2412
+ *
2413
+ * It was split from `IonReactRouter` because these hooks must be
2414
+ * descendants of a `<Router>` component, which `BrowserRouter` provides.
2415
+ */
2416
+ const RouterContent$2 = ({ children }) => {
2417
+ const location = useLocation();
2418
+ const navigationType = useNavigationType();
2419
+ const historyListenHandler = useRef();
2420
+ const registerHistoryListener = useCallback((cb) => {
2421
+ historyListenHandler.current = cb;
2422
+ }, []);
854
2423
  /**
855
- * history@4.x passes separate location and action
856
- * params. history@5.x passes location and action
857
- * together as a single object.
858
- * TODO: If support for React Router <=5 is dropped
859
- * this logic is no longer needed. We can just assume
860
- * a single object with both location and action.
2424
+ * Processes navigation changes within the application.
2425
+ *
2426
+ * Its purpose is to relay the current `location` and the associated
2427
+ * `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
2428
+ * primarily for `IonRouter` to manage Ionic-specific UI updates and
2429
+ * navigation stack behavior.
2430
+ *
2431
+ * @param loc The current browser history location object.
2432
+ * @param act The type of navigation action ('PUSH', 'POP', or
2433
+ * 'REPLACE').
861
2434
  */
862
- handleHistoryChange(location, action) {
863
- const locationValue = location.location || location;
864
- const actionValue = location.action || action;
865
- if (this.historyListenHandler) {
866
- this.historyListenHandler(locationValue, actionValue);
2435
+ const handleHistoryChange = useCallback((loc, act) => {
2436
+ if (historyListenHandler.current) {
2437
+ historyListenHandler.current(loc, act);
867
2438
  }
868
- }
869
- registerHistoryListener(cb) {
870
- this.historyListenHandler = cb;
871
- }
872
- render() {
873
- const _a = this.props, { children } = _a, props = __rest(_a, ["children"]);
874
- return (React.createElement(Router, Object.assign({ history: this.history }, props),
875
- React.createElement(IonRouter, { registerHistoryListener: this.registerHistoryListener }, children)));
876
- }
877
- }
2439
+ }, []);
2440
+ useEffect(() => {
2441
+ handleHistoryChange(location, navigationType);
2442
+ }, [location, navigationType, handleHistoryChange]);
2443
+ return React.createElement(IonRouter, { registerHistoryListener: registerHistoryListener }, children);
2444
+ };
2445
+ const IonReactRouter = (_a) => {
2446
+ var { children } = _a, browserRouterProps = __rest(_a, ["children"]);
2447
+ return (React.createElement(BrowserRouter, Object.assign({}, browserRouterProps),
2448
+ React.createElement(RouterContent$2, null, children)));
2449
+ };
878
2450
 
879
- class IonReactMemoryRouter extends React.Component {
880
- constructor(props) {
881
- super(props);
882
- this.history = props.history;
883
- this.history.listen(this.handleHistoryChange.bind(this));
884
- this.registerHistoryListener = this.registerHistoryListener.bind(this);
885
- }
2451
+ /**
2452
+ * `IonReactMemoryRouter` provides a way to use `react-router` in
2453
+ * environments where a traditional browser history (like `BrowserRouter`)
2454
+ * isn't available or desirable.
2455
+ */
2456
+ const RouterContent$1 = ({ children }) => {
2457
+ const location = useLocation$1();
2458
+ const navigationType = useNavigationType$1();
2459
+ const historyListenHandler = useRef();
2460
+ const registerHistoryListener = (cb) => {
2461
+ historyListenHandler.current = cb;
2462
+ };
886
2463
  /**
887
- * history@4.x passes separate location and action
888
- * params. history@5.x passes location and action
889
- * together as a single object.
890
- * TODO: If support for React Router <=5 is dropped
891
- * this logic is no longer needed. We can just assume
892
- * a single object with both location and action.
2464
+ * Processes navigation changes within the application.
2465
+ *
2466
+ * Its purpose is to relay the current `location` and the associated
2467
+ * `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
2468
+ * primarily for `IonRouter` to manage Ionic-specific UI updates and
2469
+ * navigation stack behavior.
2470
+ *
2471
+ * @param location The current browser history location object.
2472
+ * @param action The type of navigation action ('PUSH', 'POP', or
2473
+ * 'REPLACE').
893
2474
  */
894
- handleHistoryChange(location, action) {
895
- const locationValue = location.location || location;
896
- const actionValue = location.action || action;
897
- if (this.historyListenHandler) {
898
- this.historyListenHandler(locationValue, actionValue);
2475
+ const handleHistoryChange = (location, action) => {
2476
+ if (historyListenHandler.current) {
2477
+ historyListenHandler.current(location, action);
899
2478
  }
900
- }
901
- registerHistoryListener(cb) {
902
- this.historyListenHandler = cb;
903
- }
904
- render() {
905
- const _a = this.props, { children } = _a, props = __rest(_a, ["children"]);
906
- return (React.createElement(Router$1, Object.assign({}, props),
907
- React.createElement(IonRouter, { registerHistoryListener: this.registerHistoryListener }, children)));
908
- }
909
- }
2479
+ };
2480
+ useEffect(() => {
2481
+ handleHistoryChange(location, navigationType);
2482
+ }, [location, navigationType]);
2483
+ return React.createElement(IonRouter, { registerHistoryListener: registerHistoryListener }, children);
2484
+ };
2485
+ const IonReactMemoryRouter = (_a) => {
2486
+ var { children } = _a, routerProps = __rest(_a, ["children"]);
2487
+ return (React.createElement(MemoryRouter, Object.assign({}, routerProps),
2488
+ React.createElement(RouterContent$1, null, children)));
2489
+ };
910
2490
 
911
- class IonReactHashRouter extends React.Component {
912
- constructor(props) {
913
- super(props);
914
- const { history } = props, rest = __rest(props, ["history"]);
915
- this.history = history || createHashHistory(rest);
916
- this.history.listen(this.handleHistoryChange.bind(this));
917
- this.registerHistoryListener = this.registerHistoryListener.bind(this);
918
- }
2491
+ /**
2492
+ * `IonReactHashRouter` provides a way to use hash-based routing in Ionic
2493
+ * React applications.
2494
+ */
2495
+ const RouterContent = ({ children }) => {
2496
+ const location = useLocation();
2497
+ const navigationType = useNavigationType();
2498
+ const historyListenHandler = useRef();
2499
+ const registerHistoryListener = (cb) => {
2500
+ historyListenHandler.current = cb;
2501
+ };
919
2502
  /**
920
- * history@4.x passes separate location and action
921
- * params. history@5.x passes location and action
922
- * together as a single object.
923
- * TODO: If support for React Router <=5 is dropped
924
- * this logic is no longer needed. We can just assume
925
- * a single object with both location and action.
2503
+ * Processes navigation changes within the application.
2504
+ *
2505
+ * Its purpose is to relay the current `location` and the associated
2506
+ * `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
2507
+ * primarily for `IonRouter` to manage Ionic-specific UI updates and
2508
+ * navigation stack behavior.
2509
+ *
2510
+ * @param location The current browser history location object.
2511
+ * @param action The type of navigation action ('PUSH', 'POP', or
2512
+ * 'REPLACE').
926
2513
  */
927
- handleHistoryChange(location, action) {
928
- const locationValue = location.location || location;
929
- const actionValue = location.action || action;
930
- if (this.historyListenHandler) {
931
- this.historyListenHandler(locationValue, actionValue);
2514
+ const handleHistoryChange = (location, action) => {
2515
+ if (historyListenHandler.current) {
2516
+ historyListenHandler.current(location, action);
932
2517
  }
933
- }
934
- registerHistoryListener(cb) {
935
- this.historyListenHandler = cb;
936
- }
937
- render() {
938
- const _a = this.props, { children } = _a, props = __rest(_a, ["children"]);
939
- return (React.createElement(Router, Object.assign({ history: this.history }, props),
940
- React.createElement(IonRouter, { registerHistoryListener: this.registerHistoryListener }, children)));
941
- }
942
- }
2518
+ };
2519
+ useEffect(() => {
2520
+ handleHistoryChange(location, navigationType);
2521
+ }, [location, navigationType]);
2522
+ return React.createElement(IonRouter, { registerHistoryListener: registerHistoryListener }, children);
2523
+ };
2524
+ const IonReactHashRouter = (_a) => {
2525
+ var { children } = _a, routerProps = __rest(_a, ["children"]);
2526
+ return (React.createElement(HashRouter, Object.assign({}, routerProps),
2527
+ React.createElement(RouterContent, null, children)));
2528
+ };
943
2529
 
944
2530
  export { IonReactHashRouter, IonReactMemoryRouter, IonReactRouter };
945
2531
  //# sourceMappingURL=index.js.map