hybrid-navigation 5.1.1 → 5.3.0

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.
Files changed (101) hide show
  1. package/README.md +9 -20
  2. package/android/src/main/java/com/navigation/androidx/AwesomeFragment.java +5 -13
  3. package/android/src/main/java/com/navigation/androidx/DefaultTabBarProvider.java +2 -2
  4. package/android/src/main/java/com/navigation/androidx/TabBarFragment.java +0 -50
  5. package/android/src/main/java/com/navigation/androidx/TabBarItem.java +0 -4
  6. package/android/src/main/java/com/reactnative/hybridnavigation/GlobalStyle.java +0 -7
  7. package/android/src/main/java/com/reactnative/hybridnavigation/HybridFragment.java +7 -43
  8. package/android/src/main/java/com/reactnative/hybridnavigation/NativeNavigation.java +5 -39
  9. package/android/src/main/java/com/reactnative/hybridnavigation/ReactFragment.java +62 -135
  10. package/android/src/main/java/com/reactnative/hybridnavigation/ReactManager.java +0 -20
  11. package/android/src/main/java/com/reactnative/hybridnavigation/ReactTabBarFragment.java +10 -21
  12. package/android/src/main/java/com/reactnative/hybridnavigation/navigator/ScreenNavigator.java +39 -87
  13. package/android/src/main/java/com/reactnative/hybridnavigation/navigator/TabNavigator.java +2 -16
  14. package/dist/NativeEvent.d.ts +1 -11
  15. package/dist/NativeNavigation.d.ts +7 -6
  16. package/dist/Navigation.d.ts +8 -20
  17. package/dist/Navigation.js +32 -163
  18. package/dist/NavigationComponentWrap.d.ts +3 -3
  19. package/dist/Navigator.d.ts +4 -5
  20. package/dist/Navigator.js +13 -36
  21. package/dist/Options.d.ts +2 -2
  22. package/dist/Route.d.ts +12 -33
  23. package/dist/handler/DispatchCommandHandler.d.ts +3 -17
  24. package/dist/handler/DispatchCommandHandler.js +17 -62
  25. package/dist/handler/LayoutCommandHandler.d.ts +2 -3
  26. package/dist/handler/LayoutCommandHandler.js +0 -3
  27. package/dist/handler/LeaveGuardHandler.d.ts +2 -2
  28. package/dist/handler/LeaveGuardHandler.js +88 -46
  29. package/dist/handler/LifecycleEventHandler.d.ts +2 -14
  30. package/dist/handler/LifecycleEventHandler.js +2 -79
  31. package/dist/handler/ResultEventHandler.d.ts +0 -1
  32. package/dist/handler/ResultEventHandler.js +0 -3
  33. package/dist/handler/SceneExitHandler.d.ts +3 -0
  34. package/dist/handler/SceneExitHandler.js +76 -0
  35. package/dist/hooks.d.ts +2 -2
  36. package/dist/hooks.js +39 -22
  37. package/dist/index.d.ts +1 -12
  38. package/dist/index.js +0 -3
  39. package/dist/router/index.d.ts +0 -1
  40. package/dist/router/index.js +43 -11
  41. package/dist/sceneCoverage.d.ts +2 -0
  42. package/dist/sceneCoverage.js +25 -0
  43. package/dist/store.d.ts +0 -2
  44. package/dist/store.js +0 -4
  45. package/ios/HBDGlobalStyle.h +0 -1
  46. package/ios/HBDGlobalStyle.mm +0 -7
  47. package/ios/HybridNavigation.h +0 -1
  48. package/ios/Navigator/HBDScreenNavigator.mm +89 -237
  49. package/ios/Navigator/HBDStackNavigator.mm +1 -1
  50. package/ios/Navigator/HBDTabNavigator.mm +15 -30
  51. package/ios/React/HBDNativeNavigation.mm +4 -31
  52. package/ios/React/HBDReactBridgeManager.h +0 -5
  53. package/ios/React/HBDReactBridgeManager.mm +0 -17
  54. package/ios/ViewController/HBDReactViewController.h +1 -1
  55. package/ios/ViewController/HBDReactViewController.mm +34 -9
  56. package/ios/ViewController/HBDTabBarController.h +2 -11
  57. package/ios/ViewController/HBDTabBarController.mm +14 -170
  58. package/ios/ViewController/HBDViewController.h +0 -1
  59. package/ios/ViewController/HBDViewController.mm +9 -57
  60. package/ios/ViewController/UIViewController+HBD.h +2 -0
  61. package/ios/ViewController/UIViewController+HBD.mm +5 -0
  62. package/package.json +1 -3
  63. package/src/NativeEvent.ts +1 -12
  64. package/src/NativeNavigation.ts +8 -7
  65. package/src/Navigation.ts +49 -257
  66. package/src/NavigationComponentWrap.tsx +3 -11
  67. package/src/Navigator.ts +15 -45
  68. package/src/Options.ts +2 -3
  69. package/src/Route.ts +17 -54
  70. package/src/handler/DispatchCommandHandler.ts +29 -109
  71. package/src/handler/LayoutCommandHandler.ts +2 -6
  72. package/src/handler/LeaveGuardHandler.ts +97 -46
  73. package/src/handler/LifecycleEventHandler.ts +22 -122
  74. package/src/handler/ResultEventHandler.ts +0 -6
  75. package/src/handler/SceneExitHandler.ts +86 -0
  76. package/src/hooks.ts +39 -22
  77. package/src/index.ts +0 -14
  78. package/src/router/index.ts +45 -12
  79. package/src/sceneCoverage.ts +30 -0
  80. package/src/store.ts +0 -5
  81. package/dist/defineRoutes.d.ts +0 -19
  82. package/dist/defineRoutes.js +0 -6
  83. package/dist/handler/PresentationCoordinator.d.ts +0 -24
  84. package/dist/handler/PresentationCoordinator.js +0 -456
  85. package/dist/handler/TabEventHandler.d.ts +0 -8
  86. package/dist/handler/TabEventHandler.js +0 -25
  87. package/dist/reveal.d.ts +0 -46
  88. package/dist/reveal.js +0 -431
  89. package/dist/routeGraph.d.ts +0 -12
  90. package/dist/routeGraph.js +0 -68
  91. package/dist/testing.d.ts +0 -79
  92. package/dist/testing.js +0 -251
  93. package/ios/ViewController/HBDTabBarRenderer.h +0 -28
  94. package/src/defineRoutes.ts +0 -46
  95. package/src/handler/PresentationCoordinator.ts +0 -566
  96. package/src/handler/TabEventHandler.ts +0 -31
  97. package/src/reveal.ts +0 -565
  98. package/src/routeGraph.ts +0 -87
  99. package/src/testing.ts +0 -395
  100. package/testing.d.ts +0 -1
  101. package/testing.js +0 -3
