@ionic/react-router 8.7.13-dev.11765560568.1a8772e8 → 8.7.13-dev.11765569652.136c6b13

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