@ionic/react-router 8.8.1-dev.11773242897.1966d6b2 → 8.8.1-dev.11773432149.19826d0c

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,1301 @@
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, matchRoutes, useLocation, useNavigate, BrowserRouter, useNavigationType, HashRouter } from 'react-router-dom';
4
+ import { IonRoute, ViewStacks, generateId, ViewLifeCycleManager, 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, index, caseSensitive, element }) => {
8
+ return React.createElement(Route, { path: path, index: index, caseSensitive: caseSensitive, 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 pathname falls within the scope of a mount path using
167
+ * segment-aware comparison. Prevents false positives like "/tabs-secondary"
168
+ * matching mount path "/tabs".
169
+ */
170
+ const isPathnameInScope = (pathname, mountPath) => {
171
+ if (mountPath === '/')
172
+ return true;
173
+ return pathname === mountPath || pathname.startsWith(mountPath + '/');
174
+ };
175
+ /**
176
+ * Checks if a route path is a "splat-only" route (just `*` or `/*`).
177
+ */
178
+ const isSplatOnlyRoute = (routePath) => {
179
+ return routePath === '*' || routePath === '/*';
180
+ };
181
+ /**
182
+ * Checks if a route has an embedded wildcard (e.g., "tab1/*" but not "*" or "/*").
183
+ */
184
+ const hasEmbeddedWildcard = (routePath) => {
185
+ return !!routePath && routePath.includes('*') && !isSplatOnlyRoute(routePath);
186
+ };
187
+ /**
188
+ * Checks if a route with an embedded wildcard matches a pathname.
189
+ */
190
+ const matchesEmbeddedWildcardRoute = (route, pathname) => {
191
+ const routePath = route.props.path;
192
+ if (!hasEmbeddedWildcard(routePath)) {
36
193
  return false;
37
194
  }
38
- return match;
195
+ return !!matchPath({ pathname, componentProps: route.props });
196
+ };
197
+ /**
198
+ * Checks if a route is a specific match (not wildcard-only or index).
199
+ */
200
+ const isSpecificRouteMatch = (route, remainingPath) => {
201
+ const routePath = route.props.path;
202
+ if (route.props.index || isSplatOnlyRoute(routePath)) {
203
+ return false;
204
+ }
205
+ return !!matchPath({ pathname: remainingPath, componentProps: route.props });
206
+ };
207
+ /**
208
+ * Analyzes route children to determine their characteristics.
209
+ *
210
+ * @param routeChildren The route children to analyze.
211
+ * @returns Analysis of the route characteristics.
212
+ */
213
+ const analyzeRouteChildren = (routeChildren) => {
214
+ const hasRelativeRoutes = routeChildren.some((route) => {
215
+ const path = route.props.path;
216
+ return path && !path.startsWith('/') && path !== '*';
217
+ });
218
+ const hasIndexRoute = routeChildren.some((route) => route.props.index);
219
+ const hasWildcardRoute = routeChildren.some((route) => {
220
+ const routePath = route.props.path;
221
+ return routePath === '*' || routePath === '/*';
222
+ });
223
+ return { hasRelativeRoutes, hasIndexRoute, hasWildcardRoute, routeChildren };
224
+ };
225
+ /**
226
+ * Checks if any route matches as a specific (non-wildcard, non-index) route.
227
+ */
228
+ const findSpecificMatch = (routeChildren, remainingPath) => {
229
+ return routeChildren.some((route) => isSpecificRouteMatch(route, remainingPath) || matchesEmbeddedWildcardRoute(route, remainingPath));
230
+ };
231
+ /**
232
+ * Returns the first route that matches as a specific (non-wildcard, non-index) route.
233
+ */
234
+ const findFirstSpecificMatchingRoute = (routeChildren, remainingPath) => {
235
+ return routeChildren.find((route) => isSpecificRouteMatch(route, remainingPath) || matchesEmbeddedWildcardRoute(route, remainingPath));
236
+ };
237
+ /**
238
+ * Checks if any specific route could plausibly match the remaining path.
239
+ * Used to determine if we should fall back to a wildcard match.
240
+ *
241
+ * Uses exact first-segment matching: the remaining path's first segment
242
+ * must exactly equal a route's first segment to block the wildcard.
243
+ * The outlet's mount path is always known from React Router's RouteContext,
244
+ * so no heuristic-based discovery is needed.
245
+ */
246
+ const couldSpecificRouteMatch = (routeChildren, remainingPath) => {
247
+ const remainingFirstSegment = remainingPath.split('/')[0];
248
+ return routeChildren.some((route) => {
249
+ const routePath = route.props.path;
250
+ if (!routePath || routePath === '*' || routePath === '/*')
251
+ return false;
252
+ if (route.props.index)
253
+ return false;
254
+ const routeFirstSegment = routePath.split('/')[0].replace(/[*:]/g, '');
255
+ if (!routeFirstSegment)
256
+ return false;
257
+ return routeFirstSegment === remainingFirstSegment;
258
+ });
259
+ };
260
+ /**
261
+ * Determines the best parent path from the available matches.
262
+ * Priority: specific > wildcard > index
263
+ */
264
+ const selectBestMatch = (specificMatch, wildcardMatch, indexMatch) => {
265
+ var _a;
266
+ return (_a = specificMatch !== null && specificMatch !== void 0 ? specificMatch : wildcardMatch) !== null && _a !== void 0 ? _a : indexMatch;
267
+ };
268
+ /**
269
+ * Handles outlets with only absolute routes by computing their common prefix.
270
+ */
271
+ const computeAbsoluteRoutesParentPath = (routeChildren, currentPathname, outletMountPath) => {
272
+ const absolutePathRoutes = routeChildren.filter((route) => {
273
+ const path = route.props.path;
274
+ return path && path.startsWith('/');
275
+ });
276
+ if (absolutePathRoutes.length === 0) {
277
+ return undefined;
278
+ }
279
+ const absolutePaths = absolutePathRoutes.map((r) => r.props.path);
280
+ const commonPrefix = computeCommonPrefix(absolutePaths);
281
+ if (!commonPrefix || commonPrefix === '/') {
282
+ return undefined;
283
+ }
284
+ const newOutletMountPath = outletMountPath || commonPrefix;
285
+ if (!currentPathname.startsWith(commonPrefix)) {
286
+ return { parentPath: undefined, outletMountPath: newOutletMountPath };
287
+ }
288
+ return { parentPath: commonPrefix, outletMountPath: newOutletMountPath };
289
+ };
290
+ /**
291
+ * Computes the parent path for a nested outlet based on the current pathname
292
+ * and the outlet's route configuration.
293
+ *
294
+ * When the mount path is known (seeded from React Router's RouteContext), the
295
+ * parent path is simply the mount path — no iterative discovery needed. The
296
+ * iterative fallback only runs for outlets where RouteContext doesn't provide
297
+ * a parent match (typically root-level outlets on first render).
298
+ *
299
+ * @param options The options for computing the parent path.
300
+ * @returns The computed parent path result.
301
+ */
302
+ const computeParentPath = (options) => {
303
+ const { currentPathname, outletMountPath, routeChildren, hasRelativeRoutes, hasIndexRoute, hasWildcardRoute } = options;
304
+ // If pathname is outside the established mount path scope, skip computation.
305
+ // Use segment-aware comparison: /tabs-secondary must NOT match /tabs scope.
306
+ if (outletMountPath && !isPathnameInScope(currentPathname, outletMountPath)) {
307
+ return { parentPath: undefined, outletMountPath };
308
+ }
309
+ // Fast path: when the mount path is known (from React Router's RouteContext),
310
+ // the parent path IS the mount path. The iterative segment-by-segment discovery
311
+ // below was needed when the mount depth had to be guessed from URL structure,
312
+ // but with RouteContext we already know exactly where this outlet is mounted.
313
+ if (outletMountPath && (hasRelativeRoutes || hasIndexRoute)) {
314
+ return { parentPath: outletMountPath, outletMountPath };
315
+ }
316
+ // Fallback: mount path not yet known. Iterate through path segments to discover
317
+ // the correct parent depth. This only runs on first render of outlets where
318
+ // RouteContext doesn't provide a parent match (typically root-level outlets,
319
+ // which usually have absolute routes and take the absolute routes path below).
320
+ if (!outletMountPath && (hasRelativeRoutes || hasIndexRoute) && currentPathname.includes('/')) {
321
+ const segments = currentPathname.split('/').filter(Boolean);
322
+ if (segments.length >= 1) {
323
+ let firstSpecificMatch;
324
+ let firstWildcardMatch;
325
+ let indexMatchAtMount;
326
+ for (let i = 1; i <= segments.length; i++) {
327
+ const parentPath = '/' + segments.slice(0, i).join('/');
328
+ const remainingPath = segments.slice(i).join('/');
329
+ // Check for specific route match (highest priority)
330
+ if (!firstSpecificMatch && findSpecificMatch(routeChildren, remainingPath)) {
331
+ // Don't let empty/default path routes (path="" or undefined) drive
332
+ // the parent deeper than a wildcard match. An empty path route matching
333
+ // when remainingPath is "" just means all segments were consumed.
334
+ if (firstWildcardMatch) {
335
+ const matchingRoute = findFirstSpecificMatchingRoute(routeChildren, remainingPath);
336
+ if (matchingRoute) {
337
+ const matchingPath = matchingRoute.props.path;
338
+ if (!matchingPath || matchingPath === '') {
339
+ continue;
340
+ }
341
+ }
342
+ }
343
+ firstSpecificMatch = parentPath;
344
+ break;
345
+ }
346
+ // Check for wildcard match (only if remaining path is non-empty)
347
+ const hasNonEmptyRemaining = remainingPath !== '' && remainingPath !== '/';
348
+ if (!firstWildcardMatch && hasNonEmptyRemaining && hasWildcardRoute) {
349
+ if (!couldSpecificRouteMatch(routeChildren, remainingPath)) {
350
+ firstWildcardMatch = parentPath;
351
+ }
352
+ }
353
+ // Check for index route match
354
+ if ((remainingPath === '' || remainingPath === '/') && hasIndexRoute) {
355
+ indexMatchAtMount = parentPath;
356
+ }
357
+ }
358
+ // Fallback: check root level for embedded wildcard routes (e.g., "tab1/*")
359
+ if (!firstSpecificMatch) {
360
+ const fullRemainingPath = segments.join('/');
361
+ if (routeChildren.some((route) => matchesEmbeddedWildcardRoute(route, fullRemainingPath))) {
362
+ firstSpecificMatch = '/';
363
+ }
364
+ }
365
+ const bestPath = selectBestMatch(firstSpecificMatch, firstWildcardMatch, indexMatchAtMount);
366
+ return { parentPath: bestPath, outletMountPath: bestPath };
367
+ }
368
+ }
369
+ // Handle outlets with only absolute routes
370
+ if (!hasRelativeRoutes && !hasIndexRoute) {
371
+ const result = computeAbsoluteRoutesParentPath(routeChildren, currentPathname, outletMountPath);
372
+ if (result) {
373
+ return result;
374
+ }
375
+ }
376
+ return { parentPath: outletMountPath, outletMountPath };
377
+ };
378
+
379
+ /**
380
+ * Ensures the given path has a leading slash.
381
+ *
382
+ * @param value The path string to normalize.
383
+ * @returns The path with a leading slash.
384
+ */
385
+ const ensureLeadingSlash = (value) => {
386
+ if (value === '') {
387
+ return '/';
388
+ }
389
+ return value.startsWith('/') ? value : `/${value}`;
390
+ };
391
+ /**
392
+ * Strips the trailing slash from a path, unless it's the root path.
393
+ *
394
+ * @param value The path string to normalize.
395
+ * @returns The path without a trailing slash.
396
+ */
397
+ const stripTrailingSlash = (value) => {
398
+ return value.length > 1 && value.endsWith('/') ? value.slice(0, -1) : value;
399
+ };
400
+ /**
401
+ * Normalizes a pathname for comparison by ensuring a leading slash
402
+ * and removing trailing slashes.
403
+ *
404
+ * @param value The pathname to normalize, can be undefined.
405
+ * @returns A normalized pathname string.
406
+ */
407
+ const normalizePathnameForComparison = (value) => {
408
+ if (!value || value === '') {
409
+ return '/';
410
+ }
411
+ const withLeadingSlash = ensureLeadingSlash(value);
412
+ return stripTrailingSlash(withLeadingSlash);
39
413
  };
40
414
 
415
+ /**
416
+ * Extracts the children from a Routes wrapper component.
417
+ * The use of `<Routes />` is encouraged with React Router v6.
418
+ *
419
+ * @param node The React node to extract Routes children from.
420
+ * @returns The children of the Routes component, or undefined if not found.
421
+ */
422
+ const getRoutesChildren = (node) => {
423
+ let routesNode;
424
+ React.Children.forEach(node, (child) => {
425
+ if (child.type === Routes) {
426
+ routesNode = child;
427
+ }
428
+ });
429
+ if (routesNode) {
430
+ // The children of the `<Routes />` component are most likely
431
+ // (and should be) the `<Route />` components.
432
+ return routesNode.props.children;
433
+ }
434
+ return undefined;
435
+ };
436
+ /**
437
+ * Extracts Route children from a node (either directly or from a Routes wrapper).
438
+ *
439
+ * @param children The children to extract routes from.
440
+ * @returns An array of Route elements.
441
+ */
442
+ const extractRouteChildren = (children) => {
443
+ var _a;
444
+ const routesChildren = (_a = getRoutesChildren(children)) !== null && _a !== void 0 ? _a : children;
445
+ return React.Children.toArray(routesChildren).filter((child) => React.isValidElement(child) && (child.type === Route || child.type === IonRoute));
446
+ };
447
+ /**
448
+ * Checks if a React element is a Navigate component (redirect).
449
+ *
450
+ * @param element The element to check.
451
+ * @returns True if the element is a Navigate component.
452
+ */
453
+ const isNavigateElement = (element) => {
454
+ return (React.isValidElement(element) &&
455
+ (element.type === Navigate || (typeof element.type === 'function' && element.type.name === 'Navigate')));
456
+ };
457
+
458
+ /**
459
+ * Compares two routes by specificity for sorting (most specific first).
460
+ *
461
+ * Sort order:
462
+ * 1. Index routes come first
463
+ * 2. Wildcard-only routes (* or /*) come last
464
+ * 3. Exact matches (no wildcards/params) before wildcard/param routes
465
+ * 4. Among routes with same status, longer paths are more specific
466
+ */
467
+ const compareRouteSpecificity = (a, b) => {
468
+ // Index routes come first
469
+ if (a.index && !b.index)
470
+ return -1;
471
+ if (!a.index && b.index)
472
+ return 1;
473
+ // Wildcard-only routes (* or /*) should come last
474
+ const aIsWildcardOnly = a.path === '*' || a.path === '/*';
475
+ const bIsWildcardOnly = b.path === '*' || b.path === '/*';
476
+ if (!aIsWildcardOnly && bIsWildcardOnly)
477
+ return -1;
478
+ if (aIsWildcardOnly && !bIsWildcardOnly)
479
+ return 1;
480
+ // Exact matches (no wildcards/params) come before wildcard/param routes
481
+ const aHasWildcard = a.path.includes('*') || a.path.includes(':');
482
+ const bHasWildcard = b.path.includes('*') || b.path.includes(':');
483
+ if (!aHasWildcard && bHasWildcard)
484
+ return -1;
485
+ if (aHasWildcard && !bHasWildcard)
486
+ return 1;
487
+ // Among routes with same wildcard status, longer paths are more specific
488
+ if (a.path.length !== b.path.length) {
489
+ return b.path.length - a.path.length;
490
+ }
491
+ return 0;
492
+ };
493
+ /**
494
+ * Sorts view items by route specificity (most specific first).
495
+ *
496
+ * Sort order aligns with findViewItemByPath in ReactRouterViewStack.tsx:
497
+ * 1. Index routes come first
498
+ * 2. Wildcard-only routes (* or /*) come last
499
+ * 3. Exact matches (no wildcards/params) come before wildcard/param routes
500
+ * 4. Among routes with same wildcard status, longer paths are more specific
501
+ *
502
+ * @param views The view items to sort.
503
+ * @returns A new sorted array of view items.
504
+ */
505
+ const sortViewsBySpecificity = (views) => {
506
+ return [...views].sort((a, b) => {
507
+ var _a, _b, _c, _d, _e, _f, _g, _h;
508
+ return compareRouteSpecificity({ path: ((_b = (_a = a.routeData) === null || _a === void 0 ? void 0 : _a.childProps) === null || _b === void 0 ? void 0 : _b.path) || '', index: !!((_d = (_c = a.routeData) === null || _c === void 0 ? void 0 : _c.childProps) === null || _d === void 0 ? void 0 : _d.index) }, { path: ((_f = (_e = b.routeData) === null || _e === void 0 ? void 0 : _e.childProps) === null || _f === void 0 ? void 0 : _f.path) || '', index: !!((_h = (_g = b.routeData) === null || _g === void 0 ? void 0 : _g.childProps) === null || _h === void 0 ? void 0 : _h.index) });
509
+ });
510
+ };
511
+
512
+ /**
513
+ * `ReactRouterViewStack` is a custom navigation manager used in Ionic React
514
+ * apps to map React Router route elements (such as `<IonRoute>`) to "view
515
+ * items" that Ionic can manage in a view stack. This is critical to maintain
516
+ * Ionic’s animation, lifecycle, and history behavior across views.
517
+ */
518
+ /**
519
+ * Delay in milliseconds before removing a Navigate view item after a redirect.
520
+ * This ensures the redirect navigation completes before the view is removed.
521
+ */
522
+ const NAVIGATE_REDIRECT_DELAY_MS = 100;
523
+ /**
524
+ * Delay in milliseconds before cleaning up a view without an IonPage element.
525
+ * This double-checks that the view is truly not needed before removal.
526
+ */
527
+ const VIEW_CLEANUP_DELAY_MS = 200;
528
+ /**
529
+ * Computes the absolute pathnameBase for a route element based on its type.
530
+ * Handles relative paths, index routes, and splat routes differently.
531
+ */
532
+ const computeAbsolutePathnameBase = (routeElement, routeMatch, parentPathnameBase, routeInfoPathname) => {
533
+ const routePath = routeElement.props.path;
534
+ const isRelativePath = routePath && !routePath.startsWith('/');
535
+ const isIndexRoute = !!routeElement.props.index;
536
+ const isSplatOnlyRoute = routePath === '*' || routePath === '/*';
537
+ if (isSplatOnlyRoute) {
538
+ // Splat routes should NOT contribute their matched portion to pathnameBase
539
+ // This aligns with React Router v7's v7_relativeSplatPath behavior
540
+ return parentPathnameBase;
541
+ }
542
+ if (isRelativePath && (routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.pathnameBase)) {
543
+ const relativeBase = routeMatch.pathnameBase.startsWith('/')
544
+ ? routeMatch.pathnameBase.slice(1)
545
+ : routeMatch.pathnameBase;
546
+ return parentPathnameBase === '/' ? `/${relativeBase}` : `${parentPathnameBase}/${relativeBase}`;
547
+ }
548
+ if (isIndexRoute) {
549
+ return parentPathnameBase;
550
+ }
551
+ return (routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.pathnameBase) || routeInfoPathname;
552
+ };
553
+ /**
554
+ * Gets fallback params from view items in other outlets when parent context is empty.
555
+ * This handles cases where React context propagation doesn't work as expected.
556
+ */
557
+ const getFallbackParamsFromViewItems = (allViewItems, currentOutletId, currentPathname) => {
558
+ var _a;
559
+ const matchingViews = [];
560
+ for (const otherViewItem of allViewItems) {
561
+ if (otherViewItem.outletId === currentOutletId)
562
+ continue;
563
+ const otherMatch = (_a = otherViewItem.routeData) === null || _a === void 0 ? void 0 : _a.match;
564
+ if ((otherMatch === null || otherMatch === void 0 ? void 0 : otherMatch.params) && Object.keys(otherMatch.params).length > 0) {
565
+ const matchedPathname = otherMatch.pathnameBase || otherMatch.pathname;
566
+ if (matchedPathname && currentPathname.startsWith(matchedPathname)) {
567
+ matchingViews.push({
568
+ params: otherMatch.params,
569
+ pathLength: matchedPathname.length,
570
+ });
571
+ }
572
+ }
573
+ }
574
+ // Sort ascending by path length so more-specific (longer) paths are applied
575
+ // last and their params take priority over less-specific ones.
576
+ matchingViews.sort((a, b) => a.pathLength - b.pathLength);
577
+ const params = {};
578
+ for (const view of matchingViews) {
579
+ Object.assign(params, view.params);
580
+ }
581
+ return params;
582
+ };
583
+ /**
584
+ * Builds the matches array for RouteContext.
585
+ */
586
+ const buildContextMatches = (parentMatches, combinedParams, routeMatch, routeInfoPathname, absolutePathnameBase, viewItem, routeElement, componentElement) => {
587
+ return [
588
+ ...parentMatches,
589
+ {
590
+ params: combinedParams,
591
+ pathname: (routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.pathname) || routeInfoPathname,
592
+ pathnameBase: absolutePathnameBase,
593
+ route: {
594
+ id: viewItem.id,
595
+ path: routeElement.props.path,
596
+ element: componentElement,
597
+ index: !!routeElement.props.index,
598
+ caseSensitive: routeElement.props.caseSensitive,
599
+ hasErrorBoundary: false,
600
+ },
601
+ },
602
+ ];
603
+ };
604
+ const createDefaultMatch = (fullPathname, routeProps) => {
605
+ var _a, _b;
606
+ const isIndexRoute = !!routeProps.index;
607
+ const patternPath = (_a = routeProps.path) !== null && _a !== void 0 ? _a : '';
608
+ const pathnameBase = fullPathname === '' ? '/' : fullPathname;
609
+ const computedEnd = routeProps.end !== undefined ? routeProps.end : patternPath !== '' ? !patternPath.endsWith('*') : true;
610
+ return {
611
+ params: {},
612
+ pathname: isIndexRoute ? '' : fullPathname,
613
+ pathnameBase,
614
+ pattern: {
615
+ path: patternPath,
616
+ caseSensitive: (_b = routeProps.caseSensitive) !== null && _b !== void 0 ? _b : false,
617
+ end: isIndexRoute ? true : computedEnd,
618
+ },
619
+ };
620
+ };
621
+ const computeRelativeToParent = (pathname, parentPath) => {
622
+ if (!parentPath)
623
+ return null;
624
+ const normalizedParent = normalizePathnameForComparison(parentPath);
625
+ const normalizedPathname = normalizePathnameForComparison(pathname);
626
+ if (normalizedPathname === normalizedParent) {
627
+ return '';
628
+ }
629
+ const withSlash = normalizedParent === '/' ? '/' : normalizedParent + '/';
630
+ if (normalizedPathname.startsWith(withSlash)) {
631
+ return normalizedPathname.slice(withSlash.length);
632
+ }
633
+ return null;
634
+ };
635
+ const resolveIndexRouteMatch = (viewItem, pathname, parentPath) => {
636
+ var _a, _b, _c;
637
+ if (!((_b = (_a = viewItem.routeData) === null || _a === void 0 ? void 0 : _a.childProps) === null || _b === void 0 ? void 0 : _b.index)) {
638
+ return null;
639
+ }
640
+ // Prefer computing against the parent path when available to align with RRv6 semantics
641
+ const relative = computeRelativeToParent(pathname, parentPath);
642
+ if (relative !== null) {
643
+ // Index routes match only when there is no remaining path
644
+ if (relative === '' || relative === '/') {
645
+ return createDefaultMatch(parentPath || pathname, viewItem.routeData.childProps);
646
+ }
647
+ return null;
648
+ }
649
+ // Fallback: use previously computed match base for equality check
650
+ const previousMatch = (_c = viewItem.routeData) === null || _c === void 0 ? void 0 : _c.match;
651
+ if (!previousMatch) {
652
+ return null;
653
+ }
654
+ const normalizedPathname = normalizePathnameForComparison(pathname);
655
+ const normalizedBase = normalizePathnameForComparison(previousMatch.pathnameBase || previousMatch.pathname || '');
656
+ return normalizedPathname === normalizedBase ? previousMatch : null;
657
+ };
41
658
  class ReactRouterViewStack extends ViewStacks {
42
659
  constructor() {
43
660
  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);
661
+ /**
662
+ * Stores the computed parent path for each outlet.
663
+ * Used by findViewItemByPath to correctly evaluate index route matches
664
+ * without requiring the outlet's React element or route children.
665
+ */
666
+ this.outletParentPaths = new Map();
667
+ /**
668
+ * Stores the computed mount path for each outlet.
669
+ * Fed back into computeParentPath on subsequent calls to stabilize
670
+ * the parent path computation across navigations (mirrors StackManager.outletMountPath).
671
+ */
672
+ this.outletMountPaths = new Map();
673
+ /**
674
+ * Creates a new view item for the given outlet and react route element.
675
+ * Associates route props with the matched route path for further lookups.
676
+ */
677
+ this.createViewItem = (outletId, reactElement, routeInfo, page) => {
678
+ var _a, _b;
679
+ const routePath = reactElement.props.path || '';
680
+ // Check if we already have a view item for this exact route that we can reuse
681
+ // Include wildcard routes like tabs/* since they should be reused
682
+ // Also check unmounted items that might have been preserved for browser navigation
683
+ const existingViewItem = this.getViewItemsForOutlet(outletId).find((v) => {
684
+ var _a, _b, _c, _d, _e, _f, _g, _h;
685
+ const existingRouteProps = (_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) !== null && _b !== void 0 ? _b : {};
686
+ const existingPath = existingRouteProps.path || '';
687
+ const existingElement = existingRouteProps.element;
688
+ const newElement = reactElement.props.element;
689
+ const existingIsIndexRoute = !!existingRouteProps.index;
690
+ const newIsIndexRoute = !!reactElement.props.index;
691
+ // For Navigate components, match by destination
692
+ const existingIsNavigate = React.isValidElement(existingElement) && existingElement.type === Navigate;
693
+ const newIsNavigate = React.isValidElement(newElement) && newElement.type === Navigate;
694
+ if (existingIsNavigate && newIsNavigate) {
695
+ const existingTo = (_c = existingElement.props) === null || _c === void 0 ? void 0 : _c.to;
696
+ const newTo = (_d = newElement.props) === null || _d === void 0 ? void 0 : _d.to;
697
+ if (existingTo === newTo) {
698
+ return true;
699
+ }
700
+ }
701
+ if (existingIsIndexRoute && newIsIndexRoute) {
702
+ return true;
703
+ }
704
+ // Reuse view items with the same path
705
+ // Special case: reuse tabs/* and other specific wildcard routes
706
+ // Don't reuse index routes (empty path) or generic catch-all wildcards (*)
707
+ if (existingPath === routePath && existingPath !== '' && existingPath !== '*') {
708
+ // Parameterized routes need pathname matching to ensure /details/1 and /details/2
709
+ // get separate view items. For wildcard routes (e.g., user/:userId/*), compare
710
+ // pathnameBase to allow child path changes while preserving the parent view.
711
+ const hasParams = routePath.includes(':');
712
+ const isWildcard = routePath.includes('*');
713
+ if (hasParams) {
714
+ if (isWildcard) {
715
+ const existingPathnameBase = (_f = (_e = v.routeData) === null || _e === void 0 ? void 0 : _e.match) === null || _f === void 0 ? void 0 : _f.pathnameBase;
716
+ const newMatch = matchComponent$1(reactElement, routeInfo.pathname, false, this.outletParentPaths.get(outletId));
717
+ const newPathnameBase = newMatch === null || newMatch === void 0 ? void 0 : newMatch.pathnameBase;
718
+ if (existingPathnameBase !== newPathnameBase) {
719
+ return false;
720
+ }
721
+ }
722
+ else {
723
+ const existingPathname = (_h = (_g = v.routeData) === null || _g === void 0 ? void 0 : _g.match) === null || _h === void 0 ? void 0 : _h.pathname;
724
+ if (existingPathname !== routeInfo.pathname) {
725
+ return false;
726
+ }
727
+ }
728
+ }
729
+ return true;
730
+ }
731
+ // Also reuse specific wildcard routes like tabs/*
732
+ if (existingPath === routePath && existingPath.endsWith('/*') && existingPath !== '/*') {
733
+ return true;
734
+ }
735
+ return false;
78
736
  });
79
- if (viewItem) {
80
- viewItem.reactElement = child;
737
+ if (existingViewItem) {
738
+ // Update and ensure the existing view item is properly configured
739
+ existingViewItem.reactElement = reactElement;
740
+ existingViewItem.mount = true;
741
+ existingViewItem.ionPageElement = page || existingViewItem.ionPageElement;
742
+ const updatedMatch = matchComponent$1(reactElement, routeInfo.pathname, false, this.outletParentPaths.get(outletId)) ||
743
+ ((_a = existingViewItem.routeData) === null || _a === void 0 ? void 0 : _a.match) ||
744
+ createDefaultMatch(routeInfo.pathname, reactElement.props);
745
+ existingViewItem.routeData = {
746
+ match: updatedMatch,
747
+ childProps: reactElement.props,
748
+ lastPathname: (_b = existingViewItem.routeData) === null || _b === void 0 ? void 0 : _b.lastPathname, // Preserve navigation history
749
+ };
750
+ return existingViewItem;
81
751
  }
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
- })));
752
+ const id = `${outletId}-${generateId(outletId)}`;
753
+ const viewItem = {
754
+ id,
755
+ outletId,
756
+ ionPageElement: page,
757
+ reactElement,
758
+ mount: true,
759
+ ionRoute: true,
760
+ };
761
+ if (reactElement.type === IonRoute) {
762
+ viewItem.disableIonPageManagement = reactElement.props.disableIonPageManagement;
89
763
  }
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;
764
+ const initialMatch = matchComponent$1(reactElement, routeInfo.pathname, true, this.outletParentPaths.get(outletId)) ||
765
+ createDefaultMatch(routeInfo.pathname, reactElement.props);
766
+ viewItem.routeData = {
767
+ match: initialMatch,
768
+ childProps: reactElement.props,
769
+ };
770
+ this.add(viewItem);
771
+ return viewItem;
772
+ };
773
+ /**
774
+ * Renders a ViewLifeCycleManager for the given view item.
775
+ * Handles cleanup if the view no longer matches.
776
+ *
777
+ * - Deactivates view if it no longer matches the current route
778
+ * - Wraps the route element in <Routes> to support nested routing and ensure remounting
779
+ * - Adds a unique key to <Routes> so React Router remounts routes when switching
780
+ */
781
+ this.renderViewItem = (viewItem, routeInfo, parentPath, reRender) => {
782
+ var _a, _b, _c, _d, _e, _f, _g, _h;
783
+ const routePath = viewItem.reactElement.props.path || '';
784
+ let match = matchComponent$1(viewItem.reactElement, routeInfo.pathname, false, parentPath);
785
+ if (!match) {
786
+ const indexMatch = resolveIndexRouteMatch(viewItem, routeInfo.pathname, parentPath);
787
+ if (indexMatch) {
788
+ match = indexMatch;
789
+ }
790
+ }
791
+ // For parameterized routes, check if this is a navigation to a different path instance
792
+ // In that case, we should NOT reuse this view - a new view should be created
793
+ const isParameterRoute = routePath.includes(':');
794
+ const previousMatch = (_a = viewItem.routeData) === null || _a === void 0 ? void 0 : _a.match;
795
+ const isSamePath = (match === null || match === void 0 ? void 0 : match.pathname) === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathname);
796
+ // Flag to indicate this view should not be reused for this different parameterized path
797
+ const shouldSkipForDifferentParam = isParameterRoute && match && previousMatch && !isSamePath;
798
+ // Don't deactivate views automatically - let the StackManager handle view lifecycle
799
+ // This preserves views in the stack for navigation history like native apps
800
+ // Views will be hidden/shown by the StackManager's transition logic instead of being unmounted
801
+ // Special handling for Navigate components - they should unmount after redirecting
802
+ const elementComponent = (_c = (_b = viewItem.reactElement) === null || _b === void 0 ? void 0 : _b.props) === null || _c === void 0 ? void 0 : _c.element;
803
+ const isNavigateComponent = isNavigateElement(elementComponent);
804
+ if (isNavigateComponent) {
805
+ // Navigate components should only be mounted when they match
806
+ // Once they redirect (no longer match), they should be removed completely
807
+ // IMPORTANT: For index routes, we need to check indexMatch too since matchComponent
808
+ // may not properly match index routes without explicit parent path context
809
+ const indexMatch = ((_e = (_d = viewItem.routeData) === null || _d === void 0 ? void 0 : _d.childProps) === null || _e === void 0 ? void 0 : _e.index)
810
+ ? resolveIndexRouteMatch(viewItem, routeInfo.pathname, parentPath)
811
+ : null;
812
+ const hasValidMatch = match || indexMatch;
813
+ if (!hasValidMatch && viewItem.mount) {
97
814
  viewItem.mount = false;
815
+ // Schedule removal of the Navigate view item after a short delay
816
+ // This ensures the redirect completes before removal
817
+ setTimeout(() => {
818
+ this.remove(viewItem);
819
+ reRender === null || reRender === void 0 ? void 0 : reRender();
820
+ }, NAVIGATE_REDIRECT_DELAY_MS);
98
821
  }
99
822
  }
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;
823
+ // Components that don't have IonPage elements and no longer match should be cleaned up
824
+ // BUT we need to be careful not to remove them if they're part of browser navigation history
825
+ // This handles components that perform immediate actions like programmatic navigation
826
+ // EXCEPTION: Navigate components should ALWAYS remain mounted until they redirect
827
+ // since they need to be rendered to trigger the navigation
828
+ if (!match && viewItem.mount && !viewItem.ionPageElement && !isNavigateComponent) {
829
+ // Check if this view item should be preserved for browser navigation
830
+ // We'll keep it if it was recently active (within the last navigation)
831
+ const shouldPreserve = viewItem.routeData.lastPathname === routeInfo.pathname ||
832
+ ((_f = viewItem.routeData.match) === null || _f === void 0 ? void 0 : _f.pathname) === routeInfo.lastPathname;
833
+ if (!shouldPreserve) {
834
+ // This view item doesn't match and doesn't have an IonPage
835
+ // It's likely a utility component that performs an action and navigates away
836
+ viewItem.mount = false;
837
+ // Schedule removal to allow it to be recreated on next navigation
838
+ setTimeout(() => {
839
+ // Double-check before removing - the view might be needed again
840
+ const stillNotNeeded = !viewItem.mount && !viewItem.ionPageElement;
841
+ if (stillNotNeeded) {
842
+ this.remove(viewItem);
843
+ reRender === null || reRender === void 0 ? void 0 : reRender();
844
+ }
845
+ }, VIEW_CLEANUP_DELAY_MS);
846
+ }
847
+ else {
848
+ // Preserve it but unmount it for now
849
+ viewItem.mount = false;
850
+ }
851
+ }
852
+ // Reactivate view if it matches but was previously deactivated
853
+ // Don't reactivate if this is a parameterized route navigating to a different path instance
854
+ // Don't reactivate catch-all wildcard routes — they are created fresh by createViewItem
855
+ const isCatchAllWildcard = routePath === '*' || routePath === '/*';
856
+ if (match && !viewItem.mount && !shouldSkipForDifferentParam && !isCatchAllWildcard) {
857
+ viewItem.mount = true;
858
+ viewItem.routeData.match = match;
859
+ }
860
+ // Deactivate wildcard (catch-all) and empty-path (default) routes when a more-specific route matches.
861
+ // This prevents "Not found" or fallback pages from showing alongside valid routes.
862
+ if (routePath === '*' || routePath === '') {
863
+ // Check if any other view in this outlet has a match for the current route
864
+ const outletViews = this.getViewItemsForOutlet(viewItem.outletId);
865
+ // When parent path context is available, compute the relative pathname once
866
+ // outside the loop since both routeInfo.pathname and parentPath are invariant.
867
+ const relativePathname = parentPath
868
+ ? computeRelativeToParent(routeInfo.pathname, parentPath)
869
+ : null;
870
+ let hasSpecificMatch = outletViews.some((v) => {
871
+ var _a, _b;
872
+ if (v.id === viewItem.id)
873
+ return false; // Skip self
874
+ const vRoutePath = ((_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path) || '';
875
+ if (vRoutePath === '*' || vRoutePath === '')
876
+ return false; // Skip other wildcard/empty routes
877
+ // When parent path context is available and the route is relative, use
878
+ // parent-path-aware matching. This avoids false positives from
879
+ // derivePathnameToMatch's tail-slice heuristic, which can incorrectly
880
+ // match route literals that appear at the wrong position in the pathname.
881
+ // Example: pathname /parent/extra/details/99 with route details/:id —
882
+ // the tail-slice extracts ["details","99"] producing a false match.
883
+ if (parentPath && vRoutePath && !vRoutePath.startsWith('/')) {
884
+ if (relativePathname === null) {
885
+ return false; // Pathname is outside this outlet's parent scope
886
+ }
887
+ return !!matchPath({
888
+ pathname: relativePathname,
889
+ componentProps: v.reactElement.props,
890
+ });
891
+ }
892
+ // Fallback to matchComponent when no parent path context is available
893
+ const vMatch = v.reactElement ? matchComponent$1(v.reactElement, routeInfo.pathname) : null;
894
+ return !!vMatch;
895
+ });
896
+ // For catch-all * routes, also deactivate when the pathname matches the outlet's
897
+ // parent path exactly. This means there are no remaining segments for the wildcard
898
+ // to catch, so the empty-path or index route should handle it instead.
899
+ if (!hasSpecificMatch && routePath === '*') {
900
+ const outletParentPath = this.outletParentPaths.get(viewItem.outletId);
901
+ if (outletParentPath) {
902
+ const normalizedParent = normalizePathnameForComparison(outletParentPath);
903
+ const normalizedPathname = normalizePathnameForComparison(routeInfo.pathname);
904
+ if (normalizedPathname === normalizedParent) {
905
+ // Check if there's an empty-path or index view item that should handle this
906
+ const hasDefaultRoute = outletViews.some((v) => {
907
+ var _a, _b, _c, _d;
908
+ if (v.id === viewItem.id)
909
+ return false;
910
+ const vRoutePath = (_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
911
+ return vRoutePath === '' || vRoutePath === undefined || !!((_d = (_c = v.routeData) === null || _c === void 0 ? void 0 : _c.childProps) === null || _d === void 0 ? void 0 : _d.index);
912
+ });
913
+ if (hasDefaultRoute) {
914
+ hasSpecificMatch = true;
915
+ }
916
+ }
917
+ }
918
+ }
919
+ if (hasSpecificMatch) {
920
+ viewItem.mount = false;
921
+ if (viewItem.ionPageElement) {
922
+ viewItem.ionPageElement.classList.add('ion-page-hidden');
923
+ viewItem.ionPageElement.setAttribute('aria-hidden', 'true');
924
+ }
925
+ }
926
+ }
927
+ const routeElement = React.cloneElement(viewItem.reactElement);
928
+ const componentElement = routeElement.props.element;
929
+ // Don't update match for parameterized routes navigating to different path instances
930
+ // This preserves the original match so that findViewItemByPath can correctly skip this view
931
+ if (match && viewItem.routeData.match !== match && !shouldSkipForDifferentParam) {
932
+ viewItem.routeData.match = match;
933
+ }
934
+ 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);
935
+ return (React.createElement(UNSAFE_RouteContext.Consumer, { key: `view-context-${viewItem.id}` }, (parentContext) => {
936
+ var _a, _b;
937
+ const parentMatches = ((_a = parentContext === null || parentContext === void 0 ? void 0 : parentContext.matches) !== null && _a !== void 0 ? _a : []);
938
+ // Accumulate params from parent matches, with fallback to other outlets
939
+ let accumulatedParentParams = parentMatches.reduce((acc, m) => (Object.assign(Object.assign({}, acc), m.params)), {});
940
+ if (parentMatches.length === 0 && Object.keys(accumulatedParentParams).length === 0) {
941
+ accumulatedParentParams = getFallbackParamsFromViewItems(this.getAllViewItems(), viewItem.outletId, routeInfo.pathname);
942
+ }
943
+ const combinedParams = Object.assign(Object.assign({}, accumulatedParentParams), ((_b = routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.params) !== null && _b !== void 0 ? _b : {}));
944
+ const parentPathnameBase = parentMatches.length > 0 ? parentMatches[parentMatches.length - 1].pathnameBase : '/';
945
+ const absolutePathnameBase = computeAbsolutePathnameBase(routeElement, routeMatch, parentPathnameBase, routeInfo.pathname);
946
+ const contextMatches = buildContextMatches(parentMatches, combinedParams, routeMatch, routeInfo.pathname, absolutePathnameBase, viewItem, routeElement, componentElement);
947
+ const routeContextValue = parentContext
948
+ ? Object.assign(Object.assign({}, parentContext), { matches: contextMatches }) : { outlet: null, matches: contextMatches, isDataRoute: false };
949
+ return (React.createElement(ViewLifeCycleManager, { key: `view-${viewItem.id}`, mount: viewItem.mount, removeView: () => this.remove(viewItem) },
950
+ React.createElement(UNSAFE_RouteContext.Provider, { value: routeContextValue }, componentElement)));
951
+ }));
952
+ };
953
+ /**
954
+ * Re-renders all active view items for the specified outlet.
955
+ * Ensures React elements are updated with the latest match.
956
+ *
957
+ * 1. Iterates through children of IonRouterOutlet
958
+ * 2. Updates each matching viewItem with the current child React element
959
+ * (important for updating props or changes to elements)
960
+ * 3. Returns a list of React components that will be rendered inside the outlet
961
+ * Each view is wrapped in <ViewLifeCycleManager> to manage lifecycle and rendering
962
+ */
963
+ this.getChildrenToRender = (outletId, ionRouterOutlet, routeInfo, reRender, parentPathnameBase) => {
964
+ const viewItems = this.getViewItemsForOutlet(outletId);
965
+ // Seed the mount path from the parent route context if available.
966
+ // This provides the outlet's mount path immediately on first render,
967
+ // eliminating the need for heuristic-based discovery in computeParentPath.
968
+ if (parentPathnameBase && !this.outletMountPaths.has(outletId)) {
969
+ this.outletMountPaths.set(outletId, parentPathnameBase);
970
+ }
971
+ // Determine parentPath for outlets with relative or index routes.
972
+ // This populates outletParentPaths for findViewItemByPath's matchView
973
+ // and the catch-all deactivation logic in renderViewItem.
974
+ let parentPath = undefined;
975
+ try {
976
+ const routeChildren = extractRouteChildren(ionRouterOutlet.props.children);
977
+ const { hasRelativeRoutes, hasIndexRoute, hasWildcardRoute } = analyzeRouteChildren(routeChildren);
978
+ if (hasRelativeRoutes || hasIndexRoute) {
979
+ const result = computeParentPath({
980
+ currentPathname: routeInfo.pathname,
981
+ outletMountPath: this.outletMountPaths.get(outletId),
982
+ routeChildren,
983
+ hasRelativeRoutes,
984
+ hasIndexRoute,
985
+ hasWildcardRoute,
986
+ });
987
+ parentPath = result.parentPath;
988
+ // Persist the mount path for subsequent calls, mirroring StackManager.outletMountPath.
989
+ // Unlike outletParentPaths (cleared when parentPath is undefined), the mount path is
990
+ // intentionally sticky — it anchors the outlet's scope and is only removed in clear().
991
+ if (result.outletMountPath && !this.outletMountPaths.has(outletId)) {
992
+ this.outletMountPaths.set(outletId, result.outletMountPath);
993
+ }
994
+ }
995
+ }
996
+ catch (e) {
997
+ // Non-fatal: if we fail to compute parentPath, fall back to previous behavior
998
+ }
999
+ // Store the computed parentPath for use in findViewItemByPath.
1000
+ // Clear stale entries when parentPath is undefined (e.g., navigated out of scope).
1001
+ if (parentPath !== undefined) {
1002
+ this.outletParentPaths.set(outletId, parentPath);
1003
+ }
1004
+ else if (this.outletParentPaths.has(outletId)) {
1005
+ this.outletParentPaths.delete(outletId);
1006
+ }
1007
+ // Sync child elements with stored viewItems (e.g. to reflect new props)
1008
+ React.Children.forEach(ionRouterOutlet.props.children, (child) => {
1009
+ // Ensure the child is a valid React element since we
1010
+ // might have whitespace strings or other non-element children
1011
+ if (React.isValidElement(child)) {
1012
+ // Find view item by exact path match to avoid wildcard routes overwriting specific routes
1013
+ const childPath = child.props.path;
1014
+ const viewItem = viewItems.find((v) => {
1015
+ var _a, _b;
1016
+ const viewItemPath = (_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1017
+ // Only update if paths match exactly (prevents wildcard routes from overwriting specific routes)
1018
+ return viewItemPath === childPath;
1019
+ });
1020
+ if (viewItem) {
1021
+ viewItem.reactElement = child;
1022
+ }
1023
+ }
1024
+ });
1025
+ // Filter out duplicate view items by ID (but keep all mounted items)
1026
+ const uniqueViewItems = viewItems.filter((viewItem, index, array) => {
1027
+ // Remove duplicates by ID (keep first occurrence)
1028
+ const isFirstOccurrence = array.findIndex((v) => v.id === viewItem.id) === index;
1029
+ return isFirstOccurrence;
1030
+ });
1031
+ // Filter out unmounted Navigate components to prevent them from being rendered
1032
+ // and triggering unwanted redirects
1033
+ const renderableViewItems = uniqueViewItems.filter((viewItem) => {
1034
+ var _a, _b, _c, _d;
1035
+ const elementComponent = (_b = (_a = viewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.element;
1036
+ const isNavigateComponent = isNavigateElement(elementComponent);
1037
+ // Exclude unmounted Navigate components from rendering
1038
+ if (isNavigateComponent && !viewItem.mount) {
1039
+ return false;
1040
+ }
1041
+ // Filter out views that are unmounted, have no ionPageElement, and don't match the current route.
1042
+ // These are "stale" views from previous routes that should not be rendered.
1043
+ // Views WITH ionPageElement are handled by the normal lifecycle events.
1044
+ // Views that MATCH the current route should be kept (they might be transitioning).
1045
+ if (!viewItem.mount && !viewItem.ionPageElement) {
1046
+ // Check if this view's route path matches the current pathname
1047
+ const viewRoutePath = (_d = (_c = viewItem.reactElement) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.path;
1048
+ if (viewRoutePath) {
1049
+ // First try exact match using matchComponent
1050
+ const routeMatch = matchComponent$1(viewItem.reactElement, routeInfo.pathname, false, parentPath);
1051
+ if (routeMatch) {
1052
+ // View matches current route, keep it
1053
+ return true;
1054
+ }
1055
+ // For parent routes (like /multiple-tabs or /routing), check if current pathname
1056
+ // starts with this route's path. This handles views with IonSplitPane/IonTabs
1057
+ // that don't have IonPage but should remain mounted while navigating within their children.
1058
+ const normalizedViewPath = normalizePathnameForComparison(viewRoutePath.replace(/\/?\*$/, '')); // Remove trailing wildcard
1059
+ const normalizedCurrentPath = normalizePathnameForComparison(routeInfo.pathname);
1060
+ // Check if current pathname is within this view's route hierarchy
1061
+ const isWithinRouteHierarchy = normalizedCurrentPath === normalizedViewPath || normalizedCurrentPath.startsWith(normalizedViewPath + '/');
1062
+ if (!isWithinRouteHierarchy) {
1063
+ // View is outside current route hierarchy, remove it
1064
+ setTimeout(() => {
1065
+ this.remove(viewItem);
1066
+ reRender();
1067
+ }, 0);
1068
+ return false;
1069
+ }
1070
+ }
1071
+ }
1072
+ return true;
1073
+ });
1074
+ const renderedItems = renderableViewItems.map((viewItem) => this.renderViewItem(viewItem, routeInfo, parentPath, reRender));
1075
+ return renderedItems;
1076
+ };
1077
+ /**
1078
+ * Finds a view item matching the current route, optionally updating its match state.
1079
+ */
1080
+ this.findViewItemByRouteInfo = (routeInfo, outletId, updateMatch) => {
1081
+ const { viewItem, match } = this.findViewItemByPath(routeInfo.pathname, outletId);
1082
+ const shouldUpdateMatch = updateMatch === undefined || updateMatch === true;
1083
+ if (shouldUpdateMatch && viewItem && match) {
1084
+ viewItem.routeData.match = match;
1085
+ }
1086
+ return viewItem;
1087
+ };
1088
+ /**
1089
+ * Finds the view item that was previously active before a route change.
1090
+ */
1091
+ this.findLeavingViewItemByRouteInfo = (routeInfo, outletId, mustBeIonRoute = true) => {
1092
+ // If the lastPathname is not set, we cannot find a leaving view item
1093
+ if (!routeInfo.lastPathname) {
1094
+ return undefined;
1095
+ }
1096
+ const { viewItem } = this.findViewItemByPath(routeInfo.lastPathname, outletId, mustBeIonRoute);
1097
+ return viewItem;
1098
+ };
1099
+ /**
1100
+ * Finds a view item by pathname only, used in simpler queries.
1101
+ */
1102
+ this.findViewItemByPathname = (pathname, outletId) => {
1103
+ const { viewItem } = this.findViewItemByPath(pathname, outletId);
1104
+ return viewItem;
1105
+ };
1106
+ /**
1107
+ * Clean up old, unmounted view items to prevent memory leaks
1108
+ */
1109
+ this.cleanupStaleViewItems = (outletId) => {
1110
+ const viewItems = this.getViewItemsForOutlet(outletId);
1111
+ // Keep only the most recent mounted views and a few unmounted ones for history
1112
+ const maxUnmountedItems = 3;
1113
+ const unmountedItems = viewItems.filter((v) => !v.mount);
1114
+ if (unmountedItems.length > maxUnmountedItems) {
1115
+ // Remove oldest unmounted items
1116
+ const itemsToRemove = unmountedItems.slice(0, unmountedItems.length - maxUnmountedItems);
1117
+ itemsToRemove.forEach((item) => {
1118
+ this.remove(item);
1119
+ });
1120
+ }
1121
+ };
1122
+ /**
1123
+ * Override add to prevent duplicate view items with the same ID in the same outlet
1124
+ * But allow multiple view items for the same route path (for navigation history)
1125
+ */
1126
+ this.add = (viewItem) => {
1127
+ const existingViewItem = this.getViewItemsForOutlet(viewItem.outletId).find((v) => v.id === viewItem.id);
1128
+ if (existingViewItem) {
1129
+ return;
1130
+ }
1131
+ super.add(viewItem);
1132
+ this.cleanupStaleViewItems(viewItem.outletId);
1133
+ };
1134
+ /**
1135
+ * Override clear to also clean up the stored parent path for the outlet.
1136
+ */
1137
+ this.clear = (outletId) => {
1138
+ this.outletParentPaths.delete(outletId);
1139
+ this.outletMountPaths.delete(outletId);
1140
+ return super.clear(outletId);
1141
+ };
1142
+ /**
1143
+ * Override remove
1144
+ */
1145
+ this.remove = (viewItem) => {
1146
+ super.remove(viewItem);
1147
+ };
119
1148
  }
120
1149
  /**
121
- * Returns the matching view item and the match result for a given pathname.
1150
+ * Core function that matches a given pathname against all view items.
1151
+ * Returns both the matched view item and match metadata.
122
1152
  */
123
- findViewItemByPath(pathname, outletId, mustBeIonRoute) {
1153
+ findViewItemByPath(pathname, outletId, mustBeIonRoute, allowDefaultMatch = true) {
124
1154
  let viewItem;
125
- let match;
1155
+ let match = null;
126
1156
  let viewStack;
1157
+ // Capture stored parent paths for use in nested matchView/matchDefaultRoute functions
1158
+ const storedParentPaths = this.outletParentPaths;
127
1159
  if (outletId) {
128
- viewStack = this.getViewItemsForOutlet(outletId);
1160
+ viewStack = sortViewsBySpecificity(this.getViewItemsForOutlet(outletId));
129
1161
  viewStack.some(matchView);
130
- if (!viewItem) {
1162
+ if (!viewItem && allowDefaultMatch)
131
1163
  viewStack.some(matchDefaultRoute);
132
- }
133
1164
  }
134
1165
  else {
135
- const viewItems = this.getAllViewItems();
1166
+ const viewItems = sortViewsBySpecificity(this.getAllViewItems());
136
1167
  viewItems.some(matchView);
137
- if (!viewItem) {
1168
+ if (!viewItem && allowDefaultMatch)
138
1169
  viewItems.some(matchDefaultRoute);
139
- }
140
1170
  }
1171
+ // If we still have not found a view item for this outlet, try to find a matching
1172
+ // view item across all outlets and adopt it into the current outlet. This helps
1173
+ // recover when an outlet remounts and receives a new id, leaving views associated
1174
+ // with the previous outlet id.
1175
+ // Do not adopt across outlets; if we didn't find a view for this outlet,
1176
+ // defer to route matching to create a new one.
141
1177
  return { viewItem, match };
1178
+ /**
1179
+ * Matches a route path with dynamic parameters (e.g. /tabs/:id)
1180
+ */
142
1181
  function matchView(v) {
143
- var _a, _b;
144
- if (mustBeIonRoute && !v.ionRoute) {
1182
+ var _a;
1183
+ if (mustBeIonRoute && !v.ionRoute)
1184
+ return false;
1185
+ const viewItemPath = v.routeData.childProps.path || '';
1186
+ // Skip unmounted catch-all wildcard views. After back navigation unmounts
1187
+ // a wildcard view, it should not be reused for subsequent navigations.
1188
+ // A fresh wildcard view will be created by createViewItem when needed.
1189
+ if ((viewItemPath === '*' || viewItemPath === '/*') && !v.mount)
145
1190
  return false;
1191
+ const isIndexRoute = !!v.routeData.childProps.index;
1192
+ const previousMatch = (_a = v.routeData) === null || _a === void 0 ? void 0 : _a.match;
1193
+ const outletParentPath = storedParentPaths.get(v.outletId);
1194
+ const result = v.reactElement ? matchComponent$1(v.reactElement, pathname, false, outletParentPath) : null;
1195
+ if (!result) {
1196
+ const indexMatch = resolveIndexRouteMatch(v, pathname, outletParentPath);
1197
+ if (indexMatch) {
1198
+ match = indexMatch;
1199
+ viewItem = v;
1200
+ return true;
1201
+ }
1202
+ // Empty path routes (path="") should match when the pathname matches the
1203
+ // outlet's parent path exactly (no remaining segments). matchComponent doesn't
1204
+ // handle this because it lacks parent path context. Without this check, a
1205
+ // catch-all * view item (which matches any pathname) would be incorrectly
1206
+ // returned instead of the empty path route on back navigation.
1207
+ if (viewItemPath === '' && !isIndexRoute && outletParentPath) {
1208
+ const normalizedParent = normalizePathnameForComparison(outletParentPath);
1209
+ const normalizedPathname = normalizePathnameForComparison(pathname);
1210
+ if (normalizedPathname === normalizedParent) {
1211
+ match = createDefaultMatch(pathname, v.routeData.childProps);
1212
+ viewItem = v;
1213
+ return true;
1214
+ }
1215
+ }
146
1216
  }
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))) {
1217
+ if (result) {
1218
+ const hasParams = result.params && Object.keys(result.params).length > 0;
1219
+ const isSamePath = result.pathname === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathname);
1220
+ const isWildcardRoute = viewItemPath.includes('*');
1221
+ const isParameterRoute = viewItemPath.includes(':');
1222
+ // Don't allow view items with undefined paths to match specific routes
1223
+ // This prevents broken index route view items from interfering with navigation
1224
+ if (!viewItemPath && !isIndexRoute && pathname !== '/' && pathname !== '') {
1225
+ return false;
1226
+ }
1227
+ // For parameterized routes, check if we should reuse the view item.
1228
+ // Wildcard routes (e.g., user/:userId/*) compare pathnameBase to allow
1229
+ // child path changes while preserving the parent view.
1230
+ if (isParameterRoute && !isSamePath) {
1231
+ if (isWildcardRoute) {
1232
+ const isSameBase = result.pathnameBase === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathnameBase);
1233
+ if (isSameBase) {
1234
+ match = result;
1235
+ viewItem = v;
1236
+ return true;
1237
+ }
1238
+ }
1239
+ return false;
1240
+ }
1241
+ // For routes without params, or when navigating to the exact same path,
1242
+ // or when there's no previous match, reuse the view item
1243
+ if (!hasParams || isSamePath || !previousMatch) {
1244
+ match = result;
160
1245
  viewItem = v;
161
1246
  return true;
162
1247
  }
1248
+ // For pure wildcard routes (without : params), compare pathnameBase to allow
1249
+ // child path changes while preserving the parent view. This handles container
1250
+ // routes like /tabs/* where switching between /tabs/tab1 and /tabs/tab2
1251
+ // should reuse the same ViewItem.
1252
+ if (isWildcardRoute && !isParameterRoute) {
1253
+ const isSameBase = result.pathnameBase === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathnameBase);
1254
+ if (isSameBase) {
1255
+ match = result;
1256
+ viewItem = v;
1257
+ return true;
1258
+ }
1259
+ }
163
1260
  }
164
1261
  return false;
165
1262
  }
1263
+ /**
1264
+ * Matches a view with no path prop (default fallback route) or index route.
1265
+ */
166
1266
  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) {
1267
+ var _a, _b, _c;
1268
+ const childProps = v.routeData.childProps;
1269
+ const isDefaultRoute = childProps.path === undefined || childProps.path === '';
1270
+ const isIndexRoute = !!childProps.index;
1271
+ if (isIndexRoute) {
1272
+ const outletParentPath = storedParentPaths.get(v.outletId);
1273
+ const indexMatch = resolveIndexRouteMatch(v, pathname, outletParentPath);
1274
+ if (indexMatch) {
1275
+ match = indexMatch;
1276
+ viewItem = v;
1277
+ return true;
1278
+ }
1279
+ return false;
1280
+ }
1281
+ // For empty path routes, only match if we're at the same level as when the view was created.
1282
+ // This prevents an empty path view item from being reused for different routes.
1283
+ if (isDefaultRoute) {
1284
+ const previousPathnameBase = ((_b = (_a = v.routeData) === null || _a === void 0 ? void 0 : _a.match) === null || _b === void 0 ? void 0 : _b.pathnameBase) || '';
1285
+ const normalizedBase = normalizePathnameForComparison(previousPathnameBase);
1286
+ const normalizedPathname = normalizePathnameForComparison(pathname);
1287
+ if (normalizedPathname !== normalizedBase) {
1288
+ return false;
1289
+ }
169
1290
  match = {
170
- path: pathname,
171
- url: pathname,
172
- isExact: true,
173
1291
  params: {},
1292
+ pathname,
1293
+ pathnameBase: pathname === '' ? '/' : pathname,
1294
+ pattern: {
1295
+ path: '',
1296
+ caseSensitive: (_c = childProps.caseSensitive) !== null && _c !== void 0 ? _c : false,
1297
+ end: true,
1298
+ },
174
1299
  };
175
1300
  viewItem = v;
176
1301
  return true;
@@ -179,11 +1304,40 @@ class ReactRouterViewStack extends ViewStacks {
179
1304
  }
180
1305
  }
181
1306
  }
182
- function matchComponent$1(node, pathname) {
183
- return matchPath({
184
- pathname,
185
- componentProps: node.props,
1307
+ /**
1308
+ * Utility to apply matchPath to a React element and return its match state.
1309
+ */
1310
+ function matchComponent$1(node, pathname, allowFallback = false, parentPath) {
1311
+ var _a;
1312
+ const routeProps = (_a = node === null || node === void 0 ? void 0 : node.props) !== null && _a !== void 0 ? _a : {};
1313
+ const routePath = routeProps.path;
1314
+ let pathnameToMatch;
1315
+ if (parentPath && routePath && !routePath.startsWith('/')) {
1316
+ // When parent path is known, compute exact relative pathname
1317
+ // instead of using the tail-slice heuristic
1318
+ const relative = pathname.startsWith(parentPath)
1319
+ ? pathname.slice(parentPath.length).replace(/^\//, '')
1320
+ : pathname;
1321
+ pathnameToMatch = relative;
1322
+ }
1323
+ else {
1324
+ pathnameToMatch = derivePathnameToMatch(pathname, routePath);
1325
+ }
1326
+ const match = matchPath({
1327
+ pathname: pathnameToMatch,
1328
+ componentProps: routeProps,
186
1329
  });
1330
+ if (match || !allowFallback) {
1331
+ return match;
1332
+ }
1333
+ const isIndexRoute = !!routeProps.index;
1334
+ if (isIndexRoute) {
1335
+ return createDefaultMatch(pathname, routeProps);
1336
+ }
1337
+ if (!routePath || routePath === '') {
1338
+ return createDefaultMatch(pathname, routeProps);
1339
+ }
1340
+ return null;
187
1341
  }
188
1342
 
189
1343
  function clonePageElement(leavingViewHtml) {
@@ -208,7 +1362,37 @@ function clonePageElement(leavingViewHtml) {
208
1362
  return undefined;
209
1363
  }
210
1364
 
211
- const isViewVisible = (el) => !el.classList.contains('ion-page-invisible') && !el.classList.contains('ion-page-hidden');
1365
+ /**
1366
+ * `StackManager` is responsible for managing page transitions, keeping track
1367
+ * of views (pages), and ensuring that navigation behaves like native apps —
1368
+ * particularly with animations and swipe gestures.
1369
+ */
1370
+ /**
1371
+ * Delay in milliseconds before unmounting a view after a transition completes.
1372
+ * This ensures the page transition animation finishes before the view is removed.
1373
+ */
1374
+ const VIEW_UNMOUNT_DELAY_MS = 250;
1375
+ /**
1376
+ * Delay (ms) to wait for an IonPage to mount before proceeding with a
1377
+ * page transition. Only container routes (nested outlets with no direct
1378
+ * IonPage) actually hit this timeout; normal routes clear it early via
1379
+ * registerIonPage, so a larger value here doesn't affect the happy path.
1380
+ */
1381
+ const ION_PAGE_WAIT_TIMEOUT_MS = 300;
1382
+ const isViewVisible = (el) => !el.classList.contains('ion-page-invisible') && !el.classList.contains('ion-page-hidden') && el.style.visibility !== 'hidden';
1383
+ const hideIonPageElement = (element) => {
1384
+ if (element) {
1385
+ element.classList.add('ion-page-hidden');
1386
+ element.setAttribute('aria-hidden', 'true');
1387
+ }
1388
+ };
1389
+ const showIonPageElement = (element) => {
1390
+ if (element) {
1391
+ element.style.removeProperty('visibility');
1392
+ element.classList.remove('ion-page-hidden');
1393
+ element.removeAttribute('aria-hidden');
1394
+ }
1395
+ };
212
1396
  class StackManager extends React.PureComponent {
213
1397
  constructor(props) {
214
1398
  super(props);
@@ -217,14 +1401,514 @@ class StackManager extends React.PureComponent {
217
1401
  isInOutlet: () => true,
218
1402
  };
219
1403
  this.pendingPageTransition = false;
1404
+ this.waitingForIonPage = false;
1405
+ /** Tracks whether the component is mounted to guard async transition paths. */
1406
+ this._isMounted = false;
1407
+ /** In-flight requestAnimationFrame IDs from transitionPage, cancelled on unmount. */
1408
+ this.transitionRafIds = [];
1409
+ this.outletMountPath = undefined;
1410
+ /**
1411
+ * Whether this outlet is at the root level (no parent route matches).
1412
+ * Derived from UNSAFE_RouteContext in render() — empty matches means root.
1413
+ */
1414
+ this.isRootOutlet = true;
220
1415
  this.registerIonPage = this.registerIonPage.bind(this);
221
1416
  this.transitionPage = this.transitionPage.bind(this);
222
1417
  this.handlePageTransition = this.handlePageTransition.bind(this);
223
- this.id = generateId('routerOutlet');
1418
+ this.id = props.id || `routerOutlet-${generateId('routerOutlet')}`;
224
1419
  this.prevProps = undefined;
225
1420
  this.skipTransition = false;
226
1421
  }
1422
+ /**
1423
+ * Determines the parent path for nested routing in React Router 6.
1424
+ *
1425
+ * When the mount path is known (seeded from UNSAFE_RouteContext), returns
1426
+ * it directly — no iterative discovery needed. The computeParentPath
1427
+ * fallback only runs for root outlets where RouteContext doesn't provide
1428
+ * a parent match.
1429
+ */
1430
+ getParentPath() {
1431
+ const currentPathname = this.props.routeInfo.pathname;
1432
+ // Prevent out-of-scope outlets from adopting unrelated routes.
1433
+ // Uses segment-aware comparison: /tabs-secondary must NOT match /tabs scope.
1434
+ if (this.outletMountPath && !isPathnameInScope(currentPathname, this.outletMountPath)) {
1435
+ return undefined;
1436
+ }
1437
+ // Fast path: mount path is known from RouteContext. The parent path IS the
1438
+ // mount path — no need to run the iterative computeParentPath algorithm.
1439
+ if (this.outletMountPath && !this.isRootOutlet) {
1440
+ return this.outletMountPath;
1441
+ }
1442
+ // Fallback: root outlet or mount path not yet seeded. Run the full
1443
+ // computeParentPath algorithm to discover the parent depth.
1444
+ if (this.ionRouterOutlet) {
1445
+ const routeChildren = extractRouteChildren(this.ionRouterOutlet.props.children);
1446
+ const { hasRelativeRoutes, hasIndexRoute, hasWildcardRoute } = analyzeRouteChildren(routeChildren);
1447
+ if (!this.isRootOutlet || hasRelativeRoutes || hasIndexRoute) {
1448
+ const result = computeParentPath({
1449
+ currentPathname,
1450
+ outletMountPath: this.outletMountPath,
1451
+ routeChildren,
1452
+ hasRelativeRoutes,
1453
+ hasIndexRoute,
1454
+ hasWildcardRoute,
1455
+ });
1456
+ if (result.outletMountPath && !this.outletMountPath) {
1457
+ this.outletMountPath = result.outletMountPath;
1458
+ }
1459
+ return result.parentPath;
1460
+ }
1461
+ }
1462
+ return this.outletMountPath;
1463
+ }
1464
+ /**
1465
+ * Finds the entering and leaving view items, handling redirect cases.
1466
+ */
1467
+ findViewItems(routeInfo) {
1468
+ const enteringViewItem = this.context.findViewItemByRouteInfo(routeInfo, this.id);
1469
+ let leavingViewItem = this.context.findLeavingViewItemByRouteInfo(routeInfo, this.id);
1470
+ // Try to find leaving view by previous pathname
1471
+ if (!leavingViewItem && routeInfo.prevRouteLastPathname) {
1472
+ leavingViewItem = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1473
+ }
1474
+ // For redirects where entering === leaving, find the actual previous view
1475
+ if (enteringViewItem &&
1476
+ leavingViewItem &&
1477
+ enteringViewItem === leavingViewItem &&
1478
+ routeInfo.routeAction === 'replace' &&
1479
+ routeInfo.prevRouteLastPathname) {
1480
+ const actualLeavingView = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1481
+ if (actualLeavingView && actualLeavingView !== enteringViewItem) {
1482
+ leavingViewItem = actualLeavingView;
1483
+ }
1484
+ }
1485
+ // Handle redirect scenario with no leaving view
1486
+ if (enteringViewItem &&
1487
+ !leavingViewItem &&
1488
+ routeInfo.routeAction === 'replace' &&
1489
+ routeInfo.prevRouteLastPathname) {
1490
+ const actualLeavingView = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1491
+ if (actualLeavingView && actualLeavingView !== enteringViewItem) {
1492
+ leavingViewItem = actualLeavingView;
1493
+ }
1494
+ }
1495
+ return { enteringViewItem, leavingViewItem };
1496
+ }
1497
+ shouldUnmountLeavingView(routeInfo, enteringViewItem, leavingViewItem) {
1498
+ var _a, _b, _c, _d;
1499
+ if (!leavingViewItem) {
1500
+ return false;
1501
+ }
1502
+ if (routeInfo.routeAction === 'replace') {
1503
+ const enteringRoutePath = (_b = (_a = enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1504
+ const leavingRoutePath = (_d = (_c = leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.reactElement) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.path;
1505
+ // Never unmount root path - needed for back navigation
1506
+ if (leavingRoutePath === '/' || leavingRoutePath === '') {
1507
+ return false;
1508
+ }
1509
+ if (enteringRoutePath && leavingRoutePath) {
1510
+ const getParentPath = (path) => {
1511
+ const normalized = path.replace(/\/\*$/, '');
1512
+ const lastSlash = normalized.lastIndexOf('/');
1513
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : '/';
1514
+ };
1515
+ const enteringParent = getParentPath(enteringRoutePath);
1516
+ const leavingParent = getParentPath(leavingRoutePath);
1517
+ // Unmount if routes are siblings or entering is a child of leaving (redirect)
1518
+ const areSiblings = enteringParent === leavingParent && enteringParent !== '/';
1519
+ const isChildRedirect = enteringRoutePath.startsWith(leavingRoutePath) ||
1520
+ (leavingRoutePath.endsWith('/*') && enteringRoutePath.startsWith(leavingRoutePath.slice(0, -2)));
1521
+ return areSiblings || isChildRedirect;
1522
+ }
1523
+ return false;
1524
+ }
1525
+ // For non-replace actions, only unmount for back navigation
1526
+ const isForwardPush = routeInfo.routeAction === 'push' && routeInfo.routeDirection === 'forward';
1527
+ if (!isForwardPush && routeInfo.routeDirection !== 'none' && enteringViewItem !== leavingViewItem) {
1528
+ return true;
1529
+ }
1530
+ return false;
1531
+ }
1532
+ /**
1533
+ * Handles out-of-scope outlet. Returns true if transition should be aborted.
1534
+ */
1535
+ handleOutOfScopeOutlet(routeInfo) {
1536
+ if (!this.outletMountPath || routeInfo.pathname.startsWith(this.outletMountPath)) {
1537
+ return false;
1538
+ }
1539
+ if (this.outOfScopeUnmountTimeout) {
1540
+ clearTimeout(this.outOfScopeUnmountTimeout);
1541
+ this.outOfScopeUnmountTimeout = undefined;
1542
+ }
1543
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
1544
+ allViewsInOutlet.forEach((viewItem) => {
1545
+ hideIonPageElement(viewItem.ionPageElement);
1546
+ this.context.unMountViewItem(viewItem);
1547
+ });
1548
+ this.forceUpdate();
1549
+ return true;
1550
+ }
1551
+ /**
1552
+ * Handles nested outlet with relative routes but no parent path. Returns true to abort.
1553
+ */
1554
+ handleOutOfContextNestedOutlet(parentPath, leavingViewItem) {
1555
+ var _a;
1556
+ if (this.isRootOutlet || parentPath !== undefined || !this.ionRouterOutlet) {
1557
+ return false;
1558
+ }
1559
+ const routesChildren = (_a = getRoutesChildren(this.ionRouterOutlet.props.children)) !== null && _a !== void 0 ? _a : this.ionRouterOutlet.props.children;
1560
+ const routeChildren = React.Children.toArray(routesChildren).filter((child) => React.isValidElement(child) && (child.type === Route || child.type === IonRoute));
1561
+ const hasRelativeRoutes = routeChildren.some((route) => {
1562
+ const path = route.props.path;
1563
+ return path && !path.startsWith('/') && path !== '*';
1564
+ });
1565
+ if (hasRelativeRoutes) {
1566
+ hideIonPageElement(leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement);
1567
+ if (leavingViewItem) {
1568
+ leavingViewItem.mount = false;
1569
+ }
1570
+ this.forceUpdate();
1571
+ return true;
1572
+ }
1573
+ return false;
1574
+ }
1575
+ /**
1576
+ * Handles nested outlet with no matching route. Returns true to abort.
1577
+ */
1578
+ handleNoMatchingRoute(enteringRoute, enteringViewItem, leavingViewItem) {
1579
+ if (this.isRootOutlet || enteringRoute || enteringViewItem) {
1580
+ return false;
1581
+ }
1582
+ hideIonPageElement(leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement);
1583
+ if (leavingViewItem) {
1584
+ leavingViewItem.mount = false;
1585
+ }
1586
+ this.forceUpdate();
1587
+ return true;
1588
+ }
1589
+ /**
1590
+ * Handles transition when entering view has ion-page element ready.
1591
+ */
1592
+ handleReadyEnteringView(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem) {
1593
+ var _a, _b;
1594
+ const routePath = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1595
+ const isParameterizedRoute = routePath ? routePath.includes(':') : false;
1596
+ const isWildcardContainerRoute = routePath ? routePath.endsWith('/*') : false;
1597
+ // Handle same-view transitions (parameterized routes like /user/:id or container routes like /tabs/*)
1598
+ // When entering === leaving, the view is already visible - skip transition to prevent flash
1599
+ if (enteringViewItem === leavingViewItem) {
1600
+ if (isParameterizedRoute || isWildcardContainerRoute) {
1601
+ const updatedMatch = matchComponent(enteringViewItem.reactElement, routeInfo.pathname, true, this.outletMountPath);
1602
+ if (updatedMatch) {
1603
+ enteringViewItem.routeData.match = updatedMatch;
1604
+ }
1605
+ const enteringEl = enteringViewItem.ionPageElement;
1606
+ if (enteringEl) {
1607
+ showIonPageElement(enteringEl);
1608
+ enteringEl.classList.remove('ion-page-invisible');
1609
+ }
1610
+ this.forceUpdate();
1611
+ return;
1612
+ }
1613
+ }
1614
+ // For wildcard container routes, check if we're navigating within the same container.
1615
+ // If both the current pathname and the previous pathname match the same container route,
1616
+ // skip the transition - the nested outlet will handle the actual page change.
1617
+ // This handles cases where leavingViewItem lookup fails (e.g., no IonPage wrapper).
1618
+ if (isWildcardContainerRoute && routeInfo.lastPathname) {
1619
+ // routePath is guaranteed to exist since isWildcardContainerRoute checks routePath?.endsWith('/*')
1620
+ const containerBase = routePath.replace(/\/\*$/, '');
1621
+ const currentInContainer = routeInfo.pathname.startsWith(containerBase + '/') || routeInfo.pathname === containerBase;
1622
+ const previousInContainer = routeInfo.lastPathname.startsWith(containerBase + '/') || routeInfo.lastPathname === containerBase;
1623
+ if (currentInContainer && previousInContainer) {
1624
+ const updatedMatch = matchComponent(enteringViewItem.reactElement, routeInfo.pathname, true, this.outletMountPath);
1625
+ if (updatedMatch) {
1626
+ enteringViewItem.routeData.match = updatedMatch;
1627
+ }
1628
+ this.forceUpdate();
1629
+ return;
1630
+ }
1631
+ }
1632
+ if (!leavingViewItem && this.props.routeInfo.prevRouteLastPathname) {
1633
+ leavingViewItem = this.context.findViewItemByPathname(this.props.routeInfo.prevRouteLastPathname, this.id);
1634
+ }
1635
+ // Re-mount views that were previously unmounted (e.g., navigating back to home)
1636
+ if (!enteringViewItem.mount) {
1637
+ enteringViewItem.mount = true;
1638
+ }
1639
+ // Check visibility state BEFORE showing entering view
1640
+ const enteringWasVisible = enteringViewItem.ionPageElement && isViewVisible(enteringViewItem.ionPageElement);
1641
+ const leavingIsHidden = leavingViewItem !== undefined && leavingViewItem.ionPageElement && !isViewVisible(leavingViewItem.ionPageElement);
1642
+ const currentTransition = {
1643
+ enteringId: enteringViewItem.id,
1644
+ leavingId: leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.id,
1645
+ };
1646
+ const isDuplicateTransition = leavingViewItem &&
1647
+ this.lastTransition &&
1648
+ this.lastTransition.leavingId &&
1649
+ this.lastTransition.enteringId === currentTransition.enteringId &&
1650
+ this.lastTransition.leavingId === currentTransition.leavingId;
1651
+ // Skip if transition already performed (e.g., via swipe gesture)
1652
+ if (enteringWasVisible && leavingIsHidden && isDuplicateTransition) {
1653
+ if (this.skipTransition &&
1654
+ shouldUnmountLeavingViewItem &&
1655
+ leavingViewItem &&
1656
+ enteringViewItem !== leavingViewItem) {
1657
+ leavingViewItem.mount = false;
1658
+ // Trigger ionViewDidLeave lifecycle for ViewLifeCycleManager cleanup
1659
+ this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, 'back');
1660
+ }
1661
+ this.skipTransition = false;
1662
+ this.forceUpdate();
1663
+ return;
1664
+ }
1665
+ showIonPageElement(enteringViewItem.ionPageElement);
1666
+ // Handle duplicate transition or swipe gesture completion
1667
+ if (isDuplicateTransition || this.skipTransition) {
1668
+ if (this.skipTransition &&
1669
+ shouldUnmountLeavingViewItem &&
1670
+ leavingViewItem &&
1671
+ enteringViewItem !== leavingViewItem) {
1672
+ leavingViewItem.mount = false;
1673
+ // Re-fire ionViewDidLeave since gesture completed before mount=false was set
1674
+ this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, 'back');
1675
+ }
1676
+ this.skipTransition = false;
1677
+ this.forceUpdate();
1678
+ return;
1679
+ }
1680
+ this.lastTransition = currentTransition;
1681
+ const shouldSkipAnimation = this.applySkipAnimationIfNeeded(enteringViewItem, leavingViewItem);
1682
+ this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, undefined, false, shouldSkipAnimation);
1683
+ if (shouldUnmountLeavingViewItem && leavingViewItem && enteringViewItem !== leavingViewItem) {
1684
+ leavingViewItem.mount = false;
1685
+ this.handleLeavingViewUnmount(routeInfo, enteringViewItem, leavingViewItem);
1686
+ }
1687
+ // Clean up orphaned sibling views after replace actions (redirects)
1688
+ this.cleanupOrphanedSiblingViews(routeInfo, enteringViewItem, leavingViewItem);
1689
+ }
1690
+ /**
1691
+ * Handles leaving view unmount for replace actions.
1692
+ */
1693
+ handleLeavingViewUnmount(routeInfo, enteringViewItem, leavingViewItem) {
1694
+ var _a, _b, _c, _d, _e, _f;
1695
+ if (!leavingViewItem.ionPageElement) {
1696
+ return;
1697
+ }
1698
+ // Only replace actions unmount views; push/pop cache for navigation history
1699
+ if (routeInfo.routeAction !== 'replace') {
1700
+ return;
1701
+ }
1702
+ const enteringRoutePath = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1703
+ const leavingRoutePath = (_d = (_c = leavingViewItem.reactElement) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.path;
1704
+ const isEnteringContainerRoute = enteringRoutePath && enteringRoutePath.endsWith('/*');
1705
+ const isLeavingSpecificRoute = leavingRoutePath &&
1706
+ leavingRoutePath !== '' &&
1707
+ leavingRoutePath !== '*' &&
1708
+ !leavingRoutePath.endsWith('/*') &&
1709
+ !((_f = (_e = leavingViewItem.reactElement) === null || _e === void 0 ? void 0 : _e.props) === null || _f === void 0 ? void 0 : _f.index);
1710
+ // Skip removal for container-to-container transitions (e.g., /tabs/* → /settings/*).
1711
+ // These routes manage their own nested outlets; unmounting would disrupt child views.
1712
+ if (isEnteringContainerRoute && !isLeavingSpecificRoute) {
1713
+ return;
1714
+ }
1715
+ const viewToUnmount = leavingViewItem;
1716
+ setTimeout(() => {
1717
+ this.context.unMountViewItem(viewToUnmount);
1718
+ this.forceUpdate();
1719
+ }, VIEW_UNMOUNT_DELAY_MS);
1720
+ }
1721
+ /**
1722
+ * Cleans up orphaned sibling views after replace actions or push-to-container navigations.
1723
+ */
1724
+ cleanupOrphanedSiblingViews(routeInfo, enteringViewItem, leavingViewItem) {
1725
+ var _a, _b, _c, _d, _e, _f, _g;
1726
+ const enteringRoutePath = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1727
+ if (!enteringRoutePath) {
1728
+ return;
1729
+ }
1730
+ const leavingRoutePath = (_d = (_c = leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.reactElement) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.path;
1731
+ const isContainerRoute = (path) => path === null || path === void 0 ? void 0 : path.endsWith('/*');
1732
+ const isReplaceAction = routeInfo.routeAction === 'replace';
1733
+ const isPushToContainer = routeInfo.routeAction === 'push' && routeInfo.routeDirection === 'none' && isContainerRoute(enteringRoutePath);
1734
+ if (!isReplaceAction && !isPushToContainer) {
1735
+ return;
1736
+ }
1737
+ // Skip cleanup for tab switches
1738
+ const isSameView = enteringViewItem === leavingViewItem;
1739
+ const isSameContainerRoute = isContainerRoute(enteringRoutePath) && leavingRoutePath === enteringRoutePath;
1740
+ const isNavigatingWithinContainer = isPushToContainer &&
1741
+ !leavingViewItem &&
1742
+ ((_e = routeInfo.prevRouteLastPathname) === null || _e === void 0 ? void 0 : _e.startsWith(enteringRoutePath.replace(/\/\*$/, '')));
1743
+ if (isSameView || isSameContainerRoute || isNavigatingWithinContainer) {
1744
+ return;
1745
+ }
1746
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
1747
+ const areSiblingRoutes = (path1, path2) => {
1748
+ const path1IsRelative = !path1.startsWith('/');
1749
+ const path2IsRelative = !path2.startsWith('/');
1750
+ if (path1IsRelative && path2IsRelative) {
1751
+ const path1Depth = path1.replace(/\/\*$/, '').split('/').filter(Boolean).length;
1752
+ const path2Depth = path2.replace(/\/\*$/, '').split('/').filter(Boolean).length;
1753
+ return path1Depth === path2Depth && path1Depth <= 1;
1754
+ }
1755
+ const getParent = (path) => {
1756
+ const normalized = path.replace(/\/\*$/, '');
1757
+ const lastSlash = normalized.lastIndexOf('/');
1758
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : '/';
1759
+ };
1760
+ return getParent(path1) === getParent(path2);
1761
+ };
1762
+ for (const viewItem of allViewsInOutlet) {
1763
+ const viewRoutePath = (_g = (_f = viewItem.reactElement) === null || _f === void 0 ? void 0 : _f.props) === null || _g === void 0 ? void 0 : _g.path;
1764
+ const shouldSkip = viewItem.id === enteringViewItem.id ||
1765
+ (leavingViewItem && viewItem.id === leavingViewItem.id) ||
1766
+ !viewItem.mount ||
1767
+ !viewRoutePath ||
1768
+ (viewRoutePath.endsWith('/*') && enteringRoutePath.endsWith('/*'));
1769
+ if (shouldSkip) {
1770
+ continue;
1771
+ }
1772
+ if (areSiblingRoutes(enteringRoutePath, viewRoutePath)) {
1773
+ hideIonPageElement(viewItem.ionPageElement);
1774
+ viewItem.mount = false;
1775
+ const viewToRemove = viewItem;
1776
+ setTimeout(() => {
1777
+ this.context.unMountViewItem(viewToRemove);
1778
+ this.forceUpdate();
1779
+ }, VIEW_UNMOUNT_DELAY_MS);
1780
+ }
1781
+ }
1782
+ }
1783
+ /**
1784
+ * Determines whether to skip the transition animation and, if so, immediately
1785
+ * hides the leaving view with inline `display:none`.
1786
+ *
1787
+ * Skips transitions in outlets nested inside a parent IonPage. These outlets
1788
+ * render pages inside a parent page's content area. The MD animation shows
1789
+ * both entering and leaving pages simultaneously, causing text overlap and
1790
+ * nested scrollbars (each page has its own IonContent). Top-level outlets
1791
+ * are unaffected and animate normally.
1792
+ *
1793
+ * Uses inline visibility:hidden rather than ion-page-hidden class because
1794
+ * core's beforeTransition() removes ion-page-hidden via setPageHidden().
1795
+ * Inline visibility:hidden survives that removal, keeping the page hidden
1796
+ * until React unmounts it after ionViewDidLeave fires. Unlike display:none,
1797
+ * visibility:hidden preserves element geometry so commit() animations
1798
+ * can resolve normally.
1799
+ */
1800
+ applySkipAnimationIfNeeded(enteringViewItem, leavingViewItem) {
1801
+ var _a;
1802
+ const isNestedOutlet = !!((_a = this.routerOutletElement) === null || _a === void 0 ? void 0 : _a.closest('.ion-page'));
1803
+ const shouldSkip = isNestedOutlet && !!leavingViewItem && enteringViewItem !== leavingViewItem;
1804
+ if (shouldSkip && (leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement)) {
1805
+ leavingViewItem.ionPageElement.style.setProperty('visibility', 'hidden');
1806
+ leavingViewItem.ionPageElement.setAttribute('aria-hidden', 'true');
1807
+ }
1808
+ return shouldSkip;
1809
+ }
1810
+ /**
1811
+ * Handles entering view with no ion-page element yet (waiting for render).
1812
+ */
1813
+ handleWaitingForIonPage(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem) {
1814
+ var _a, _b;
1815
+ const enteringRouteElement = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.element;
1816
+ // Handle Navigate components (they never render an IonPage)
1817
+ if (isNavigateElement(enteringRouteElement)) {
1818
+ this.waitingForIonPage = false;
1819
+ if (this.ionPageWaitTimeout) {
1820
+ clearTimeout(this.ionPageWaitTimeout);
1821
+ this.ionPageWaitTimeout = undefined;
1822
+ }
1823
+ this.pendingPageTransition = false;
1824
+ // Hide ALL other visible views in this outlet for Navigate redirects.
1825
+ // Same rationale as the timeout path: intermediate redirects can shift
1826
+ // the leaving view reference, leaving the original page visible.
1827
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
1828
+ allViewsInOutlet.forEach((viewItem) => {
1829
+ if (viewItem.id !== enteringViewItem.id && viewItem.ionPageElement) {
1830
+ hideIonPageElement(viewItem.ionPageElement);
1831
+ }
1832
+ });
1833
+ // Don't unmount if entering and leaving are the same view item
1834
+ if (shouldUnmountLeavingViewItem && leavingViewItem && enteringViewItem !== leavingViewItem) {
1835
+ leavingViewItem.mount = false;
1836
+ }
1837
+ this.forceUpdate();
1838
+ return;
1839
+ }
1840
+ // Do not hide the leaving view here - wait until the entering view is ready.
1841
+ // Hiding the leaving view while the entering view is still mounting causes a flash
1842
+ // where both views are hidden/invisible simultaneously.
1843
+ // The leaving view will be hidden in transitionPage() after the entering view is visible.
1844
+ this.waitingForIonPage = true;
1845
+ if (this.ionPageWaitTimeout) {
1846
+ clearTimeout(this.ionPageWaitTimeout);
1847
+ }
1848
+ this.ionPageWaitTimeout = setTimeout(() => {
1849
+ var _a, _b;
1850
+ this.ionPageWaitTimeout = undefined;
1851
+ if (!this.waitingForIonPage) {
1852
+ return;
1853
+ }
1854
+ this.waitingForIonPage = false;
1855
+ const latestEnteringView = (_a = this.context.findViewItemByRouteInfo(routeInfo, this.id)) !== null && _a !== void 0 ? _a : enteringViewItem;
1856
+ const latestLeavingView = (_b = this.context.findLeavingViewItemByRouteInfo(routeInfo, this.id)) !== null && _b !== void 0 ? _b : leavingViewItem;
1857
+ if (latestEnteringView === null || latestEnteringView === void 0 ? void 0 : latestEnteringView.ionPageElement) {
1858
+ const shouldSkipAnimation = this.applySkipAnimationIfNeeded(latestEnteringView, latestLeavingView !== null && latestLeavingView !== void 0 ? latestLeavingView : undefined);
1859
+ this.transitionPage(routeInfo, latestEnteringView, latestLeavingView !== null && latestLeavingView !== void 0 ? latestLeavingView : undefined, undefined, false, shouldSkipAnimation);
1860
+ if (shouldUnmountLeavingViewItem && latestLeavingView && latestEnteringView !== latestLeavingView) {
1861
+ latestLeavingView.mount = false;
1862
+ // Call handleLeavingViewUnmount to ensure the view is properly removed
1863
+ this.handleLeavingViewUnmount(routeInfo, latestEnteringView, latestLeavingView);
1864
+ }
1865
+ this.forceUpdate();
1866
+ }
1867
+ else {
1868
+ /**
1869
+ * Timeout fired and entering view still has no ionPageElement.
1870
+ * This happens for container routes that render nested outlets without a direct IonPage.
1871
+ * Hide ALL other visible views in this outlet, not just the computed leaving view.
1872
+ * This handles cases where intermediate redirects (e.g., Navigate in nested routes)
1873
+ * change the leaving view reference, leaving the original page still visible.
1874
+ */
1875
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
1876
+ allViewsInOutlet.forEach((viewItem) => {
1877
+ if (viewItem.id !== latestEnteringView.id && viewItem.ionPageElement) {
1878
+ hideIonPageElement(viewItem.ionPageElement);
1879
+ }
1880
+ });
1881
+ this.forceUpdate();
1882
+ // Safety net: after forceUpdate triggers a React render cycle, check if
1883
+ // any pages in this outlet are stuck with ion-page-invisible. This can
1884
+ // happen when view lookup fails (e.g., wildcard-to-index transitions
1885
+ // where the view item gets corrupted). The forceUpdate above causes
1886
+ // React to render the correct component, but ion-page-invisible may
1887
+ // persist if no transition runs for that page.
1888
+ setTimeout(() => {
1889
+ if (!this._isMounted || !this.routerOutletElement)
1890
+ return;
1891
+ const stuckPages = this.routerOutletElement.querySelectorAll(':scope > .ion-page-invisible');
1892
+ stuckPages.forEach((page) => {
1893
+ page.classList.remove('ion-page-invisible');
1894
+ });
1895
+ }, ION_PAGE_WAIT_TIMEOUT_MS);
1896
+ }
1897
+ }, ION_PAGE_WAIT_TIMEOUT_MS);
1898
+ this.forceUpdate();
1899
+ }
1900
+ /**
1901
+ * Gets the route info to use for finding views during swipe-to-go-back gestures.
1902
+ * This pattern is used in multiple places in setupRouterOutlet.
1903
+ */
1904
+ getSwipeBackRouteInfo() {
1905
+ const { routeInfo } = this.props;
1906
+ return this.prevProps && this.prevProps.routeInfo.pathname === routeInfo.pushedByRoute
1907
+ ? this.prevProps.routeInfo
1908
+ : { pathname: routeInfo.pushedByRoute || '' };
1909
+ }
227
1910
  componentDidMount() {
1911
+ this._isMounted = true;
228
1912
  if (this.clearOutletTimeout) {
229
1913
  /**
230
1914
  * The clearOutlet integration with React Router is a bit hacky.
@@ -255,117 +1939,186 @@ class StackManager extends React.PureComponent {
255
1939
  }
256
1940
  }
257
1941
  componentWillUnmount() {
1942
+ this._isMounted = false;
1943
+ // Cancel any in-flight transition rAFs
1944
+ for (const id of this.transitionRafIds) {
1945
+ cancelAnimationFrame(id);
1946
+ }
1947
+ this.transitionRafIds = [];
1948
+ // Disconnect any in-flight MutationObserver from waitForComponentsReady
1949
+ if (this.transitionObserver) {
1950
+ this.transitionObserver.disconnect();
1951
+ this.transitionObserver = undefined;
1952
+ }
1953
+ if (this.ionPageWaitTimeout) {
1954
+ clearTimeout(this.ionPageWaitTimeout);
1955
+ this.ionPageWaitTimeout = undefined;
1956
+ }
1957
+ if (this.outOfScopeUnmountTimeout) {
1958
+ clearTimeout(this.outOfScopeUnmountTimeout);
1959
+ this.outOfScopeUnmountTimeout = undefined;
1960
+ }
1961
+ this.waitingForIonPage = false;
1962
+ // Hide all views in this outlet before clearing.
1963
+ // This is critical for nested outlets - when the parent component unmounts,
1964
+ // the nested outlet's componentDidUpdate won't be called, so we must hide
1965
+ // the ion-page elements here to prevent them from remaining visible on top
1966
+ // of other content after navigation to a different route.
1967
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
1968
+ allViewsInOutlet.forEach((viewItem) => {
1969
+ hideIonPageElement(viewItem.ionPageElement);
1970
+ });
258
1971
  this.clearOutletTimeout = this.context.clearOutlet(this.id);
259
1972
  }
1973
+ /**
1974
+ * Sets the transition between pages within this router outlet.
1975
+ * This function determines the entering and leaving views based on the
1976
+ * provided route information and triggers the appropriate animation.
1977
+ * It also handles scenarios like initial loads, back navigation, and
1978
+ * navigation to the same view with different parameters.
1979
+ *
1980
+ * @param routeInfo It contains info about the current route,
1981
+ * the previous route, and the action taken (e.g., push, replace).
1982
+ *
1983
+ * @returns A promise that resolves when the transition is complete.
1984
+ * If no transition is needed or if the router outlet isn't ready,
1985
+ * the Promise may resolve immediately.
1986
+ */
260
1987
  async handlePageTransition(routeInfo) {
261
- var _a, _b;
1988
+ var _a;
1989
+ // Wait for router outlet to mount
262
1990
  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
1991
  this.pendingPageTransition = true;
1992
+ return;
271
1993
  }
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
- }
1994
+ // Find entering and leaving view items
1995
+ const viewItems = this.findViewItems(routeInfo);
1996
+ let enteringViewItem = viewItems.enteringViewItem;
1997
+ const leavingViewItem = viewItems.leavingViewItem;
1998
+ const shouldUnmountLeavingViewItem = this.shouldUnmountLeavingView(routeInfo, enteringViewItem, leavingViewItem);
1999
+ // Get parent path for nested outlets
2000
+ const parentPath = this.getParentPath();
2001
+ // Handle out-of-scope outlet (route outside mount path)
2002
+ if (this.handleOutOfScopeOutlet(routeInfo)) {
2003
+ return;
2004
+ }
2005
+ // Clear any pending out-of-scope unmount timeout
2006
+ if (this.outOfScopeUnmountTimeout) {
2007
+ clearTimeout(this.outOfScopeUnmountTimeout);
2008
+ this.outOfScopeUnmountTimeout = undefined;
2009
+ }
2010
+ // Handle nested outlet with relative routes but no valid parent path
2011
+ if (this.handleOutOfContextNestedOutlet(parentPath, leavingViewItem)) {
2012
+ return;
2013
+ }
2014
+ // Find the matching route element
2015
+ const enteringRoute = findRouteByRouteInfo((_a = this.ionRouterOutlet) === null || _a === void 0 ? void 0 : _a.props.children, routeInfo, parentPath);
2016
+ // Handle nested outlet with no matching route
2017
+ if (this.handleNoMatchingRoute(enteringRoute, enteringViewItem, leavingViewItem)) {
2018
+ return;
2019
+ }
2020
+ // Create or update the entering view item
2021
+ if (enteringViewItem && enteringRoute) {
2022
+ enteringViewItem.reactElement = enteringRoute;
2023
+ }
2024
+ else if (enteringRoute) {
2025
+ enteringViewItem = this.context.createViewItem(this.id, enteringRoute, routeInfo);
2026
+ this.context.addViewItem(enteringViewItem);
2027
+ }
2028
+ // Handle transition based on ion-page element availability
2029
+ // Check if the ionPageElement is still in the document.
2030
+ // If the view was previously unmounted (mount=false), the ViewLifeCycleManager
2031
+ // removes the React component from the tree, which removes the IonPage from the DOM.
2032
+ // The ionPageElement reference becomes stale and we need to wait for a new one.
2033
+ const ionPageIsInDocument = (enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement) && document.body.contains(enteringViewItem.ionPageElement);
2034
+ if (enteringViewItem && ionPageIsInDocument) {
2035
+ // Clear waiting state
2036
+ if (this.waitingForIonPage) {
2037
+ this.waitingForIonPage = false;
291
2038
  }
292
- const enteringRoute = matchRoute((_b = this.ionRouterOutlet) === null || _b === void 0 ? void 0 : _b.props.children, routeInfo);
293
- if (enteringViewItem) {
294
- enteringViewItem.reactElement = enteringRoute;
2039
+ if (this.ionPageWaitTimeout) {
2040
+ clearTimeout(this.ionPageWaitTimeout);
2041
+ this.ionPageWaitTimeout = undefined;
295
2042
  }
296
- else if (enteringRoute) {
297
- enteringViewItem = this.context.createViewItem(this.id, enteringRoute, routeInfo);
298
- this.context.addViewItem(enteringViewItem);
2043
+ this.handleReadyEnteringView(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem);
2044
+ }
2045
+ else if (enteringViewItem && !ionPageIsInDocument) {
2046
+ // Wait for ion-page to mount
2047
+ // This handles both: no ionPageElement, or stale ionPageElement (not in document)
2048
+ // Clear stale reference if the element is no longer in the document
2049
+ if (enteringViewItem.ionPageElement && !document.body.contains(enteringViewItem.ionPageElement)) {
2050
+ enteringViewItem.ionPageElement = undefined;
299
2051
  }
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);
2052
+ // Ensure the view is marked as mounted so ViewLifeCycleManager renders the IonPage
2053
+ if (!enteringViewItem.mount) {
2054
+ enteringViewItem.mount = true;
350
2055
  }
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');
2056
+ this.handleWaitingForIonPage(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem);
2057
+ return;
2058
+ }
2059
+ else if (!enteringViewItem && !enteringRoute) {
2060
+ // No view or route found - likely leaving to another outlet
2061
+ if (leavingViewItem) {
2062
+ hideIonPageElement(leavingViewItem.ionPageElement);
2063
+ if (shouldUnmountLeavingViewItem) {
2064
+ leavingViewItem.mount = false;
359
2065
  }
360
- // }, 250);
361
2066
  }
362
- this.forceUpdate();
363
2067
  }
2068
+ this.forceUpdate();
364
2069
  }
2070
+ /**
2071
+ * Registers an `<IonPage>` DOM element with the `StackManager`.
2072
+ * This is called when `<IonPage>` has been mounted.
2073
+ *
2074
+ * @param page The element of the rendered `<IonPage>`.
2075
+ * @param routeInfo The route information that associates with `<IonPage>`.
2076
+ */
365
2077
  registerIonPage(page, routeInfo) {
2078
+ /**
2079
+ * DO NOT remove ion-page-invisible here.
2080
+ *
2081
+ * PageManager's ref callback adds ion-page-invisible synchronously to prevent flash.
2082
+ * At this point, the <IonPage> div exists but its CHILDREN (header, toolbar, menu-button)
2083
+ * have NOT rendered yet. If we remove ion-page-invisible now, the page becomes visible
2084
+ * with empty/incomplete content, causing a flicker (especially for ion-menu-button which
2085
+ * starts with menu-button-hidden class).
2086
+ *
2087
+ * Instead, let transitionPage handle visibility AFTER waiting for components to be ready.
2088
+ * This ensures the page only becomes visible when its content is fully rendered.
2089
+ */
2090
+ this.waitingForIonPage = false;
2091
+ if (this.ionPageWaitTimeout) {
2092
+ clearTimeout(this.ionPageWaitTimeout);
2093
+ this.ionPageWaitTimeout = undefined;
2094
+ }
2095
+ this.pendingPageTransition = false;
366
2096
  const foundView = this.context.findViewItemByRouteInfo(routeInfo, this.id);
367
2097
  if (foundView) {
368
2098
  const oldPageElement = foundView.ionPageElement;
2099
+ /**
2100
+ * FIX for issue #28878: Reject orphaned IonPage registrations.
2101
+ *
2102
+ * When a component conditionally renders different IonPages (e.g., list vs empty state)
2103
+ * using React keys, and state changes simultaneously with navigation, the new IonPage
2104
+ * tries to register for a route we're navigating away from. This creates a stale view.
2105
+ *
2106
+ * Only reject if both pageIds exist and differ, to allow nested outlet registrations.
2107
+ */
2108
+ if (this.shouldRejectOrphanedPage(page, oldPageElement, routeInfo)) {
2109
+ this.hideAndRemoveOrphanedPage(page);
2110
+ return;
2111
+ }
2112
+ /**
2113
+ * Don't let a nested element (e.g., ion-router-outlet with ionPage prop)
2114
+ * override an existing IonPage registration when the existing element is
2115
+ * an ancestor of the new one. This ensures ionPageElement always points
2116
+ * to the outermost IonPage, which is needed to properly hide the entire
2117
+ * page during back navigation (not just the inner outlet).
2118
+ */
2119
+ if (oldPageElement && oldPageElement !== page && oldPageElement.isConnected && oldPageElement.contains(page)) {
2120
+ return;
2121
+ }
369
2122
  foundView.ionPageElement = page;
370
2123
  foundView.ionRoute = true;
371
2124
  /**
@@ -377,8 +2130,34 @@ class StackManager extends React.PureComponent {
377
2130
  return;
378
2131
  }
379
2132
  }
380
- this.handlePageTransition(routeInfo);
2133
+ this.handlePageTransition(routeInfo);
2134
+ }
2135
+ /**
2136
+ * Checks if a new IonPage should be rejected (component re-rendered while navigating away).
2137
+ */
2138
+ shouldRejectOrphanedPage(newPage, oldPageElement, routeInfo) {
2139
+ if (!oldPageElement || oldPageElement === newPage) {
2140
+ return false;
2141
+ }
2142
+ const newPageId = newPage.getAttribute('data-pageid');
2143
+ const oldPageId = oldPageElement.getAttribute('data-pageid');
2144
+ if (!newPageId || !oldPageId || newPageId === oldPageId) {
2145
+ return false;
2146
+ }
2147
+ return this.props.routeInfo.pathname !== routeInfo.pathname;
2148
+ }
2149
+ hideAndRemoveOrphanedPage(page) {
2150
+ page.classList.add('ion-page-hidden');
2151
+ page.setAttribute('aria-hidden', 'true');
2152
+ setTimeout(() => {
2153
+ if (page.parentElement) {
2154
+ page.remove();
2155
+ }
2156
+ }, VIEW_UNMOUNT_DELAY_MS);
381
2157
  }
2158
+ /**
2159
+ * Configures swipe-to-go-back gesture for the router outlet.
2160
+ */
382
2161
  async setupRouterOutlet(routerOutlet) {
383
2162
  const canStart = () => {
384
2163
  const config = getConfig();
@@ -387,40 +2166,34 @@ class StackManager extends React.PureComponent {
387
2166
  return false;
388
2167
  }
389
2168
  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
- */
401
- 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);
2169
+ const swipeBackRouteInfo = this.getSwipeBackRouteInfo();
2170
+ let enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, this.id, false);
2171
+ if (!enteringViewItem) {
2172
+ enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, undefined, false);
2173
+ }
2174
+ // View might have mount=false but ionPageElement still in DOM
2175
+ const ionPageInDocument = Boolean((enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement) && document.body.contains(enteringViewItem.ionPageElement));
2176
+ const canStartSwipe = !!enteringViewItem &&
2177
+ (enteringViewItem.mount || ionPageInDocument) &&
2178
+ enteringViewItem.routeData.match.pattern.path !== routeInfo.pathname;
2179
+ return canStartSwipe;
411
2180
  };
412
2181
  const onStart = async () => {
413
2182
  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);
2183
+ const swipeBackRouteInfo = this.getSwipeBackRouteInfo();
2184
+ // First try to find the view in the current outlet, then search all outlets
2185
+ let enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, this.id, false);
2186
+ if (!enteringViewItem) {
2187
+ enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, undefined, false);
2188
+ }
418
2189
  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
- */
2190
+ // Ensure the entering view is mounted so React keeps rendering it during the gesture.
2191
+ // This is important when the view was previously marked for unmount but its
2192
+ // ionPageElement is still in the DOM.
2193
+ if (enteringViewItem && !enteringViewItem.mount) {
2194
+ enteringViewItem.mount = true;
2195
+ }
2196
+ // When the gesture starts, kick off a transition controlled via swipe gesture
424
2197
  if (enteringViewItem && leavingViewItem) {
425
2198
  await this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, 'back', true);
426
2199
  }
@@ -428,34 +2201,23 @@ class StackManager extends React.PureComponent {
428
2201
  };
429
2202
  const onEnd = (shouldContinue) => {
430
2203
  if (shouldContinue) {
2204
+ // User finished the swipe gesture, so complete the back navigation
431
2205
  this.skipTransition = true;
432
2206
  this.context.goBack();
433
2207
  }
434
2208
  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
- */
2209
+ // Swipe gesture was aborted - re-hide the page that was going to enter
440
2210
  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);
2211
+ const swipeBackRouteInfo = this.getSwipeBackRouteInfo();
2212
+ // First try to find the view in the current outlet, then search all outlets
2213
+ let enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, this.id, false);
2214
+ if (!enteringViewItem) {
2215
+ enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, undefined, false);
2216
+ }
445
2217
  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
- */
2218
+ // Don't hide if entering and leaving are the same (parameterized route edge case)
455
2219
  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');
2220
+ hideIonPageElement(enteringViewItem.ionPageElement);
459
2221
  }
460
2222
  }
461
2223
  };
@@ -465,7 +2227,23 @@ class StackManager extends React.PureComponent {
465
2227
  onEnd,
466
2228
  };
467
2229
  }
468
- async transitionPage(routeInfo, enteringViewItem, leavingViewItem, direction, progressAnimation = false) {
2230
+ /**
2231
+ * Animates the transition between the entering and leaving pages within the
2232
+ * router outlet.
2233
+ *
2234
+ * @param routeInfo Info about the current route.
2235
+ * @param enteringViewItem The view item that is entering.
2236
+ * @param leavingViewItem The view item that is leaving.
2237
+ * @param direction The direction of the transition.
2238
+ * @param progressAnimation Indicates if the transition is part of a
2239
+ * gesture controlled animation (e.g., swipe to go back).
2240
+ * Defaults to `false`.
2241
+ * @param skipAnimation When true, forces `duration: 0` so the page
2242
+ * swap is instant (no visible animation). Used for ionPage outlets
2243
+ * and back navigations that unmount the leaving view to prevent
2244
+ * overlapping content during the transition. Defaults to `false`.
2245
+ */
2246
+ async transitionPage(routeInfo, enteringViewItem, leavingViewItem, direction, progressAnimation = false, skipAnimation = false) {
469
2247
  const runCommit = async (enteringEl, leavingEl) => {
470
2248
  const skipTransition = this.skipTransition;
471
2249
  /**
@@ -493,24 +2271,43 @@ class StackManager extends React.PureComponent {
493
2271
  }
494
2272
  else {
495
2273
  enteringEl.classList.add('ion-page');
496
- enteringEl.classList.add('ion-page-invisible');
2274
+ /**
2275
+ * Only add ion-page-invisible if the element is not already visible.
2276
+ * During tab switches, the container page (e.g., TabContext wrapper) is
2277
+ * already visible and should remain so. Adding ion-page-invisible would
2278
+ * cause a flash where the visible page briefly becomes invisible.
2279
+ */
2280
+ if (!isViewVisible(enteringEl)) {
2281
+ enteringEl.classList.add('ion-page-invisible');
2282
+ }
497
2283
  }
498
- await routerOutlet.commit(enteringEl, leavingEl, {
499
- duration: skipTransition || directionToUse === undefined ? 0 : undefined,
2284
+ const commitDuration = skipTransition || skipAnimation || directionToUse === undefined ? 0 : undefined;
2285
+ // Race commit against a timeout to recover from hangs
2286
+ const commitPromise = routerOutlet.commit(enteringEl, leavingEl, {
2287
+ duration: commitDuration,
500
2288
  direction: directionToUse,
501
2289
  showGoBack: !!routeInfo.pushedByRoute,
502
2290
  progressAnimation,
503
2291
  animationBuilder: routeInfo.routeAnimation,
504
2292
  });
2293
+ const timeoutMs = 5000;
2294
+ const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve('timeout'), timeoutMs));
2295
+ const result = await Promise.race([commitPromise.then(() => 'done'), timeoutPromise]);
2296
+ if (result === 'timeout') {
2297
+ // Force entering page visible even though commit hung
2298
+ enteringEl.classList.remove('ion-page-invisible');
2299
+ }
2300
+ if (!progressAnimation) {
2301
+ enteringEl.classList.remove('ion-page-invisible');
2302
+ }
505
2303
  };
506
2304
  const routerOutlet = this.routerOutletElement;
507
2305
  const routeInfoFallbackDirection = routeInfo.routeDirection === 'none' || routeInfo.routeDirection === 'root' ? undefined : routeInfo.routeDirection;
508
2306
  const directionToUse = direction !== null && direction !== void 0 ? direction : routeInfoFallbackDirection;
509
2307
  if (enteringViewItem && enteringViewItem.ionPageElement && this.routerOutletElement) {
510
2308
  if (leavingViewItem && leavingViewItem.ionPageElement && enteringViewItem === leavingViewItem) {
511
- // If a page is transitioning to another version of itself
512
- // we clone it so we can have an animation to show
513
- const match = matchComponent(leavingViewItem.reactElement, routeInfo.pathname, true);
2309
+ // Clone page for same-view transitions (e.g., /user/1 /user/2)
2310
+ const match = matchComponent(leavingViewItem.reactElement, routeInfo.pathname, undefined, this.outletMountPath);
514
2311
  if (match) {
515
2312
  const newLeavingElement = clonePageElement(leavingViewItem.ionPageElement.outerHTML);
516
2313
  if (newLeavingElement) {
@@ -520,14 +2317,104 @@ class StackManager extends React.PureComponent {
520
2317
  }
521
2318
  }
522
2319
  else {
2320
+ // Route no longer matches (e.g., /user/1 → /settings)
523
2321
  await runCommit(enteringViewItem.ionPageElement, undefined);
524
2322
  }
525
2323
  }
526
2324
  else {
527
- await runCommit(enteringViewItem.ionPageElement, leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement);
528
- if (leavingViewItem && leavingViewItem.ionPageElement && !progressAnimation) {
529
- leavingViewItem.ionPageElement.classList.add('ion-page-hidden');
530
- leavingViewItem.ionPageElement.setAttribute('aria-hidden', 'true');
2325
+ const leavingEl = leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement;
2326
+ // For non-animated transitions, don't pass leaving element to commit() to avoid
2327
+ // flicker caused by commit() briefly unhiding the leaving page
2328
+ const isNonAnimatedTransition = directionToUse === undefined && !progressAnimation;
2329
+ if (isNonAnimatedTransition && leavingEl) {
2330
+ /**
2331
+ * Skip commit() for non-animated transitions (like tab switches).
2332
+ * commit() runs animation logic that can cause intermediate paints
2333
+ * even with duration: 0. Instead, swap visibility synchronously.
2334
+ *
2335
+ * Synchronous DOM class changes are batched into a single browser
2336
+ * paint, so there's no gap frame where neither page is visible and
2337
+ * no overlap frame where both pages are visible.
2338
+ */
2339
+ const enteringEl = enteringViewItem.ionPageElement;
2340
+ // Ensure entering element has proper base classes
2341
+ enteringEl.classList.add('ion-page');
2342
+ // Clear ALL hidden state from entering element. showIonPageElement
2343
+ // removes visibility:hidden (from applySkipAnimationIfNeeded),
2344
+ // ion-page-hidden, and aria-hidden in one call.
2345
+ showIonPageElement(enteringEl);
2346
+ // Handle can-go-back class since we're skipping commit() which normally sets this
2347
+ if (routeInfo.pushedByRoute) {
2348
+ enteringEl.classList.add('can-go-back');
2349
+ }
2350
+ else {
2351
+ enteringEl.classList.remove('can-go-back');
2352
+ }
2353
+ /**
2354
+ * Wait for components to be ready. Menu buttons start hidden (menu-button-hidden)
2355
+ * and become visible after componentDidLoad. Wait for hydration and visibility.
2356
+ */
2357
+ const waitForComponentsReady = () => {
2358
+ return new Promise((resolve) => {
2359
+ const checkReady = () => {
2360
+ const ionicComponents = enteringEl.querySelectorAll('ion-header, ion-toolbar, ion-buttons, ion-menu-button, ion-title, ion-content');
2361
+ const allHydrated = Array.from(ionicComponents).every((el) => el.classList.contains('hydrated'));
2362
+ const menuButtons = enteringEl.querySelectorAll('ion-menu-button');
2363
+ const menuButtonsReady = Array.from(menuButtons).every((el) => !el.classList.contains('menu-button-hidden'));
2364
+ return allHydrated && menuButtonsReady;
2365
+ };
2366
+ if (checkReady()) {
2367
+ resolve();
2368
+ return;
2369
+ }
2370
+ let resolved = false;
2371
+ const observer = new MutationObserver(() => {
2372
+ if (!resolved && checkReady()) {
2373
+ resolved = true;
2374
+ observer.disconnect();
2375
+ if (this.transitionObserver === observer) {
2376
+ this.transitionObserver = undefined;
2377
+ }
2378
+ resolve();
2379
+ }
2380
+ });
2381
+ // Disconnect any previous observer before tracking the new one
2382
+ if (this.transitionObserver) {
2383
+ this.transitionObserver.disconnect();
2384
+ }
2385
+ this.transitionObserver = observer;
2386
+ observer.observe(enteringEl, {
2387
+ subtree: true,
2388
+ attributes: true,
2389
+ attributeFilter: ['class'],
2390
+ });
2391
+ setTimeout(() => {
2392
+ if (!resolved) {
2393
+ resolved = true;
2394
+ observer.disconnect();
2395
+ if (this.transitionObserver === observer) {
2396
+ this.transitionObserver = undefined;
2397
+ }
2398
+ resolve();
2399
+ }
2400
+ }, 100);
2401
+ });
2402
+ };
2403
+ await waitForComponentsReady();
2404
+ // Bail out if the component unmounted during waitForComponentsReady
2405
+ if (!this._isMounted)
2406
+ return;
2407
+ // Swap visibility synchronously - show entering, hide leaving
2408
+ enteringEl.classList.remove('ion-page-invisible');
2409
+ leavingEl.classList.add('ion-page-hidden');
2410
+ leavingEl.setAttribute('aria-hidden', 'true');
2411
+ }
2412
+ else {
2413
+ await runCommit(enteringViewItem.ionPageElement, leavingEl);
2414
+ if (leavingEl && !progressAnimation) {
2415
+ leavingEl.classList.add('ion-page-hidden');
2416
+ leavingEl.setAttribute('aria-hidden', 'true');
2417
+ }
531
2418
  }
532
2419
  }
533
2420
  }
@@ -535,193 +2422,448 @@ class StackManager extends React.PureComponent {
535
2422
  render() {
536
2423
  const { children } = this.props;
537
2424
  const ionRouterOutlet = React.Children.only(children);
2425
+ // Store reference for use in getParentPath() and handlePageTransition()
538
2426
  this.ionRouterOutlet = ionRouterOutlet;
539
- const components = this.context.getChildrenToRender(this.id, this.ionRouterOutlet, this.props.routeInfo, () => {
540
- this.forceUpdate();
541
- });
542
- return (React.createElement(StackContext.Provider, { value: this.stackContextValue }, React.cloneElement(ionRouterOutlet, {
543
- ref: (node) => {
544
- if (ionRouterOutlet.props.setRef) {
545
- ionRouterOutlet.props.setRef(node);
546
- }
547
- if (ionRouterOutlet.props.forwardedRef) {
548
- ionRouterOutlet.props.forwardedRef.current = node;
549
- }
550
- this.routerOutletElement = node;
551
- const { ref } = ionRouterOutlet;
552
- if (typeof ref === 'function') {
553
- ref(node);
554
- }
555
- },
556
- }, components)));
2427
+ return (React.createElement(UNSAFE_RouteContext.Consumer, null, (parentContext) => {
2428
+ // Derive the outlet's mount path from React Router's matched route context.
2429
+ // This eliminates the need for heuristic-based mount path discovery in
2430
+ // computeParentPath, since React Router already knows the matched base path.
2431
+ const parentMatches = parentContext === null || parentContext === void 0 ? void 0 : parentContext.matches;
2432
+ const parentPathnameBase = parentMatches && parentMatches.length > 0
2433
+ ? parentMatches[parentMatches.length - 1].pathnameBase
2434
+ : undefined;
2435
+ // Derive isRootOutlet from RouteContext: empty matches means root.
2436
+ this.isRootOutlet = !parentMatches || parentMatches.length === 0;
2437
+ // Seed StackManager's mount path from the parent route context
2438
+ if (parentPathnameBase && !this.outletMountPath) {
2439
+ this.outletMountPath = parentPathnameBase;
2440
+ }
2441
+ const components = this.context.getChildrenToRender(this.id, this.ionRouterOutlet, this.props.routeInfo, () => {
2442
+ // Callback triggers re-render when view items are modified during getChildrenToRender
2443
+ this.forceUpdate();
2444
+ }, parentPathnameBase);
2445
+ return (React.createElement(StackContext.Provider, { value: this.stackContextValue }, React.cloneElement(ionRouterOutlet, {
2446
+ ref: (node) => {
2447
+ if (ionRouterOutlet.props.setRef) {
2448
+ // Needed to handle external refs from devs.
2449
+ ionRouterOutlet.props.setRef(node);
2450
+ }
2451
+ if (ionRouterOutlet.props.forwardedRef) {
2452
+ // Needed to handle external refs from devs.
2453
+ ionRouterOutlet.props.forwardedRef.current = node;
2454
+ }
2455
+ this.routerOutletElement = node;
2456
+ const { ref } = ionRouterOutlet;
2457
+ // Check for legacy refs.
2458
+ if (typeof ref === 'function') {
2459
+ ref(node);
2460
+ }
2461
+ },
2462
+ }, components)));
2463
+ }));
557
2464
  }
558
2465
  static get contextType() {
559
2466
  return RouteManagerContext;
560
2467
  }
561
2468
  }
562
- function matchRoute(node, routeInfo) {
563
- let matchedNode;
564
- React.Children.forEach(node, (child) => {
565
- const match = matchPath({
566
- pathname: routeInfo.pathname,
567
- componentProps: child.props,
568
- });
569
- if (match) {
570
- matchedNode = child;
2469
+ /**
2470
+ * Converts React Route elements to RouteObject format for use with matchRoutes().
2471
+ * Filters out pathless routes (which are handled by fallback logic separately).
2472
+ *
2473
+ * When a basename is provided, absolute route paths are relativized by stripping
2474
+ * the basename prefix. This is necessary because matchRoutes() strips the basename
2475
+ * from the LOCATION pathname but not from route paths — absolute paths must be
2476
+ * made relative to the basename for matching to work correctly.
2477
+ *
2478
+ * @param routeChildren The flat array of Route/IonRoute elements from the outlet.
2479
+ * @param basename The resolved parent path (without trailing slash or `/*`) used to relativize absolute paths.
2480
+ */
2481
+ function routeElementsToRouteObjects(routeChildren, basename) {
2482
+ return routeChildren
2483
+ .filter((child) => child.props.path != null || child.props.index)
2484
+ .map((child) => {
2485
+ const handle = { _element: child };
2486
+ let path = child.props.path;
2487
+ // Relativize absolute paths by stripping the basename prefix
2488
+ if (path && path.startsWith('/') && basename) {
2489
+ if (path === basename) {
2490
+ path = '';
2491
+ }
2492
+ else if (path.startsWith(basename + '/')) {
2493
+ path = path.slice(basename.length + 1);
2494
+ }
2495
+ }
2496
+ if (child.props.index) {
2497
+ return {
2498
+ index: true,
2499
+ handle,
2500
+ caseSensitive: child.props.caseSensitive || undefined,
2501
+ };
571
2502
  }
2503
+ return {
2504
+ path,
2505
+ handle,
2506
+ caseSensitive: child.props.caseSensitive || undefined,
2507
+ };
572
2508
  });
573
- if (matchedNode) {
574
- return matchedNode;
2509
+ }
2510
+ /**
2511
+ * Finds the `<Route />` node matching the current route info.
2512
+ * If no `<Route />` can be matched, a fallback node is returned.
2513
+ * Routes are prioritized by specificity (most specific first).
2514
+ *
2515
+ * @param node The root node to search for `<Route />` nodes.
2516
+ * @param routeInfo The route information to match against.
2517
+ * @param parentPath The parent path that was matched by the parent outlet (for nested routing)
2518
+ */
2519
+ function findRouteByRouteInfo(node, routeInfo, parentPath) {
2520
+ var _a, _b, _c;
2521
+ let matchedNode;
2522
+ let fallbackNode;
2523
+ // `<Route />` nodes are rendered inside of a <Routes /> node
2524
+ const routesChildren = (_a = getRoutesChildren(node)) !== null && _a !== void 0 ? _a : node;
2525
+ // Collect all route children
2526
+ const routeChildren = React.Children.toArray(routesChildren).filter((child) => React.isValidElement(child) && (child.type === Route || child.type === IonRoute));
2527
+ // Delegate route matching to RR6's matchRoutes(), which handles specificity ranking internally.
2528
+ const basename = parentPath ? stripTrailingSlash(parentPath.replace('/*', '')) : undefined;
2529
+ const routeObjects = routeElementsToRouteObjects(routeChildren, basename);
2530
+ const matches = matchRoutes(routeObjects, { pathname: routeInfo.pathname }, basename);
2531
+ if (matches && matches.length > 0) {
2532
+ const bestMatch = matches[matches.length - 1];
2533
+ matchedNode = (_c = (_b = bestMatch.route.handle) === null || _b === void 0 ? void 0 : _b._element) !== null && _c !== void 0 ? _c : undefined;
575
2534
  }
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;
2535
+ // Fallback: try pathless routes, but only if pathname is within scope.
2536
+ if (!matchedNode) {
2537
+ let pathnameInScope = true;
2538
+ if (parentPath) {
2539
+ pathnameInScope = isPathnameInScope(routeInfo.pathname, parentPath);
581
2540
  }
582
- });
583
- return matchedNode;
2541
+ else {
2542
+ const absolutePathRoutes = routeChildren.filter((r) => r.props.path && r.props.path.startsWith('/'));
2543
+ if (absolutePathRoutes.length > 0) {
2544
+ const absolutePaths = absolutePathRoutes.map((r) => r.props.path);
2545
+ const commonPrefix = computeCommonPrefix(absolutePaths);
2546
+ if (commonPrefix && commonPrefix !== '/') {
2547
+ pathnameInScope = routeInfo.pathname.startsWith(commonPrefix);
2548
+ }
2549
+ }
2550
+ }
2551
+ if (pathnameInScope) {
2552
+ for (const child of routeChildren) {
2553
+ if (!child.props.path) {
2554
+ fallbackNode = child;
2555
+ break;
2556
+ }
2557
+ }
2558
+ }
2559
+ }
2560
+ return matchedNode !== null && matchedNode !== void 0 ? matchedNode : fallbackNode;
584
2561
  }
585
- function matchComponent(node, pathname, forceExact) {
2562
+ function matchComponent(node, pathname, forceExact, parentPath) {
2563
+ var _a;
2564
+ const routePath = (_a = node === null || node === void 0 ? void 0 : node.props) === null || _a === void 0 ? void 0 : _a.path;
2565
+ let pathnameToMatch;
2566
+ if (parentPath && routePath && !routePath.startsWith('/')) {
2567
+ // When parent path is known, compute exact relative pathname
2568
+ const relative = pathname.startsWith(parentPath)
2569
+ ? pathname.slice(parentPath.length).replace(/^\//, '')
2570
+ : pathname;
2571
+ pathnameToMatch = relative;
2572
+ }
2573
+ else {
2574
+ pathnameToMatch = derivePathnameToMatch(pathname, routePath);
2575
+ }
586
2576
  return matchPath({
587
- pathname,
588
- componentProps: Object.assign(Object.assign({}, node.props), { exact: forceExact }),
2577
+ pathname: pathnameToMatch,
2578
+ componentProps: Object.assign(Object.assign({}, node.props), { end: forceExact }),
589
2579
  });
590
2580
  }
591
2581
 
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
- };
2582
+ /**
2583
+ * `IonRouter` is responsible for managing the application's navigation
2584
+ * state, tracking the history of visited routes, and coordinating
2585
+ * transitions between different views. It intercepts route changes from
2586
+ * React Router and translates them into actions that Ionic can understand
2587
+ * and animate.
2588
+ */
2589
+ const filterUndefinedParams = (params) => {
2590
+ const result = {};
2591
+ for (const key of Object.keys(params)) {
2592
+ const value = params[key];
2593
+ if (value !== undefined) {
2594
+ result[key] = value;
2595
+ }
626
2596
  }
627
- handleChangeTab(tab, path, routeOptions) {
628
- if (!path) {
2597
+ return result;
2598
+ };
2599
+ const areParamsEqual = (a, b) => {
2600
+ const paramsA = a || {};
2601
+ const paramsB = b || {};
2602
+ const keysA = Object.keys(paramsA);
2603
+ const keysB = Object.keys(paramsB);
2604
+ if (keysA.length !== keysB.length) {
2605
+ return false;
2606
+ }
2607
+ return keysA.every((key) => {
2608
+ const valueA = paramsA[key];
2609
+ const valueB = paramsB[key];
2610
+ if (Array.isArray(valueA) && Array.isArray(valueB)) {
2611
+ if (valueA.length !== valueB.length) {
2612
+ return false;
2613
+ }
2614
+ return valueA.every((entry, idx) => entry === valueB[idx]);
2615
+ }
2616
+ return valueA === valueB;
2617
+ });
2618
+ };
2619
+ const IonRouter = ({ children, registerHistoryListener }) => {
2620
+ const location = useLocation();
2621
+ const navigate = useNavigate();
2622
+ const didMountRef = useRef(false);
2623
+ const locationHistory = useRef(new LocationHistory());
2624
+ const currentTab = useRef(undefined);
2625
+ const viewStack = useRef(new ReactRouterViewStack());
2626
+ const incomingRouteParams = useRef(null);
2627
+ /**
2628
+ * Tracks location keys that the user navigated away from via browser back.
2629
+ * When a POP event's destination key matches the top of this stack, it's a
2630
+ * browser forward navigation. Uses React Router's unique location.key
2631
+ * instead of URLs to correctly handle duplicate URLs in history (e.g.,
2632
+ * navigating to /details, then /settings, then /details via routerLink,
2633
+ * then pressing back).
2634
+ * Cleared on PUSH (new navigation invalidates forward history).
2635
+ */
2636
+ const forwardStack = useRef([]);
2637
+ /**
2638
+ * Tracks the current location key so we can push it onto the forward stack
2639
+ * when navigating back. Updated after each history change.
2640
+ */
2641
+ const currentLocationKeyRef = useRef(location.key);
2642
+ const [routeInfo, setRouteInfo] = useState({
2643
+ id: generateId('routeInfo'),
2644
+ pathname: location.pathname,
2645
+ search: location.search,
2646
+ params: {},
2647
+ });
2648
+ useEffect(() => {
2649
+ if (didMountRef.current) {
629
2650
  return;
630
2651
  }
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 : ''));
2652
+ // Seed the history stack with the initial location and begin listening
2653
+ // for future navigations once React has committed the mount. This avoids
2654
+ // duplicate entries when React StrictMode runs an extra render pre-commit.
2655
+ locationHistory.current.add(routeInfo);
2656
+ // If IonTabBar already called handleSetCurrentTab during render (before this
2657
+ // effect), the tab was stored in currentTab.current but the history entry was
2658
+ // not yet seeded. Apply the pending tab to the seed entry now.
2659
+ if (currentTab.current) {
2660
+ const ri = Object.assign({}, locationHistory.current.current());
2661
+ if (ri.tab !== currentTab.current) {
2662
+ ri.tab = currentTab.current;
2663
+ locationHistory.current.update(ri);
644
2664
  }
645
2665
  }
646
- else {
647
- this.handleNavigate(pathname, 'push', 'none', undefined, routeOptions, tab);
2666
+ registerHistoryListener(handleHistoryChange);
2667
+ didMountRef.current = true;
2668
+ }, []);
2669
+ // Sync route params extracted by React Router's path matching back into routeInfo.
2670
+ // The view stack's match may contain params (e.g., :id) not present in the initial routeInfo.
2671
+ useEffect(() => {
2672
+ var _a;
2673
+ const activeView = viewStack.current.findViewItemByRouteInfo(routeInfo, undefined, true);
2674
+ const matchedParams = (_a = activeView === null || activeView === void 0 ? void 0 : activeView.routeData.match) === null || _a === void 0 ? void 0 : _a.params;
2675
+ if (matchedParams) {
2676
+ const paramsCopy = filterUndefinedParams(Object.assign({}, matchedParams));
2677
+ if (areParamsEqual(routeInfo.params, paramsCopy)) {
2678
+ return;
2679
+ }
2680
+ const updatedRouteInfo = Object.assign(Object.assign({}, routeInfo), { params: paramsCopy });
2681
+ locationHistory.current.update(updatedRouteInfo);
2682
+ setRouteInfo(updatedRouteInfo);
648
2683
  }
649
- }
650
- handleHistoryChange(location, action) {
651
- var _a, _b, _c;
2684
+ }, [routeInfo]);
2685
+ /**
2686
+ * Triggered whenever the history changes, either through user navigation
2687
+ * or programmatic changes. It transforms the raw browser history changes
2688
+ * into `RouteInfo` objects, which are needed Ionic's animations and
2689
+ * navigation patterns.
2690
+ *
2691
+ * @param location The current location object from the history.
2692
+ * @param action The action that triggered the history change.
2693
+ */
2694
+ const handleHistoryChange = (location, action) => {
2695
+ var _a, _b, _c, _d, _e;
652
2696
  let leavingLocationInfo;
653
- if (this.incomingRouteParams) {
654
- if (this.incomingRouteParams.routeAction === 'replace') {
655
- leavingLocationInfo = this.locationHistory.previous();
2697
+ /**
2698
+ * A programmatic navigation was triggered.
2699
+ * e.g., `<Navigate />`, `navigate()`, or `handleNavigate()`
2700
+ */
2701
+ if (incomingRouteParams.current) {
2702
+ /**
2703
+ * The current history entry is overwritten, so the previous entry
2704
+ * is the one we are leaving.
2705
+ */
2706
+ if (((_a = incomingRouteParams.current) === null || _a === void 0 ? void 0 : _a.routeAction) === 'replace') {
2707
+ leavingLocationInfo = locationHistory.current.previous();
656
2708
  }
657
2709
  else {
658
- leavingLocationInfo = this.locationHistory.current();
2710
+ // If the action is 'push' or 'pop', we want to use the current route.
2711
+ leavingLocationInfo = locationHistory.current.current();
659
2712
  }
660
2713
  }
661
2714
  else {
662
- leavingLocationInfo = this.locationHistory.current();
2715
+ /**
2716
+ * An external navigation was triggered
2717
+ * e.g., browser back/forward button or direct link
2718
+ *
2719
+ * The leaving location is the current route.
2720
+ */
2721
+ leavingLocationInfo = locationHistory.current.current();
663
2722
  }
664
2723
  const leavingUrl = leavingLocationInfo.pathname + leavingLocationInfo.search;
665
- if (leavingUrl !== location.pathname) {
666
- if (!this.incomingRouteParams) {
2724
+ if (leavingUrl !== location.pathname + location.search) {
2725
+ if (!incomingRouteParams.current) {
2726
+ // Use history-based tab detection instead of URL-pattern heuristics,
2727
+ // so tab routes work with any URL structure (not just paths containing "/tabs").
2728
+ // Fall back to currentTab.current only when the destination is within the
2729
+ // current tab's path hierarchy (prevents non-tab routes from inheriting a tab).
2730
+ let tabToUse = locationHistory.current.findTabForPathname(location.pathname);
2731
+ if (!tabToUse && currentTab.current) {
2732
+ const tabFirstRoute = locationHistory.current.getFirstRouteInfoForTab(currentTab.current);
2733
+ const tabRootPath = tabFirstRoute === null || tabFirstRoute === void 0 ? void 0 : tabFirstRoute.pathname;
2734
+ if (tabRootPath && (location.pathname === tabRootPath || location.pathname.startsWith(tabRootPath + '/'))) {
2735
+ tabToUse = currentTab.current;
2736
+ }
2737
+ }
2738
+ /**
2739
+ * A `REPLACE` action can be triggered by React Router's
2740
+ * `<Navigate />` component.
2741
+ */
667
2742
  if (action === 'REPLACE') {
668
- this.incomingRouteParams = {
2743
+ incomingRouteParams.current = {
669
2744
  routeAction: 'replace',
670
2745
  routeDirection: 'none',
671
- tab: this.currentTab,
2746
+ tab: tabToUse,
672
2747
  };
673
2748
  }
2749
+ /**
2750
+ * A `POP` action can be triggered by the browser's back/forward
2751
+ * button. Both fire as POP events, so we use a forward stack to
2752
+ * distinguish them: when going back, we push the leaving pathname
2753
+ * onto the stack. When the next POP's destination matches the top
2754
+ * of the stack, it's a forward navigation.
2755
+ */
674
2756
  if (action === 'POP') {
675
- const currentRoute = this.locationHistory.current();
676
- if (currentRoute && currentRoute.pushedByRoute) {
677
- const prevInfo = this.locationHistory.findLastLocation(currentRoute);
678
- this.incomingRouteParams = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back' });
2757
+ const currentRoute = locationHistory.current.current();
2758
+ const isForwardNavigation = forwardStack.current.length > 0 &&
2759
+ forwardStack.current[forwardStack.current.length - 1] === location.key;
2760
+ if (isForwardNavigation) {
2761
+ forwardStack.current.pop();
2762
+ incomingRouteParams.current = {
2763
+ routeAction: 'push',
2764
+ routeDirection: 'forward',
2765
+ tab: tabToUse,
2766
+ };
2767
+ }
2768
+ else if (currentRoute && currentRoute.pushedByRoute) {
2769
+ // Back navigation. Record current location key for potential forward
2770
+ forwardStack.current.push(currentLocationKeyRef.current);
2771
+ const prevInfo = locationHistory.current.findLastLocation(currentRoute);
2772
+ incomingRouteParams.current = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back' });
679
2773
  }
680
2774
  else {
681
- this.incomingRouteParams = {
2775
+ // It's a non-linear history path like a direct link.
2776
+ // Still push the current location key so browser forward is detectable.
2777
+ forwardStack.current.push(currentLocationKeyRef.current);
2778
+ incomingRouteParams.current = {
682
2779
  routeAction: 'pop',
683
2780
  routeDirection: 'none',
684
- tab: this.currentTab,
2781
+ tab: tabToUse,
685
2782
  };
686
2783
  }
687
2784
  }
688
- if (!this.incomingRouteParams) {
689
- this.incomingRouteParams = {
2785
+ if (!incomingRouteParams.current) {
2786
+ const state = location.state;
2787
+ incomingRouteParams.current = {
690
2788
  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,
2789
+ routeDirection: (state === null || state === void 0 ? void 0 : state.direction) || 'forward',
2790
+ routeOptions: state === null || state === void 0 ? void 0 : state.routerOptions,
2791
+ tab: tabToUse,
694
2792
  };
695
2793
  }
696
2794
  }
2795
+ // New navigation (PUSH) invalidates browser forward history,
2796
+ // so clear our forward stack to stay in sync.
2797
+ if (action === 'PUSH') {
2798
+ forwardStack.current = [];
2799
+ }
697
2800
  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);
2801
+ // If we're navigating away from tabs to a non-tab route, clear the current tab
2802
+ if (!locationHistory.current.findTabForPathname(location.pathname) && currentTab.current) {
2803
+ currentTab.current = undefined;
2804
+ }
2805
+ /**
2806
+ * An existing id indicates that it's re-activating an existing route.
2807
+ * e.g., tab switching or navigating back to a previous route
2808
+ */
2809
+ if ((_b = incomingRouteParams.current) === null || _b === void 0 ? void 0 : _b.id) {
2810
+ routeInfo = Object.assign(Object.assign({}, incomingRouteParams.current), { lastPathname: leavingLocationInfo.pathname });
2811
+ locationHistory.current.add(routeInfo);
2812
+ /**
2813
+ * A new route is being created since it's not re-activating
2814
+ * an existing route.
2815
+ */
701
2816
  }
702
2817
  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 });
2818
+ const isPushed = ((_c = incomingRouteParams.current) === null || _c === void 0 ? void 0 : _c.routeAction) === 'push' &&
2819
+ incomingRouteParams.current.routeDirection === 'forward';
2820
+ 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)
2821
+ ? filterUndefinedParams(incomingRouteParams.current.params)
2822
+ : {}, prevRouteLastPathname: leavingLocationInfo.lastPathname });
705
2823
  if (isPushed) {
706
- routeInfo.tab = leavingLocationInfo.tab;
2824
+ // Only inherit tab from leaving route if we don't already have one.
2825
+ // This preserves tab context for same-tab navigation while allowing cross-tab navigation.
2826
+ routeInfo.tab = routeInfo.tab || leavingLocationInfo.tab;
707
2827
  routeInfo.pushedByRoute = leavingLocationInfo.pathname;
2828
+ // Triggered by a browser back button or handleNavigateBack.
708
2829
  }
709
2830
  else if (routeInfo.routeAction === 'pop') {
710
- const r = this.locationHistory.findLastLocation(routeInfo);
2831
+ // Find the route that pushed this one.
2832
+ const r = locationHistory.current.findLastLocation(routeInfo);
711
2833
  routeInfo.pushedByRoute = r === null || r === void 0 ? void 0 : r.pushedByRoute;
2834
+ // Navigating to a new tab.
712
2835
  }
713
2836
  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;
2837
+ /**
2838
+ * If we are switching tabs grab the last route info for the
2839
+ * tab and use its `pushedByRoute`.
2840
+ */
2841
+ const lastRoute = locationHistory.current.getCurrentRouteInfoForTab(routeInfo.tab);
2842
+ /**
2843
+ * Tab bar switches (direction 'none') should not create cross-tab back
2844
+ * navigation. Only inherit pushedByRoute from the tab's own history.
2845
+ */
2846
+ if (routeInfo.routeDirection === 'none') {
2847
+ routeInfo.pushedByRoute = lastRoute === null || lastRoute === void 0 ? void 0 : lastRoute.pushedByRoute;
2848
+ }
2849
+ else {
2850
+ routeInfo.pushedByRoute = (_e = lastRoute === null || lastRoute === void 0 ? void 0 : lastRoute.pushedByRoute) !== null && _e !== void 0 ? _e : leavingLocationInfo.pathname;
2851
+ }
2852
+ // Triggered by `navigate()` with replace or a `<Navigate />` component, etc.
717
2853
  }
718
2854
  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
2855
  /**
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.
2856
+ * Make sure to set the `lastPathname`, etc.. to the current route
2857
+ * so the page transitions out.
2858
+ */
2859
+ const currentRouteInfo = locationHistory.current.current();
2860
+ /**
2861
+ * Special handling for `replace` to ensure correct `pushedByRoute`
2862
+ * and `lastPathname`.
2863
+ *
2864
+ * If going from `/home` to `/child`, then replacing from
2865
+ * `/child` to `/home`, we don't want the route info to
2866
+ * say that `/home` was pushed by `/home` which is not correct.
725
2867
  */
726
2868
  const currentPushedBy = currentRouteInfo === null || currentRouteInfo === void 0 ? void 0 : currentRouteInfo.pushedByRoute;
727
2869
  const pushedByRoute = currentPushedBy !== undefined && currentPushedBy !== routeInfo.pathname
@@ -739,46 +2881,116 @@ class IonRouterInner extends React.PureComponent {
739
2881
  routeInfo.routeDirection = routeInfo.routeDirection || (currentRouteInfo === null || currentRouteInfo === void 0 ? void 0 : currentRouteInfo.routeDirection);
740
2882
  routeInfo.routeAnimation = routeInfo.routeAnimation || (currentRouteInfo === null || currentRouteInfo === void 0 ? void 0 : currentRouteInfo.routeAnimation);
741
2883
  }
742
- this.locationHistory.add(routeInfo);
2884
+ locationHistory.current.add(routeInfo);
743
2885
  }
744
- this.setState({
745
- routeInfo,
746
- });
2886
+ setRouteInfo(routeInfo);
747
2887
  }
748
- this.incomingRouteParams = undefined;
749
- }
2888
+ // Update the current location key after processing the history change.
2889
+ // This ensures the forward stack records the correct key when navigating back.
2890
+ currentLocationKeyRef.current = location.key;
2891
+ incomingRouteParams.current = null;
2892
+ };
750
2893
  /**
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.
2894
+ * Resets the specified tab to its initial, root route.
2895
+ *
2896
+ * @param tab The tab to reset.
2897
+ * @param originalHref The original href for the tab.
2898
+ * @param originalRouteOptions The original route options for the tab.
755
2899
  */
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);
2900
+ const handleResetTab = (tab, originalHref, originalRouteOptions) => {
2901
+ const routeInfo = locationHistory.current.getFirstRouteInfoForTab(tab);
2902
+ if (routeInfo) {
2903
+ const newRouteInfo = Object.assign({}, routeInfo);
2904
+ newRouteInfo.pathname = originalHref;
2905
+ newRouteInfo.routeOptions = originalRouteOptions;
2906
+ incomingRouteParams.current = Object.assign(Object.assign({}, newRouteInfo), { routeAction: 'pop', routeDirection: 'back' });
2907
+ navigate(newRouteInfo.pathname + (newRouteInfo.search || ''));
2908
+ }
2909
+ };
2910
+ /**
2911
+ * Handles tab changes.
2912
+ *
2913
+ * @param tab The tab to switch to.
2914
+ * @param path The new path for the tab.
2915
+ * @param routeOptions Additional route options.
2916
+ */
2917
+ const handleChangeTab = (tab, path, routeOptions) => {
2918
+ if (!path) {
2919
+ return;
2920
+ }
2921
+ const routeInfo = locationHistory.current.getCurrentRouteInfoForTab(tab);
2922
+ const [pathname, search] = path.split('?');
2923
+ // User has navigated to the current tab before.
2924
+ if (routeInfo) {
2925
+ const routeParams = Object.assign(Object.assign({}, routeInfo), { routeAction: 'push', routeDirection: 'none' });
2926
+ /**
2927
+ * User is navigating to the same tab.
2928
+ * e.g., `/tabs/home` → `/tabs/home`
2929
+ */
2930
+ if (routeInfo.pathname === pathname) {
2931
+ incomingRouteParams.current = Object.assign(Object.assign({}, routeParams), { routeOptions });
2932
+ navigate(routeInfo.pathname + (routeInfo.search || ''));
2933
+ /**
2934
+ * User is navigating to a different tab.
2935
+ * e.g., `/tabs/home` → `/tabs/settings`
2936
+ */
2937
+ }
2938
+ else {
2939
+ incomingRouteParams.current = Object.assign(Object.assign({}, routeParams), { pathname, search: search ? '?' + search : undefined, routeOptions });
2940
+ navigate(pathname + (search ? '?' + search : ''));
2941
+ }
2942
+ // User has not navigated to this tab before.
771
2943
  }
772
2944
  else {
773
- this.props.history.replace(path);
2945
+ handleNavigate(pathname, 'push', 'none', undefined, routeOptions, tab);
774
2946
  }
775
- }
776
- handleNavigateBack(defaultHref = '/', routeAnimation) {
2947
+ };
2948
+ /**
2949
+ * Set the current active tab in `locationHistory`.
2950
+ * This is crucial for maintaining tab history since each tab has
2951
+ * its own navigation stack.
2952
+ *
2953
+ * @param tab The tab to set as active.
2954
+ */
2955
+ const handleSetCurrentTab = (tab) => {
2956
+ currentTab.current = tab;
2957
+ const current = locationHistory.current.current();
2958
+ if (!current) {
2959
+ // locationHistory not yet seeded (e.g., called during initial render
2960
+ // before mount effect). The mount effect will seed the correct entry.
2961
+ return;
2962
+ }
2963
+ const ri = Object.assign({}, current);
2964
+ if (ri.tab !== tab) {
2965
+ ri.tab = tab;
2966
+ locationHistory.current.update(ri);
2967
+ }
2968
+ };
2969
+ /**
2970
+ * Handles the native back button press.
2971
+ * It's usually called when a user presses the platform-native back action.
2972
+ */
2973
+ const handleNativeBack = () => {
2974
+ navigate(-1);
2975
+ };
2976
+ /**
2977
+ * Used to manage the back navigation within the Ionic React's routing
2978
+ * system. It's deeply integrated with Ionic's view lifecycle, animations,
2979
+ * and its custom history tracking (`locationHistory`) to provide a
2980
+ * native-like transition and maintain correct application state.
2981
+ *
2982
+ * @param defaultHref The fallback URL to navigate to if there's no
2983
+ * previous entry in the `locationHistory` stack.
2984
+ * @param routeAnimation A custom animation builder to override the
2985
+ * default "back" animation.
2986
+ */
2987
+ const handleNavigateBack = (defaultHref = '/', routeAnimation) => {
777
2988
  const config = getConfig();
778
2989
  defaultHref = defaultHref ? defaultHref : config && config.get('backButtonDefaultHref');
779
- const routeInfo = this.locationHistory.current();
2990
+ const routeInfo = locationHistory.current.current();
2991
+ // It's a linear navigation.
780
2992
  if (routeInfo && routeInfo.pushedByRoute) {
781
- const prevInfo = this.locationHistory.findLastLocation(routeInfo);
2993
+ const prevInfo = locationHistory.current.findLastLocation(routeInfo);
782
2994
  if (prevInfo) {
783
2995
  /**
784
2996
  * This needs to be passed to handleNavigate
@@ -786,160 +2998,243 @@ class IonRouterInner extends React.PureComponent {
786
2998
  * will be overridden.
787
2999
  */
788
3000
  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();
3001
+ incomingRouteParams.current = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back', routeAnimation: incomingAnimation });
3002
+ /**
3003
+ * Check if it's a simple linear back navigation (not tabbed).
3004
+ * e.g., `/home` `/settings` back to `/home`
3005
+ */
3006
+ const condition1 = routeInfo.lastPathname === routeInfo.pushedByRoute;
3007
+ const condition2 = prevInfo.pathname === routeInfo.pushedByRoute && !routeInfo.tab && !prevInfo.tab;
3008
+ if (condition1 || condition2) {
3009
+ // Record the current location key so browser forward is detectable
3010
+ forwardStack.current.push(currentLocationKeyRef.current);
3011
+ navigate(-1);
807
3012
  }
808
3013
  else {
809
- this.handleNavigate(prevInfo.pathname + (prevInfo.search || ''), 'pop', 'back', incomingAnimation);
3014
+ /**
3015
+ * It's a non-linear back navigation.
3016
+ * e.g., direct link or tab switch or nested navigation with redirects
3017
+ * Clear forward stack since the REPLACE-based navigate resets history
3018
+ * position, making any prior forward entries unreachable.
3019
+ */
3020
+ forwardStack.current = [];
3021
+ handleNavigate(prevInfo.pathname + (prevInfo.search || ''), 'pop', 'back', incomingAnimation);
810
3022
  }
3023
+ /**
3024
+ * `pushedByRoute` exists, but no corresponding previous entry in
3025
+ * the history stack.
3026
+ */
811
3027
  }
812
3028
  else {
813
- this.handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
3029
+ handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
814
3030
  }
3031
+ /**
3032
+ * No `pushedByRoute` (e.g., initial page load or tab root).
3033
+ * Tabs with no back history should not navigate.
3034
+ */
815
3035
  }
816
3036
  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 || ''));
3037
+ if (routeInfo && routeInfo.tab) {
3038
+ return;
3039
+ }
3040
+ handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
828
3041
  }
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);
3042
+ };
3043
+ /**
3044
+ * Used to programmatically navigate through the app.
3045
+ *
3046
+ * @param path The path to navigate to.
3047
+ * @param routeAction The action to take (push, replace, etc.).
3048
+ * @param routeDirection The direction of the navigation (forward,
3049
+ * back, etc.).
3050
+ * @param routeAnimation The animation to use for the transition.
3051
+ * @param routeOptions Additional options for the route.
3052
+ * @param tab The tab to navigate to, if applicable.
3053
+ */
3054
+ const handleNavigate = (path, routeAction, routeDirection, routeAnimation, routeOptions, tab) => {
3055
+ var _a;
3056
+ const normalizedRouteDirection = routeAction === 'push' && routeDirection === undefined ? 'forward' : routeDirection;
3057
+ // When navigating from tabs context, we need to determine if the destination
3058
+ // is also within tabs. If not, we should clear the tab context.
3059
+ let navigationTab = tab;
3060
+ // If no explicit tab is provided and we're in a tab context,
3061
+ // check if the destination path is outside of the current tab context.
3062
+ // Uses history-based tab detection instead of URL pattern matching,
3063
+ // so it works with any tab URL structure.
3064
+ if (!tab && currentTab.current && path) {
3065
+ // Check if destination was previously visited in a tab context
3066
+ const destinationTab = locationHistory.current.findTabForPathname(path);
3067
+ if (destinationTab) {
3068
+ // Previously visited as a tab route - use the known tab
3069
+ navigationTab = destinationTab;
3070
+ }
3071
+ else {
3072
+ // New destination - check if it's a child of the current tab's root path
3073
+ const tabFirstRoute = locationHistory.current.getFirstRouteInfoForTab(currentTab.current);
3074
+ if (tabFirstRoute) {
3075
+ const tabRootPath = tabFirstRoute.pathname;
3076
+ if (path === tabRootPath || path.startsWith(tabRootPath + '/')) {
3077
+ // Still within the current tab's path hierarchy
3078
+ navigationTab = currentTab.current;
3079
+ }
3080
+ else {
3081
+ // Destination is outside the current tab context
3082
+ currentTab.current = undefined;
3083
+ navigationTab = undefined;
3084
+ }
3085
+ }
3086
+ }
836
3087
  }
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);
3088
+ const baseParams = (_a = incomingRouteParams.current) !== null && _a !== void 0 ? _a : {};
3089
+ incomingRouteParams.current = Object.assign(Object.assign({}, baseParams), { routeAction, routeDirection: normalizedRouteDirection, routeOptions,
3090
+ routeAnimation, tab: navigationTab });
3091
+ navigate(path, { replace: routeAction !== 'push' });
3092
+ };
3093
+ const routeMangerContextValue = {
3094
+ canGoBack: () => locationHistory.current.canGoBack(),
3095
+ clearOutlet: viewStack.current.clear,
3096
+ findViewItemByPathname: viewStack.current.findViewItemByPathname,
3097
+ getChildrenToRender: viewStack.current.getChildrenToRender,
3098
+ getViewItemsForOutlet: viewStack.current.getViewItemsForOutlet.bind(viewStack.current),
3099
+ goBack: () => handleNavigateBack(),
3100
+ createViewItem: viewStack.current.createViewItem,
3101
+ findViewItemByRouteInfo: viewStack.current.findViewItemByRouteInfo,
3102
+ findLeavingViewItemByRouteInfo: viewStack.current.findLeavingViewItemByRouteInfo,
3103
+ addViewItem: viewStack.current.add,
3104
+ unMountViewItem: viewStack.current.remove,
3105
+ };
3106
+ return (React.createElement(RouteManagerContext.Provider, { value: routeMangerContextValue },
3107
+ React.createElement(NavManager, { ionRoute: IonRouteInner, stackManager: StackManager, routeInfo: routeInfo, onNativeBack: handleNativeBack, onNavigateBack: handleNavigateBack, onNavigate: handleNavigate, onSetCurrentTab: handleSetCurrentTab, onChangeTab: handleChangeTab, onResetTab: handleResetTab, locationHistory: locationHistory.current }, children)));
3108
+ };
844
3109
  IonRouter.displayName = 'IonRouter';
845
3110
 
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
- }
3111
+ /**
3112
+ * `IonReactRouter` facilitates the integration of Ionic's specific
3113
+ * navigation and UI management with the standard React Router mechanisms,
3114
+ * allowing an inner Ionic-specific router (`IonRouter`) to react to
3115
+ * navigation events.
3116
+ */
3117
+ /**
3118
+ * This component acts as a bridge to ensure React Router hooks like
3119
+ * `useLocation` and `useNavigationType` are called within the valid
3120
+ * context of a `<BrowserRouter>`.
3121
+ *
3122
+ * It was split from `IonReactRouter` because these hooks must be
3123
+ * descendants of a `<Router>` component, which `BrowserRouter` provides.
3124
+ */
3125
+ const RouterContent$2 = ({ children }) => {
3126
+ const location = useLocation();
3127
+ const navigationType = useNavigationType();
3128
+ const historyListenHandler = useRef();
3129
+ const registerHistoryListener = useCallback((cb) => {
3130
+ historyListenHandler.current = cb;
3131
+ }, []);
854
3132
  /**
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.
3133
+ * Processes navigation changes within the application.
3134
+ *
3135
+ * Its purpose is to relay the current `location` and the associated
3136
+ * `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
3137
+ * primarily for `IonRouter` to manage Ionic-specific UI updates and
3138
+ * navigation stack behavior.
3139
+ *
3140
+ * @param loc The current browser history location object.
3141
+ * @param act The type of navigation action ('PUSH', 'POP', or
3142
+ * 'REPLACE').
861
3143
  */
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);
3144
+ const handleHistoryChange = useCallback((loc, act) => {
3145
+ if (historyListenHandler.current) {
3146
+ historyListenHandler.current(loc, act);
867
3147
  }
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
- }
3148
+ }, []);
3149
+ useEffect(() => {
3150
+ handleHistoryChange(location, navigationType);
3151
+ }, [location, navigationType, handleHistoryChange]);
3152
+ return React.createElement(IonRouter, { registerHistoryListener: registerHistoryListener }, children);
3153
+ };
3154
+ const IonReactRouter = (_a) => {
3155
+ var { children } = _a, browserRouterProps = __rest(_a, ["children"]);
3156
+ return (React.createElement(BrowserRouter, Object.assign({}, browserRouterProps),
3157
+ React.createElement(RouterContent$2, null, children)));
3158
+ };
878
3159
 
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
- }
3160
+ /**
3161
+ * `IonReactMemoryRouter` provides a way to use `react-router` in
3162
+ * environments where a traditional browser history (like `BrowserRouter`)
3163
+ * isn't available or desirable.
3164
+ */
3165
+ const RouterContent$1 = ({ children }) => {
3166
+ const location = useLocation$1();
3167
+ const navigationType = useNavigationType$1();
3168
+ const historyListenHandler = useRef();
3169
+ const registerHistoryListener = useCallback((cb) => {
3170
+ historyListenHandler.current = cb;
3171
+ }, []);
886
3172
  /**
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.
3173
+ * Processes navigation changes within the application.
3174
+ *
3175
+ * Its purpose is to relay the current `location` and the associated
3176
+ * `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
3177
+ * primarily for `IonRouter` to manage Ionic-specific UI updates and
3178
+ * navigation stack behavior.
3179
+ *
3180
+ * @param location The current browser history location object.
3181
+ * @param action The type of navigation action ('PUSH', 'POP', or
3182
+ * 'REPLACE').
893
3183
  */
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);
3184
+ const handleHistoryChange = useCallback((loc, act) => {
3185
+ if (historyListenHandler.current) {
3186
+ historyListenHandler.current(loc, act);
899
3187
  }
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
- }
3188
+ }, []);
3189
+ useEffect(() => {
3190
+ handleHistoryChange(location, navigationType);
3191
+ }, [location, navigationType, handleHistoryChange]);
3192
+ return React.createElement(IonRouter, { registerHistoryListener: registerHistoryListener }, children);
3193
+ };
3194
+ const IonReactMemoryRouter = (_a) => {
3195
+ var { children } = _a, routerProps = __rest(_a, ["children"]);
3196
+ return (React.createElement(MemoryRouter, Object.assign({}, routerProps),
3197
+ React.createElement(RouterContent$1, null, children)));
3198
+ };
910
3199
 
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
- }
3200
+ /**
3201
+ * `IonReactHashRouter` provides a way to use hash-based routing in Ionic
3202
+ * React applications.
3203
+ */
3204
+ const RouterContent = ({ children }) => {
3205
+ const location = useLocation();
3206
+ const navigationType = useNavigationType();
3207
+ const historyListenHandler = useRef();
3208
+ const registerHistoryListener = useCallback((cb) => {
3209
+ historyListenHandler.current = cb;
3210
+ }, []);
919
3211
  /**
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.
3212
+ * Processes navigation changes within the application.
3213
+ *
3214
+ * Its purpose is to relay the current `location` and the associated
3215
+ * `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
3216
+ * primarily for `IonRouter` to manage Ionic-specific UI updates and
3217
+ * navigation stack behavior.
3218
+ *
3219
+ * @param location The current browser history location object.
3220
+ * @param action The type of navigation action ('PUSH', 'POP', or
3221
+ * 'REPLACE').
926
3222
  */
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);
3223
+ const handleHistoryChange = useCallback((loc, act) => {
3224
+ if (historyListenHandler.current) {
3225
+ historyListenHandler.current(loc, act);
932
3226
  }
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
- }
3227
+ }, []);
3228
+ useEffect(() => {
3229
+ handleHistoryChange(location, navigationType);
3230
+ }, [location, navigationType, handleHistoryChange]);
3231
+ return React.createElement(IonRouter, { registerHistoryListener: registerHistoryListener }, children);
3232
+ };
3233
+ const IonReactHashRouter = (_a) => {
3234
+ var { children } = _a, routerProps = __rest(_a, ["children"]);
3235
+ return (React.createElement(HashRouter, Object.assign({}, routerProps),
3236
+ React.createElement(RouterContent, null, children)));
3237
+ };
943
3238
 
944
3239
  export { IonReactHashRouter, IonReactMemoryRouter, IonReactRouter };
945
3240
  //# sourceMappingURL=index.js.map