@ionic/react-router 8.7.12 → 8.7.13-dev.11765472680.117902a6

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