@ionic/react-router 8.8.16-dev.11784914346.10d0804c → 8.8.16-dev.11785274070.1b3387c9

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,245 +1,2213 @@
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, LocationHistory, NavManager, getConfig } 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;
110
+ }
111
+ if (seg.startsWith(':')) {
112
+ return true;
113
+ }
114
+ return target === seg;
115
+ }));
116
+ if (startIndex >= 0) {
117
+ return fullSegments.slice(startIndex).join('/');
118
+ }
119
+ }
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
+ };
125
+
126
+ /**
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.
132
+ */
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)) {
193
+ return false;
194
+ }
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
+ });
510
+ };
511
+
512
+ /**
513
+ * `ReactRouterViewStack` is a custom navigation manager used in Ionic React
514
+ * apps to map React Router route elements (such as `<IonRoute>`) to "view
515
+ * items" that Ionic can manage in a view stack. This is critical to maintain
516
+ * Ionic’s animation, lifecycle, and history behavior across views.
517
+ */
518
+ /**
519
+ * Delay in milliseconds before removing a Navigate view item after a redirect.
520
+ * This ensures the redirect navigation completes before the view is removed.
521
+ */
522
+ const NAVIGATE_REDIRECT_DELAY_MS = 100;
523
+ /**
524
+ * Delay in milliseconds before cleaning up a view without an IonPage element.
525
+ * This double-checks that the view is truly not needed before removal.
526
+ */
527
+ const VIEW_CLEANUP_DELAY_MS = 200;
528
+ /**
529
+ * Computes the absolute pathnameBase for a route element based on its type.
530
+ * Handles relative paths, index routes, and splat routes differently.
531
+ */
532
+ const computeAbsolutePathnameBase = (routeElement, routeMatch, parentPathnameBase, routeInfoPathname) => {
533
+ const routePath = routeElement.props.path;
534
+ const isRelativePath = routePath && !routePath.startsWith('/');
535
+ const isIndexRoute = !!routeElement.props.index;
536
+ const isSplatOnlyRoute = routePath === '*' || routePath === '/*';
537
+ if (isSplatOnlyRoute) {
538
+ // Splat routes should NOT contribute their matched portion to pathnameBase
539
+ // This aligns with React Router v7's v7_relativeSplatPath behavior
540
+ return parentPathnameBase;
541
+ }
542
+ if (isRelativePath && (routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.pathnameBase)) {
543
+ const relativeBase = routeMatch.pathnameBase.startsWith('/')
544
+ ? routeMatch.pathnameBase.slice(1)
545
+ : routeMatch.pathnameBase;
546
+ return parentPathnameBase === '/' ? `/${relativeBase}` : `${parentPathnameBase}/${relativeBase}`;
547
+ }
548
+ if (isIndexRoute) {
549
+ return parentPathnameBase;
550
+ }
551
+ return (routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.pathnameBase) || routeInfoPathname;
552
+ };
553
+ /**
554
+ * Gets fallback params from view items in other outlets when parent context is empty.
555
+ * This handles cases where React context propagation doesn't work as expected.
556
+ */
557
+ const getFallbackParamsFromViewItems = (allViewItems, currentOutletId, currentPathname) => {
558
+ var _a;
559
+ const matchingViews = [];
560
+ for (const otherViewItem of allViewItems) {
561
+ if (otherViewItem.outletId === currentOutletId)
562
+ continue;
563
+ const otherMatch = (_a = otherViewItem.routeData) === null || _a === void 0 ? void 0 : _a.match;
564
+ if ((otherMatch === null || otherMatch === void 0 ? void 0 : otherMatch.params) && Object.keys(otherMatch.params).length > 0) {
565
+ const matchedPathname = otherMatch.pathnameBase || otherMatch.pathname;
566
+ if (matchedPathname && currentPathname.startsWith(matchedPathname)) {
567
+ matchingViews.push({
568
+ params: otherMatch.params,
569
+ pathLength: matchedPathname.length,
570
+ });
571
+ }
572
+ }
573
+ }
574
+ // Sort ascending by path length so more-specific (longer) paths are applied
575
+ // last and their params take priority over less-specific ones.
576
+ matchingViews.sort((a, b) => a.pathLength - b.pathLength);
577
+ const params = {};
578
+ for (const view of matchingViews) {
579
+ Object.assign(params, view.params);
580
+ }
581
+ return params;
582
+ };
583
+ /**
584
+ * Builds the matches array for RouteContext.
585
+ */
586
+ const buildContextMatches = (parentMatches, combinedParams, routeMatch, routeInfoPathname, absolutePathnameBase, viewItem, routeElement, componentElement) => {
587
+ return [
588
+ ...parentMatches,
589
+ {
590
+ params: combinedParams,
591
+ pathname: (routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.pathname) || routeInfoPathname,
592
+ pathnameBase: absolutePathnameBase,
593
+ route: {
594
+ id: viewItem.id,
595
+ path: routeElement.props.path,
596
+ element: componentElement,
597
+ index: !!routeElement.props.index,
598
+ caseSensitive: routeElement.props.caseSensitive,
599
+ hasErrorBoundary: false,
600
+ },
601
+ },
602
+ ];
603
+ };
604
+ const createDefaultMatch = (fullPathname, routeProps) => {
605
+ var _a, _b;
606
+ const isIndexRoute = !!routeProps.index;
607
+ const patternPath = (_a = routeProps.path) !== null && _a !== void 0 ? _a : '';
608
+ const pathnameBase = fullPathname === '' ? '/' : fullPathname;
609
+ const computedEnd = routeProps.end !== undefined ? routeProps.end : patternPath !== '' ? !patternPath.endsWith('*') : true;
610
+ return {
611
+ params: {},
612
+ pathname: isIndexRoute ? '' : fullPathname,
613
+ pathnameBase,
614
+ pattern: {
615
+ path: patternPath,
616
+ caseSensitive: (_b = routeProps.caseSensitive) !== null && _b !== void 0 ? _b : false,
617
+ end: isIndexRoute ? true : computedEnd,
618
+ },
619
+ };
620
+ };
621
+ const computeRelativeToParent = (pathname, parentPath) => {
622
+ if (!parentPath)
623
+ return null;
624
+ const normalizedParent = normalizePathnameForComparison(parentPath);
625
+ const normalizedPathname = normalizePathnameForComparison(pathname);
626
+ if (normalizedPathname === normalizedParent) {
627
+ return '';
628
+ }
629
+ const withSlash = normalizedParent === '/' ? '/' : normalizedParent + '/';
630
+ if (normalizedPathname.startsWith(withSlash)) {
631
+ return normalizedPathname.slice(withSlash.length);
632
+ }
633
+ return null;
634
+ };
635
+ const resolveIndexRouteMatch = (viewItem, pathname, parentPath) => {
636
+ var _a, _b, _c;
637
+ if (!((_b = (_a = viewItem.routeData) === null || _a === void 0 ? void 0 : _a.childProps) === null || _b === void 0 ? void 0 : _b.index)) {
638
+ return null;
639
+ }
640
+ // Prefer computing against the parent path when available to align with RRv6 semantics
641
+ const relative = computeRelativeToParent(pathname, parentPath);
642
+ if (relative !== null) {
643
+ // Index routes match only when there is no remaining path
644
+ if (relative === '' || relative === '/') {
645
+ return createDefaultMatch(parentPath || pathname, viewItem.routeData.childProps);
646
+ }
647
+ return null;
648
+ }
649
+ // Fallback: use previously computed match base for equality check
650
+ const previousMatch = (_c = viewItem.routeData) === null || _c === void 0 ? void 0 : _c.match;
651
+ if (!previousMatch) {
652
+ return null;
653
+ }
654
+ const normalizedPathname = normalizePathnameForComparison(pathname);
655
+ const normalizedBase = normalizePathnameForComparison(previousMatch.pathnameBase || previousMatch.pathname || '');
656
+ return normalizedPathname === normalizedBase ? previousMatch : null;
657
+ };
658
+ class ReactRouterViewStack extends ViewStacks {
659
+ constructor() {
660
+ super();
661
+ /**
662
+ * Stores the computed parent path for each outlet.
663
+ * Used by findViewItemByPath to correctly evaluate index route matches
664
+ * without requiring the outlet's React element or route children.
665
+ */
666
+ this.outletParentPaths = new Map();
667
+ /**
668
+ * Stores the computed mount path for each outlet.
669
+ * Fed back into computeParentPath on subsequent calls to stabilize
670
+ * the parent path computation across navigations (mirrors StackManager.outletMountPath).
671
+ */
672
+ this.outletMountPaths = new Map();
673
+ /**
674
+ * Creates a new view item for the given outlet and react route element.
675
+ * Associates route props with the matched route path for further lookups.
676
+ */
677
+ this.createViewItem = (outletId, reactElement, routeInfo, page) => {
678
+ var _a, _b;
679
+ const routePath = reactElement.props.path || '';
680
+ // Check if we already have a view item for this exact route that we can reuse
681
+ // Include wildcard routes like tabs/* since they should be reused
682
+ // Also check unmounted items that might have been preserved for browser navigation
683
+ const existingViewItem = this.getViewItemsForOutlet(outletId).find((v) => {
684
+ var _a, _b, _c, _d, _e, _f, _g, _h;
685
+ const existingRouteProps = (_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) !== null && _b !== void 0 ? _b : {};
686
+ const existingPath = existingRouteProps.path || '';
687
+ const existingElement = existingRouteProps.element;
688
+ const newElement = reactElement.props.element;
689
+ const existingIsIndexRoute = !!existingRouteProps.index;
690
+ const newIsIndexRoute = !!reactElement.props.index;
691
+ // For Navigate components, match by destination
692
+ const existingIsNavigate = React.isValidElement(existingElement) && existingElement.type === Navigate;
693
+ const newIsNavigate = React.isValidElement(newElement) && newElement.type === Navigate;
694
+ if (existingIsNavigate && newIsNavigate) {
695
+ const existingTo = (_c = existingElement.props) === null || _c === void 0 ? void 0 : _c.to;
696
+ const newTo = (_d = newElement.props) === null || _d === void 0 ? void 0 : _d.to;
697
+ if (existingTo === newTo) {
698
+ return true;
699
+ }
700
+ }
701
+ if (existingIsIndexRoute && newIsIndexRoute) {
702
+ return true;
703
+ }
704
+ // Reuse view items with the same path
705
+ // Special case: reuse tabs/* and other specific wildcard routes
706
+ // Don't reuse index routes (empty path) or generic catch-all wildcards (*)
707
+ if (existingPath === routePath && existingPath !== '' && existingPath !== '*') {
708
+ // Parameterized routes need pathname matching to ensure /details/1 and /details/2
709
+ // get separate view items. For wildcard routes (e.g., user/:userId/*), compare
710
+ // pathnameBase to allow child path changes while preserving the parent view.
711
+ const hasParams = routePath.includes(':');
712
+ const isWildcard = routePath.includes('*');
713
+ if (hasParams) {
714
+ if (isWildcard) {
715
+ const existingPathnameBase = (_f = (_e = v.routeData) === null || _e === void 0 ? void 0 : _e.match) === null || _f === void 0 ? void 0 : _f.pathnameBase;
716
+ const newMatch = matchComponent$1(reactElement, routeInfo.pathname, false, this.outletParentPaths.get(outletId));
717
+ const newPathnameBase = newMatch === null || newMatch === void 0 ? void 0 : newMatch.pathnameBase;
718
+ if (existingPathnameBase !== newPathnameBase) {
719
+ return false;
720
+ }
721
+ }
722
+ else {
723
+ const existingPathname = (_h = (_g = v.routeData) === null || _g === void 0 ? void 0 : _g.match) === null || _h === void 0 ? void 0 : _h.pathname;
724
+ if (existingPathname !== routeInfo.pathname) {
725
+ return false;
726
+ }
727
+ }
728
+ }
729
+ return true;
730
+ }
731
+ // Also reuse specific wildcard routes like tabs/*
732
+ if (existingPath === routePath && existingPath.endsWith('/*') && existingPath !== '/*') {
733
+ return true;
734
+ }
735
+ return false;
736
+ });
737
+ if (existingViewItem) {
738
+ // Update and ensure the existing view item is properly configured
739
+ existingViewItem.reactElement = reactElement;
740
+ existingViewItem.mount = true;
741
+ existingViewItem.ionPageElement = page || existingViewItem.ionPageElement;
742
+ const updatedMatch = matchComponent$1(reactElement, routeInfo.pathname, false, this.outletParentPaths.get(outletId)) ||
743
+ ((_a = existingViewItem.routeData) === null || _a === void 0 ? void 0 : _a.match) ||
744
+ createDefaultMatch(routeInfo.pathname, reactElement.props);
745
+ existingViewItem.routeData = {
746
+ match: updatedMatch,
747
+ childProps: reactElement.props,
748
+ lastPathname: (_b = existingViewItem.routeData) === null || _b === void 0 ? void 0 : _b.lastPathname, // Preserve navigation history
749
+ };
750
+ return existingViewItem;
751
+ }
752
+ const id = `${outletId}-${generateId(outletId)}`;
753
+ const viewItem = {
754
+ id,
755
+ outletId,
756
+ ionPageElement: page,
757
+ reactElement,
758
+ mount: true,
759
+ ionRoute: true,
760
+ };
761
+ if (reactElement.type === IonRoute) {
762
+ viewItem.disableIonPageManagement = reactElement.props.disableIonPageManagement;
763
+ }
764
+ const initialMatch = matchComponent$1(reactElement, routeInfo.pathname, true, this.outletParentPaths.get(outletId)) ||
765
+ createDefaultMatch(routeInfo.pathname, reactElement.props);
766
+ viewItem.routeData = {
767
+ match: initialMatch,
768
+ childProps: reactElement.props,
769
+ };
770
+ this.add(viewItem);
771
+ return viewItem;
772
+ };
773
+ /**
774
+ * Renders a ViewLifeCycleManager for the given view item.
775
+ * Handles cleanup if the view no longer matches.
776
+ *
777
+ * - Deactivates view if it no longer matches the current route
778
+ * - Wraps the route element in <Routes> to support nested routing and ensure remounting
779
+ * - Adds a unique key to <Routes> so React Router remounts routes when switching
780
+ */
781
+ this.renderViewItem = (viewItem, routeInfo, parentPath, reRender) => {
782
+ var _a, _b, _c, _d, _e, _f, _g, _h;
783
+ const routePath = viewItem.reactElement.props.path || '';
784
+ let match = matchComponent$1(viewItem.reactElement, routeInfo.pathname, false, parentPath);
785
+ if (!match) {
786
+ const indexMatch = resolveIndexRouteMatch(viewItem, routeInfo.pathname, parentPath);
787
+ if (indexMatch) {
788
+ match = indexMatch;
789
+ }
790
+ }
791
+ // For parameterized routes, check if this is a navigation to a different path instance
792
+ // In that case, we should NOT reuse this view - a new view should be created
793
+ const isParameterRoute = routePath.includes(':');
794
+ const previousMatch = (_a = viewItem.routeData) === null || _a === void 0 ? void 0 : _a.match;
795
+ const isSamePath = (match === null || match === void 0 ? void 0 : match.pathname) === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathname);
796
+ // Flag to indicate this view should not be reused for this different parameterized path
797
+ const shouldSkipForDifferentParam = isParameterRoute && match && previousMatch && !isSamePath;
798
+ // Don't deactivate views automatically - let the StackManager handle view lifecycle
799
+ // This preserves views in the stack for navigation history like native apps
800
+ // Views will be hidden/shown by the StackManager's transition logic instead of being unmounted
801
+ // Special handling for Navigate components - they should unmount after redirecting
802
+ const elementComponent = (_c = (_b = viewItem.reactElement) === null || _b === void 0 ? void 0 : _b.props) === null || _c === void 0 ? void 0 : _c.element;
803
+ const isNavigateComponent = isNavigateElement(elementComponent);
804
+ if (isNavigateComponent) {
805
+ // Navigate components should only be mounted when they match
806
+ // Once they redirect (no longer match), they should be removed completely
807
+ // IMPORTANT: For index routes, we need to check indexMatch too since matchComponent
808
+ // may not properly match index routes without explicit parent path context
809
+ const indexMatch = ((_e = (_d = viewItem.routeData) === null || _d === void 0 ? void 0 : _d.childProps) === null || _e === void 0 ? void 0 : _e.index)
810
+ ? resolveIndexRouteMatch(viewItem, routeInfo.pathname, parentPath)
811
+ : null;
812
+ const hasValidMatch = match || indexMatch;
813
+ if (!hasValidMatch && viewItem.mount) {
814
+ viewItem.mount = false;
815
+ // Schedule removal of the Navigate view item after a short delay
816
+ // This ensures the redirect completes before removal
817
+ setTimeout(() => {
818
+ this.remove(viewItem);
819
+ reRender === null || reRender === void 0 ? void 0 : reRender();
820
+ }, NAVIGATE_REDIRECT_DELAY_MS);
821
+ }
822
+ }
823
+ // Components that don't have IonPage elements and no longer match should be cleaned up
824
+ // BUT we need to be careful not to remove them if they're part of browser navigation history
825
+ // This handles components that perform immediate actions like programmatic navigation
826
+ // EXCEPTION: Navigate components should ALWAYS remain mounted until they redirect
827
+ // since they need to be rendered to trigger the navigation
828
+ if (!match && viewItem.mount && !viewItem.ionPageElement && !isNavigateComponent) {
829
+ // Check if this view item should be preserved for browser navigation
830
+ // We'll keep it if it was recently active (within the last navigation)
831
+ const shouldPreserve = viewItem.routeData.lastPathname === routeInfo.pathname ||
832
+ ((_f = viewItem.routeData.match) === null || _f === void 0 ? void 0 : _f.pathname) === routeInfo.lastPathname;
833
+ if (!shouldPreserve) {
834
+ // This view item doesn't match and doesn't have an IonPage
835
+ // It's likely a utility component that performs an action and navigates away
836
+ viewItem.mount = false;
837
+ // Schedule removal to allow it to be recreated on next navigation
838
+ setTimeout(() => {
839
+ // Double-check before removing - the view might be needed again
840
+ const stillNotNeeded = !viewItem.mount && !viewItem.ionPageElement;
841
+ if (stillNotNeeded) {
842
+ this.remove(viewItem);
843
+ reRender === null || reRender === void 0 ? void 0 : reRender();
844
+ }
845
+ }, VIEW_CLEANUP_DELAY_MS);
846
+ }
847
+ else {
848
+ // Preserve it but unmount it for now
849
+ viewItem.mount = false;
850
+ }
851
+ }
852
+ // Reactivate view if it matches but was previously deactivated
853
+ // Don't reactivate if this is a parameterized route navigating to a different path instance
854
+ // Don't reactivate catch-all wildcard routes — they are created fresh by createViewItem
855
+ const isCatchAllWildcard = routePath === '*' || routePath === '/*';
856
+ if (match && !viewItem.mount && !shouldSkipForDifferentParam && !isCatchAllWildcard) {
857
+ viewItem.mount = true;
858
+ viewItem.routeData.match = match;
859
+ }
860
+ // Deactivate wildcard (catch-all) and empty-path (default) routes when a more-specific route matches.
861
+ // This prevents "Not found" or fallback pages from showing alongside valid routes.
862
+ if (routePath === '*' || routePath === '') {
863
+ // Check if any other view in this outlet has a match for the current route
864
+ const outletViews = this.getViewItemsForOutlet(viewItem.outletId);
865
+ // When parent path context is available, compute the relative pathname once
866
+ // outside the loop since both routeInfo.pathname and parentPath are invariant.
867
+ const relativePathname = parentPath
868
+ ? computeRelativeToParent(routeInfo.pathname, parentPath)
869
+ : null;
870
+ let hasSpecificMatch = outletViews.some((v) => {
871
+ var _a, _b;
872
+ if (v.id === viewItem.id)
873
+ return false; // Skip self
874
+ const vRoutePath = ((_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path) || '';
875
+ if (vRoutePath === '*' || vRoutePath === '')
876
+ return false; // Skip other wildcard/empty routes
877
+ // When parent path context is available and the route is relative, use
878
+ // parent-path-aware matching. This avoids false positives from
879
+ // derivePathnameToMatch's tail-slice heuristic, which can incorrectly
880
+ // match route literals that appear at the wrong position in the pathname.
881
+ // Example: pathname /parent/extra/details/99 with route details/:id —
882
+ // the tail-slice extracts ["details","99"] producing a false match.
883
+ if (parentPath && vRoutePath && !vRoutePath.startsWith('/')) {
884
+ if (relativePathname === null) {
885
+ return false; // Pathname is outside this outlet's parent scope
886
+ }
887
+ return !!matchPath({
888
+ pathname: relativePathname,
889
+ componentProps: v.reactElement.props,
890
+ });
891
+ }
892
+ // Fallback to matchComponent when no parent path context is available
893
+ const vMatch = v.reactElement ? matchComponent$1(v.reactElement, routeInfo.pathname) : null;
894
+ return !!vMatch;
895
+ });
896
+ // For catch-all * routes, also deactivate when the pathname matches the outlet's
897
+ // parent path exactly. This means there are no remaining segments for the wildcard
898
+ // to catch, so the empty-path or index route should handle it instead.
899
+ if (!hasSpecificMatch && routePath === '*') {
900
+ const outletParentPath = this.outletParentPaths.get(viewItem.outletId);
901
+ if (outletParentPath) {
902
+ const normalizedParent = normalizePathnameForComparison(outletParentPath);
903
+ const normalizedPathname = normalizePathnameForComparison(routeInfo.pathname);
904
+ if (normalizedPathname === normalizedParent) {
905
+ // Check if there's an empty-path or index view item that should handle this
906
+ const hasDefaultRoute = outletViews.some((v) => {
907
+ var _a, _b, _c, _d;
908
+ if (v.id === viewItem.id)
909
+ return false;
910
+ const vRoutePath = (_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
911
+ return vRoutePath === '' || vRoutePath === undefined || !!((_d = (_c = v.routeData) === null || _c === void 0 ? void 0 : _c.childProps) === null || _d === void 0 ? void 0 : _d.index);
912
+ });
913
+ if (hasDefaultRoute) {
914
+ hasSpecificMatch = true;
915
+ }
916
+ }
917
+ }
918
+ }
919
+ if (hasSpecificMatch) {
920
+ viewItem.mount = false;
921
+ if (viewItem.ionPageElement) {
922
+ viewItem.ionPageElement.classList.add('ion-page-hidden');
923
+ viewItem.ionPageElement.setAttribute('aria-hidden', 'true');
924
+ }
925
+ }
926
+ }
927
+ const routeElement = React.cloneElement(viewItem.reactElement);
928
+ const componentElement = routeElement.props.element;
929
+ // Don't update match for parameterized routes navigating to different path instances
930
+ // This preserves the original match so that findViewItemByPath can correctly skip this view
931
+ if (match && viewItem.routeData.match !== match && !shouldSkipForDifferentParam) {
932
+ viewItem.routeData.match = match;
933
+ }
934
+ const routeMatch = shouldSkipForDifferentParam ? (_g = viewItem.routeData) === null || _g === void 0 ? void 0 : _g.match : match || ((_h = viewItem.routeData) === null || _h === void 0 ? void 0 : _h.match);
935
+ return (React.createElement(UNSAFE_RouteContext.Consumer, { key: `view-context-${viewItem.id}` }, (parentContext) => {
936
+ var _a, _b;
937
+ const parentMatches = ((_a = parentContext === null || parentContext === void 0 ? void 0 : parentContext.matches) !== null && _a !== void 0 ? _a : []);
938
+ // Accumulate params from parent matches, with fallback to other outlets
939
+ let accumulatedParentParams = parentMatches.reduce((acc, m) => (Object.assign(Object.assign({}, acc), m.params)), {});
940
+ if (parentMatches.length === 0 && Object.keys(accumulatedParentParams).length === 0) {
941
+ accumulatedParentParams = getFallbackParamsFromViewItems(this.getAllViewItems(), viewItem.outletId, routeInfo.pathname);
942
+ }
943
+ const combinedParams = Object.assign(Object.assign({}, accumulatedParentParams), ((_b = routeMatch === null || routeMatch === void 0 ? void 0 : routeMatch.params) !== null && _b !== void 0 ? _b : {}));
944
+ const parentPathnameBase = parentMatches.length > 0 ? parentMatches[parentMatches.length - 1].pathnameBase : '/';
945
+ const absolutePathnameBase = computeAbsolutePathnameBase(routeElement, routeMatch, parentPathnameBase, routeInfo.pathname);
946
+ const contextMatches = buildContextMatches(parentMatches, combinedParams, routeMatch, routeInfo.pathname, absolutePathnameBase, viewItem, routeElement, componentElement);
947
+ const routeContextValue = parentContext
948
+ ? Object.assign(Object.assign({}, parentContext), { matches: contextMatches }) : { outlet: null, matches: contextMatches, isDataRoute: false };
949
+ return (React.createElement(ViewLifeCycleManager, { key: `view-${viewItem.id}`, mount: viewItem.mount, removeView: () => this.remove(viewItem) },
950
+ React.createElement(UNSAFE_RouteContext.Provider, { value: routeContextValue }, componentElement)));
951
+ }));
952
+ };
953
+ /**
954
+ * Re-renders all active view items for the specified outlet.
955
+ * Ensures React elements are updated with the latest match.
956
+ *
957
+ * 1. Iterates through children of IonRouterOutlet
958
+ * 2. Updates each matching viewItem with the current child React element
959
+ * (important for updating props or changes to elements)
960
+ * 3. Returns a list of React components that will be rendered inside the outlet
961
+ * Each view is wrapped in <ViewLifeCycleManager> to manage lifecycle and rendering
962
+ */
963
+ this.getChildrenToRender = (outletId, ionRouterOutlet, routeInfo, reRender, parentPathnameBase) => {
964
+ const viewItems = this.getViewItemsForOutlet(outletId);
965
+ // Seed the mount path from the parent route context if available.
966
+ // This provides the outlet's mount path immediately on first render,
967
+ // eliminating the need for heuristic-based discovery in computeParentPath.
968
+ if (parentPathnameBase && !this.outletMountPaths.has(outletId)) {
969
+ this.outletMountPaths.set(outletId, parentPathnameBase);
970
+ }
971
+ // Determine parentPath for outlets with relative or index routes.
972
+ // This populates outletParentPaths for findViewItemByPath's matchView
973
+ // and the catch-all deactivation logic in renderViewItem.
974
+ let parentPath = undefined;
975
+ try {
976
+ const routeChildren = extractRouteChildren(ionRouterOutlet.props.children);
977
+ const { hasRelativeRoutes, hasIndexRoute, hasWildcardRoute } = analyzeRouteChildren(routeChildren);
978
+ if (hasRelativeRoutes || hasIndexRoute) {
979
+ const result = computeParentPath({
980
+ currentPathname: routeInfo.pathname,
981
+ outletMountPath: this.outletMountPaths.get(outletId),
982
+ routeChildren,
983
+ hasRelativeRoutes,
984
+ hasIndexRoute,
985
+ hasWildcardRoute,
986
+ });
987
+ parentPath = result.parentPath;
988
+ // Persist the mount path for subsequent calls, mirroring StackManager.outletMountPath.
989
+ // Unlike outletParentPaths (cleared when parentPath is undefined), the mount path is
990
+ // intentionally sticky — it anchors the outlet's scope and is only removed in clear().
991
+ if (result.outletMountPath && !this.outletMountPaths.has(outletId)) {
992
+ this.outletMountPaths.set(outletId, result.outletMountPath);
993
+ }
994
+ }
995
+ }
996
+ catch (e) {
997
+ // Non-fatal: if we fail to compute parentPath, fall back to previous behavior
998
+ }
999
+ // Store the computed parentPath for use in findViewItemByPath.
1000
+ // Clear stale entries when parentPath is undefined (e.g., navigated out of scope).
1001
+ if (parentPath !== undefined) {
1002
+ this.outletParentPaths.set(outletId, parentPath);
1003
+ }
1004
+ else if (this.outletParentPaths.has(outletId)) {
1005
+ this.outletParentPaths.delete(outletId);
1006
+ }
1007
+ // Re-sync each route element onto its stored viewItem so prop changes from a
1008
+ // parent re-render reach the child. extractRouteChildren unwraps the <Routes>
1009
+ // wrapper, which has no path of its own. Without it we'd iterate props.children
1010
+ // directly, never match a viewItem, and the child's props would go stale.
1011
+ extractRouteChildren(ionRouterOutlet.props.children).forEach((child) => {
1012
+ // Match on exact path so a wildcard route doesn't overwrite a specific one.
1013
+ const childPath = child.props.path;
1014
+ const viewItem = viewItems.find((v) => {
1015
+ var _a, _b;
1016
+ const viewItemPath = (_b = (_a = v.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1017
+ return viewItemPath === childPath;
1018
+ });
1019
+ if (viewItem) {
1020
+ viewItem.reactElement = child;
1021
+ }
1022
+ });
1023
+ // Filter out duplicate view items by ID (but keep all mounted items)
1024
+ const uniqueViewItems = viewItems.filter((viewItem, index, array) => {
1025
+ // Remove duplicates by ID (keep first occurrence)
1026
+ const isFirstOccurrence = array.findIndex((v) => v.id === viewItem.id) === index;
1027
+ return isFirstOccurrence;
1028
+ });
1029
+ // Filter out unmounted Navigate components to prevent them from being rendered
1030
+ // and triggering unwanted redirects
1031
+ const renderableViewItems = uniqueViewItems.filter((viewItem) => {
1032
+ var _a, _b, _c, _d;
1033
+ const elementComponent = (_b = (_a = viewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.element;
1034
+ const isNavigateComponent = isNavigateElement(elementComponent);
1035
+ // Exclude unmounted Navigate components from rendering
1036
+ if (isNavigateComponent && !viewItem.mount) {
1037
+ return false;
1038
+ }
1039
+ // Filter out views that are unmounted, have no ionPageElement, and don't match the current route.
1040
+ // These are "stale" views from previous routes that should not be rendered.
1041
+ // Views WITH ionPageElement are handled by the normal lifecycle events.
1042
+ // Views that MATCH the current route should be kept (they might be transitioning).
1043
+ if (!viewItem.mount && !viewItem.ionPageElement) {
1044
+ // Check if this view's route path matches the current pathname
1045
+ const viewRoutePath = (_d = (_c = viewItem.reactElement) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.path;
1046
+ if (viewRoutePath) {
1047
+ // First try exact match using matchComponent
1048
+ const routeMatch = matchComponent$1(viewItem.reactElement, routeInfo.pathname, false, parentPath);
1049
+ if (routeMatch) {
1050
+ // View matches current route, keep it
1051
+ return true;
1052
+ }
1053
+ // For parent routes (like /multiple-tabs or /routing), check if current pathname
1054
+ // starts with this route's path. This handles views with IonSplitPane/IonTabs
1055
+ // that don't have IonPage but should remain mounted while navigating within their children.
1056
+ const normalizedViewPath = normalizePathnameForComparison(viewRoutePath.replace(/\/?\*$/, '')); // Remove trailing wildcard
1057
+ const normalizedCurrentPath = normalizePathnameForComparison(routeInfo.pathname);
1058
+ // Check if current pathname is within this view's route hierarchy
1059
+ const isWithinRouteHierarchy = normalizedCurrentPath === normalizedViewPath || normalizedCurrentPath.startsWith(normalizedViewPath + '/');
1060
+ if (!isWithinRouteHierarchy) {
1061
+ // View is outside current route hierarchy, remove it
1062
+ setTimeout(() => {
1063
+ this.remove(viewItem);
1064
+ reRender();
1065
+ }, 0);
1066
+ return false;
1067
+ }
1068
+ }
1069
+ }
1070
+ return true;
1071
+ });
1072
+ const renderedItems = renderableViewItems.map((viewItem) => this.renderViewItem(viewItem, routeInfo, parentPath, reRender));
1073
+ return renderedItems;
1074
+ };
1075
+ /**
1076
+ * Finds a view item matching the current route, optionally updating its match state.
1077
+ */
1078
+ this.findViewItemByRouteInfo = (routeInfo, outletId, updateMatch) => {
1079
+ const { viewItem, match } = this.findViewItemByPath(routeInfo.pathname, outletId);
1080
+ const shouldUpdateMatch = updateMatch === undefined || updateMatch === true;
1081
+ if (shouldUpdateMatch && viewItem && match) {
1082
+ viewItem.routeData.match = match;
1083
+ }
1084
+ return viewItem;
1085
+ };
1086
+ /**
1087
+ * Finds the view item that was previously active before a route change.
1088
+ */
1089
+ this.findLeavingViewItemByRouteInfo = (routeInfo, outletId, mustBeIonRoute = true) => {
1090
+ // If the lastPathname is not set, we cannot find a leaving view item
1091
+ if (!routeInfo.lastPathname) {
1092
+ return undefined;
1093
+ }
1094
+ const { viewItem } = this.findViewItemByPath(routeInfo.lastPathname, outletId, mustBeIonRoute);
1095
+ return viewItem;
1096
+ };
1097
+ /**
1098
+ * Finds a view item by pathname only, used in simpler queries.
1099
+ */
1100
+ this.findViewItemByPathname = (pathname, outletId) => {
1101
+ const { viewItem } = this.findViewItemByPath(pathname, outletId);
1102
+ return viewItem;
1103
+ };
1104
+ /**
1105
+ * Clean up old, unmounted view items to prevent memory leaks
1106
+ */
1107
+ this.cleanupStaleViewItems = (outletId) => {
1108
+ const viewItems = this.getViewItemsForOutlet(outletId);
1109
+ // Keep only the most recent mounted views and a few unmounted ones for history
1110
+ const maxUnmountedItems = 3;
1111
+ const unmountedItems = viewItems.filter((v) => !v.mount);
1112
+ if (unmountedItems.length > maxUnmountedItems) {
1113
+ // Remove oldest unmounted items
1114
+ const itemsToRemove = unmountedItems.slice(0, unmountedItems.length - maxUnmountedItems);
1115
+ itemsToRemove.forEach((item) => {
1116
+ this.remove(item);
1117
+ });
1118
+ }
1119
+ };
1120
+ /**
1121
+ * Override add to prevent duplicate view items with the same ID in the same outlet
1122
+ * But allow multiple view items for the same route path (for navigation history)
1123
+ */
1124
+ this.add = (viewItem) => {
1125
+ const existingViewItem = this.getViewItemsForOutlet(viewItem.outletId).find((v) => v.id === viewItem.id);
1126
+ if (existingViewItem) {
1127
+ return;
1128
+ }
1129
+ super.add(viewItem);
1130
+ this.cleanupStaleViewItems(viewItem.outletId);
1131
+ };
1132
+ /**
1133
+ * Override clear to also clean up the stored parent path for the outlet.
1134
+ */
1135
+ this.clear = (outletId) => {
1136
+ this.outletParentPaths.delete(outletId);
1137
+ this.outletMountPaths.delete(outletId);
1138
+ return super.clear(outletId);
1139
+ };
1140
+ /**
1141
+ * Override remove
1142
+ */
1143
+ this.remove = (viewItem) => {
1144
+ super.remove(viewItem);
1145
+ };
1146
+ }
1147
+ /**
1148
+ * Core function that matches a given pathname against all view items.
1149
+ * Returns both the matched view item and match metadata.
1150
+ */
1151
+ findViewItemByPath(pathname, outletId, mustBeIonRoute, allowDefaultMatch = true) {
1152
+ let viewItem;
1153
+ let match = null;
1154
+ let viewStack;
1155
+ // Capture stored parent paths for use in nested matchView/matchDefaultRoute functions
1156
+ const storedParentPaths = this.outletParentPaths;
1157
+ if (outletId) {
1158
+ viewStack = sortViewsBySpecificity(this.getViewItemsForOutlet(outletId));
1159
+ viewStack.some(matchView);
1160
+ if (!viewItem && allowDefaultMatch)
1161
+ viewStack.some(matchDefaultRoute);
1162
+ }
1163
+ else {
1164
+ const viewItems = sortViewsBySpecificity(this.getAllViewItems());
1165
+ viewItems.some(matchView);
1166
+ if (!viewItem && allowDefaultMatch)
1167
+ viewItems.some(matchDefaultRoute);
1168
+ }
1169
+ // If we still have not found a view item for this outlet, try to find a matching
1170
+ // view item across all outlets and adopt it into the current outlet. This helps
1171
+ // recover when an outlet remounts and receives a new id, leaving views associated
1172
+ // with the previous outlet id.
1173
+ // Do not adopt across outlets; if we didn't find a view for this outlet,
1174
+ // defer to route matching to create a new one.
1175
+ return { viewItem, match };
1176
+ /**
1177
+ * Matches a route path with dynamic parameters (e.g. /tabs/:id)
1178
+ */
1179
+ function matchView(v) {
1180
+ var _a;
1181
+ if (mustBeIonRoute && !v.ionRoute)
1182
+ return false;
1183
+ const viewItemPath = v.routeData.childProps.path || '';
1184
+ // Skip unmounted catch-all wildcard views. After back navigation unmounts
1185
+ // a wildcard view, it should not be reused for subsequent navigations.
1186
+ // A fresh wildcard view will be created by createViewItem when needed.
1187
+ if ((viewItemPath === '*' || viewItemPath === '/*') && !v.mount)
1188
+ return false;
1189
+ const isIndexRoute = !!v.routeData.childProps.index;
1190
+ const previousMatch = (_a = v.routeData) === null || _a === void 0 ? void 0 : _a.match;
1191
+ const outletParentPath = storedParentPaths.get(v.outletId);
1192
+ const result = v.reactElement ? matchComponent$1(v.reactElement, pathname, false, outletParentPath) : null;
1193
+ if (!result) {
1194
+ const indexMatch = resolveIndexRouteMatch(v, pathname, outletParentPath);
1195
+ if (indexMatch) {
1196
+ match = indexMatch;
1197
+ viewItem = v;
1198
+ return true;
1199
+ }
1200
+ // Empty path routes (path="") should match when the pathname matches the
1201
+ // outlet's parent path exactly (no remaining segments). matchComponent doesn't
1202
+ // handle this because it lacks parent path context. Without this check, a
1203
+ // catch-all * view item (which matches any pathname) would be incorrectly
1204
+ // returned instead of the empty path route on back navigation.
1205
+ if (viewItemPath === '' && !isIndexRoute && outletParentPath) {
1206
+ const normalizedParent = normalizePathnameForComparison(outletParentPath);
1207
+ const normalizedPathname = normalizePathnameForComparison(pathname);
1208
+ if (normalizedPathname === normalizedParent) {
1209
+ match = createDefaultMatch(pathname, v.routeData.childProps);
1210
+ viewItem = v;
1211
+ return true;
1212
+ }
1213
+ }
1214
+ }
1215
+ if (result) {
1216
+ const hasParams = result.params && Object.keys(result.params).length > 0;
1217
+ const isSamePath = result.pathname === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathname);
1218
+ const isWildcardRoute = viewItemPath.includes('*');
1219
+ const isParameterRoute = viewItemPath.includes(':');
1220
+ // Don't allow view items with undefined paths to match specific routes
1221
+ // This prevents broken index route view items from interfering with navigation
1222
+ if (!viewItemPath && !isIndexRoute && pathname !== '/' && pathname !== '') {
1223
+ return false;
1224
+ }
1225
+ // For parameterized routes, check if we should reuse the view item.
1226
+ // Wildcard routes (e.g., user/:userId/*) compare pathnameBase to allow
1227
+ // child path changes while preserving the parent view.
1228
+ if (isParameterRoute && !isSamePath) {
1229
+ if (isWildcardRoute) {
1230
+ const isSameBase = result.pathnameBase === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathnameBase);
1231
+ if (isSameBase) {
1232
+ match = result;
1233
+ viewItem = v;
1234
+ return true;
1235
+ }
1236
+ }
1237
+ return false;
1238
+ }
1239
+ // For routes without params, or when navigating to the exact same path,
1240
+ // or when there's no previous match, reuse the view item
1241
+ if (!hasParams || isSamePath || !previousMatch) {
1242
+ match = result;
1243
+ viewItem = v;
1244
+ return true;
1245
+ }
1246
+ // For pure wildcard routes (without : params), compare pathnameBase to allow
1247
+ // child path changes while preserving the parent view. This handles container
1248
+ // routes like /tabs/* where switching between /tabs/tab1 and /tabs/tab2
1249
+ // should reuse the same ViewItem.
1250
+ if (isWildcardRoute && !isParameterRoute) {
1251
+ const isSameBase = result.pathnameBase === (previousMatch === null || previousMatch === void 0 ? void 0 : previousMatch.pathnameBase);
1252
+ if (isSameBase) {
1253
+ match = result;
1254
+ viewItem = v;
1255
+ return true;
1256
+ }
1257
+ }
1258
+ }
1259
+ return false;
1260
+ }
1261
+ /**
1262
+ * Matches a view with no path prop (default fallback route) or index route.
1263
+ */
1264
+ function matchDefaultRoute(v) {
1265
+ var _a, _b, _c;
1266
+ const childProps = v.routeData.childProps;
1267
+ const isDefaultRoute = childProps.path === undefined || childProps.path === '';
1268
+ const isIndexRoute = !!childProps.index;
1269
+ if (isIndexRoute) {
1270
+ const outletParentPath = storedParentPaths.get(v.outletId);
1271
+ const indexMatch = resolveIndexRouteMatch(v, pathname, outletParentPath);
1272
+ if (indexMatch) {
1273
+ match = indexMatch;
1274
+ viewItem = v;
1275
+ return true;
1276
+ }
1277
+ return false;
1278
+ }
1279
+ // For empty path routes, only match if we're at the same level as when the view was created.
1280
+ // This prevents an empty path view item from being reused for different routes.
1281
+ if (isDefaultRoute) {
1282
+ const previousPathnameBase = ((_b = (_a = v.routeData) === null || _a === void 0 ? void 0 : _a.match) === null || _b === void 0 ? void 0 : _b.pathnameBase) || '';
1283
+ const normalizedBase = normalizePathnameForComparison(previousPathnameBase);
1284
+ const normalizedPathname = normalizePathnameForComparison(pathname);
1285
+ if (normalizedPathname !== normalizedBase) {
1286
+ return false;
1287
+ }
1288
+ match = {
1289
+ params: {},
1290
+ pathname,
1291
+ pathnameBase: pathname === '' ? '/' : pathname,
1292
+ pattern: {
1293
+ path: '',
1294
+ caseSensitive: (_c = childProps.caseSensitive) !== null && _c !== void 0 ? _c : false,
1295
+ end: true,
1296
+ },
1297
+ };
1298
+ viewItem = v;
1299
+ return true;
1300
+ }
1301
+ return false;
1302
+ }
1303
+ }
1304
+ }
1305
+ /**
1306
+ * Utility to apply matchPath to a React element and return its match state.
1307
+ */
1308
+ function matchComponent$1(node, pathname, allowFallback = false, parentPath) {
1309
+ var _a;
1310
+ const routeProps = (_a = node === null || node === void 0 ? void 0 : node.props) !== null && _a !== void 0 ? _a : {};
1311
+ const routePath = routeProps.path;
1312
+ let pathnameToMatch;
1313
+ if (parentPath && routePath && !routePath.startsWith('/')) {
1314
+ // When parent path is known, compute exact relative pathname
1315
+ // instead of using the tail-slice heuristic
1316
+ const relative = pathname.startsWith(parentPath)
1317
+ ? pathname.slice(parentPath.length).replace(/^\//, '')
1318
+ : pathname;
1319
+ pathnameToMatch = relative;
1320
+ }
1321
+ else {
1322
+ pathnameToMatch = derivePathnameToMatch(pathname, routePath);
1323
+ }
1324
+ const match = matchPath({
1325
+ pathname: pathnameToMatch,
1326
+ componentProps: routeProps,
1327
+ });
1328
+ if (match || !allowFallback) {
1329
+ return match;
1330
+ }
1331
+ const isIndexRoute = !!routeProps.index;
1332
+ if (isIndexRoute) {
1333
+ return createDefaultMatch(pathname, routeProps);
1334
+ }
1335
+ if (!routePath || routePath === '') {
1336
+ return createDefaultMatch(pathname, routeProps);
1337
+ }
1338
+ return null;
1339
+ }
1340
+
1341
+ function clonePageElement(leavingViewHtml) {
1342
+ let html;
1343
+ if (typeof leavingViewHtml === 'string') {
1344
+ html = leavingViewHtml;
1345
+ }
1346
+ else {
1347
+ html = leavingViewHtml.outerHTML;
1348
+ }
1349
+ if (document) {
1350
+ const newEl = document.createElement('div');
1351
+ newEl.innerHTML = html;
1352
+ newEl.style.zIndex = '';
1353
+ // Remove an existing back button so the new element doesn't get two of them
1354
+ const ionBackButton = newEl.getElementsByTagName('ion-back-button');
1355
+ if (ionBackButton[0]) {
1356
+ ionBackButton[0].remove();
1357
+ }
1358
+ return newEl.firstChild;
1359
+ }
1360
+ return undefined;
1361
+ }
1362
+
1363
+ /**
1364
+ * `StackManager` is responsible for managing page transitions, keeping track
1365
+ * of views (pages), and ensuring that navigation behaves like native apps —
1366
+ * particularly with animations and swipe gestures.
1367
+ */
1368
+ /**
1369
+ * Delay in milliseconds before unmounting a view after a transition completes.
1370
+ * This ensures the page transition animation finishes before the view is removed.
1371
+ */
1372
+ const VIEW_UNMOUNT_DELAY_MS = 250;
1373
+ /**
1374
+ * Delay (ms) to wait for an IonPage to mount before proceeding with a
1375
+ * page transition. Only container routes (nested outlets with no direct
1376
+ * IonPage) actually hit this timeout; normal routes clear it early via
1377
+ * registerIonPage, so a larger value here doesn't affect the happy path.
1378
+ */
1379
+ const ION_PAGE_WAIT_TIMEOUT_MS = 300;
1380
+ const isViewVisible = (el) => !el.classList.contains('ion-page-invisible') && !el.classList.contains('ion-page-hidden') && el.style.visibility !== 'hidden';
1381
+ const hideIonPageElement = (element) => {
1382
+ var _a;
1383
+ if (element) {
1384
+ if (element.id === 'section-a' || element.id === 'section-b') {
1385
+ // eslint-disable-next-line no-console
1386
+ console.log('[HideIonPageElement]', JSON.stringify({
1387
+ id: element.id,
1388
+ stack: (_a = new Error().stack) === null || _a === void 0 ? void 0 : _a.split('\n').slice(1, 6).map((s) => s.trim()),
1389
+ }));
1390
+ }
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
+ // core transitions (md.transition.ts, ios.transition.ts) leave inline styles
1399
+ // on the leaving page after animation: `display: none` plus the final
1400
+ // keyframe values for `transform` and `opacity` (MD only). Preserved views
1401
+ // must clear all of these on re-entry so they render in the correct
1402
+ // position when the back direction entering animation is a no-op.
1403
+ element.style.removeProperty('display');
1404
+ element.style.removeProperty('transform');
1405
+ element.style.removeProperty('opacity');
1406
+ element.classList.remove('ion-page-hidden');
1407
+ element.removeAttribute('aria-hidden');
1408
+ }
1409
+ };
1410
+ /**
1411
+ * Variant of `showIonPageElement` for the swipe-back gesture start. Clears
1412
+ * `display: none` and the hidden class/attribute so the entering view is
1413
+ * visible, but intentionally keeps any inline `transform` and `opacity` set
1414
+ * by core's prior forward transition. The gesture's progress animation starts
1415
+ * from that pose, so clearing them here would cause a visible jump before
1416
+ * core's progress animation takes over.
1417
+ */
1418
+ const revealIonPageForSwipeBack = (element) => {
1419
+ if (element) {
1420
+ const before = {
1421
+ id: element.id,
1422
+ inlineDisplay: element.style.display,
1423
+ hasHiddenClass: element.classList.contains('ion-page-hidden'),
1424
+ ariaHidden: element.getAttribute('aria-hidden'),
1425
+ computedDisplay: getComputedStyle(element).display,
1426
+ };
1427
+ element.style.removeProperty('display');
1428
+ element.classList.remove('ion-page-hidden');
1429
+ element.removeAttribute('aria-hidden');
1430
+ // eslint-disable-next-line no-console
1431
+ console.log('[SwipeBackReveal]', JSON.stringify({
1432
+ before,
1433
+ after: {
1434
+ inlineDisplay: element.style.display,
1435
+ hasHiddenClass: element.classList.contains('ion-page-hidden'),
1436
+ ariaHidden: element.getAttribute('aria-hidden'),
1437
+ computedDisplay: getComputedStyle(element).display,
1438
+ },
1439
+ }));
1440
+ }
1441
+ else {
1442
+ // eslint-disable-next-line no-console
1443
+ console.log('[SwipeBackReveal] element is undefined');
1444
+ }
1445
+ };
1446
+ /**
1447
+ * A leaf view is "preservable" on browser-back (pop) when its React state
1448
+ * should survive a forward-pop round-trip. Non-parameterized leaf paths
1449
+ * resolve to the same view item on re-entry, so keeping them mounted retains
1450
+ * user-visible state (scroll, inputs, cleared lists, etc.).
1451
+ *
1452
+ * Excluded:
1453
+ * - Parameterized routes (`/users/:id`): each param value gets a distinct
1454
+ * view item, so preserving them accumulates hidden views in the DOM.
1455
+ * - Wildcard container routes (`/tabs/*`, `*`): wrap nested outlets and must
1456
+ * be destroyed so nested outlet state rebuilds cleanly on re-entry.
1457
+ */
1458
+ const isViewItemPreservableOnPop = (viewItem) => {
1459
+ var _a, _b;
1460
+ const path = (_b = (_a = viewItem === null || viewItem === void 0 ? void 0 : viewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1461
+ if (!path) {
1462
+ return false;
1463
+ }
1464
+ if (path === '*' || path.endsWith('/*')) {
1465
+ return false;
1466
+ }
1467
+ return !path.includes(':');
1468
+ };
1469
+ class StackManager extends React.PureComponent {
1470
+ constructor(props) {
1471
+ super(props);
1472
+ this.stackContextValue = {
1473
+ registerIonPage: this.registerIonPage.bind(this),
1474
+ isInOutlet: () => true,
1475
+ };
1476
+ this.pendingPageTransition = false;
1477
+ this.waitingForIonPage = false;
1478
+ /** Whether this outlet was previously in scope. */
1479
+ this.wasInScope = true;
1480
+ /**
1481
+ * Views that have been explicitly kept alive by the pop-preserve logic
1482
+ * (shouldPreserveLeavingView) so a future forward-pop can restore their React
1483
+ * state. These are candidates for cleanup when a fresh push invalidates the
1484
+ * forward-history path that made them reachable. Views mounted through
1485
+ * normal forward-push (which keeps the leaving view alive by default) are
1486
+ * NOT tracked here.
1487
+ */
1488
+ this.preservedViewItems = new Set();
1489
+ /** Tracks whether the component is mounted to guard async transition paths. */
1490
+ this._isMounted = false;
1491
+ /** In-flight requestAnimationFrame IDs from transitionPage, cancelled on unmount. */
1492
+ this.transitionRafIds = [];
1493
+ /**
1494
+ * Monotonically increasing counter incremented at the start of each transitionPage call.
1495
+ * Used to detect when an async commit() resolves after a newer transition has already run,
1496
+ * preventing the stale commit from hiding an element that the newer transition made visible.
1497
+ */
1498
+ this.transitionGeneration = 0;
1499
+ this.outletMountPath = undefined;
1500
+ /**
1501
+ * Whether this outlet is at the root level (no parent route matches).
1502
+ * Derived from UNSAFE_RouteContext in render() — empty matches means root.
1503
+ */
1504
+ this.isRootOutlet = true;
1505
+ this.registerIonPage = this.registerIonPage.bind(this);
1506
+ this.transitionPage = this.transitionPage.bind(this);
1507
+ this.handlePageTransition = this.handlePageTransition.bind(this);
1508
+ this.id = props.id || `routerOutlet-${generateId('routerOutlet')}`;
1509
+ this.prevProps = undefined;
1510
+ this.skipTransition = false;
1511
+ }
1512
+ /**
1513
+ * Determines the parent path for nested routing in React Router 6.
1514
+ *
1515
+ * When the mount path is known (seeded from UNSAFE_RouteContext), returns
1516
+ * it directly — no iterative discovery needed. The computeParentPath
1517
+ * fallback only runs for root outlets where RouteContext doesn't provide
1518
+ * a parent match.
1519
+ */
1520
+ getParentPath() {
1521
+ const currentPathname = this.props.routeInfo.pathname;
1522
+ // Prevent out-of-scope outlets from adopting unrelated routes.
1523
+ // Uses segment-aware comparison: /tabs-secondary must NOT match /tabs scope.
1524
+ if (this.outletMountPath && !isPathnameInScope(currentPathname, this.outletMountPath)) {
1525
+ return undefined;
1526
+ }
1527
+ // Fast path: mount path is known from RouteContext. The parent path IS the
1528
+ // mount path — no need to run the iterative computeParentPath algorithm.
1529
+ if (this.outletMountPath && !this.isRootOutlet) {
1530
+ return this.outletMountPath;
1531
+ }
1532
+ // Fallback: root outlet or mount path not yet seeded. Run the full
1533
+ // computeParentPath algorithm to discover the parent depth.
1534
+ if (this.ionRouterOutlet) {
1535
+ const routeChildren = extractRouteChildren(this.ionRouterOutlet.props.children);
1536
+ const { hasRelativeRoutes, hasIndexRoute, hasWildcardRoute } = analyzeRouteChildren(routeChildren);
1537
+ if (!this.isRootOutlet || hasRelativeRoutes || hasIndexRoute) {
1538
+ const result = computeParentPath({
1539
+ currentPathname,
1540
+ outletMountPath: this.outletMountPath,
1541
+ routeChildren,
1542
+ hasRelativeRoutes,
1543
+ hasIndexRoute,
1544
+ hasWildcardRoute,
1545
+ });
1546
+ if (result.outletMountPath && !this.outletMountPath) {
1547
+ this.outletMountPath = result.outletMountPath;
1548
+ }
1549
+ return result.parentPath;
1550
+ }
1551
+ }
1552
+ return this.outletMountPath;
1553
+ }
1554
+ /**
1555
+ * Finds the entering and leaving view items, handling redirect cases.
1556
+ */
1557
+ findViewItems(routeInfo) {
1558
+ const enteringViewItem = this.context.findViewItemByRouteInfo(routeInfo, this.id);
1559
+ let leavingViewItem = this.context.findLeavingViewItemByRouteInfo(routeInfo, this.id);
1560
+ // Try to find leaving view by previous pathname
1561
+ if (!leavingViewItem && routeInfo.prevRouteLastPathname) {
1562
+ leavingViewItem = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1563
+ }
1564
+ // For redirects where entering === leaving, find the actual previous view
1565
+ if (enteringViewItem &&
1566
+ leavingViewItem &&
1567
+ enteringViewItem === leavingViewItem &&
1568
+ routeInfo.routeAction === 'replace' &&
1569
+ routeInfo.prevRouteLastPathname) {
1570
+ const actualLeavingView = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1571
+ if (actualLeavingView && actualLeavingView !== enteringViewItem) {
1572
+ leavingViewItem = actualLeavingView;
1573
+ }
1574
+ }
1575
+ // Handle redirect scenario with no leaving view
1576
+ if (enteringViewItem &&
1577
+ !leavingViewItem &&
1578
+ routeInfo.routeAction === 'replace' &&
1579
+ routeInfo.prevRouteLastPathname) {
1580
+ const actualLeavingView = this.context.findViewItemByPathname(routeInfo.prevRouteLastPathname, this.id);
1581
+ if (actualLeavingView && actualLeavingView !== enteringViewItem) {
1582
+ leavingViewItem = actualLeavingView;
1583
+ }
1584
+ }
1585
+ return { enteringViewItem, leavingViewItem };
1586
+ }
1587
+ shouldUnmountLeavingView(routeInfo, enteringViewItem, leavingViewItem) {
1588
+ var _a, _b;
1589
+ if (!leavingViewItem) {
1590
+ return false;
1591
+ }
1592
+ if (routeInfo.routeAction === 'replace') {
1593
+ const leavingRoutePath = (_b = (_a = leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1594
+ // Never unmount root path or views without a path - needed for back navigation
1595
+ if (!leavingRoutePath || leavingRoutePath === '/' || leavingRoutePath === '') {
1596
+ return false;
1597
+ }
1598
+ // Replace actions unmount the leaving view since it's being replaced in history.
1599
+ return true;
1600
+ }
1601
+ // For non-replace actions, only unmount for back navigation
1602
+ const isForwardPush = routeInfo.routeAction === 'push' && routeInfo.routeDirection === 'forward';
1603
+ if (!isForwardPush && routeInfo.routeDirection !== 'none' && enteringViewItem !== leavingViewItem) {
1604
+ return true;
1605
+ }
1606
+ return false;
1607
+ }
1608
+ /**
1609
+ * Handles out-of-scope outlet. Returns true if transition should be aborted.
1610
+ */
1611
+ handleOutOfScopeOutlet(routeInfo) {
1612
+ var _a, _b, _c;
1613
+ if (!this.outletMountPath || isPathnameInScope(routeInfo.pathname, this.outletMountPath)) {
1614
+ this.wasInScope = true;
1615
+ // Cancel any pending deferred unmount from a previous out-of-scope transition.
1616
+ if (this.outOfScopeUnmountTimeout) {
1617
+ clearTimeout(this.outOfScopeUnmountTimeout);
1618
+ this.outOfScopeUnmountTimeout = undefined;
1619
+ }
1620
+ return false;
1621
+ }
1622
+ // Only run the out-of-scope cleanup on the first transition out of scope.
1623
+ // When parameterized routes create multiple StackManager instances with the
1624
+ // same outlet ID, a stale (hidden) instance must not destroy views that an
1625
+ // active instance just created. After the initial cleanup, the stale instance
1626
+ // stays dormant until its mount path becomes in-scope again.
1627
+ if (!this.wasInScope) {
1628
+ return true;
1629
+ }
1630
+ this.wasInScope = false;
1631
+ // For ionPage outlets whose parent outlet has swipe-to-go-back enabled,
1632
+ // preserve child views so they remain visible during the swipe gesture.
1633
+ // Without this, the deferred unmount removes child pages before the gesture
1634
+ // starts, showing an empty shell when swiping back. Views are cleaned up
1635
+ // when the parent outlet pops this view (componentWillUnmount -> clearOutlet).
1636
+ //
1637
+ // Lifecycle events are skipped in this branch because the view stays mounted
1638
+ // and visible. Firing ionViewWillLeave/DidLeave here would be asymmetric with
1639
+ // no matching ionViewWillEnter/DidEnter when the view comes back in scope.
1640
+ const isIonPageOutlet = (_a = this.routerOutletElement) === null || _a === void 0 ? void 0 : _a.classList.contains('ion-page');
1641
+ if (isIonPageOutlet) {
1642
+ const parentOutlet = (_c = (_b = this.routerOutletElement) === null || _b === void 0 ? void 0 : _b.parentElement) === null || _c === void 0 ? void 0 : _c.closest('ion-router-outlet');
1643
+ if ((parentOutlet === null || parentOutlet === void 0 ? void 0 : parentOutlet.swipeGesture) === true) {
1644
+ this.dismissPresentedOverlays();
1645
+ return true;
1646
+ }
1647
+ }
1648
+ // Fire lifecycle events on any visible view before unmounting.
1649
+ // When navigating away from a tabbed section, the parent outlet fires
1650
+ // ionViewDidLeave on the tabs container, but the active tab child page
1651
+ // never receives its own lifecycle events because the core transition
1652
+ // dispatches events with bubbles:false. This ensures tab child pages
1653
+ // get ionViewWillLeave/ionViewDidLeave so useIonViewDidLeave fires.
1654
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
1655
+ allViewsInOutlet.forEach((viewItem) => {
1656
+ if (viewItem.ionPageElement && isViewVisible(viewItem.ionPageElement)) {
1657
+ viewItem.ionPageElement.dispatchEvent(new CustomEvent('ionViewWillLeave', { bubbles: false, cancelable: false }));
1658
+ viewItem.ionPageElement.dispatchEvent(new CustomEvent('ionViewDidLeave', { bubbles: false, cancelable: false }));
1659
+ }
1660
+ });
1661
+ // Defer removal of view items to allow the parent outlet's leaving-page
1662
+ // animation to complete with content still visible. When the nested outlet
1663
+ // unmounts views immediately, React removes the child DOM elements before
1664
+ // the parent's transition animation can render them. On MD mode the back
1665
+ // animation only animates the leaving page (slide down + fade), so an
1666
+ // empty shell is invisible and the transition appears instant.
1667
+ //
1668
+ // VIEW_UNMOUNT_DELAY_MS exceeds the MD back transition (200ms).
1669
+ this.outOfScopeUnmountTimeout = setTimeout(() => {
1670
+ if (!this._isMounted)
1671
+ return;
1672
+ allViewsInOutlet.forEach((viewItem) => {
1673
+ this.context.unMountViewItem(viewItem);
1674
+ });
1675
+ this.forceUpdate();
1676
+ }, VIEW_UNMOUNT_DELAY_MS);
1677
+ return true;
1678
+ }
1679
+ /**
1680
+ * Handles root navigation by unmounting all non-entering views in this outlet.
1681
+ * Fires ionViewWillLeave / ionViewDidLeave only on views that are currently visible.
1682
+ * Views that are mounted but not visible (e.g., pages earlier in the back stack)
1683
+ * are silently unmounted without lifecycle events, consistent with the behavior
1684
+ * of out-of-scope outlet cleanup.
1685
+ */
1686
+ handleRootNavigation(enteringViewItem) {
1687
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
1688
+ allViewsInOutlet.forEach((viewItem) => {
1689
+ if (viewItem === enteringViewItem) {
1690
+ return;
1691
+ }
1692
+ if (viewItem.ionPageElement && isViewVisible(viewItem.ionPageElement)) {
1693
+ viewItem.ionPageElement.dispatchEvent(new CustomEvent('ionViewWillLeave', { bubbles: false, cancelable: false }));
1694
+ viewItem.ionPageElement.dispatchEvent(new CustomEvent('ionViewDidLeave', { bubbles: false, cancelable: false }));
1695
+ }
1696
+ this.context.unMountViewItem(viewItem);
1697
+ });
1698
+ }
1699
+ /**
1700
+ * Handles nested outlet with relative routes but no parent path. Returns true to abort.
1701
+ */
1702
+ handleOutOfContextNestedOutlet(parentPath, leavingViewItem) {
1703
+ var _a;
1704
+ if (this.isRootOutlet || parentPath !== undefined || !this.ionRouterOutlet) {
1705
+ return false;
1706
+ }
1707
+ const routesChildren = (_a = getRoutesChildren(this.ionRouterOutlet.props.children)) !== null && _a !== void 0 ? _a : this.ionRouterOutlet.props.children;
1708
+ const routeChildren = React.Children.toArray(routesChildren).filter((child) => React.isValidElement(child) && (child.type === Route || child.type === IonRoute));
1709
+ const hasRelativeRoutes = routeChildren.some((route) => {
1710
+ const path = route.props.path;
1711
+ return path && !path.startsWith('/') && path !== '*';
1712
+ });
1713
+ if (hasRelativeRoutes) {
1714
+ hideIonPageElement(leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement);
1715
+ if (leavingViewItem) {
1716
+ leavingViewItem.mount = false;
1717
+ }
1718
+ this.forceUpdate();
1719
+ return true;
1720
+ }
1721
+ return false;
1722
+ }
1723
+ /**
1724
+ * Handles nested outlet with no matching route. Returns true to abort.
1725
+ */
1726
+ handleNoMatchingRoute(enteringRoute, enteringViewItem, leavingViewItem) {
1727
+ if (this.isRootOutlet || enteringRoute || enteringViewItem) {
1728
+ return false;
1729
+ }
1730
+ hideIonPageElement(leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement);
1731
+ if (leavingViewItem) {
1732
+ leavingViewItem.mount = false;
1733
+ }
1734
+ this.forceUpdate();
1735
+ return true;
1736
+ }
1737
+ /**
1738
+ * Handles transition when entering view has ion-page element ready.
1739
+ */
1740
+ handleReadyEnteringView(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem) {
1741
+ var _a, _b;
1742
+ const routePath = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1743
+ const isParameterizedRoute = routePath ? routePath.includes(':') : false;
1744
+ const isWildcardContainerRoute = routePath ? routePath.endsWith('/*') : false;
1745
+ // Handle same-view transitions (parameterized routes like /user/:id or container routes like /tabs/*)
1746
+ // When entering === leaving, the view is already visible - skip transition to prevent flash
1747
+ if (enteringViewItem === leavingViewItem) {
1748
+ if (isParameterizedRoute || isWildcardContainerRoute) {
1749
+ const updatedMatch = matchComponent(enteringViewItem.reactElement, routeInfo.pathname, true, this.outletMountPath);
1750
+ if (updatedMatch) {
1751
+ enteringViewItem.routeData.match = updatedMatch;
1752
+ }
1753
+ const enteringEl = enteringViewItem.ionPageElement;
1754
+ if (enteringEl) {
1755
+ showIonPageElement(enteringEl);
1756
+ enteringEl.classList.remove('ion-page-invisible');
1757
+ // Maintain can-go-back state since we skip transitionPage/commit.
1758
+ // Without this, the back button disappears on re-navigation to a
1759
+ // parameterized route within a nested outlet (e.g. welcome -> item -> back -> item).
1760
+ if (routeInfo.pushedByRoute) {
1761
+ enteringEl.classList.add('can-go-back');
1762
+ }
1763
+ else {
1764
+ enteringEl.classList.remove('can-go-back');
1765
+ }
1766
+ }
1767
+ this.forceUpdate();
1768
+ return;
1769
+ }
1770
+ }
1771
+ // For wildcard container routes, check if we're navigating within the same container.
1772
+ // If both the current pathname and the previous pathname match the same container route,
1773
+ // skip the transition - the nested outlet will handle the actual page change.
1774
+ // This handles cases where leavingViewItem lookup fails (e.g., no IonPage wrapper).
1775
+ if (isWildcardContainerRoute && routeInfo.lastPathname) {
1776
+ // routePath is guaranteed to exist since isWildcardContainerRoute checks routePath?.endsWith('/*')
1777
+ const containerBase = routePath.replace(/\/\*$/, '');
1778
+ const currentInContainer = routeInfo.pathname.startsWith(containerBase + '/') || routeInfo.pathname === containerBase;
1779
+ const previousInContainer = routeInfo.lastPathname.startsWith(containerBase + '/') || routeInfo.lastPathname === containerBase;
1780
+ if (currentInContainer && previousInContainer) {
1781
+ const updatedMatch = matchComponent(enteringViewItem.reactElement, routeInfo.pathname, true, this.outletMountPath);
1782
+ if (updatedMatch) {
1783
+ enteringViewItem.routeData.match = updatedMatch;
1784
+ }
1785
+ this.forceUpdate();
1786
+ return;
1787
+ }
1788
+ }
1789
+ if (!leavingViewItem && this.props.routeInfo.prevRouteLastPathname) {
1790
+ leavingViewItem = this.context.findViewItemByPathname(this.props.routeInfo.prevRouteLastPathname, this.id);
1791
+ }
1792
+ // Re-mount views that were previously unmounted (e.g., navigating back to home)
1793
+ if (!enteringViewItem.mount) {
1794
+ enteringViewItem.mount = true;
1795
+ }
1796
+ // A view that becomes the entering view is no longer a stale preserved view.
1797
+ // It's back in the active navigation path, so drop it from the cleanup set.
1798
+ this.preservedViewItems.delete(enteringViewItem);
1799
+ // Check visibility state BEFORE showing entering view
1800
+ const enteringWasVisible = enteringViewItem.ionPageElement && isViewVisible(enteringViewItem.ionPageElement);
1801
+ const leavingIsHidden = leavingViewItem !== undefined && leavingViewItem.ionPageElement && !isViewVisible(leavingViewItem.ionPageElement);
1802
+ const currentTransition = {
1803
+ enteringId: enteringViewItem.id,
1804
+ leavingId: leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.id,
1805
+ };
1806
+ const isDuplicateTransition = leavingViewItem &&
1807
+ this.lastTransition &&
1808
+ this.lastTransition.leavingId &&
1809
+ this.lastTransition.enteringId === currentTransition.enteringId &&
1810
+ this.lastTransition.leavingId === currentTransition.leavingId;
1811
+ // Skip if transition already performed (e.g., via swipe gesture)
1812
+ if (enteringWasVisible && leavingIsHidden && isDuplicateTransition) {
1813
+ if (this.skipTransition &&
1814
+ shouldUnmountLeavingViewItem &&
1815
+ leavingViewItem &&
1816
+ enteringViewItem !== leavingViewItem) {
1817
+ leavingViewItem.mount = false;
1818
+ // Trigger ionViewDidLeave lifecycle for ViewLifeCycleManager cleanup
1819
+ this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, 'back');
1820
+ }
1821
+ this.skipTransition = false;
1822
+ this.forceUpdate();
1823
+ return;
1824
+ }
1825
+ showIonPageElement(enteringViewItem.ionPageElement);
1826
+ // Handle duplicate transition or swipe gesture completion
1827
+ if (isDuplicateTransition || this.skipTransition) {
1828
+ if (this.skipTransition &&
1829
+ shouldUnmountLeavingViewItem &&
1830
+ leavingViewItem &&
1831
+ enteringViewItem !== leavingViewItem) {
1832
+ leavingViewItem.mount = false;
1833
+ // Re-fire ionViewDidLeave since gesture completed before mount=false was set
1834
+ this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, 'back');
1835
+ }
1836
+ this.skipTransition = false;
1837
+ this.forceUpdate();
1838
+ return;
1839
+ }
1840
+ this.lastTransition = currentTransition;
1841
+ const shouldSkipAnimation = this.applySkipAnimationIfNeeded(enteringViewItem, leavingViewItem);
1842
+ this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, undefined, false, shouldSkipAnimation);
1843
+ if (shouldUnmountLeavingViewItem && leavingViewItem && enteringViewItem !== leavingViewItem) {
1844
+ // For replace actions, skip setting mount=false here. handleLeavingViewUnmount
1845
+ // sets it only after its container-to-container guard passes, avoiding zombie state.
1846
+ //
1847
+ // For pop (browser back) on preservable routes (see isViewItemPreservableOnPop),
1848
+ // keep the view alive (hidden by the transition) so its React state survives a
1849
+ // forward-pop round-trip. ionViewDidLeave already fired via the transitionPage()
1850
+ // call above. Swipe-to-go-back still destroys views through the skipTransition
1851
+ // path earlier in this method, matching native gesture behavior.
1852
+ //
1853
+ // handleLeavingViewUnmount below is a no-op for non-replace actions (early return),
1854
+ // so pop-preserved views pass through it untouched.
1855
+ const shouldPreserveLeavingView = routeInfo.routeAction === 'pop' && isViewItemPreservableOnPop(leavingViewItem);
1856
+ if (routeInfo.routeAction !== 'replace' && !shouldPreserveLeavingView) {
1857
+ leavingViewItem.mount = false;
1858
+ }
1859
+ else if (shouldPreserveLeavingView) {
1860
+ this.preservedViewItems.add(leavingViewItem);
1861
+ }
1862
+ this.handleLeavingViewUnmount(routeInfo, enteringViewItem, leavingViewItem);
1863
+ }
1864
+ // Clean up orphaned sibling views after replace actions (redirects)
1865
+ this.cleanupOrphanedSiblingViews(routeInfo, enteringViewItem, leavingViewItem);
1866
+ // On a fresh push, browser forward history is invalidated. Any views we
1867
+ // previously preserved on pop (to support forward navigation) are now
1868
+ // unreachable and should be unmounted so they don't accumulate in the DOM.
1869
+ this.cleanupPreservedViewsOnPush(routeInfo, enteringViewItem, leavingViewItem);
1870
+ }
1871
+ /**
1872
+ * Unmounts views previously kept alive by the pop-preserve logic when a fresh
1873
+ * push invalidates the forward-history path that made them reachable. Only
1874
+ * iterates views explicitly tracked in `preservedViewItems` so that views
1875
+ * naturally mounted through forward-push (the default leaving-view behavior)
1876
+ * are left untouched.
1877
+ */
1878
+ cleanupPreservedViewsOnPush(routeInfo, enteringViewItem, leavingViewItem) {
1879
+ if (routeInfo.routeAction !== 'push') {
1880
+ return;
1881
+ }
1882
+ if (this.preservedViewItems.size === 0) {
1883
+ return;
1884
+ }
1885
+ for (const viewItem of Array.from(this.preservedViewItems)) {
1886
+ if (viewItem === enteringViewItem || viewItem === leavingViewItem) {
1887
+ this.preservedViewItems.delete(viewItem);
1888
+ continue;
1889
+ }
1890
+ if (!viewItem.mount) {
1891
+ this.preservedViewItems.delete(viewItem);
1892
+ continue;
13
1893
  }
14
- : {}))));
1894
+ viewItem.mount = false;
1895
+ this.preservedViewItems.delete(viewItem);
1896
+ const viewToUnmount = viewItem;
1897
+ setTimeout(() => {
1898
+ // Skip if a follow-up transition re-entered the view (mount flipped back to true).
1899
+ if (viewToUnmount.mount) {
1900
+ return;
1901
+ }
1902
+ this.context.unMountViewItem(viewToUnmount);
1903
+ this.forceUpdate();
1904
+ }, VIEW_UNMOUNT_DELAY_MS);
1905
+ }
15
1906
  }
16
- }
17
-
18
- /**
19
- * @see https://v5.reactrouter.com/web/api/matchPath
20
- */
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 }`.
1907
+ /**
1908
+ * Handles leaving view unmount for replace actions.
28
1909
  */
29
- const matchProps = {
30
- exact,
31
- path,
32
- component,
33
- };
34
- const match = matchPath$1(pathname, matchProps);
35
- if (!match) {
36
- return false;
1910
+ handleLeavingViewUnmount(routeInfo, enteringViewItem, leavingViewItem) {
1911
+ var _a, _b, _c, _d, _e, _f;
1912
+ // Only replace actions unmount views; push/pop cache for navigation history
1913
+ if (routeInfo.routeAction !== 'replace') {
1914
+ return;
1915
+ }
1916
+ if (!leavingViewItem.ionPageElement) {
1917
+ leavingViewItem.mount = false;
1918
+ const viewToUnmount = leavingViewItem;
1919
+ setTimeout(() => {
1920
+ // Skip if a follow-up transition re-entered the view (mount flipped back to true).
1921
+ if (viewToUnmount.mount) {
1922
+ return;
1923
+ }
1924
+ this.context.unMountViewItem(viewToUnmount);
1925
+ this.forceUpdate();
1926
+ }, VIEW_UNMOUNT_DELAY_MS);
1927
+ return;
1928
+ }
1929
+ const enteringRoutePath = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1930
+ const leavingRoutePath = (_d = (_c = leavingViewItem.reactElement) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.path;
1931
+ const isEnteringContainerRoute = enteringRoutePath && enteringRoutePath.endsWith('/*');
1932
+ const isLeavingSpecificRoute = leavingRoutePath &&
1933
+ leavingRoutePath !== '' &&
1934
+ leavingRoutePath !== '*' &&
1935
+ !leavingRoutePath.endsWith('/*') &&
1936
+ !((_f = (_e = leavingViewItem.reactElement) === null || _e === void 0 ? void 0 : _e.props) === null || _f === void 0 ? void 0 : _f.index);
1937
+ // Skip removal for container-to-container transitions (e.g., /tabs/* → /settings/*).
1938
+ // These routes manage their own nested outlets; unmounting would disrupt child views.
1939
+ if (isEnteringContainerRoute && !isLeavingSpecificRoute) {
1940
+ return;
1941
+ }
1942
+ leavingViewItem.mount = false;
1943
+ const viewToUnmount = leavingViewItem;
1944
+ setTimeout(() => {
1945
+ // Skip if a follow-up transition re-entered the view (mount flipped back to true).
1946
+ if (viewToUnmount.mount) {
1947
+ return;
1948
+ }
1949
+ this.context.unMountViewItem(viewToUnmount);
1950
+ this.forceUpdate();
1951
+ }, VIEW_UNMOUNT_DELAY_MS);
37
1952
  }
38
- return match;
39
- };
40
-
41
- class ReactRouterViewStack extends ViewStacks {
42
- constructor() {
43
- 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,
1953
+ /**
1954
+ * Cleans up orphaned sibling views after replace actions or push-to-container navigations.
1955
+ */
1956
+ cleanupOrphanedSiblingViews(routeInfo, enteringViewItem, leavingViewItem) {
1957
+ var _a, _b, _c, _d, _e, _f, _g;
1958
+ const enteringRoutePath = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.path;
1959
+ if (!enteringRoutePath) {
1960
+ return;
1961
+ }
1962
+ 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;
1963
+ const isContainerRoute = (path) => path === null || path === void 0 ? void 0 : path.endsWith('/*');
1964
+ const isReplaceAction = routeInfo.routeAction === 'replace';
1965
+ const isPushToContainer = routeInfo.routeAction === 'push' && routeInfo.routeDirection === 'none' && isContainerRoute(enteringRoutePath);
1966
+ if (!isReplaceAction && !isPushToContainer) {
1967
+ return;
1968
+ }
1969
+ // Skip cleanup for tab switches
1970
+ const isSameView = enteringViewItem === leavingViewItem;
1971
+ const isSameContainerRoute = isContainerRoute(enteringRoutePath) && leavingRoutePath === enteringRoutePath;
1972
+ const isNavigatingWithinContainer = isPushToContainer &&
1973
+ !leavingViewItem &&
1974
+ ((_e = routeInfo.prevRouteLastPathname) === null || _e === void 0 ? void 0 : _e.startsWith(enteringRoutePath.replace(/\/\*$/, '')));
1975
+ if (isSameView || isSameContainerRoute || isNavigatingWithinContainer) {
1976
+ return;
1977
+ }
1978
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
1979
+ const areSiblingRoutes = (path1, path2) => {
1980
+ const path1IsRelative = !path1.startsWith('/');
1981
+ const path2IsRelative = !path2.startsWith('/');
1982
+ if (path1IsRelative && path2IsRelative) {
1983
+ const path1Depth = path1.replace(/\/\*$/, '').split('/').filter(Boolean).length;
1984
+ const path2Depth = path2.replace(/\/\*$/, '').split('/').filter(Boolean).length;
1985
+ return path1Depth === path2Depth && path1Depth <= 1;
1986
+ }
1987
+ const getParent = (path) => {
1988
+ const normalized = path.replace(/\/\*$/, '');
1989
+ const segments = normalized.split('/').filter(Boolean);
1990
+ // Strip trailing parameter segments (e.g., :id) so that
1991
+ // sibling routes like /items/list/:id and /items/detail/:id
1992
+ // resolve to the same parent (/items).
1993
+ while (segments.length > 0 && segments[segments.length - 1].startsWith(':')) {
1994
+ segments.pop();
1995
+ }
1996
+ segments.pop();
1997
+ return segments.length > 0 ? '/' + segments.join('/') : '/';
1998
+ };
1999
+ const parent = getParent(path1);
2000
+ // Exclude root-level routes from sibling detection to avoid unintended
2001
+ // cleanup of unrelated top-level routes. Also covers single-depth param
2002
+ // routes (e.g., /items/:id) which resolve to root after param stripping.
2003
+ if (parent === '/') {
2004
+ return false;
2005
+ }
2006
+ return parent === getParent(path2);
69
2007
  };
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);
78
- });
79
- if (viewItem) {
80
- viewItem.reactElement = child;
2008
+ for (const viewItem of allViewsInOutlet) {
2009
+ const viewRoutePath = (_g = (_f = viewItem.reactElement) === null || _f === void 0 ? void 0 : _f.props) === null || _g === void 0 ? void 0 : _g.path;
2010
+ const shouldSkip = viewItem.id === enteringViewItem.id ||
2011
+ (leavingViewItem && viewItem.id === leavingViewItem.id) ||
2012
+ !viewItem.mount ||
2013
+ !viewRoutePath ||
2014
+ // Don't clean up container routes when entering a container route
2015
+ // (e.g., /tabs/* and /settings/* coexist for tab switching)
2016
+ (viewRoutePath.endsWith('/*') && enteringRoutePath.endsWith('/*'));
2017
+ if (shouldSkip) {
2018
+ continue;
81
2019
  }
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
- })));
2020
+ const isOrphanedSpecificRoute = !viewRoutePath.endsWith('/*');
2021
+ // Clean up sibling non-container routes that are no longer reachable.
2022
+ let shouldCleanup = false;
2023
+ if ((isReplaceAction || isPushToContainer) && isOrphanedSpecificRoute) {
2024
+ shouldCleanup = areSiblingRoutes(enteringRoutePath, viewRoutePath);
89
2025
  }
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;
97
- viewItem.mount = false;
98
- }
2026
+ if (shouldCleanup) {
2027
+ hideIonPageElement(viewItem.ionPageElement);
2028
+ viewItem.mount = false;
2029
+ const viewToRemove = viewItem;
2030
+ setTimeout(() => {
2031
+ // Skip if a follow-up transition re-entered the view (mount flipped back to true).
2032
+ if (viewToRemove.mount) {
2033
+ return;
2034
+ }
2035
+ this.context.unMountViewItem(viewToRemove);
2036
+ this.forceUpdate();
2037
+ }, VIEW_UNMOUNT_DELAY_MS);
99
2038
  }
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
2039
  }
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;
119
2040
  }
120
2041
  /**
121
- * Returns the matching view item and the match result for a given pathname.
2042
+ * Determines whether to skip the transition animation and, if so, immediately
2043
+ * hides the leaving view with inline `visibility:hidden`.
2044
+ *
2045
+ * Skips transitions only for outlets nested inside a parent IonPage's content
2046
+ * area (i.e., an ion-content sits between the outlet and the .ion-page). These
2047
+ * outlets render child pages inside a parent page's scrollable area, and the MD
2048
+ * animation shows both entering and leaving pages simultaneously — causing text
2049
+ * overlap and nested scrollbars. Standard page-level outlets (tabs, routing,
2050
+ * swipe-to-go-back) animate normally even though they sit inside a framework-
2051
+ * managed .ion-page wrapper from the parent outlet's view stack.
2052
+ *
2053
+ * Uses inline visibility:hidden rather than ion-page-hidden class because
2054
+ * core's beforeTransition() removes ion-page-hidden via setPageHidden().
2055
+ * Inline visibility:hidden survives that removal, keeping the page hidden
2056
+ * until React unmounts it after ionViewDidLeave fires. Unlike display:none,
2057
+ * visibility:hidden preserves element geometry so commit() animations
2058
+ * can resolve normally.
122
2059
  */
123
- findViewItemByPath(pathname, outletId, mustBeIonRoute) {
124
- let viewItem;
125
- let match;
126
- let viewStack;
127
- if (outletId) {
128
- viewStack = this.getViewItemsForOutlet(outletId);
129
- viewStack.some(matchView);
130
- if (!viewItem) {
131
- viewStack.some(matchDefaultRoute);
2060
+ applySkipAnimationIfNeeded(enteringViewItem, leavingViewItem) {
2061
+ var _a, _b;
2062
+ // Only skip for outlets genuinely nested inside a page's content area.
2063
+ // Walk from the outlet up to the nearest .ion-page; if an ion-content
2064
+ // sits in between, the outlet is inside scrollable page content and
2065
+ // animating would cause overlapping pages with duplicate scrollbars.
2066
+ let isInsidePageContent = false;
2067
+ let el = (_b = (_a = this.routerOutletElement) === null || _a === void 0 ? void 0 : _a.parentElement) !== null && _b !== void 0 ? _b : null;
2068
+ while (el) {
2069
+ if (el.classList.contains('ion-page'))
2070
+ break;
2071
+ if (el.tagName === 'ION-CONTENT') {
2072
+ isInsidePageContent = true;
2073
+ break;
132
2074
  }
2075
+ el = el.parentElement;
133
2076
  }
134
- else {
135
- const viewItems = this.getAllViewItems();
136
- viewItems.some(matchView);
137
- if (!viewItem) {
138
- viewItems.some(matchDefaultRoute);
139
- }
2077
+ const shouldSkip = isInsidePageContent && !!leavingViewItem && enteringViewItem !== leavingViewItem;
2078
+ if (shouldSkip && (leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement)) {
2079
+ leavingViewItem.ionPageElement.style.setProperty('visibility', 'hidden');
2080
+ leavingViewItem.ionPageElement.setAttribute('aria-hidden', 'true');
140
2081
  }
141
- return { viewItem, match };
142
- function matchView(v) {
143
- var _a, _b;
144
- if (mustBeIonRoute && !v.ionRoute) {
145
- return false;
2082
+ return shouldSkip;
2083
+ }
2084
+ /**
2085
+ * Handles entering view with no ion-page element yet (waiting for render).
2086
+ */
2087
+ handleWaitingForIonPage(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem) {
2088
+ var _a, _b;
2089
+ const enteringRouteElement = (_b = (_a = enteringViewItem.reactElement) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.element;
2090
+ // Handle Navigate components (they never render an IonPage)
2091
+ if (isNavigateElement(enteringRouteElement)) {
2092
+ this.waitingForIonPage = false;
2093
+ if (this.ionPageWaitTimeout) {
2094
+ clearTimeout(this.ionPageWaitTimeout);
2095
+ this.ionPageWaitTimeout = undefined;
146
2096
  }
147
- match = matchPath({
148
- pathname,
149
- componentProps: v.routeData.childProps,
2097
+ this.pendingPageTransition = false;
2098
+ // Hide ALL other visible views in this outlet for Navigate redirects.
2099
+ // Same rationale as the timeout path: intermediate redirects can shift
2100
+ // the leaving view reference, leaving the original page visible.
2101
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
2102
+ allViewsInOutlet.forEach((viewItem) => {
2103
+ if (viewItem.id !== enteringViewItem.id && viewItem.ionPageElement) {
2104
+ hideIonPageElement(viewItem.ionPageElement);
2105
+ }
150
2106
  });
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))) {
160
- viewItem = v;
161
- return true;
2107
+ // Don't unmount if entering and leaving are the same view item
2108
+ if (shouldUnmountLeavingViewItem && leavingViewItem && enteringViewItem !== leavingViewItem) {
2109
+ const shouldPreserveLeavingView = routeInfo.routeAction === 'pop' && isViewItemPreservableOnPop(leavingViewItem);
2110
+ if (routeInfo.routeAction !== 'replace' && !shouldPreserveLeavingView) {
2111
+ leavingViewItem.mount = false;
162
2112
  }
2113
+ else if (shouldPreserveLeavingView) {
2114
+ this.preservedViewItems.add(leavingViewItem);
2115
+ }
2116
+ this.handleLeavingViewUnmount(routeInfo, enteringViewItem, leavingViewItem);
163
2117
  }
164
- return false;
165
- }
166
- 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) {
169
- match = {
170
- path: pathname,
171
- url: pathname,
172
- isExact: true,
173
- params: {},
174
- };
175
- viewItem = v;
176
- return true;
177
- }
178
- return false;
2118
+ this.cleanupPreservedViewsOnPush(routeInfo, enteringViewItem, leavingViewItem);
2119
+ this.forceUpdate();
2120
+ return;
179
2121
  }
180
- }
181
- }
182
- function matchComponent$1(node, pathname) {
183
- return matchPath({
184
- pathname,
185
- componentProps: node.props,
186
- });
187
- }
188
-
189
- function clonePageElement(leavingViewHtml) {
190
- let html;
191
- if (typeof leavingViewHtml === 'string') {
192
- html = leavingViewHtml;
193
- }
194
- else {
195
- html = leavingViewHtml.outerHTML;
196
- }
197
- if (document) {
198
- const newEl = document.createElement('div');
199
- newEl.innerHTML = html;
200
- newEl.style.zIndex = '';
201
- // Remove an existing back button so the new element doesn't get two of them
202
- const ionBackButton = newEl.getElementsByTagName('ion-back-button');
203
- if (ionBackButton[0]) {
204
- ionBackButton[0].remove();
2122
+ // Do not hide the leaving view here - wait until the entering view is ready.
2123
+ // Hiding the leaving view while the entering view is still mounting causes a flash
2124
+ // where both views are hidden/invisible simultaneously.
2125
+ // The leaving view will be hidden in transitionPage() after the entering view is visible.
2126
+ this.waitingForIonPage = true;
2127
+ if (this.ionPageWaitTimeout) {
2128
+ clearTimeout(this.ionPageWaitTimeout);
205
2129
  }
206
- return newEl.firstChild;
2130
+ this.ionPageWaitTimeout = setTimeout(() => {
2131
+ var _a, _b;
2132
+ this.ionPageWaitTimeout = undefined;
2133
+ if (!this.waitingForIonPage) {
2134
+ return;
2135
+ }
2136
+ this.waitingForIonPage = false;
2137
+ const latestEnteringView = (_a = this.context.findViewItemByRouteInfo(routeInfo, this.id)) !== null && _a !== void 0 ? _a : enteringViewItem;
2138
+ const latestLeavingView = (_b = this.context.findLeavingViewItemByRouteInfo(routeInfo, this.id)) !== null && _b !== void 0 ? _b : leavingViewItem;
2139
+ if (latestEnteringView === null || latestEnteringView === void 0 ? void 0 : latestEnteringView.ionPageElement) {
2140
+ const shouldSkipAnimation = this.applySkipAnimationIfNeeded(latestEnteringView, latestLeavingView !== null && latestLeavingView !== void 0 ? latestLeavingView : undefined);
2141
+ this.transitionPage(routeInfo, latestEnteringView, latestLeavingView !== null && latestLeavingView !== void 0 ? latestLeavingView : undefined, undefined, false, shouldSkipAnimation);
2142
+ if (shouldUnmountLeavingViewItem && latestLeavingView && latestEnteringView !== latestLeavingView) {
2143
+ const shouldPreserveLeavingView = routeInfo.routeAction === 'pop' && isViewItemPreservableOnPop(latestLeavingView);
2144
+ if (routeInfo.routeAction !== 'replace' && !shouldPreserveLeavingView) {
2145
+ latestLeavingView.mount = false;
2146
+ }
2147
+ else if (shouldPreserveLeavingView) {
2148
+ this.preservedViewItems.add(latestLeavingView);
2149
+ }
2150
+ this.handleLeavingViewUnmount(routeInfo, latestEnteringView, latestLeavingView);
2151
+ }
2152
+ this.cleanupPreservedViewsOnPush(routeInfo, latestEnteringView, latestLeavingView !== null && latestLeavingView !== void 0 ? latestLeavingView : undefined);
2153
+ this.forceUpdate();
2154
+ }
2155
+ else {
2156
+ /**
2157
+ * Timeout fired and entering view still has no ionPageElement.
2158
+ * This happens for container routes that render nested outlets without a direct IonPage.
2159
+ * Hide ALL other visible views in this outlet, not just the computed leaving view.
2160
+ * This handles cases where intermediate redirects (e.g., Navigate in nested routes)
2161
+ * change the leaving view reference, leaving the original page still visible.
2162
+ */
2163
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
2164
+ allViewsInOutlet.forEach((viewItem) => {
2165
+ if (viewItem.id !== latestEnteringView.id && viewItem.ionPageElement) {
2166
+ hideIonPageElement(viewItem.ionPageElement);
2167
+ }
2168
+ });
2169
+ this.forceUpdate();
2170
+ // Safety net: after forceUpdate triggers a React render cycle, check if
2171
+ // any pages in this outlet are stuck with ion-page-invisible. This can
2172
+ // happen when view lookup fails (e.g., wildcard-to-index transitions
2173
+ // where the view item gets corrupted). The forceUpdate above causes
2174
+ // React to render the correct component, but ion-page-invisible may
2175
+ // persist if no transition runs for that page.
2176
+ setTimeout(() => {
2177
+ if (!this._isMounted || !this.routerOutletElement)
2178
+ return;
2179
+ const stuckPages = this.routerOutletElement.querySelectorAll(':scope > .ion-page-invisible');
2180
+ stuckPages.forEach((page) => {
2181
+ page.classList.remove('ion-page-invisible');
2182
+ });
2183
+ }, ION_PAGE_WAIT_TIMEOUT_MS);
2184
+ }
2185
+ }, ION_PAGE_WAIT_TIMEOUT_MS);
2186
+ this.forceUpdate();
207
2187
  }
208
- return undefined;
209
- }
210
-
211
- const isViewVisible = (el) => !el.classList.contains('ion-page-invisible') && !el.classList.contains('ion-page-hidden');
212
- class StackManager extends React.PureComponent {
213
- constructor(props) {
214
- super(props);
215
- this.stackContextValue = {
216
- registerIonPage: this.registerIonPage.bind(this),
217
- isInOutlet: () => true,
218
- };
219
- this.pendingPageTransition = false;
220
- this.registerIonPage = this.registerIonPage.bind(this);
221
- this.transitionPage = this.transitionPage.bind(this);
222
- this.handlePageTransition = this.handlePageTransition.bind(this);
223
- this.id = generateId('routerOutlet');
224
- this.prevProps = undefined;
225
- this.skipTransition = false;
2188
+ /**
2189
+ * Gets the route info to use for finding views during swipe-to-go-back gestures.
2190
+ * This pattern is used in multiple places in setupRouterOutlet.
2191
+ */
2192
+ getSwipeBackRouteInfo() {
2193
+ const { routeInfo } = this.props;
2194
+ return this.prevProps && this.prevProps.routeInfo.pathname === routeInfo.pushedByRoute
2195
+ ? this.prevProps.routeInfo
2196
+ : { pathname: routeInfo.pushedByRoute || '' };
226
2197
  }
227
2198
  componentDidMount() {
228
- if (this.clearOutletTimeout) {
229
- /**
230
- * The clearOutlet integration with React Router is a bit hacky.
231
- * It uses a timeout to clear the outlet after a transition.
232
- * In React v18, components are mounted and unmounted in development mode
233
- * to check for side effects.
234
- *
235
- * This clearTimeout prevents the outlet from being cleared when the component is re-mounted,
236
- * which should only happen in development mode and as a result of a hot reload.
237
- */
238
- clearTimeout(this.clearOutletTimeout);
239
- }
2199
+ this._isMounted = true;
240
2200
  if (this.routerOutletElement) {
241
2201
  this.setupRouterOutlet(this.routerOutletElement);
242
- this.handlePageTransition(this.props.routeInfo);
2202
+ // Defer to a microtask to avoid calling forceUpdate() synchronously during
2203
+ // React 19's reappearLayoutEffects phase, which re-runs componentDidMount
2204
+ // without a preceding componentWillUnmount and causes "Maximum update depth exceeded".
2205
+ const routeInfo = this.props.routeInfo;
2206
+ queueMicrotask(() => {
2207
+ if (this._isMounted && this.props.routeInfo.pathname === routeInfo.pathname) {
2208
+ this.handlePageTransition(routeInfo);
2209
+ }
2210
+ });
243
2211
  }
244
2212
  }
245
2213
  componentDidUpdate(prevProps) {
@@ -255,117 +2223,197 @@ class StackManager extends React.PureComponent {
255
2223
  }
256
2224
  }
257
2225
  componentWillUnmount() {
258
- this.clearOutletTimeout = this.context.clearOutlet(this.id);
2226
+ this._isMounted = false;
2227
+ // Cancel any in-flight transition rAFs
2228
+ for (const id of this.transitionRafIds) {
2229
+ cancelAnimationFrame(id);
2230
+ }
2231
+ this.transitionRafIds = [];
2232
+ // Disconnect any in-flight MutationObserver from waitForComponentsReady
2233
+ if (this.transitionObserver) {
2234
+ this.transitionObserver.disconnect();
2235
+ this.transitionObserver = undefined;
2236
+ }
2237
+ if (this.ionPageWaitTimeout) {
2238
+ clearTimeout(this.ionPageWaitTimeout);
2239
+ this.ionPageWaitTimeout = undefined;
2240
+ }
2241
+ if (this.outOfScopeUnmountTimeout) {
2242
+ clearTimeout(this.outOfScopeUnmountTimeout);
2243
+ this.outOfScopeUnmountTimeout = undefined;
2244
+ }
2245
+ this.waitingForIonPage = false;
2246
+ this.preservedViewItems.clear();
2247
+ // Hide all views in this outlet before clearing.
2248
+ // This is critical for nested outlets - when the parent component unmounts,
2249
+ // the nested outlet's componentDidUpdate won't be called, so we must hide
2250
+ // the ion-page elements here to prevent them from remaining visible on top
2251
+ // of other content after navigation to a different route.
2252
+ const allViewsInOutlet = this.context.getViewItemsForOutlet(this.id);
2253
+ allViewsInOutlet.forEach((viewItem) => {
2254
+ hideIonPageElement(viewItem.ionPageElement);
2255
+ });
2256
+ this.context.clearOutlet(this.id);
259
2257
  }
2258
+ /**
2259
+ * Sets the transition between pages within this router outlet.
2260
+ * This function determines the entering and leaving views based on the
2261
+ * provided route information and triggers the appropriate animation.
2262
+ * It also handles scenarios like initial loads, back navigation, and
2263
+ * navigation to the same view with different parameters.
2264
+ *
2265
+ * @param routeInfo It contains info about the current route,
2266
+ * the previous route, and the action taken (e.g., push, replace).
2267
+ *
2268
+ * @returns A promise that resolves when the transition is complete.
2269
+ * If no transition is needed or if the router outlet isn't ready,
2270
+ * the Promise may resolve immediately.
2271
+ */
260
2272
  async handlePageTransition(routeInfo) {
261
- var _a, _b;
2273
+ var _a;
2274
+ // Wait for router outlet to mount
262
2275
  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
2276
  this.pendingPageTransition = true;
2277
+ return;
271
2278
  }
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);
2279
+ // Find entering and leaving view items
2280
+ const viewItems = this.findViewItems(routeInfo);
2281
+ let enteringViewItem = viewItems.enteringViewItem;
2282
+ let leavingViewItem = viewItems.leavingViewItem;
2283
+ let shouldUnmountLeavingViewItem = this.shouldUnmountLeavingView(routeInfo, enteringViewItem, leavingViewItem);
2284
+ // Get parent path for nested outlets
2285
+ const parentPath = this.getParentPath();
2286
+ // Handle out-of-scope outlet (route outside mount path)
2287
+ if (this.handleOutOfScopeOutlet(routeInfo)) {
2288
+ return;
2289
+ }
2290
+ // Handle root navigation: unmount all non-entering views
2291
+ if (routeInfo.routeDirection === 'root') {
2292
+ this.handleRootNavigation(enteringViewItem);
2293
+ leavingViewItem = undefined;
2294
+ shouldUnmountLeavingViewItem = false;
2295
+ }
2296
+ // Clear any pending out-of-scope unmount timeout
2297
+ if (this.outOfScopeUnmountTimeout) {
2298
+ clearTimeout(this.outOfScopeUnmountTimeout);
2299
+ this.outOfScopeUnmountTimeout = undefined;
2300
+ }
2301
+ // Handle nested outlet with relative routes but no valid parent path
2302
+ if (this.handleOutOfContextNestedOutlet(parentPath, leavingViewItem)) {
2303
+ return;
2304
+ }
2305
+ // Find the matching route element
2306
+ const enteringRoute = findRouteByRouteInfo((_a = this.ionRouterOutlet) === null || _a === void 0 ? void 0 : _a.props.children, routeInfo, parentPath);
2307
+ // Handle nested outlet with no matching route
2308
+ if (this.handleNoMatchingRoute(enteringRoute, enteringViewItem, leavingViewItem)) {
2309
+ return;
2310
+ }
2311
+ // Create or update the entering view item
2312
+ if (enteringViewItem && enteringRoute) {
2313
+ enteringViewItem.reactElement = enteringRoute;
2314
+ }
2315
+ else if (enteringRoute) {
2316
+ enteringViewItem = this.context.createViewItem(this.id, enteringRoute, routeInfo);
2317
+ this.context.addViewItem(enteringViewItem);
2318
+ }
2319
+ // Handle transition based on ion-page element availability
2320
+ // Check if the ionPageElement is still in the document.
2321
+ // If the view was previously unmounted (mount=false), the ViewLifeCycleManager
2322
+ // removes the React component from the tree, which removes the IonPage from the DOM.
2323
+ // The ionPageElement reference becomes stale and we need to wait for a new one.
2324
+ const ionPageIsInDocument = (enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement) && document.body.contains(enteringViewItem.ionPageElement);
2325
+ if (enteringViewItem && ionPageIsInDocument) {
2326
+ // Clear waiting state
2327
+ if (this.waitingForIonPage) {
2328
+ this.waitingForIonPage = false;
277
2329
  }
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
- }
2330
+ if (this.ionPageWaitTimeout) {
2331
+ clearTimeout(this.ionPageWaitTimeout);
2332
+ this.ionPageWaitTimeout = undefined;
291
2333
  }
292
- const enteringRoute = matchRoute((_b = this.ionRouterOutlet) === null || _b === void 0 ? void 0 : _b.props.children, routeInfo);
293
- if (enteringViewItem) {
294
- enteringViewItem.reactElement = enteringRoute;
2334
+ this.handleReadyEnteringView(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem);
2335
+ }
2336
+ else if (enteringViewItem && !ionPageIsInDocument) {
2337
+ // Wait for ion-page to mount
2338
+ // This handles both: no ionPageElement, or stale ionPageElement (not in document)
2339
+ // Clear stale reference if the element is no longer in the document
2340
+ if (enteringViewItem.ionPageElement && !document.body.contains(enteringViewItem.ionPageElement)) {
2341
+ enteringViewItem.ionPageElement = undefined;
295
2342
  }
296
- else if (enteringRoute) {
297
- enteringViewItem = this.context.createViewItem(this.id, enteringRoute, routeInfo);
298
- this.context.addViewItem(enteringViewItem);
2343
+ // Ensure the view is marked as mounted so ViewLifeCycleManager renders the IonPage
2344
+ if (!enteringViewItem.mount) {
2345
+ enteringViewItem.mount = true;
299
2346
  }
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;
2347
+ this.handleWaitingForIonPage(routeInfo, enteringViewItem, leavingViewItem, shouldUnmountLeavingViewItem);
2348
+ return;
2349
+ }
2350
+ else if (!enteringViewItem && !enteringRoute) {
2351
+ // No view or route found - likely leaving to another outlet
2352
+ if (leavingViewItem) {
2353
+ hideIonPageElement(leavingViewItem.ionPageElement);
2354
+ const shouldPreserveLeavingView = routeInfo.routeAction === 'pop' && isViewItemPreservableOnPop(leavingViewItem);
2355
+ if (shouldUnmountLeavingViewItem && !shouldPreserveLeavingView) {
2356
+ leavingViewItem.mount = false;
333
2357
  }
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');
2358
+ else if (shouldUnmountLeavingViewItem && shouldPreserveLeavingView) {
2359
+ this.preservedViewItems.add(leavingViewItem);
359
2360
  }
360
- // }, 250);
361
2361
  }
362
- this.forceUpdate();
363
2362
  }
2363
+ this.forceUpdate();
364
2364
  }
2365
+ /**
2366
+ * Registers an `<IonPage>` DOM element with the `StackManager`.
2367
+ * This is called when `<IonPage>` has been mounted.
2368
+ *
2369
+ * @param page The element of the rendered `<IonPage>`.
2370
+ * @param routeInfo The route information that associates with `<IonPage>`.
2371
+ */
365
2372
  registerIonPage(page, routeInfo) {
2373
+ /**
2374
+ * DO NOT remove ion-page-invisible here.
2375
+ *
2376
+ * PageManager's ref callback adds ion-page-invisible synchronously to prevent flash.
2377
+ * At this point, the <IonPage> div exists but its CHILDREN (header, toolbar, menu-button)
2378
+ * have NOT rendered yet. If we remove ion-page-invisible now, the page becomes visible
2379
+ * with empty/incomplete content, causing a flicker (especially for ion-menu-button which
2380
+ * starts with menu-button-hidden class).
2381
+ *
2382
+ * Instead, let transitionPage handle visibility AFTER waiting for components to be ready.
2383
+ * This ensures the page only becomes visible when its content is fully rendered.
2384
+ */
2385
+ this.waitingForIonPage = false;
2386
+ if (this.ionPageWaitTimeout) {
2387
+ clearTimeout(this.ionPageWaitTimeout);
2388
+ this.ionPageWaitTimeout = undefined;
2389
+ }
2390
+ this.pendingPageTransition = false;
366
2391
  const foundView = this.context.findViewItemByRouteInfo(routeInfo, this.id);
367
2392
  if (foundView) {
368
2393
  const oldPageElement = foundView.ionPageElement;
2394
+ /**
2395
+ * FIX for issue #28878: Reject orphaned IonPage registrations.
2396
+ *
2397
+ * When a component conditionally renders different IonPages (e.g., list vs empty state)
2398
+ * using React keys, and state changes simultaneously with navigation, the new IonPage
2399
+ * tries to register for a route we're navigating away from. This creates a stale view.
2400
+ *
2401
+ * Only reject if both pageIds exist and differ, to allow nested outlet registrations.
2402
+ */
2403
+ if (this.shouldRejectOrphanedPage(page, oldPageElement, routeInfo)) {
2404
+ this.hideAndRemoveOrphanedPage(page);
2405
+ return;
2406
+ }
2407
+ /**
2408
+ * Don't let a nested element (e.g., ion-router-outlet with ionPage prop)
2409
+ * override an existing IonPage registration when the existing element is
2410
+ * an ancestor of the new one. This ensures ionPageElement always points
2411
+ * to the outermost IonPage, which is needed to properly hide the entire
2412
+ * page during back navigation (not just the inner outlet).
2413
+ */
2414
+ if (oldPageElement && oldPageElement !== page && oldPageElement.isConnected && oldPageElement.contains(page)) {
2415
+ return;
2416
+ }
369
2417
  foundView.ionPageElement = page;
370
2418
  foundView.ionRoute = true;
371
2419
  /**
@@ -379,83 +2427,162 @@ class StackManager extends React.PureComponent {
379
2427
  }
380
2428
  this.handlePageTransition(routeInfo);
381
2429
  }
2430
+ /**
2431
+ * Checks if a new IonPage should be rejected (component re-rendered while navigating away).
2432
+ */
2433
+ shouldRejectOrphanedPage(newPage, oldPageElement, routeInfo) {
2434
+ if (!oldPageElement || oldPageElement === newPage) {
2435
+ return false;
2436
+ }
2437
+ const newPageId = newPage.getAttribute('data-pageid');
2438
+ const oldPageId = oldPageElement.getAttribute('data-pageid');
2439
+ if (!newPageId || !oldPageId || newPageId === oldPageId) {
2440
+ return false;
2441
+ }
2442
+ return this.props.routeInfo.pathname !== routeInfo.pathname;
2443
+ }
2444
+ hideAndRemoveOrphanedPage(page) {
2445
+ page.classList.add('ion-page-hidden');
2446
+ page.setAttribute('aria-hidden', 'true');
2447
+ setTimeout(() => {
2448
+ if (page.parentElement) {
2449
+ page.remove();
2450
+ }
2451
+ }, VIEW_UNMOUNT_DELAY_MS);
2452
+ }
2453
+ /**
2454
+ * Dismisses every presented Ionic overlay in the document. Core moves overlays
2455
+ * to ion-app when presented, so they are no longer descendants of this outlet
2456
+ * and stay visible even after the outlet is hidden, blocking the entering view.
2457
+ *
2458
+ * Scope is document-wide because the original outlet-to-overlay DOM linkage is
2459
+ * lost after presentation. Overlays without a trackable presenting element
2460
+ * cannot be safely attributed to a specific outlet.
2461
+ */
2462
+ dismissPresentedOverlays() {
2463
+ // Matches the overlay set tracked by core's getPresentedOverlays (see
2464
+ // core/src/utils/overlays.ts). An overlay is "presented" when it lacks the
2465
+ // `overlay-hidden` class.
2466
+ const overlaySelector = 'ion-modal, ion-popover, ion-action-sheet, ion-alert, ion-loading';
2467
+ document.querySelectorAll(overlaySelector).forEach((overlay) => {
2468
+ if (overlay.classList.contains('overlay-hidden') || typeof overlay.dismiss !== 'function') {
2469
+ return;
2470
+ }
2471
+ overlay.dismiss().catch(() => {
2472
+ /* Overlay may already be dismissing or its canDismiss guard may block it. */
2473
+ });
2474
+ });
2475
+ }
2476
+ /**
2477
+ * Resolves the entering view for a swipe-back gesture.
2478
+ *
2479
+ * Prefers a view owned by this outlet. Falls back to searching all outlets only
2480
+ * when the candidate's ion-page element is a descendant of this outlet. Without
2481
+ * the containment guard, a nested child outlet can claim ownership of a sibling
2482
+ * outlet's view, running the swipe gesture on the wrong router outlet.
2483
+ */
2484
+ findEnteringViewForSwipe(swipeBackRouteInfo) {
2485
+ var _a;
2486
+ const enteringViewItem = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, this.id, false);
2487
+ if (enteringViewItem) {
2488
+ return enteringViewItem;
2489
+ }
2490
+ const candidate = this.context.findViewItemByRouteInfo(swipeBackRouteInfo, undefined, false);
2491
+ if ((candidate === null || candidate === void 0 ? void 0 : candidate.ionPageElement) && ((_a = this.routerOutletElement) === null || _a === void 0 ? void 0 : _a.contains(candidate.ionPageElement))) {
2492
+ return candidate;
2493
+ }
2494
+ return undefined;
2495
+ }
2496
+ /**
2497
+ * Configures swipe-to-go-back gesture for the router outlet.
2498
+ */
382
2499
  async setupRouterOutlet(routerOutlet) {
383
2500
  const canStart = () => {
384
- const config = getConfig();
385
- const swipeEnabled = config && config.get('swipeBackEnabled', routerOutlet.mode === 'ios');
386
- if (!swipeEnabled) {
387
- return false;
388
- }
2501
+ var _a, _b;
389
2502
  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);
2503
+ const swipeBackRouteInfo = this.getSwipeBackRouteInfo();
2504
+ const enteringViewItem = this.findEnteringViewForSwipe(swipeBackRouteInfo);
2505
+ // View might have mount=false but ionPageElement still in DOM
2506
+ const ionPageInDocument = Boolean((enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement) && document.body.contains(enteringViewItem.ionPageElement));
2507
+ // For wildcard/parameterized routes, the pattern path (e.g. "/foo/*") will
2508
+ // never equal the resolved pathname (e.g. "/foo/bar"), so the pattern check
2509
+ // alone isn't sufficient. Also, verify the entering view's resolved pathname
2510
+ // differs from the current pathname if they match, the entering and leaving
2511
+ // views are the same and the swipe gesture shouldn't start.
2512
+ const canStartSwipe = !!enteringViewItem &&
2513
+ (enteringViewItem.mount || ionPageInDocument) &&
2514
+ enteringViewItem.routeData.match.pattern.path !== routeInfo.pathname &&
2515
+ enteringViewItem.routeData.match.pathname !== routeInfo.pathname;
2516
+ // eslint-disable-next-line no-console
2517
+ console.log('[SwipeBackCanStart]', JSON.stringify({
2518
+ outletId: this.id,
2519
+ routePathname: routeInfo.pathname,
2520
+ swipeBackPathname: swipeBackRouteInfo === null || swipeBackRouteInfo === void 0 ? void 0 : swipeBackRouteInfo.pathname,
2521
+ enteringViewId: enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.id,
2522
+ enteringViewPath: (_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,
2523
+ enteringMount: enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.mount,
2524
+ ionPageInDocument,
2525
+ canStartSwipe,
2526
+ }));
2527
+ return canStartSwipe;
411
2528
  };
412
2529
  const onStart = async () => {
2530
+ var _a, _b, _c, _d, _e, _f;
413
2531
  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);
2532
+ const swipeBackRouteInfo = this.getSwipeBackRouteInfo();
2533
+ const enteringViewItem = this.findEnteringViewForSwipe(swipeBackRouteInfo);
418
2534
  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
- */
2535
+ // eslint-disable-next-line no-console
2536
+ console.log('[SwipeBackOnStart:entry]', JSON.stringify({
2537
+ outletId: this.id,
2538
+ routePathname: routeInfo.pathname,
2539
+ swipeBackPathname: swipeBackRouteInfo === null || swipeBackRouteInfo === void 0 ? void 0 : swipeBackRouteInfo.pathname,
2540
+ enteringViewId: enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.id,
2541
+ enteringViewPath: (_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,
2542
+ enteringMount: enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.mount,
2543
+ hasEnteringIonPageElement: !!(enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement),
2544
+ leavingViewId: leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.id,
2545
+ }));
2546
+ // Ensure the entering view is mounted so React keeps rendering it during the gesture.
2547
+ // This is important when the view was previously marked for unmount but its
2548
+ // ionPageElement is still in the DOM.
2549
+ if (enteringViewItem && !enteringViewItem.mount) {
2550
+ enteringViewItem.mount = true;
2551
+ }
2552
+ // Reveal synchronously. `transitionPage` defers this behind async commit,
2553
+ // but the gesture's first progress frame fires in the same tick as onStart,
2554
+ // so an async reveal leaves the entering page hidden until the next frame.
2555
+ revealIonPageForSwipeBack(enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement);
2556
+ // When the gesture starts, kick off a transition controlled via swipe gesture
424
2557
  if (enteringViewItem && leavingViewItem) {
425
2558
  await this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, 'back', true);
426
2559
  }
2560
+ // eslint-disable-next-line no-console
2561
+ console.log('[SwipeBackOnStart:exit]', JSON.stringify({
2562
+ outletId: this.id,
2563
+ enteringFinalComputedDisplay: (enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement)
2564
+ ? getComputedStyle(enteringViewItem.ionPageElement).display
2565
+ : null,
2566
+ enteringFinalInlineDisplay: (_d = (_c = enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement) === null || _c === void 0 ? void 0 : _c.style.display) !== null && _d !== void 0 ? _d : null,
2567
+ enteringFinalHiddenClass: (_f = (_e = enteringViewItem === null || enteringViewItem === void 0 ? void 0 : enteringViewItem.ionPageElement) === null || _e === void 0 ? void 0 : _e.classList.contains('ion-page-hidden')) !== null && _f !== void 0 ? _f : null,
2568
+ }));
427
2569
  return Promise.resolve();
428
2570
  };
429
2571
  const onEnd = (shouldContinue) => {
430
2572
  if (shouldContinue) {
2573
+ // User finished the swipe gesture, so complete the back navigation
431
2574
  this.skipTransition = true;
432
2575
  this.context.goBack();
433
2576
  }
434
2577
  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
- */
2578
+ // Swipe gesture was aborted - re-hide the page that was going to enter
440
2579
  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);
445
- 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
- */
2580
+ const swipeBackRouteInfo = this.getSwipeBackRouteInfo();
2581
+ const enteringViewItem = this.findEnteringViewForSwipe(swipeBackRouteInfo);
2582
+ const leavingViewItem = this.context.findViewItemByRouteInfo(routeInfo, this.id, false);
2583
+ // Don't hide if entering and leaving are the same (parameterized route edge case)
455
2584
  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');
2585
+ hideIonPageElement(enteringViewItem.ionPageElement);
459
2586
  }
460
2587
  }
461
2588
  };
@@ -465,7 +2592,24 @@ class StackManager extends React.PureComponent {
465
2592
  onEnd,
466
2593
  };
467
2594
  }
468
- async transitionPage(routeInfo, enteringViewItem, leavingViewItem, direction, progressAnimation = false) {
2595
+ /**
2596
+ * Animates the transition between the entering and leaving pages within the
2597
+ * router outlet.
2598
+ *
2599
+ * @param routeInfo Info about the current route.
2600
+ * @param enteringViewItem The view item that is entering.
2601
+ * @param leavingViewItem The view item that is leaving.
2602
+ * @param direction The direction of the transition.
2603
+ * @param progressAnimation Indicates if the transition is part of a
2604
+ * gesture controlled animation (e.g., swipe to go back).
2605
+ * Defaults to `false`.
2606
+ * @param skipAnimation When true, forces `duration: 0` so the page
2607
+ * swap is instant (no visible animation). Used for ionPage outlets
2608
+ * and back navigations that unmount the leaving view to prevent
2609
+ * overlapping content during the transition. Defaults to `false`.
2610
+ */
2611
+ async transitionPage(routeInfo, enteringViewItem, leavingViewItem, direction, progressAnimation = false, skipAnimation = false) {
2612
+ const myGeneration = ++this.transitionGeneration;
469
2613
  const runCommit = async (enteringEl, leavingEl) => {
470
2614
  const skipTransition = this.skipTransition;
471
2615
  /**
@@ -493,24 +2637,56 @@ class StackManager extends React.PureComponent {
493
2637
  }
494
2638
  else {
495
2639
  enteringEl.classList.add('ion-page');
496
- enteringEl.classList.add('ion-page-invisible');
2640
+ /**
2641
+ * Only add ion-page-invisible if the element is not already visible.
2642
+ * During tab switches, the container page (e.g., TabContext wrapper) is
2643
+ * already visible and should remain so. Adding ion-page-invisible would
2644
+ * cause a flash where the visible page briefly becomes invisible.
2645
+ */
2646
+ if (!isViewVisible(enteringEl)) {
2647
+ enteringEl.classList.add('ion-page-invisible');
2648
+ }
497
2649
  }
498
- await routerOutlet.commit(enteringEl, leavingEl, {
499
- duration: skipTransition || directionToUse === undefined ? 0 : undefined,
2650
+ const commitDuration = skipTransition || skipAnimation || directionToUse === undefined ? 0 : undefined;
2651
+ // Race commit against a timeout to recover from hangs
2652
+ const commitPromise = routerOutlet.commit(enteringEl, leavingEl, {
2653
+ duration: commitDuration,
500
2654
  direction: directionToUse,
501
2655
  showGoBack: !!routeInfo.pushedByRoute,
502
2656
  progressAnimation,
503
2657
  animationBuilder: routeInfo.routeAnimation,
504
2658
  });
2659
+ const timeoutMs = 5000;
2660
+ const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve('timeout'), timeoutMs));
2661
+ const result = await Promise.race([commitPromise.then(() => 'done'), timeoutPromise]);
2662
+ // Bail out if the component unmounted during the commit animation
2663
+ if (!this._isMounted)
2664
+ return;
2665
+ if (result === 'timeout') {
2666
+ // Force entering page visible even though commit hung
2667
+ enteringEl.classList.remove('ion-page-invisible');
2668
+ }
2669
+ /**
2670
+ * If a newer transitionPage call ran while this commit was in-flight (e.g., a tab
2671
+ * switch fired during a forward animation), the core commit may have applied
2672
+ * ion-page-hidden to leavingEl even though the newer transition already made it
2673
+ * visible. Undo that stale hide so the newer transition's DOM state wins.
2674
+ */
2675
+ if (myGeneration !== this.transitionGeneration && leavingEl && leavingEl === this.transitionEnteringElement) {
2676
+ showIonPageElement(leavingEl);
2677
+ }
2678
+ if (!progressAnimation) {
2679
+ enteringEl.classList.remove('ion-page-invisible');
2680
+ }
505
2681
  };
506
2682
  const routerOutlet = this.routerOutletElement;
507
2683
  const routeInfoFallbackDirection = routeInfo.routeDirection === 'none' || routeInfo.routeDirection === 'root' ? undefined : routeInfo.routeDirection;
508
2684
  const directionToUse = direction !== null && direction !== void 0 ? direction : routeInfoFallbackDirection;
509
2685
  if (enteringViewItem && enteringViewItem.ionPageElement && this.routerOutletElement) {
2686
+ this.transitionEnteringElement = enteringViewItem.ionPageElement;
510
2687
  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);
2688
+ // Clone page for same-view transitions (e.g., /user/1 /user/2)
2689
+ const match = matchComponent(leavingViewItem.reactElement, routeInfo.pathname, undefined, this.outletMountPath);
514
2690
  if (match) {
515
2691
  const newLeavingElement = clonePageElement(leavingViewItem.ionPageElement.outerHTML);
516
2692
  if (newLeavingElement) {
@@ -520,14 +2696,111 @@ class StackManager extends React.PureComponent {
520
2696
  }
521
2697
  }
522
2698
  else {
2699
+ // Route no longer matches (e.g., /user/1 → /settings)
523
2700
  await runCommit(enteringViewItem.ionPageElement, undefined);
524
2701
  }
525
2702
  }
526
2703
  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');
2704
+ const leavingEl = leavingViewItem === null || leavingViewItem === void 0 ? void 0 : leavingViewItem.ionPageElement;
2705
+ // For non-animated transitions, don't pass leaving element to commit() to avoid
2706
+ // flicker caused by commit() briefly unhiding the leaving page
2707
+ const isNonAnimatedTransition = directionToUse === undefined && !progressAnimation;
2708
+ if (isNonAnimatedTransition && leavingEl) {
2709
+ /**
2710
+ * Skip commit() for non-animated transitions (like tab switches).
2711
+ * commit() runs animation logic that can cause intermediate paints
2712
+ * even with duration: 0. Instead, swap visibility synchronously.
2713
+ *
2714
+ * Synchronous DOM class changes are batched into a single browser
2715
+ * paint, so there's no gap frame where neither page is visible and
2716
+ * no overlap frame where both pages are visible.
2717
+ */
2718
+ const enteringEl = enteringViewItem.ionPageElement;
2719
+ // Ensure entering element has proper base classes
2720
+ enteringEl.classList.add('ion-page');
2721
+ // Clear ALL hidden state from entering element. showIonPageElement
2722
+ // removes visibility:hidden (from applySkipAnimationIfNeeded),
2723
+ // ion-page-hidden, and aria-hidden in one call.
2724
+ showIonPageElement(enteringEl);
2725
+ // Handle can-go-back class since we're skipping commit() which normally sets this
2726
+ if (routeInfo.pushedByRoute) {
2727
+ enteringEl.classList.add('can-go-back');
2728
+ }
2729
+ else {
2730
+ enteringEl.classList.remove('can-go-back');
2731
+ }
2732
+ /**
2733
+ * Wait for components to be ready. Menu buttons start hidden (menu-button-hidden)
2734
+ * and become visible after componentDidLoad. Wait for hydration and visibility.
2735
+ */
2736
+ const waitForComponentsReady = () => {
2737
+ return new Promise((resolve) => {
2738
+ const checkReady = () => {
2739
+ const ionicComponents = enteringEl.querySelectorAll('ion-header, ion-toolbar, ion-buttons, ion-menu-button, ion-title, ion-content');
2740
+ const allHydrated = Array.from(ionicComponents).every((el) => el.classList.contains('hydrated'));
2741
+ const menuButtons = enteringEl.querySelectorAll('ion-menu-button');
2742
+ const menuButtonsReady = Array.from(menuButtons).every((el) => !el.classList.contains('menu-button-hidden'));
2743
+ return allHydrated && menuButtonsReady;
2744
+ };
2745
+ if (checkReady()) {
2746
+ resolve();
2747
+ return;
2748
+ }
2749
+ let resolved = false;
2750
+ const observer = new MutationObserver(() => {
2751
+ if (!resolved && checkReady()) {
2752
+ resolved = true;
2753
+ observer.disconnect();
2754
+ if (this.transitionObserver === observer) {
2755
+ this.transitionObserver = undefined;
2756
+ }
2757
+ resolve();
2758
+ }
2759
+ });
2760
+ // Disconnect any previous observer before tracking the new one
2761
+ if (this.transitionObserver) {
2762
+ this.transitionObserver.disconnect();
2763
+ }
2764
+ this.transitionObserver = observer;
2765
+ observer.observe(enteringEl, {
2766
+ subtree: true,
2767
+ attributes: true,
2768
+ attributeFilter: ['class'],
2769
+ });
2770
+ setTimeout(() => {
2771
+ if (!resolved) {
2772
+ resolved = true;
2773
+ observer.disconnect();
2774
+ if (this.transitionObserver === observer) {
2775
+ this.transitionObserver = undefined;
2776
+ }
2777
+ resolve();
2778
+ }
2779
+ }, 100);
2780
+ });
2781
+ };
2782
+ await waitForComponentsReady();
2783
+ // Bail out if the component unmounted during waitForComponentsReady
2784
+ if (!this._isMounted)
2785
+ return;
2786
+ // Swap visibility synchronously - show entering, hide leaving
2787
+ // Skip hiding if a newer transition already made leavingEl the entering view
2788
+ enteringEl.classList.remove('ion-page-invisible');
2789
+ if (myGeneration === this.transitionGeneration || leavingEl !== this.transitionEnteringElement) {
2790
+ leavingEl.classList.add('ion-page-hidden');
2791
+ leavingEl.setAttribute('aria-hidden', 'true');
2792
+ }
2793
+ }
2794
+ else {
2795
+ await runCommit(enteringViewItem.ionPageElement, leavingEl);
2796
+ if (leavingEl && !progressAnimation) {
2797
+ // Skip hiding if a newer transition already made leavingEl the entering view
2798
+ // runCommit's generation check has already restored its visibility in that case
2799
+ if (myGeneration === this.transitionGeneration || leavingEl !== this.transitionEnteringElement) {
2800
+ leavingEl.classList.add('ion-page-hidden');
2801
+ leavingEl.setAttribute('aria-hidden', 'true');
2802
+ }
2803
+ }
531
2804
  }
532
2805
  }
533
2806
  }
@@ -535,193 +2808,474 @@ class StackManager extends React.PureComponent {
535
2808
  render() {
536
2809
  const { children } = this.props;
537
2810
  const ionRouterOutlet = React.Children.only(children);
2811
+ // Store reference for use in getParentPath() and handlePageTransition()
538
2812
  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)));
2813
+ return (React.createElement(UNSAFE_RouteContext.Consumer, null, (parentContext) => {
2814
+ // Derive the outlet's mount path from React Router's matched route context.
2815
+ // This eliminates the need for heuristic-based mount path discovery in
2816
+ // computeParentPath, since React Router already knows the matched base path.
2817
+ const parentMatches = parentContext === null || parentContext === void 0 ? void 0 : parentContext.matches;
2818
+ const parentPathnameBase = parentMatches && parentMatches.length > 0
2819
+ ? parentMatches[parentMatches.length - 1].pathnameBase
2820
+ : undefined;
2821
+ // Derive isRootOutlet from RouteContext: empty matches means root.
2822
+ this.isRootOutlet = !parentMatches || parentMatches.length === 0;
2823
+ // Seed StackManager's mount path from the parent route context
2824
+ if (parentPathnameBase && !this.outletMountPath) {
2825
+ this.outletMountPath = parentPathnameBase;
2826
+ }
2827
+ const components = this.context.getChildrenToRender(this.id, this.ionRouterOutlet, this.props.routeInfo, () => {
2828
+ // Callback triggers re-render when view items are modified during getChildrenToRender
2829
+ this.forceUpdate();
2830
+ }, parentPathnameBase);
2831
+ return (React.createElement(StackContext.Provider, { value: this.stackContextValue }, React.cloneElement(ionRouterOutlet, {
2832
+ ref: (node) => {
2833
+ if (ionRouterOutlet.props.setRef) {
2834
+ // Needed to handle external refs from devs.
2835
+ ionRouterOutlet.props.setRef(node);
2836
+ }
2837
+ if (ionRouterOutlet.props.forwardedRef) {
2838
+ // Needed to handle external refs from devs.
2839
+ ionRouterOutlet.props.forwardedRef.current = node;
2840
+ }
2841
+ this.routerOutletElement = node;
2842
+ const { ref } = ionRouterOutlet;
2843
+ // Check for legacy refs.
2844
+ if (typeof ref === 'function') {
2845
+ ref(node);
2846
+ }
2847
+ },
2848
+ }, components)));
2849
+ }));
557
2850
  }
558
2851
  static get contextType() {
559
2852
  return RouteManagerContext;
560
2853
  }
561
2854
  }
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;
2855
+ /**
2856
+ * Converts React Route elements to RouteObject format for use with matchRoutes().
2857
+ * Filters out pathless routes (which are handled by fallback logic separately).
2858
+ *
2859
+ * When a basename is provided, absolute route paths are relativized by stripping
2860
+ * the basename prefix. This is necessary because matchRoutes() strips the basename
2861
+ * from the LOCATION pathname but not from route paths — absolute paths must be
2862
+ * made relative to the basename for matching to work correctly.
2863
+ *
2864
+ * @param routeChildren The flat array of Route/IonRoute elements from the outlet.
2865
+ * @param basename The resolved parent path (without trailing slash or `/*`) used to relativize absolute paths.
2866
+ */
2867
+ function routeElementsToRouteObjects(routeChildren, basename) {
2868
+ return routeChildren
2869
+ .filter((child) => child.props.path != null || child.props.index)
2870
+ .map((child) => {
2871
+ const handle = { _element: child };
2872
+ let path = child.props.path;
2873
+ // Relativize absolute paths by stripping the basename prefix
2874
+ if (path && path.startsWith('/') && basename) {
2875
+ if (path === basename) {
2876
+ path = '';
2877
+ }
2878
+ else if (path.startsWith(basename + '/')) {
2879
+ path = path.slice(basename.length + 1);
2880
+ }
571
2881
  }
2882
+ if (child.props.index) {
2883
+ return {
2884
+ index: true,
2885
+ handle,
2886
+ caseSensitive: child.props.caseSensitive || undefined,
2887
+ };
2888
+ }
2889
+ return {
2890
+ path,
2891
+ handle,
2892
+ caseSensitive: child.props.caseSensitive || undefined,
2893
+ };
572
2894
  });
573
- if (matchedNode) {
574
- return matchedNode;
2895
+ }
2896
+ /**
2897
+ * Finds the `<Route />` node matching the current route info.
2898
+ * If no `<Route />` can be matched, a fallback node is returned.
2899
+ * Routes are prioritized by specificity (most specific first).
2900
+ *
2901
+ * @param node The root node to search for `<Route />` nodes.
2902
+ * @param routeInfo The route information to match against.
2903
+ * @param parentPath The parent path that was matched by the parent outlet (for nested routing)
2904
+ */
2905
+ function findRouteByRouteInfo(node, routeInfo, parentPath) {
2906
+ var _a, _b, _c;
2907
+ let matchedNode;
2908
+ let fallbackNode;
2909
+ // `<Route />` nodes are rendered inside of a <Routes /> node
2910
+ const routesChildren = (_a = getRoutesChildren(node)) !== null && _a !== void 0 ? _a : node;
2911
+ // Collect all route children
2912
+ const routeChildren = React.Children.toArray(routesChildren).filter((child) => React.isValidElement(child) && (child.type === Route || child.type === IonRoute));
2913
+ // Delegate route matching to RR6's matchRoutes(), which handles specificity ranking internally.
2914
+ const basename = parentPath ? stripTrailingSlash(parentPath.replace('/*', '')) : undefined;
2915
+ const routeObjects = routeElementsToRouteObjects(routeChildren, basename);
2916
+ const matches = matchRoutes(routeObjects, { pathname: routeInfo.pathname }, basename);
2917
+ if (matches && matches.length > 0) {
2918
+ const bestMatch = matches[matches.length - 1];
2919
+ matchedNode = (_c = (_b = bestMatch.route.handle) === null || _b === void 0 ? void 0 : _b._element) !== null && _c !== void 0 ? _c : undefined;
575
2920
  }
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;
2921
+ // Fallback: try pathless routes, but only if pathname is within scope.
2922
+ if (!matchedNode) {
2923
+ let pathnameInScope = true;
2924
+ if (parentPath) {
2925
+ pathnameInScope = isPathnameInScope(routeInfo.pathname, parentPath);
581
2926
  }
582
- });
583
- return matchedNode;
2927
+ else {
2928
+ const absolutePathRoutes = routeChildren.filter((r) => r.props.path && r.props.path.startsWith('/'));
2929
+ if (absolutePathRoutes.length > 0) {
2930
+ const absolutePaths = absolutePathRoutes.map((r) => r.props.path);
2931
+ const commonPrefix = computeCommonPrefix(absolutePaths);
2932
+ if (commonPrefix && commonPrefix !== '/') {
2933
+ pathnameInScope = routeInfo.pathname.startsWith(commonPrefix);
2934
+ }
2935
+ }
2936
+ }
2937
+ if (pathnameInScope) {
2938
+ for (const child of routeChildren) {
2939
+ if (!child.props.path) {
2940
+ fallbackNode = child;
2941
+ break;
2942
+ }
2943
+ }
2944
+ }
2945
+ }
2946
+ return matchedNode !== null && matchedNode !== void 0 ? matchedNode : fallbackNode;
584
2947
  }