package/src/Route.ts CHANGED
@@ -1,33 +1,8 @@
1
1
  import type { NavigationItem } from './Options';
2
- import type { CustomLayoutMap, NavigationParamList, NavigationTypeConfig } from './index';
3
-
4
- export type Visibility = 'visible' | 'invisible' | 'pending';
2
+ import type { CustomLayoutMap, NavigationParamList } from './index';
5
3
 
6
4
  export type SceneLifecycleState = 'created' | 'visible' | 'invisible' | 'destroyed';
7
5
 
8
- export interface SceneInfo {
9
- sceneId: string;
10
- moduleName?: string;
11
- mode: LayoutMode;
12
- presentingId: string | null;
13
- state: SceneLifecycleState;
14
- }
15
-
16
- export interface TabPressEvent {
17
- index: number;
18
- tabKey?: string;
19
- previousIndex: number;
20
- reselected: boolean;
21
- }
22
-
23
- export type TabPressListener = (event: TabPressEvent) => void;
24
-
25
- export interface NavigationSnapshot {
26
- rootGeneration: number;
27
- currentRoute: Route | null;
28
- layers: RouteGraph[];
29
- }
30
-
31
6
  export type DispatchResultCode =
32
7
  | 'ok'
33
8
  | 'intercepted'
@@ -46,10 +21,6 @@ export interface DispatchResult {
46
21
  sceneId?: string;
47
22
  }
48
23
 
49
- export type CloseTarget = 'self' | 'presented';
50
-
51
- export type CoveredPolicy = 'fail' | 'defer';
52
-
53
24
  export type SceneExitRestoreReason = DispatchResultCode | 'exit_error';
54
25
 
