@ionic/react-router 8.7.12-dev.11764961567.138743ff → 8.7.12-dev.11765219790.17cbe2e9

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