585
- function matchComponent(node, pathname, forceExact) {
2948
+ function matchComponent(node, pathname, forceExact, parentPath) {
2949
+ var _a;
2950
+ const routePath = (_a = node === null || node === void 0 ? void 0 : node.props) === null || _a === void 0 ? void 0 : _a.path;
2951
+ let pathnameToMatch;
2952
+ if (parentPath && routePath && !routePath.startsWith('/')) {
2953
+ // When parent path is known, compute exact relative pathname
2954
+ const relative = pathname.startsWith(parentPath)
2955
+ ? pathname.slice(parentPath.length).replace(/^\//, '')
2956
+ : pathname;
2957
+ pathnameToMatch = relative;
2958
+ }
2959
+ else {
2960
+ pathnameToMatch = derivePathnameToMatch(pathname, routePath);
2961
+ }
586
2962
  return matchPath({
587
- pathname,
588
- componentProps: Object.assign(Object.assign({}, node.props), { exact: forceExact }),
2963
+ pathname: pathnameToMatch,
2964
+ componentProps: Object.assign(Object.assign({}, node.props), { end: forceExact }),
589
2965
  });
590
2966
  }
591
2967
 
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
- };
626
- }
627
- handleChangeTab(tab, path, routeOptions) {
628
- if (!path) {
629
- return;
2968
+ /**
2969
+ * `IonRouter` is responsible for managing the application's navigation
2970
+ * state, tracking the history of visited routes, and coordinating
2971
+ * transitions between different views. It intercepts route changes from
2972
+ * React Router and translates them into actions that Ionic can understand
2973
+ * and animate.
2974
+ */
2975
+ const filterUndefinedParams = (params) => {
2976
+ const result = {};
2977
+ for (const key of Object.keys(params)) {
2978
+ const value = params[key];
2979
+ if (value !== undefined) {
2980
+ result[key] = value;
630
2981
  }
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 : ''));
2982
+ }
2983
+ return result;
2984
+ };
2985
+ /**
2986
+ * Checks if a POP event is a multi-step back navigation (navigate(-n) where n > 1).
2987
+ * Walks the pushedByRoute chain from prevInfo to verify the destination is an ancestor
2988
+ * in the same navigation chain. This distinguishes multi-step back from tab-crossing
2989
+ * back navigation where prevInfo.pathname also differs from the browser destination.
2990
+ */
2991
+ const checkIsMultiStepBack = (prevInfo, destinationPathname, history) => {
2992
+ if (!prevInfo || prevInfo.pathname === destinationPathname)
2993
+ return false;
2994
+ const visited = new Set();
2995
+ let walker = prevInfo;
2996
+ while (walker === null || walker === void 0 ? void 0 : walker.pushedByRoute) {
2997
+ if (visited.has(walker.id))
2998
+ break; // cycle guard
2999
+ visited.add(walker.id);
3000
+ if (walker.pushedByRoute === destinationPathname)
3001
+ return true;
3002
+ walker = history.findLastLocation(walker);
3003
+ }
3004
+ return false;
3005
+ };
3006
+ const areParamsEqual = (a, b) => {
3007
+ const paramsA = a || {};
3008
+ const paramsB = b || {};
3009
+ const keysA = Object.keys(paramsA);
3010
+ const keysB = Object.keys(paramsB);
3011
+ if (keysA.length !== keysB.length) {
3012
+ return false;
3013
+ }
3014
+ return keysA.every((key) => {
3015
+ const valueA = paramsA[key];
3016
+ const valueB = paramsB[key];
3017
+ if (Array.isArray(valueA) && Array.isArray(valueB)) {
3018
+ if (valueA.length !== valueB.length) {
3019
+ return false;
644
3020
  }
3021
+ return valueA.every((entry, idx) => entry === valueB[idx]);
645
3022
  }
646
- else {
647
- this.handleNavigate(pathname, 'push', 'none', undefined, routeOptions, tab);
3023
+ return valueA === valueB;
3024
+ });
3025
+ };
3026
+ const IonRouter = ({ children, registerHistoryListener }) => {
3027
+ const location = useLocation();
3028
+ const navigate = useNavigate();
3029
+ const didMountRef = useRef(false);
3030
+ const locationHistory = useRef(new LocationHistory());
3031
+ const currentTab = useRef(undefined);
3032
+ const viewStack = useRef(new ReactRouterViewStack());
3033
+ const incomingRouteParams = useRef(null);
3034
+ /**
3035
+ * Tracks location keys that the user navigated away from via browser back.
3036
+ * When a POP event's destination key matches the top of this stack, it's a
3037
+ * browser forward navigation. Uses React Router's unique location.key
3038
+ * instead of URLs to correctly handle duplicate URLs in history (e.g.,
3039
+ * navigating to /details, then /settings, then /details via routerLink,
3040
+ * then pressing back).
3041
+ * Cleared on PUSH (new navigation invalidates forward history).
3042
+ */
3043
+ const forwardStack = useRef([]);
3044
+ /**
3045
+ * Tracks the current location key so we can push it onto the forward stack
3046
+ * when navigating back. Updated after each history change.
3047
+ */
3048
+ const currentLocationKeyRef = useRef(location.key);
3049
+ const [routeInfo, setRouteInfo] = useState({
3050
+ id: generateId('routeInfo'),
3051
+ pathname: location.pathname,
3052
+ search: location.search,
3053
+ params: {},
3054
+ });
3055
+ useEffect(() => {
3056
+ if (didMountRef.current) {
3057
+ return;
648
3058
  }
649
- }
650
- handleHistoryChange(location, action) {
651
- var _a, _b, _c;
652
- let leavingLocationInfo;
653
- if (this.incomingRouteParams) {
654
- if (this.incomingRouteParams.routeAction === 'replace') {
655
- leavingLocationInfo = this.locationHistory.previous();
656
- }
657
- else {
658
- leavingLocationInfo = this.locationHistory.current();
3059
+ // Seed the history stack with the initial location and begin listening
3060
+ // for future navigations once React has committed the mount. This avoids
3061
+ // duplicate entries when React StrictMode runs an extra render pre-commit.
3062
+ locationHistory.current.add(routeInfo);
3063
+ // If IonTabBar already called handleSetCurrentTab during render (before this
3064
+ // effect), the tab was stored in currentTab.current but the history entry was
3065
+ // not yet seeded. Apply the pending tab to the seed entry now.
3066
+ if (currentTab.current) {
3067
+ const ri = Object.assign({}, locationHistory.current.current());
3068
+ if (ri.tab !== currentTab.current) {
3069
+ ri.tab = currentTab.current;
3070
+ locationHistory.current.update(ri);
659
3071
  }
660
3072
  }
661
- else {
662
- leavingLocationInfo = this.locationHistory.current();
3073
+ registerHistoryListener(handleHistoryChange);
3074
+ didMountRef.current = true;
3075
+ }, []);
3076
+ // Sync route params extracted by React Router's path matching back into routeInfo.
3077
+ // The view stack's match may contain params (e.g., :id) not present in the initial routeInfo.
3078
+ useEffect(() => {
3079
+ var _a;
3080
+ const activeView = viewStack.current.findViewItemByRouteInfo(routeInfo, undefined, true);
3081
+ const matchedParams = (_a = activeView === null || activeView === void 0 ? void 0 : activeView.routeData.match) === null || _a === void 0 ? void 0 : _a.params;
3082
+ if (matchedParams) {
3083
+ const paramsCopy = filterUndefinedParams(Object.assign({}, matchedParams));
3084
+ if (areParamsEqual(routeInfo.params, paramsCopy)) {
3085
+ return;
3086
+ }
3087
+ const updatedRouteInfo = Object.assign(Object.assign({}, routeInfo), { params: paramsCopy });
3088
+ locationHistory.current.update(updatedRouteInfo);
3089
+ setRouteInfo(updatedRouteInfo);
663
3090
  }
3091
+ }, [routeInfo]);
3092
+ /**
3093
+ * Triggered whenever the history changes, either through user navigation
3094
+ * or programmatic changes. It transforms the raw browser history changes
3095
+ * into `RouteInfo` objects, which are needed Ionic's animations and
3096
+ * navigation patterns.
3097
+ *
3098
+ * @param location The current location object from the history.
3099
+ * @param action The action that triggered the history change.
3100
+ */
3101
+ const handleHistoryChange = (location, action) => {
3102
+ var _a, _b, _c, _d;
3103
+ /**
3104
+ * The leaving location is always the current route, for both programmatic
3105
+ * and external navigations. Using `previous()` for replace actions was
3106
+ * incorrect: it caused the equality check below to skip navigation when
3107
+ * the replace destination matched the entry two slots back in history.
3108
+ */
3109
+ const leavingLocationInfo = locationHistory.current.current();
664
3110
  const leavingUrl = leavingLocationInfo.pathname + leavingLocationInfo.search;
665
- if (leavingUrl !== location.pathname) {
666
- if (!this.incomingRouteParams) {
3111
+ if (leavingUrl !== location.pathname + location.search) {
3112
+ if (!incomingRouteParams.current) {
3113
+ // Use history-based tab detection instead of URL-pattern heuristics,
3114
+ // so tab routes work with any URL structure (not just paths containing "/tabs").
3115
+ // Fall back to currentTab.current only when the destination is within the
3116
+ // current tab's path hierarchy (prevents non-tab routes from inheriting a tab).
3117
+ let tabToUse = locationHistory.current.findTabForPathname(location.pathname);
3118
+ if (!tabToUse && currentTab.current) {
3119
+ const tabFirstRoute = locationHistory.current.getFirstRouteInfoForTab(currentTab.current);
3120
+ const tabRootPath = tabFirstRoute === null || tabFirstRoute === void 0 ? void 0 : tabFirstRoute.pathname;
3121
+ if (tabRootPath && (location.pathname === tabRootPath || location.pathname.startsWith(tabRootPath + '/'))) {
3122
+ tabToUse = currentTab.current;
3123
+ }
3124
+ }
3125
+ /**
3126
+ * A `REPLACE` action can be triggered by React Router's
3127
+ * `<Navigate />` component.
3128
+ */
667
3129
  if (action === 'REPLACE') {
668
- this.incomingRouteParams = {
3130
+ incomingRouteParams.current = {
669
3131
  routeAction: 'replace',
670
3132
  routeDirection: 'none',
671
- tab: this.currentTab,
3133
+ tab: tabToUse,
672
3134
  };
673
3135
  }
3136
+ /**
3137
+ * A `POP` action can be triggered by the browser's back/forward
3138
+ * button. Both fire as POP events, so we use a forward stack to
3139
+ * distinguish them: when going back, we push the leaving pathname
3140
+ * onto the stack. When the next POP's destination matches the top
3141
+ * of the stack, it's a forward navigation.
3142
+ */
674
3143
  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' });
3144
+ const currentRoute = locationHistory.current.current();
3145
+ const isForwardNavigation = forwardStack.current.length > 0 &&
3146
+ forwardStack.current[forwardStack.current.length - 1] === location.key;
3147
+ if (isForwardNavigation) {
3148
+ forwardStack.current.pop();
3149
+ incomingRouteParams.current = {
3150
+ routeAction: 'push',
3151
+ routeDirection: 'forward',
3152
+ tab: tabToUse,
3153
+ };
3154
+ }
3155
+ else if (currentRoute && currentRoute.pushedByRoute) {
3156
+ // Back navigation. Record current location key for potential forward
3157
+ forwardStack.current.push(currentLocationKeyRef.current);
3158
+ const prevInfo = locationHistory.current.findLastLocation(currentRoute);
3159
+ const isMultiStepBack = checkIsMultiStepBack(prevInfo, location.pathname, locationHistory.current);
3160
+ if (isMultiStepBack) {
3161
+ const destinationInfo = locationHistory.current.findLastLocationByPathname(location.pathname);
3162
+ incomingRouteParams.current = Object.assign(Object.assign({}, (destinationInfo || {})), { routeAction: 'pop', routeDirection: 'back' });
3163
+ }
3164
+ else if (prevInfo && prevInfo.pathname !== location.pathname && currentRoute.tab) {
3165
+ // Browser POP destination differs from within-tab back target.
3166
+ // Sync URL via replace, like handleNavigateBack's non-linear path (#25141).
3167
+ incomingRouteParams.current = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back' });
3168
+ forwardStack.current = [];
3169
+ handleNavigate(prevInfo.pathname + (prevInfo.search || ''), 'pop', 'back', undefined, undefined, prevInfo.tab);
3170
+ return;
3171
+ }
3172
+ else {
3173
+ incomingRouteParams.current = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back' });
3174
+ }
679
3175
  }
680
3176
  else {
681
- this.incomingRouteParams = {
3177
+ // It's a non-linear history path like a direct link.
3178
+ // Still push the current location key so browser forward is detectable.
3179
+ forwardStack.current.push(currentLocationKeyRef.current);
3180
+ incomingRouteParams.current = {
682
3181
  routeAction: 'pop',
683
3182
  routeDirection: 'none',
684
- tab: this.currentTab,
3183
+ tab: tabToUse,
685
3184
  };
686
3185
  }
687
3186
  }
688
- if (!this.incomingRouteParams) {
689
- this.incomingRouteParams = {
3187
+ if (!incomingRouteParams.current) {
3188
+ const state = location.state;
3189
+ incomingRouteParams.current = {
690
3190
  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,
3191
+ routeDirection: (state === null || state === void 0 ? void 0 : state.direction) || 'forward',
3192
+ routeOptions: state === null || state === void 0 ? void 0 : state.routerOptions,
3193
+ tab: tabToUse,
694
3194
  };
695
3195
  }
696
3196
  }
3197
+ // New navigation (PUSH) invalidates browser forward history,
3198
+ // so clear our forward stack to stay in sync.
3199
+ if (action === 'PUSH') {
3200
+ forwardStack.current = [];
3201
+ }
697
3202
  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);
3203
+ // If we're navigating away from tabs to a non-tab route, clear the current tab
3204
+ if (!locationHistory.current.findTabForPathname(location.pathname) && currentTab.current) {
3205
+ currentTab.current = undefined;
3206
+ }
3207
+ /**
3208
+ * An existing id indicates that it's re-activating an existing route.
3209
+ * e.g., tab switching or navigating back to a previous route
3210
+ */
3211
+ if ((_a = incomingRouteParams.current) === null || _a === void 0 ? void 0 : _a.id) {
3212
+ routeInfo = Object.assign(Object.assign({}, incomingRouteParams.current), { lastPathname: leavingLocationInfo.pathname });
3213
+ locationHistory.current.add(routeInfo);
3214
+ /**
3215
+ * A new route is being created since it's not re-activating
3216
+ * an existing route.
3217
+ */
701
3218
  }
702
3219
  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 });
3220
+ const isPushed = ((_b = incomingRouteParams.current) === null || _b === void 0 ? void 0 : _b.routeAction) === 'push' &&
3221
+ incomingRouteParams.current.routeDirection === 'forward';
3222
+ routeInfo = Object.assign(Object.assign({ id: generateId('routeInfo') }, incomingRouteParams.current), { lastPathname: leavingLocationInfo.pathname, pathname: location.pathname, search: location.search, params: ((_c = incomingRouteParams.current) === null || _c === void 0 ? void 0 : _c.params)
3223
+ ? filterUndefinedParams(incomingRouteParams.current.params)
3224
+ : {}, prevRouteLastPathname: leavingLocationInfo.lastPathname });
705
3225
  if (isPushed) {
706
- routeInfo.tab = leavingLocationInfo.tab;
3226
+ // Only inherit tab from leaving route if we don't already have one.
3227
+ // This preserves tab context for same-tab navigation while allowing cross-tab navigation.
3228
+ routeInfo.tab = routeInfo.tab || leavingLocationInfo.tab;
3229
+ routeInfo.pushedByRoute = leavingLocationInfo.pathname;
3230
+ }
3231
+ else if (routeInfo.routeAction === 'push' &&
3232
+ routeInfo.routeDirection === 'none' &&
3233
+ routeInfo.tab === leavingLocationInfo.tab) {
3234
+ // Push with routerDirection="none" within the same tab (or non-tab) context.
3235
+ // Still needs pushedByRoute so the back button can navigate back correctly.
3236
+ // Cross-tab navigations with direction "none" are handled by the tab-switching
3237
+ // block below which has different pushedByRoute semantics.
3238
+ routeInfo.tab = routeInfo.tab || leavingLocationInfo.tab;
707
3239
  routeInfo.pushedByRoute = leavingLocationInfo.pathname;
708
3240
  }
709
3241
  else if (routeInfo.routeAction === 'pop') {
710
- const r = this.locationHistory.findLastLocation(routeInfo);
3242
+ // Triggered by a browser back button or handleNavigateBack.
3243
+ // Find the route that pushed this one.
3244
+ const r = locationHistory.current.findLastLocation(routeInfo);
711
3245
  routeInfo.pushedByRoute = r === null || r === void 0 ? void 0 : r.pushedByRoute;
3246
+ // Navigating to a new tab.
712
3247
  }
713
3248
  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;
3249
+ /**
3250
+ * If we are switching tabs grab the last route info for the
3251
+ * tab and use its `pushedByRoute`.
3252
+ */
3253
+ const lastRoute = locationHistory.current.getCurrentRouteInfoForTab(routeInfo.tab);
3254
+ /**
3255
+ * Tab bar switches (direction 'none') should not create cross-tab back
3256
+ * navigation. Only inherit pushedByRoute from the tab's own history.
3257
+ */
3258
+ if (routeInfo.routeDirection === 'none') {
3259
+ routeInfo.pushedByRoute = lastRoute === null || lastRoute === void 0 ? void 0 : lastRoute.pushedByRoute;
3260
+ }
3261
+ else {
3262
+ routeInfo.pushedByRoute = (_d = lastRoute === null || lastRoute === void 0 ? void 0 : lastRoute.pushedByRoute) !== null && _d !== void 0 ? _d : leavingLocationInfo.pathname;
3263
+ }
3264
+ // Triggered by `navigate()` with replace or a `<Navigate />` component, etc.
717
3265
  }
718
3266
  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
3267
  /**
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.
3268
+ * Make sure to set the `lastPathname`, etc.. to the current route
3269
+ * so the page transitions out.
3270
+ */
3271
+ const currentRouteInfo = locationHistory.current.current();
3272
+ /**
3273
+ * Special handling for `replace` to ensure correct `pushedByRoute`
3274
+ * and `lastPathname`.
3275
+ *
3276
+ * If going from `/home` to `/child`, then replacing from
3277
+ * `/child` to `/home`, we don't want the route info to
3278
+ * say that `/home` was pushed by `/home` which is not correct.
725
3279
  */
726
3280
  const currentPushedBy = currentRouteInfo === null || currentRouteInfo === void 0 ? void 0 : currentRouteInfo.pushedByRoute;
727
3281
  const pushedByRoute = currentPushedBy !== undefined && currentPushedBy !== routeInfo.pathname
@@ -739,46 +3293,121 @@ class IonRouterInner extends React.PureComponent {
739
3293
  routeInfo.routeDirection = routeInfo.routeDirection || (currentRouteInfo === null || currentRouteInfo === void 0 ? void 0 : currentRouteInfo.routeDirection);
740
3294
  routeInfo.routeAnimation = routeInfo.routeAnimation || (currentRouteInfo === null || currentRouteInfo === void 0 ? void 0 : currentRouteInfo.routeAnimation);
741
3295
  }
742
- this.locationHistory.add(routeInfo);
3296
+ locationHistory.current.add(routeInfo);
743
3297
  }
744
- this.setState({
745
- routeInfo,
746
- });
3298
+ setRouteInfo(routeInfo);
747
3299
  }
748
- this.incomingRouteParams = undefined;
749
- }
3300
+ // Update the current location key after processing the history change.
3301
+ // This ensures the forward stack records the correct key when navigating back.
3302
+ currentLocationKeyRef.current = location.key;
3303
+ incomingRouteParams.current = null;
3304
+ };
750
3305
  /**
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.
3306
+ * Resets the specified tab to its initial, root route.
3307
+ *
3308
+ * @param tab The tab to reset.
3309
+ * @param originalHref The original href for the tab.
3310
+ * @param originalRouteOptions The original route options for the tab.
755
3311
  */
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);
3312
+ const handleResetTab = (tab, originalHref, originalRouteOptions) => {
3313
+ const routeInfo = locationHistory.current.getFirstRouteInfoForTab(tab);
3314
+ if (routeInfo) {
3315
+ const [pathname, search] = originalHref.split('?');
3316
+ const newRouteInfo = Object.assign({}, routeInfo);
3317
+ newRouteInfo.pathname = pathname;
3318
+ newRouteInfo.search = search ? '?' + search : '';
3319
+ newRouteInfo.routeOptions = originalRouteOptions;
3320
+ incomingRouteParams.current = Object.assign(Object.assign({}, newRouteInfo), { routeAction: 'pop', routeDirection: 'back' });
3321
+ navigate(newRouteInfo.pathname + (newRouteInfo.search || ''));
3322
+ }
3323
+ };
3324
+ /**
3325
+ * Handles tab changes.
3326
+ *
3327
+ * @param tab The tab to switch to.
3328
+ * @param path The new path for the tab.
3329
+ * @param routeOptions Additional route options.
3330
+ */
3331
+ const handleChangeTab = (tab, path, routeOptions) => {
3332
+ if (!path) {
3333
+ return;
3334
+ }
3335
+ const routeInfo = locationHistory.current.getCurrentRouteInfoForTab(tab);
3336
+ const [pathname, search] = path.split('?');
3337
+ // User has navigated to the current tab before.
3338
+ if (routeInfo) {
3339
+ const routeParams = Object.assign(Object.assign({}, routeInfo), { routeAction: 'push', routeDirection: 'none' });
3340
+ /**
3341
+ * User is navigating to the same tab.
3342
+ * e.g., `/tabs/home` → `/tabs/home`
3343
+ */
3344
+ if (routeInfo.pathname === pathname) {
3345
+ const newSearch = search ? '?' + search : routeInfo.search;
3346
+ incomingRouteParams.current = Object.assign(Object.assign({}, routeParams), { search: newSearch || '', routeOptions });
3347
+ navigate(routeInfo.pathname + (newSearch || ''));
3348
+ /**
3349
+ * User is navigating to a different tab.
3350
+ * e.g., `/tabs/home` → `/tabs/settings`
3351
+ */
3352
+ }
3353
+ else {
3354
+ incomingRouteParams.current = Object.assign(Object.assign({}, routeParams), { pathname, search: search ? '?' + search : '', routeOptions });
3355
+ navigate(pathname + (search ? '?' + search : ''));
3356
+ }
3357
+ // User has not navigated to this tab before.
771
3358
  }
772
3359
  else {
773
- this.props.history.replace(path);
3360
+ const fullPath = pathname + (search ? '?' + search : '');
3361
+ handleNavigate(fullPath, 'push', 'none', undefined, routeOptions, tab);
774
3362
  }
775
- }
776
- handleNavigateBack(defaultHref = '/', routeAnimation) {
3363
+ };
3364
+ /**
3365
+ * Set the current active tab in `locationHistory`.
3366
+ * This is crucial for maintaining tab history since each tab has
3367
+ * its own navigation stack.
3368
+ *
3369
+ * @param tab The tab to set as active.
3370
+ */
3371
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3372
+ const handleSetCurrentTab = (tab, _routeInfo) => {
3373
+ currentTab.current = tab;
3374
+ const current = locationHistory.current.current();
3375
+ if (!current) {
3376
+ // locationHistory not yet seeded (e.g., called during initial render
3377
+ // before mount effect). The mount effect will seed the correct entry.
3378
+ return;
3379
+ }
3380
+ const ri = Object.assign({}, current);
3381
+ if (ri.tab !== tab) {
3382
+ ri.tab = tab;
3383
+ locationHistory.current.update(ri);
3384
+ }
3385
+ };
3386
+ /**
3387
+ * Handles the native back button press.
3388
+ * It's usually called when a user presses the platform-native back action.
3389
+ */
3390
+ const handleNativeBack = () => {
3391
+ navigate(-1);
3392
+ };
3393
+ /**
3394
+ * Used to manage the back navigation within the Ionic React's routing
3395
+ * system. It's deeply integrated with Ionic's view lifecycle, animations,
3396
+ * and its custom history tracking (`locationHistory`) to provide a
3397
+ * native-like transition and maintain correct application state.
3398
+ *
3399
+ * @param defaultHref The fallback URL to navigate to if there's no
3400
+ * previous entry in the `locationHistory` stack.
3401
+ * @param routeAnimation A custom animation builder to override the
3402
+ * default "back" animation.
3403
+ */
3404
+ const handleNavigateBack = (defaultHref, routeAnimation) => {
777
3405
  const config = getConfig();
778
- defaultHref = defaultHref ? defaultHref : config && config.get('backButtonDefaultHref');
779
- const routeInfo = this.locationHistory.current();
3406
+ defaultHref = defaultHref !== null && defaultHref !== void 0 ? defaultHref : (config && config.get('backButtonDefaultHref'));
3407
+ const routeInfo = locationHistory.current.current();
3408
+ // It's a linear navigation.
780
3409
  if (routeInfo && routeInfo.pushedByRoute) {
781
- const prevInfo = this.locationHistory.findLastLocation(routeInfo);
3410
+ const prevInfo = locationHistory.current.findLastLocation(routeInfo);
782
3411
  if (prevInfo) {
783
3412
  /**
784
3413
  * This needs to be passed to handleNavigate
@@ -786,160 +3415,280 @@ class IonRouterInner extends React.PureComponent {
786
3415
  * will be overridden.
787
3416
  */
788
3417
  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();
3418
+ incomingRouteParams.current = Object.assign(Object.assign({}, prevInfo), { routeAction: 'pop', routeDirection: 'back', routeAnimation: incomingAnimation });
3419
+ /**
3420
+ * Check if it's a simple linear back navigation (not tabbed).
3421
+ * e.g., `/home` `/settings` back to `/home`
3422
+ */
3423
+ const condition1 = routeInfo.lastPathname === routeInfo.pushedByRoute;
3424
+ const condition2 = prevInfo.pathname === routeInfo.pushedByRoute && !routeInfo.tab && !prevInfo.tab;
3425
+ if (condition1 || condition2) {
3426
+ // Record the current location key so browser forward is detectable
3427
+ forwardStack.current.push(currentLocationKeyRef.current);
3428
+ navigate(-1);
807
3429
  }
808
3430
  else {
809
- this.handleNavigate(prevInfo.pathname + (prevInfo.search || ''), 'pop', 'back', incomingAnimation);
3431
+ /**
3432
+ * It's a non-linear back navigation.
3433
+ * e.g., direct link or tab switch or nested navigation with redirects
3434
+ * Clear forward stack since the REPLACE-based navigate resets history
3435
+ * position, making any prior forward entries unreachable.
3436
+ */
3437
+ forwardStack.current = [];
3438
+ handleNavigate(prevInfo.pathname + (prevInfo.search || ''), 'pop', 'back', incomingAnimation);
810
3439
  }
3440
+ /**
3441
+ * `pushedByRoute` exists, but no corresponding previous entry in
3442
+ * the history stack.
3443
+ */
811
3444
  }
812
- else {
813
- this.handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
3445
+ else if (defaultHref) {
3446
+ handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
814
3447
  }
3448
+ /**
3449
+ * No `pushedByRoute` (e.g., initial page load or tab root).
3450
+ * Navigate to defaultHref so the back button works on direct
3451
+ * deep-link loads (e.g., loading /tab1/child directly).
3452
+ * Only navigate when defaultHref is explicitly set. The core
3453
+ * back-button component hides itself when no defaultHref is
3454
+ * provided, so a click here means the user set one intentionally.
3455
+ */
815
3456
  }
816
- else {
817
- this.handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
3457
+ else if (defaultHref) {
3458
+ handleNavigate(defaultHref, 'pop', 'back', routeAnimation);
818
3459
  }
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 || ''));
3460
+ };
3461
+ /**
3462
+ * Used to programmatically navigate through the app.
3463
+ *
3464
+ * @param path The path to navigate to.
3465
+ * @param routeAction The action to take (push, replace, etc.).
3466
+ * @param routeDirection The direction of the navigation (forward,
3467
+ * back, etc.).
3468
+ * @param routeAnimation The animation to use for the transition.
3469
+ * @param routeOptions Additional options for the route.
3470
+ * @param tab The tab to navigate to, if applicable.
3471
+ */
3472
+ const handleNavigate = (path, routeAction, routeDirection, routeAnimation, routeOptions, tab) => {
3473
+ var _a;
3474
+ const normalizedRouteDirection = routeAction === 'push' && routeDirection === undefined ? 'forward' : routeDirection;
3475
+ // When navigating from tabs context, we need to determine if the destination
3476
+ // is also within tabs. If not, we should clear the tab context.
3477
+ let navigationTab = tab;
3478
+ // If no explicit tab is provided and we're in a tab context,
3479
+ // check if the destination path is outside of the current tab context.
3480
+ // Uses history-based tab detection instead of URL pattern matching,
3481
+ // so it works with any tab URL structure.
3482
+ if (!tab && currentTab.current && path) {
3483
+ // Check if destination was previously visited in a tab context
3484
+ const destinationTab = locationHistory.current.findTabForPathname(path);
3485
+ if (destinationTab) {
3486
+ // Previously visited as a tab route - use the known tab
3487
+ navigationTab = destinationTab;
3488
+ }
3489
+ else {
3490
+ // New destination - check if it's a child of the current tab's root path
3491
+ const tabFirstRoute = locationHistory.current.getFirstRouteInfoForTab(currentTab.current);
3492
+ if (tabFirstRoute) {
3493
+ const tabRootPath = tabFirstRoute.pathname;
3494
+ if (path === tabRootPath || path.startsWith(tabRootPath + '/')) {
3495
+ // Still within the current tab's path hierarchy
3496
+ navigationTab = currentTab.current;
3497
+ }
3498
+ else {
3499
+ // Destination is outside the current tab context
3500
+ currentTab.current = undefined;
3501
+ navigationTab = undefined;
3502
+ }
3503
+ }
3504
+ }
828
3505
  }
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);
3506
+ // When a replace action targets the same URL as the immediately previous
3507
+ // history entry, using replaceState would create a duplicate browser history
3508
+ // entry (the previous and current entries would both have the same URL).
3509
+ // Navigate back to the previous entry instead to avoid the duplicate.
3510
+ // Keep routeAction as 'replace' so StackManager correctly unmounts the
3511
+ // leaving view through handleLeavingViewUnmount rather than treating it
3512
+ // as a browser-back pop (which preserves views for back/forward history).
3513
+ if (routeAction === 'replace') {
3514
+ const prevEntry = locationHistory.current.previous();
3515
+ const currentEntry = locationHistory.current.current();
3516
+ const prevPath = prevEntry ? prevEntry.pathname + (prevEntry.search || '') : undefined;
3517
+ if (prevEntry && currentEntry && prevEntry !== currentEntry && prevPath === path) {
3518
+ incomingRouteParams.current = Object.assign(Object.assign({}, prevEntry), { routeAction: 'replace', routeDirection: 'back', routeAnimation });
3519
+ forwardStack.current.push(currentLocationKeyRef.current);
3520
+ navigate(-1);
3521
+ return;
3522
+ }
836
3523
  }
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);
3524
+ const baseParams = (_a = incomingRouteParams.current) !== null && _a !== void 0 ? _a : {};
3525
+ incomingRouteParams.current = Object.assign(Object.assign({}, baseParams), { routeAction, routeDirection: normalizedRouteDirection, routeOptions,
3526
+ routeAnimation, tab: navigationTab });
3527
+ navigate(path, { replace: routeAction !== 'push' });
3528
+ };
3529
+ /**
3530
+ * Navigates to a new root path, clearing Ionic's navigation history so that
3531
+ * canGoBack() returns false after the transition. All previously mounted views
3532
+ * are unmounted. Useful for post-login / post-logout root navigation.
3533
+ *
3534
+ * @param pathname The path to navigate to.
3535
+ * @param routeAnimation An optional custom animation builder.
3536
+ */
3537
+ const handleNavigateRoot = (pathname, routeAnimation) => {
3538
+ currentTab.current = undefined;
3539
+ forwardStack.current = [];
3540
+ incomingRouteParams.current = {
3541
+ routeAction: 'replace',
3542
+ routeDirection: 'root',
3543
+ routeAnimation,
3544
+ };
3545
+ navigate(pathname, { replace: true });
3546
+ };
3547
+ const routeMangerContextValue = {
3548
+ canGoBack: () => locationHistory.current.canGoBack(),
3549
+ clearOutlet: viewStack.current.clear,
3550
+ findViewItemByPathname: viewStack.current.findViewItemByPathname,
3551
+ getChildrenToRender: viewStack.current.getChildrenToRender,
3552
+ getViewItemsForOutlet: viewStack.current.getViewItemsForOutlet.bind(viewStack.current),
3553
+ goBack: () => handleNavigateBack(),
3554
+ createViewItem: viewStack.current.createViewItem,
3555
+ findViewItemByRouteInfo: viewStack.current.findViewItemByRouteInfo,
3556
+ findLeavingViewItemByRouteInfo: viewStack.current.findLeavingViewItemByRouteInfo,
3557
+ addViewItem: viewStack.current.add,
3558
+ unMountViewItem: viewStack.current.remove,
3559
+ };
3560
+ return (React.createElement(RouteManagerContext.Provider, { value: routeMangerContextValue },
3561
+ React.createElement(NavManager, { ionRoute: IonRouteInner, stackManager: StackManager, routeInfo: routeInfo, onNativeBack: handleNativeBack, onNavigateBack: handleNavigateBack, onNavigate: handleNavigate, onNavigateRoot: handleNavigateRoot, onSetCurrentTab: handleSetCurrentTab, onChangeTab: handleChangeTab, onResetTab: handleResetTab, locationHistory: locationHistory.current }, children)));
3562
+ };
844
3563
  IonRouter.displayName = 'IonRouter';