55
26
  export interface SceneExitHandler {
@@ -60,11 +31,8 @@ export interface SceneExitHandler {
60
31
  }
61
32
 
62
33
  export interface CloseSelfOptions<T extends ResultMap = ResultMap> {
63
- result?: {
64
- code: number;
65
- data?: T | null;
66
- };
67
- onCovered?: CoveredPolicy;
34
+ bypassBeforeRemove?: boolean;
35
+ result?: { code: number; data?: T | null };
68
36
  }
69
37
 
70
38
  export type LeaveAction =
@@ -77,9 +45,12 @@ export type LeaveAction =
77
45
  | 'close'
78
46
  | 'redirectTo';
79
47
 
48
+ export type BeforeRemoveSource = 'back' | 'self' | 'external';
49
+
80
50
  export interface BeforeRemoveEvent {
81
51
  sceneId: string;
82
52
  action: LeaveAction;
53
+ source: BeforeRemoveSource;
83
54
  proceed: () => Promise<DispatchResult>;
84
55
  }
85
56
 
@@ -125,18 +96,8 @@ export type ScreenRoute<
125
96
 
126
97
  export type HasTypedRoutes = keyof NavigationParamList extends never ? false : true;
127
98
 
128
- export type AllowUnregisteredRoutes = NavigationTypeConfig extends {
129
- allowUnregisteredRoutes: true;
130
- }
131
- ? true
132
- : false;
133
-
134
- export type RegisteredRouteName = Extract<keyof NavigationParamList, string>;
135
-
136
99
  export type RouteName = HasTypedRoutes extends true
137
- ? AllowUnregisteredRoutes extends true
138
- ? RegisteredRouteName | (string & {})
139
- : RegisteredRouteName
100
+ ? Extract<keyof NavigationParamList, string>
140
101
  : string;
141
102
 
142
103
  type RawRouteEntry<Name extends string> = Name extends keyof NavigationParamList
@@ -181,11 +142,9 @@ type RequiredKeysOf<T> = {
181
142
  export type IsPropsRequired<P> = [RequiredKeysOf<P>] extends [never] ? false : true;
182
143
 
183
144
  export type ScreenPropsArgs<Name extends string> = HasTypedRoutes extends true
184
- ? [Name] extends [RegisteredRouteName]
185
- ? IsPropsRequired<RoutePropsOf<Name>> extends true
186
- ? [props: RoutePropsOf<Name>, options?: NavigationItem]
187
- : [props?: RoutePropsOf<Name>, options?: NavigationItem]
188
- : [props?: Record<string, any>, options?: NavigationItem]
145
+ ? IsPropsRequired<RoutePropsOf<Name>> extends true
146
+ ? [props: RoutePropsOf<Name>, options?: NavigationItem]
147
+ : [props?: RoutePropsOf<Name>, options?: NavigationItem]
189
148
  : [props?: Record<string, any>, options?: NavigationItem];
190
149
 
191
150
  export type Screen<Name extends RouteName = RouteName> = HasTypedRoutes extends true
@@ -220,7 +179,6 @@ export interface Tabs {
220
179
  children: Array<Layout>;
221
180
  options?: {
222
181
  selectedIndex?: number;
223
- renderer?: string;
224
182
  };
225
183
  };
226
184
  }
@@ -245,7 +203,6 @@ export type CustomLayout = HasCustomLayouts extends true
245
203
  : never;
246
204
 
247
205
  export type BuiltInLayout = TypedScreen | Stack | Tabs | Drawer;
248
- export type BuildInLayout = BuiltInLayout;
249
206
  export type Layout = BuiltInLayout | CustomLayout;
250
207
 
251
208
  export type RouteMode = 'modal' | 'present' | 'push';
@@ -259,6 +216,12 @@ export interface Route {
259
216
  requestCode: number;
260
217
  }
261
218
 
219
+ export interface NavigationSnapshot {
220
+ rootGeneration: number;
221
+ currentRoute: Route | null;
222
+ layers: RouteGraph[];
223
+ }
224
+
262
225
  export interface RouteGraph {
263
226
  layout: string;
264
227
  sceneId: string;
@@ -268,7 +231,7 @@ export interface RouteGraph {
268
231
 
269
232
  export interface RouteConfig {
270
233
  path?: string;
271
- dependency?: string;
234
+ dependency?: RouteName;
272
235
  mode?: RouteMode;
273
236
  options?: NavigationItem;
274
237
  lazy?: boolean;
@@ -1,23 +1,8 @@
1
1
  import NativeNavigation, { DispatchResultWire } from '../NativeNavigation';
2
2
  import { NavigationItem } from '../Options';
3
- import type {
4
- BuildInLayout,
5
- CloseTarget,
6
- CoveredPolicy,
7
- DispatchResult,
8
- DispatchResultCode,
9
- Layout,
10
- } from '../Route';
11
- import { resultHandler } from './ResultEventHandler';
12
-
13
- const INTERCEPT_CHECKED_PROP = '__hbdInterceptChecked';
14
- const INTERNAL_DISPATCH_PROPS = [
15
- INTERCEPT_CHECKED_PROP,
16
- 'onCovered',
17
- 'bypassBeforeRemove',
18
- '__hbdBypassBeforeRemove',
19
- '__hbdApprovedBeforeRemoveScenes',
20
- ] as const;
3
+ import type { DispatchResult, DispatchResultCode, Layout } from '../Route';
4
+ import { leaveGuardHandler, BEFORE_REMOVE_SOURCE_PROP } from './LeaveGuardHandler';
5
+ import { closeWithExitHandler } from './SceneExitHandler';
21
6
 
22
7
  const VALID_DISPATCH_CODES = new Set<DispatchResultCode>([
23
8
  'ok',
@@ -42,14 +27,12 @@ export function normalizeDispatchResult(
42
27
  : wire.ok
43
28
  ? 'ok'
44
29
  : 'invalid_action';
45
- const result: DispatchResult = { ok: Boolean(wire.ok), code };
46
- if (wire.message) {
47
- result.message = wire.message;
48
- }
49
- if (wire.sceneId) {
50
- result.sceneId = wire.sceneId;
51
- }
52
- return result;
30
+ return {
31
+ ok: Boolean(wire.ok),
32
+ code,
33
+ ...(wire.message && { message: wire.message }),
34
+ ...(wire.sceneId && { sceneId: wire.sceneId }),
35
+ };
53
36
  }
54
37
 
55
38
  export interface DispatchParams {
@@ -58,17 +41,9 @@ export interface DispatchParams {
58
41
  moduleName?: string;
59
42
  from?: string | number;
60
43
  to?: string | number;
61
- layout?: BuildInLayout | Layout;
44
+ layout?: Layout;
62
45
  popToRoot?: boolean;
63
- tabKey?: string;
64
46
  requestCode?: number;
65
- target?: CloseTarget;
66
- onCovered?: CoveredPolicy;
67
- result?: {
68
- code: number;
69
- data?: any;
70
- };
71
- bypassBeforeRemove?: boolean;
72
47
  props?: object;
73
48
  options?: NavigationItem;
74
49
  [index: string]: any;
@@ -86,26 +61,23 @@ export type NavigationInterceptor = (
86
61
  params: InterceptParams,
87
62
  ) => boolean | Promise<boolean>;
88
63
 
89
- export type DispatchMiddleware = (
90
- sceneId: string,
91
- action: string,
92
- params: DispatchParams,
93
- next: (sceneId: string, action: string, params: DispatchParams) => Promise<DispatchResult>,
94
- ) => Promise<DispatchResult>;
95
-
96
64
  export default class DispatchCommandHandler {
97
65
  private interceptors: NavigationInterceptor[] = [];
98
- private systemMiddlewares: DispatchMiddleware[] = [];
99
-
100
- addMiddleware(middleware: DispatchMiddleware) {
101
- this.systemMiddlewares.push(middleware);
102
- }
103
66
 
104
- removeMiddleware(middleware: DispatchMiddleware) {
105
- this.systemMiddlewares = this.systemMiddlewares.filter(item => item !== middleware);
67
+ async dispatch(
68
+ sceneId: string,
69
+ action: string,
70
+ params: DispatchParams,
71
+ ): Promise<DispatchResult> {
72
+ return leaveGuardHandler.middleware(sceneId, action, params, this.dispatchApproved);
106
73
  }
107
74
 
108
- interceptorMiddleware: DispatchMiddleware = async (sceneId, action, params, next) => {
75
+ private dispatchApproved = async (
76
+ sceneId: string,
77
+ action: string,
78
+ params: DispatchParams,
79
+ ): Promise<DispatchResult> => {
80
+ const { [BEFORE_REMOVE_SOURCE_PROP]: _source, ...nativeParams } = params;
109
81
  const { from, to, props } = params;
110
82
  const intercepted = await this.intercept(action, {
111
83
  sceneId,
@@ -113,66 +85,18 @@ export default class DispatchCommandHandler {
113
85
  to,
114
86
  props,
115
87
  });
88
+
116
89
  if (intercepted) {
117
90
  return { ok: false, code: 'intercepted' };
118
91
  }
119
- return next(sceneId, action, { ...params, [INTERCEPT_CHECKED_PROP]: true });
92
+ const dispatchNative = async () =>
93
+ normalizeDispatchResult(await NativeNavigation.dispatch(sceneId, action, nativeParams));
94
+ const closingOwnLayer = params.target === 'self' && (action === 'dismiss' || action === 'hideModal');
95
+ return action === 'close' || closingOwnLayer
96
+ ? closeWithExitHandler(sceneId, dispatchNative)
97
+ : dispatchNative();
120
98
  };
121
99
 
122
- async dispatchRaw(
123
- sceneId: string,
124
- action: string,
125
- params: DispatchParams,
126
- ): Promise<DispatchResult> {
127
- if (!params[INTERCEPT_CHECKED_PROP]) {
128
- const { from, to, props } = params;
129
- const intercepted = await this.intercept(action, {
130
- sceneId,
131
- from,
132
- to,
133
- props,
134
- });
135
-
136
- if (intercepted) {
137
- return { ok: false, code: 'intercepted' };
138
- }
139
- }
140
-
141
- const nativeParams: DispatchParams = { ...params };
142
- for (const key of INTERNAL_DISPATCH_PROPS) {
143
- delete nativeParams[key];
144
- }
145
- if (nativeParams.result !== undefined) {
146
- nativeParams.result = resultHandler.normalizePendingResult(nativeParams.result);
147
- }
148
-
149
- const wire = await NativeNavigation.dispatch(sceneId, action, nativeParams);
150
- return normalizeDispatchResult(wire);
151
- }
152
-
153
- async dispatch(
154
- sceneId: string,
155
- action: string,
156
- params: DispatchParams,
157
- ): Promise<DispatchResult> {
158
- const chain = this.systemMiddlewares.slice();
159
- const invoke = (
160
- cursor: number,
161
- currentSceneId: string,
162
- currentAction: string,
163
- currentParams: DispatchParams,
164
- ): Promise<DispatchResult> => {
165
- if (cursor < chain.length) {
166
- const middleware = chain[cursor];
167
- return middleware(currentSceneId, currentAction, currentParams, (s, a, p) =>
168
- invoke(cursor + 1, s, a, p),
169
- );
170
- }
171
- return this.dispatchRaw(currentSceneId, currentAction, currentParams);
172
- };
173
- return invoke(0, sceneId, action, params);
174
- }
175
-
176
100
  private async intercept(action: string, params: InterceptParams): Promise<boolean> {
177
101
  for (const interceptor of this.interceptors.slice()) {
178
102
  const result = interceptor(action, params);
@@ -191,10 +115,6 @@ export default class DispatchCommandHandler {
191
115
  removeInterceptor(interceptor: NavigationInterceptor) {
192
116
  this.interceptors = this.interceptors.filter(item => item !== interceptor);
193
117
  }
194
-
195
- clearInterceptors() {
196
- this.interceptors = [];
197
- }
198
118
  }
199
119
 
200
120
  export const dispatchHandler = new DispatchCommandHandler();
@@ -1,4 +1,4 @@
1
- import type { BuildInLayout, DispatchResult, Layout, SetRootOptions } from '../Route';
1
+ import type { DispatchResult, Layout, SetRootOptions } from '../Route';
2
2
  import NativeEvent from '../NativeEvent';
3
3
  import NativeNavigation from '../NativeNavigation';
4
4
  import { normalizeDispatchResult } from './DispatchCommandHandler';
@@ -28,7 +28,7 @@ export default class LayoutCommandHandler {
28
28
  }
29
29
 
30
30
  async setRoot(
31
- layout: BuildInLayout | Layout,
31
+ layout: Layout,
32
32
  options?: SetRootOptions,
33
33
  ): Promise<DispatchResult> {
34
34
  const sticky = Boolean(options?.stickyAndroid);
@@ -46,10 +46,6 @@ export default class LayoutCommandHandler {
46
46
  this.listeners = this.listeners.filter(item => item !== record);
47
47
  };
48
48
  }
49
-
50
- clearListeners() {
51
- this.listeners = [];
52
- }
53
49
  }
54
50
 
55
51
  export const layoutHandler = new LayoutCommandHandler();
@@ -4,14 +4,43 @@ import type {
4
4
  BeforeRemoveEvent,
5
5
  BeforeRemoveListener,
6
6
  BeforeRemoveOptions,
7
+ BeforeRemoveSource,
7
8
  DispatchResult,
8
9
  LeaveAction,
9
10
  RouteGraph,
10
11
  } from '../Route';
11
- import { containsScene, findSceneInGraph } from '../routeGraph';
12
+ import { isScreenGraph, type ScreenGraph } from '../router/screen';
12
13
  import type { DispatchParams } from './DispatchCommandHandler';
13
14
  import { lifecycleHandler } from './LifecycleEventHandler';
14
15
 
16
+ function containsScene(graph: RouteGraph, sceneId: string): boolean {
17
+ if (graph.sceneId === sceneId) {
18
+ return true;
19
+ }
20
+ return Boolean(graph.children?.some(child => containsScene(child, sceneId)));
21
+ }
22
+
23
+ function findSceneInGraph(
24
+ graph: RouteGraph,
25
+ predicate: (node: ScreenGraph) => boolean,
26
+ ): ScreenGraph | null {
27
+ if (isScreenGraph(graph)) {
28
+ return predicate(graph) ? graph : null;
29
+ }
30
+ if (!graph.children) {
31
+ return null;
32
+ }
33
+ for (const child of graph.children) {
34
+ const found = findSceneInGraph(child, predicate);
35
+ if (found) {
36
+ return found;
37
+ }
38
+ }
39
+ return null;
40
+ }
41
+
42
+ export const BEFORE_REMOVE_SOURCE_PROP = '__hbdBeforeRemoveSource';
43
+
15
44
  const GUARDED_ACTIONS = new Set<LeaveAction>([
16
45
  'pop',
17
46
  'popTo',
@@ -25,6 +54,10 @@ const GUARDED_ACTIONS = new Set<LeaveAction>([
25
54
  const BYPASS_PROP = '__hbdBypassBeforeRemove';
26
55
  const APPROVED_SCENES_PROP = '__hbdApprovedBeforeRemoveScenes';
27
56
 
57
+ function isBeforeRemoveSource(value: unknown): value is BeforeRemoveSource {
58
+ return value === 'back' || value === 'self' || value === 'external';
59
+ }
60
+
28
61
  function collectScreenIds(graph: RouteGraph, out: string[]): void {
29
62
  if (graph.layout === 'screen') {
30
63
  out.push(graph.sceneId);
@@ -39,30 +72,14 @@ function collectScreenIds(graph: RouteGraph, out: string[]): void {
39
72
  }
40
73
 
41
74
  function findContainingStack(graph: RouteGraph, sceneId: string): RouteGraph | null {
42
- if (graph.layout === 'stack' && Array.isArray(graph.children)) {
43
- for (const child of graph.children) {
44
- const nested = findContainingStack(child, sceneId);
45
- if (nested) {
46
- return nested;
47
- }
48
- }
49
- if (graph.children.some(child => containsScene(child, sceneId))) {
50
- return graph;
51
- }
52
- }
53
- if (!graph.children) {
54
- return null;
55
- }
56
- for (const child of graph.children) {
57
- const found = findContainingStack(child, sceneId);
58
- if (found) {
59
- return found;
60
- }
75
+ for (const child of graph.children ?? []) {
76
+ if (!containsScene(child, sceneId)) continue;
77
+ return findContainingStack(child, sceneId) ?? (graph.layout === 'stack' ? graph : null);
61
78
  }
62
79
  return null;
63
80
  }
64
81
 
65
- export function collectRemovedStackScenes(
82
+ function collectRemovedStackScenes(
66
83
  layers: RouteGraph[],
67
84
  sceneId: string,
68
85
  action: 'popTo' | 'popToRoot',
@@ -77,34 +94,39 @@ export function collectRemovedStackScenes(
77
94
  }
78
95
  }
79
96
  if (!stack || !Array.isArray(stack.children) || stack.children.length <= 1) {
80
- return [sceneId];
81
- }
82
- const fromIndex = stack.children.findIndex(child => containsScene(child, sceneId));
83
- if (fromIndex <= 0) {
84
- return [sceneId];
97
+ return [];
85
98
  }
99
+ const topIndex = stack.children.length - 1;
86
100
  let stopIndex = 0;
87
101
  if (action === 'popTo') {
88
102
  if (!targetModuleOrSceneId) {
89
- return [sceneId];
103
+ return [];
90
104
  }
91
- const targetIndex = stack.children.findIndex(
92
- child =>
105
+ // Match native iOS/Android top-down lookup; router.open dispatches popTo on the target sceneId,
106
+ // so removal always starts from the stack top (topIndex), not from the dispatching sceneId.
107
+ let targetIndex = -1;
108
+ for (let i = topIndex; i >= 0; i--) {
109
+ const child = stack.children[i];
110
+ if (
93
111
  child.sceneId === targetModuleOrSceneId ||
94
112
  containsScene(child, targetModuleOrSceneId) ||
95
- Boolean(findSceneInGraph(child, node => node.moduleName === targetModuleOrSceneId)),
96
- );
97
- if (targetIndex < 0 || targetIndex >= fromIndex) {
98
- return [sceneId];
113
+ Boolean(findSceneInGraph(child, node => node.moduleName === targetModuleOrSceneId))
114
+ ) {
115
+ targetIndex = i;
116
+ break;
117
+ }
118
+ }
119
+ if (targetIndex < 0) {
120
+ return [];
99
121
  }
100
122
  // Match native iOS/Android behavior: inclusive && targetIndex > 0 pops targetIndex itself.
101
123
  stopIndex = inclusive && targetIndex > 0 ? targetIndex - 1 : targetIndex;
102
124
  }
103
125
  const removed: string[] = [];
104
- for (let i = fromIndex; i > stopIndex; i--) {
126
+ for (let i = topIndex; i > stopIndex; i--) {
105
127
  collectScreenIds(stack.children[i], removed);
106
128
  }
107
- return removed.length > 0 ? removed : [sceneId];
129
+ return removed;
108
130
  }
109
131
 
110
132
  function collectPresentedAboveScenes(layers: RouteGraph[], sceneId: string): string[] {
@@ -127,15 +149,14 @@ interface BeforeRemoveEntry {
127
149
  actions?: Set<LeaveAction>;
128
150
  }
129
151
 
130
- function matchesAction(entry: BeforeRemoveEntry, action: LeaveAction, sceneId?: string): boolean {
152
+ function matchesAction(entry: BeforeRemoveEntry, action: LeaveAction, mode?: string): boolean {
131
153
  if (!entry.actions) {
132
154
  return true;
133
155
  }
134
156
  if (entry.actions.has(action)) {
135
157
  return true;
136
158
  }
137
- if (action === 'close' && sceneId) {
138
- const mode = lifecycleHandler.getSceneInfo(sceneId)?.mode;
159
+ if (action === 'close') {
139
160
  if (mode === 'modal' && entry.actions.has('hideModal')) {
140
161
  return true;
141
162
  }
@@ -152,6 +173,7 @@ function matchesAction(entry: BeforeRemoveEntry, action: LeaveAction, sceneId?:
152
173
  function runGuardedChain(
153
174
  sceneId: string,
154
175
  action: LeaveAction,
176
+ source: BeforeRemoveSource,
155
177
  matching: BeforeRemoveEntry[],
156
178
  executeFinalProceed: () => Promise<DispatchResult>,
157
179
  ): Promise<DispatchResult> {
@@ -171,6 +193,7 @@ function runGuardedChain(
171
193
  const event: BeforeRemoveEvent = {
172
194
  sceneId,
173
195
  action,
196
+ source,
174
197
  proceed: () => {
175
198
  if (!stepProceedPromise) {
176
199
  stepProceedPromise = runAt(index + 1);
@@ -247,10 +270,14 @@ export default class LeaveGuardHandler {
247
270
  if (!this.nativeEnabledScenes.has(sceneId)) {
248
271
  NativeNavigation.setBeforeRemoveEnabled(sceneId, false);
249
272
  }
250
- void proceedClose();
273
+ void proceedClose().catch(error => {
274
+ console.warn('[hybrid-navigation] Native back dispatch failed.', error);
275
+ });
251
276
  return;
252
277
  }
253
- runGuardedChain(sceneId, leaveAction, matching, proceedClose);
278
+ void runGuardedChain(sceneId, leaveAction, 'back', matching, proceedClose).catch(error => {
279
+ console.warn('[hybrid-navigation] Native back guard failed.', error);
280
+ });
254
281
  });
255
282
  }
256
283
 
@@ -317,10 +344,11 @@ export default class LeaveGuardHandler {
317
344
  return next(sceneId, action, cleanParams);
318
345
  }
319
346
 
320
- if (!GUARDED_ACTIONS.has(action as LeaveAction) || this.listeners.size === 0) {
347
+ if (!GUARDED_ACTIONS.has(action as LeaveAction) || (this.listeners.size === 0 && !params[APPROVED_SCENES_PROP])) {
321
348
  return next(sceneId, action, params);
322
349
  }
323
350
 
351
+ const generation = this.rootGeneration;
324
352
  const leaveAction = action as LeaveAction;
325
353
  const approved: Set<string> =
326
354
  params[APPROVED_SCENES_PROP] instanceof Set ? params[APPROVED_SCENES_PROP] : new Set();
@@ -328,7 +356,7 @@ export default class LeaveGuardHandler {
328
356
  let candidateSceneIds: string[] = [sceneId];
329
357
  if (leaveAction === 'popTo' || leaveAction === 'popToRoot') {
330
358
  try {
331
- const layers = await NativeNavigation.routeGraph();
359
+ const layers = (await NativeNavigation.navigationSnapshot()).layers;
332
360
  if (Array.isArray(layers) && layers.length > 0) {
333
361
  candidateSceneIds = collectRemovedStackScenes(
334
362
  layers,
@@ -350,7 +378,7 @@ export default class LeaveGuardHandler {
350
378
  params.target !== 'self'
351
379
  ) {
352
380
  try {
353
- const layers = await NativeNavigation.routeGraph();
381
+ const layers = (await NativeNavigation.navigationSnapshot()).layers;
354
382
  const presentedAbove = collectPresentedAboveScenes(layers, sceneId);
355
383
  if (presentedAbove.length > 0) {
356
384
  candidateSceneIds = presentedAbove;
@@ -372,8 +400,23 @@ export default class LeaveGuardHandler {
372
400
  if (!set || set.size === 0) {
373
401
  continue;
374
402
  }
403
+ let mode: string | undefined;
404
+ const needsMode = leaveAction === 'close' && Array.from(set).some(({ actions }) =>
405
+ actions && !actions.has('close') &&
406
+ (actions.has('pop') || actions.has('dismiss') || actions.has('hideModal')),
407
+ );
408
+ if (needsMode) {
409
+ const { layers } = await NativeNavigation.navigationSnapshot();
410
+ for (const layer of layers) {
411
+ const scene = findSceneInGraph(layer, node => node.sceneId === candidateId);
412
+ if (scene) {
413
+ mode = scene.mode;
414
+ break;
415
+ }
416
+ }
417
+ }
375
418
  const hits = Array.from(set).filter(entry =>
376
- matchesAction(entry, leaveAction, candidateId),
419
+ matchesAction(entry, leaveAction, mode),
377
420
  );
378
421
  if (hits.length > 0) {
379
422
  guardedSceneId = candidateId;
@@ -382,6 +425,9 @@ export default class LeaveGuardHandler {
382
425
  }
383
426
  }
384
427
 
428
+ if (generation !== this.rootGeneration) {
429
+ return { ok: false, code: 'superseded' };
430
+ }
385
431
  if (!guardedSceneId || matching.length === 0) {
386
432
  const cleanParams: DispatchParams = { ...params };
387
433
  delete cleanParams[APPROVED_SCENES_PROP];
@@ -389,10 +435,15 @@ export default class LeaveGuardHandler {
389
435
  }
390
436
 
391
437
  const isMultiScene = candidateSceneIds.length > 1;
392
- const generation = this.rootGeneration;
393
438
  const targetGuardedSceneId = guardedSceneId;
439
+ const explicitSource = params[BEFORE_REMOVE_SOURCE_PROP];
440
+ const source: BeforeRemoveSource = isBeforeRemoveSource(explicitSource)
441
+ ? explicitSource
442
+ : targetGuardedSceneId !== sceneId
443
+ ? 'external'
444
+ : 'self';
394
445
 
395
- return runGuardedChain(targetGuardedSceneId, leaveAction, matching, async () => {
446
+ return runGuardedChain(targetGuardedSceneId, leaveAction, source, matching, async () => {
396
447
  if (
397
448
  generation !== this.rootGeneration ||
398
449
  lifecycleHandler.getSceneState(targetGuardedSceneId) === 'destroyed'