@ionic/react-router 8.8.1-dev.11773242897.1966d6b2 → 8.8.1-dev.11773665268.1511a6c7

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