845
3564
 
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
- }
3565
+ /**
3566
+ * `IonReactRouter` facilitates the integration of Ionic's specific
3567
+ * navigation and UI management with the standard React Router mechanisms,
3568
+ * allowing an inner Ionic-specific router (`IonRouter`) to react to
3569
+ * navigation events.
3570
+ */
3571
+ /**
3572
+ * This component acts as a bridge to ensure React Router hooks like
3573
+ * `useLocation` and `useNavigationType` are called within the valid
3574
+ * context of a `<BrowserRouter>`.
3575
+ *
3576
+ * It was split from `IonReactRouter` because these hooks must be
3577
+ * descendants of a `<Router>` component, which `BrowserRouter` provides.
3578
+ */
3579
+ const RouterContent$2 = ({ children }) => {
3580
+ const location = useLocation();
3581
+ const navigationType = useNavigationType();
3582
+ const historyListenHandler = useRef();
3583
+ const registerHistoryListener = useCallback((cb) => {
3584
+ historyListenHandler.current = cb;
3585
+ }, []);
854
3586
  /**
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.
3587
+ * Processes navigation changes within the application.
3588
+ *
3589
+ * Its purpose is to relay the current `location` and the associated
3590
+ * `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
3591
+ * primarily for `IonRouter` to manage Ionic-specific UI updates and
3592
+ * navigation stack behavior.
3593
+ *
3594
+ * @param loc The current browser history location object.
3595
+ * @param act The type of navigation action ('PUSH', 'POP', or
3596
+ * 'REPLACE').
861
3597
  */
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);
3598
+ const handleHistoryChange = useCallback((loc, act) => {
3599
+ if (historyListenHandler.current) {
3600
+ historyListenHandler.current(loc, act);
867
3601
  }
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
- }
3602
+ }, []);
3603
+ useEffect(() => {
3604
+ handleHistoryChange(location, navigationType);
3605
+ }, [location, navigationType, handleHistoryChange]);
3606
+ return React.createElement(IonRouter, { registerHistoryListener: registerHistoryListener }, children);
3607
+ };
3608
+ const IonReactRouter = (_a) => {
3609
+ var { children } = _a, browserRouterProps = __rest(_a, ["children"]);
3610
+ return (React.createElement(BrowserRouter, Object.assign({}, browserRouterProps),
3611
+ React.createElement(RouterContent$2, null, children)));
3612
+ };
878
3613
 
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
- }
3614
+ /**
3615
+ * `IonReactMemoryRouter` provides a way to use `react-router` in
3616
+ * environments where a traditional browser history (like `BrowserRouter`)
3617
+ * isn't available or desirable.
3618
+ */
3619
+ const RouterContent$1 = ({ children }) => {
3620
+ const location = useLocation$1();
3621
+ const navigationType = useNavigationType$1();
3622
+ const historyListenHandler = useRef();
3623
+ const registerHistoryListener = useCallback((cb) => {
3624
+ historyListenHandler.current = cb;
3625
+ }, []);
886
3626
  /**
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.
3627
+ * Processes navigation changes within the application.
3628
+ *
3629
+ * Its purpose is to relay the current `location` and the associated
3630
+ * `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
3631
+ * primarily for `IonRouter` to manage Ionic-specific UI updates and
3632
+ * navigation stack behavior.
3633
+ *
3634
+ * @param location The current browser history location object.
3635
+ * @param action The type of navigation action ('PUSH', 'POP', or
3636
+ * 'REPLACE').
893
3637
  */
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);
3638
+ const handleHistoryChange = useCallback((loc, act) => {
3639
+ if (historyListenHandler.current) {
3640
+ historyListenHandler.current(loc, act);
899
3641
  }
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
- }
3642
+ }, []);
3643
+ useEffect(() => {
3644
+ handleHistoryChange(location, navigationType);
3645
+ }, [location, navigationType, handleHistoryChange]);
3646
+ return React.createElement(IonRouter, { registerHistoryListener: registerHistoryListener }, children);
3647
+ };
3648
+ const IonReactMemoryRouter = (_a) => {
3649
+ var { children } = _a, routerProps = __rest(_a, ["children"]);
3650
+ return (React.createElement(MemoryRouter, Object.assign({}, routerProps),
3651
+ React.createElement(RouterContent$1, null, children)));
3652
+ };
910
3653
 
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
- }
3654
+ /**
3655
+ * `IonReactHashRouter` provides a way to use hash-based routing in Ionic
3656
+ * React applications.
3657
+ */
3658
+ const RouterContent = ({ children }) => {
3659
+ const location = useLocation();
3660
+ const navigationType = useNavigationType();
3661
+ const historyListenHandler = useRef();
3662
+ const registerHistoryListener = useCallback((cb) => {
3663
+ historyListenHandler.current = cb;
3664
+ }, []);
919
3665
  /**
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.
3666
+ * Processes navigation changes within the application.
3667
+ *
3668
+ * Its purpose is to relay the current `location` and the associated
3669
+ * `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
3670
+ * primarily for `IonRouter` to manage Ionic-specific UI updates and
3671
+ * navigation stack behavior.
3672
+ *
3673
+ * @param location The current browser history location object.
3674
+ * @param action The type of navigation action ('PUSH', 'POP', or
3675
+ * 'REPLACE').
926
3676
  */
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);
3677
+ const handleHistoryChange = useCallback((loc, act) => {
3678
+ if (historyListenHandler.current) {
3679
+ historyListenHandler.current(loc, act);
932
3680
  }
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
- }
3681
+ }, []);
3682
+ useEffect(() => {
3683
+ handleHistoryChange(location, navigationType);
3684
+ }, [location, navigationType, handleHistoryChange]);
3685
+ return React.createElement(IonRouter, { registerHistoryListener: registerHistoryListener }, children);
3686
+ };
3687
+ const IonReactHashRouter = (_a) => {
3688
+ var { children } = _a, routerProps = __rest(_a, ["children"]);
3689
+ return (React.createElement(HashRouter, Object.assign({}, routerProps),
3690
+ React.createElement(RouterContent, null, children)));
3691
+ };
943
3692
 
944
3693
  export { IonReactHashRouter, IonReactMemoryRouter, IonReactRouter };
945
3694
  //# sourceMappingURL=index.js.map