hybrid-navigation 5.4.0 → 5.5.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 (150) hide show
  1. package/HybridNavigation.podspec +1 -0
  2. package/android/proguard-rules.pro +5 -0
  3. package/android/src/main/java/com/navigation/androidx/AppUtils.java +8 -1
  4. package/android/src/main/java/com/navigation/androidx/AwesomeActivity.java +115 -36
  5. package/android/src/main/java/com/navigation/androidx/AwesomeFragment.java +153 -100
  6. package/android/src/main/java/com/navigation/androidx/DefaultTabBarProvider.java +1 -1
  7. package/android/src/main/java/com/navigation/androidx/DrawableUtils.java +5 -1
  8. package/android/src/main/java/com/navigation/androidx/DrawerFragment.java +95 -39
  9. package/android/src/main/java/com/navigation/androidx/FragmentHelper.java +195 -29
  10. package/android/src/main/java/com/navigation/androidx/HybridDrawerLayout.java +225 -27
  11. package/android/src/main/java/com/navigation/androidx/LifecycleDelegate.java +33 -9
  12. package/android/src/main/java/com/navigation/androidx/PresentationDelegate.java +5 -107
  13. package/android/src/main/java/com/navigation/androidx/StackDelegate.java +37 -10
  14. package/android/src/main/java/com/navigation/androidx/StackFragment.java +82 -19
  15. package/android/src/main/java/com/navigation/androidx/Style.java +8 -4
  16. package/android/src/main/java/com/navigation/androidx/SystemUI.java +17 -5
  17. package/android/src/main/java/com/navigation/androidx/TabBar.java +69 -29
  18. package/android/src/main/java/com/navigation/androidx/TabBarFragment.java +48 -11
  19. package/android/src/main/java/com/navigation/androidx/TabBarItem.java +1 -2
  20. package/android/src/main/java/com/navigation/androidx/TabView.java +20 -10
  21. package/android/src/main/java/com/reactnative/hybridnavigation/Constants.java +1 -0
  22. package/android/src/main/java/com/reactnative/hybridnavigation/Garden.java +19 -15
  23. package/android/src/main/java/com/reactnative/hybridnavigation/GlobalStyle.java +10 -48
  24. package/android/src/main/java/com/reactnative/hybridnavigation/HBDRootView.java +22 -23
  25. package/android/src/main/java/com/reactnative/hybridnavigation/HybridFragment.java +54 -22
  26. package/android/src/main/java/com/reactnative/hybridnavigation/NativeEvent.java +4 -2
  27. package/android/src/main/java/com/reactnative/hybridnavigation/NativeNavigation.java +35 -64
  28. package/android/src/main/java/com/reactnative/hybridnavigation/NavigationCommandQueue.java +185 -121
  29. package/android/src/main/java/com/reactnative/hybridnavigation/Navigator.java +21 -5
  30. package/android/src/main/java/com/reactnative/hybridnavigation/NavigatorRegistry.java +27 -30
  31. package/android/src/main/java/com/reactnative/hybridnavigation/OrientationCoordinator.java +41 -4
  32. package/android/src/main/java/com/reactnative/hybridnavigation/Parameters.java +55 -154
  33. package/android/src/main/java/com/reactnative/hybridnavigation/ReactAppCompatActivity.java +30 -1
  34. package/android/src/main/java/com/reactnative/hybridnavigation/ReactAppCompatActivityDelegate.java +12 -37
  35. package/android/src/main/java/com/reactnative/hybridnavigation/ReactFragment.java +31 -190
  36. package/android/src/main/java/com/reactnative/hybridnavigation/ReactManager.java +115 -71
  37. package/android/src/main/java/com/reactnative/hybridnavigation/ReactStackFragment.java +27 -16
  38. package/android/src/main/java/com/reactnative/hybridnavigation/ReactSurfaceCleanup.java +50 -8
  39. package/android/src/main/java/com/reactnative/hybridnavigation/ReactTabBarFragment.java +34 -4
  40. package/android/src/main/java/com/reactnative/hybridnavigation/ReactTabBarProvider.java +39 -10
  41. package/android/src/main/java/com/reactnative/hybridnavigation/RemovalPlan.java +76 -0
  42. package/android/src/main/java/com/reactnative/hybridnavigation/SceneLifecycleStateMachine.java +72 -6
  43. package/android/src/main/java/com/reactnative/hybridnavigation/Utils.java +19 -3
  44. package/android/src/main/java/com/reactnative/hybridnavigation/navigator/DrawerNavigator.java +11 -5
  45. package/android/src/main/java/com/reactnative/hybridnavigation/navigator/ScreenNavigator.java +217 -99
  46. package/android/src/main/java/com/reactnative/hybridnavigation/navigator/StackNavigator.java +122 -59
  47. package/android/src/main/java/com/reactnative/hybridnavigation/navigator/TabNavigator.java +87 -24
  48. package/dist/DeepLink.d.ts +3 -1
  49. package/dist/DeepLink.js +39 -19
  50. package/dist/NativeNavigation.d.ts +8 -5
  51. package/dist/Navigation.d.ts +9 -24
  52. package/dist/Navigation.js +32 -97
  53. package/dist/NavigationComponentWrap.d.ts +1 -2
  54. package/dist/NavigationComponentWrap.js +0 -15
  55. package/dist/Navigator.d.ts +7 -5
  56. package/dist/Navigator.js +38 -33
  57. package/dist/Options.d.ts +1 -7
  58. package/dist/Options.js +1 -2
  59. package/dist/Route.d.ts +24 -12
  60. package/dist/handler/DispatchCommandHandler.d.ts +4 -5
  61. package/dist/handler/DispatchCommandHandler.js +37 -16
  62. package/dist/handler/LayoutCommandHandler.js +18 -3
  63. package/dist/handler/LeaveGuardHandler.d.ts +12 -8
  64. package/dist/handler/LeaveGuardHandler.js +174 -281
  65. package/dist/handler/LifecycleEventHandler.d.ts +7 -4
  66. package/dist/handler/LifecycleEventHandler.js +119 -32
  67. package/dist/handler/ResultEventHandler.d.ts +2 -2
  68. package/dist/handler/ResultEventHandler.js +72 -36
  69. package/dist/handler/SceneExitHandler.d.ts +6 -0
  70. package/dist/handler/SceneExitHandler.js +48 -8
  71. package/dist/hooks.d.ts +1 -0
  72. package/dist/hooks.js +39 -23
  73. package/dist/index.d.ts +9 -8
  74. package/dist/index.js +5 -8
  75. package/dist/routeGraph.d.ts +5 -0
  76. package/dist/routeGraph.js +47 -0
  77. package/dist/router/drawer.d.ts +2 -2
  78. package/dist/router/drawer.js +19 -9
  79. package/dist/router/helpers.d.ts +17 -0
  80. package/dist/router/helpers.js +90 -0
  81. package/dist/router/index.d.ts +2 -2
  82. package/dist/router/index.js +169 -97
  83. package/dist/router/screen.d.ts +2 -2
  84. package/dist/router/screen.js +16 -7
  85. package/dist/router/stack.d.ts +2 -2
  86. package/dist/router/stack.js +24 -49
  87. package/dist/router/tabs.js +5 -1
  88. package/dist/store.d.ts +2 -0
  89. package/dist/store.js +4 -0
  90. package/ios/HBDGlobalStyle.h +0 -1
  91. package/ios/HBDGlobalStyle.mm +27 -39
  92. package/ios/HBDUtils.h +0 -2
  93. package/ios/HBDUtils.mm +81 -41
  94. package/ios/Navigator/HBDDrawerNavigator.mm +31 -26
  95. package/ios/Navigator/HBDNavigatorRegistry.mm +23 -26
  96. package/ios/Navigator/HBDScreenNavigator.mm +240 -137
  97. package/ios/Navigator/HBDStackNavigator.mm +147 -97
  98. package/ios/Navigator/HBDTabNavigator.mm +99 -46
  99. package/ios/React/HBDNativeEvent.mm +38 -5
  100. package/ios/React/HBDNativeNavigation.mm +49 -51
  101. package/ios/React/HBDNavigationCommandQueue.h +55 -0
  102. package/ios/React/HBDNavigationCommandQueue.mm +341 -0
  103. package/ios/React/HBDNavigator.h +20 -0
  104. package/ios/React/HBDOrientationCoordinator.mm +26 -3
  105. package/ios/React/HBDReactBridgeManager.h +18 -6
  106. package/ios/React/HBDReactBridgeManager.mm +536 -315
  107. package/ios/React/HBDSceneLifecycleStateMachine.h +2 -0
  108. package/ios/React/HBDSceneLifecycleStateMachine.mm +18 -0
  109. package/ios/View/HBDRootView.h +1 -0
  110. package/ios/View/HBDRootView.mm +112 -4
  111. package/ios/View/UIImage+WithBadge.mm +9 -7
  112. package/ios/ViewController/HBDDrawerController.h +10 -0
  113. package/ios/ViewController/HBDDrawerController.mm +103 -71
  114. package/ios/ViewController/HBDNavigationController.mm +166 -58
  115. package/ios/ViewController/HBDReactViewController.h +0 -4
  116. package/ios/ViewController/HBDReactViewController.mm +13 -110
  117. package/ios/ViewController/HBDTabBarController.mm +67 -33
  118. package/ios/ViewController/HBDViewController.h +6 -0
  119. package/ios/ViewController/HBDViewController.mm +94 -37
  120. package/ios/ViewController/UINavigationController+HBD.h +2 -2
  121. package/ios/ViewController/UINavigationController+HBD.mm +13 -13
  122. package/ios/ViewController/UIViewController+HBD.h +23 -1
  123. package/ios/ViewController/UIViewController+HBD.mm +298 -40
  124. package/package.json +1 -1
  125. package/src/DeepLink.ts +39 -19
  126. package/src/NativeNavigation.ts +17 -5
  127. package/src/Navigation.ts +49 -170
  128. package/src/NavigationComponentWrap.tsx +1 -16
  129. package/src/Navigator.ts +50 -52
  130. package/src/Options.ts +4 -10
  131. package/src/Route.ts +37 -19
  132. package/src/handler/DispatchCommandHandler.ts +42 -20
  133. package/src/handler/LayoutCommandHandler.ts +15 -3
  134. package/src/handler/LeaveGuardHandler.ts +224 -329
  135. package/src/handler/LifecycleEventHandler.ts +131 -37
  136. package/src/handler/ResultEventHandler.ts +71 -37
  137. package/src/handler/SceneExitHandler.ts +60 -9
  138. package/src/hooks.ts +54 -26
  139. package/src/index.ts +77 -8
  140. package/src/routeGraph.ts +50 -0
  141. package/src/router/drawer.ts +21 -10
  142. package/src/router/helpers.ts +113 -0
  143. package/src/router/index.ts +187 -112
  144. package/src/router/screen.ts +35 -8
  145. package/src/router/stack.ts +40 -53
  146. package/src/router/tabs.ts +5 -1
  147. package/src/store.ts +5 -0
  148. package/dist/sceneCoverage.d.ts +0 -2
  149. package/dist/sceneCoverage.js +0 -25
  150. package/src/sceneCoverage.ts +0 -30
@@ -1,5 +1,5 @@
1
1
  import NativeEvent from '../NativeEvent';
2
- import NativeNavigation from '../NativeNavigation';
2
+ import NativeNavigation, { type RemovalPlanWire } from '../NativeNavigation';
3
3
  import type {
4
4
  BeforeRemoveEvent,
5
5
  BeforeRemoveListener,
@@ -7,167 +7,42 @@ import type {
7
7
  BeforeRemoveSource,
8
8
  DispatchResult,
9
9
  LeaveAction,
10
- RouteGraph,
11
10
  } from '../Route';
12
- import { isScreenGraph, type ScreenGraph } from '../router/screen';
13
11
  import type { DispatchParams } from './DispatchCommandHandler';
14
12
  import { lifecycleHandler } from './LifecycleEventHandler';
15
13
 
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
-
44
14
  const GUARDED_ACTIONS = new Set<LeaveAction>([
45
15
  'pop',
46
16
  'popTo',
47
17
  'popToRoot',
48
18
  'dismiss',
49
- 'hideModal',
50
19
  'close',
51
20
  'redirectTo',
52
21
  ]);
53
22
 
54
- const BYPASS_PROP = '__hbdBypassBeforeRemove';
55
- const APPROVED_SCENES_PROP = '__hbdApprovedBeforeRemoveScenes';
56
-
57
- function isBeforeRemoveSource(value: unknown): value is BeforeRemoveSource {
58
- return value === 'back' || value === 'self' || value === 'external';
59
- }
60
-
61
- function collectScreenIds(graph: RouteGraph, out: string[]): void {
62
- if (graph.layout === 'screen') {
63
- out.push(graph.sceneId);
64
- return;
65
- }
66
- if (!graph.children) {
67
- return;
68
- }
69
- for (let i = graph.children.length - 1; i >= 0; i--) {
70
- collectScreenIds(graph.children[i], out);
71
- }
72
- }
73
-
74
- function findContainingStack(graph: RouteGraph, sceneId: string): RouteGraph | null {
75
- for (const child of graph.children ?? []) {
76
- if (!containsScene(child, sceneId)) continue;
77
- return findContainingStack(child, sceneId) ?? (graph.layout === 'stack' ? graph : null);
78
- }
79
- return null;
80
- }
81
-
82
- function collectRemovedStackScenes(
83
- layers: RouteGraph[],
84
- sceneId: string,
85
- action: 'popTo' | 'popToRoot',
86
- targetModuleOrSceneId?: string,
87
- inclusive: boolean = false,
88
- ): string[] {
89
- let stack: RouteGraph | null = null;
90
- for (let i = layers.length - 1; i >= 0; i--) {
91
- stack = findContainingStack(layers[i], sceneId);
92
- if (stack) {
93
- break;
94
- }
95
- }
96
- if (!stack || !Array.isArray(stack.children) || stack.children.length <= 1) {
97
- return [];
98
- }
99
- const topIndex = stack.children.length - 1;
100
- let stopIndex = 0;
101
- if (action === 'popTo') {
102
- if (!targetModuleOrSceneId) {
103
- return [];
104
- }
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 (
111
- child.sceneId === targetModuleOrSceneId ||
112
- containsScene(child, targetModuleOrSceneId) ||
113
- Boolean(findSceneInGraph(child, node => node.moduleName === targetModuleOrSceneId))
114
- ) {
115
- targetIndex = i;
116
- break;
117
- }
118
- }
119
- if (targetIndex < 0) {
120
- return [];
121
- }
122
- // Match native iOS/Android behavior: inclusive && targetIndex > 0 pops targetIndex itself.
123
- stopIndex = inclusive && targetIndex > 0 ? targetIndex - 1 : targetIndex;
124
- }
125
- const removed: string[] = [];
126
- for (let i = topIndex; i > stopIndex; i--) {
127
- collectScreenIds(stack.children[i], removed);
128
- }
129
- return removed;
130
- }
131
-
132
- function collectPresentedAboveScenes(layers: RouteGraph[], sceneId: string): string[] {
133
- if (!Array.isArray(layers) || layers.length <= 1) {
134
- return [];
135
- }
136
- const index = layers.findIndex(layer => containsScene(layer, sceneId));
137
- if (index < 0 || index >= layers.length - 1) {
138
- return [];
139
- }
140
- const removed: string[] = [];
141
- for (let i = layers.length - 1; i > index; i--) {
142
- collectScreenIds(layers[i], removed);
143
- }
144
- return removed;
145
- }
23
+ type EffectiveCloseAction = 'pop' | 'dismiss';
146
24
 
147
25
  interface BeforeRemoveEntry {
148
26
  listener: BeforeRemoveListener;
149
27
  actions?: Set<LeaveAction>;
150
28
  }
151
29
 
152
- function matchesAction(entry: BeforeRemoveEntry, action: LeaveAction, mode?: string): boolean {
153
- if (!entry.actions) {
154
- return true;
155
- }
156
- if (entry.actions.has(action)) {
30
+ export interface DispatchGuardOptions {
31
+ source?: BeforeRemoveSource;
32
+ }
33
+
34
+ function matchesAction(
35
+ entry: BeforeRemoveEntry,
36
+ action: LeaveAction,
37
+ effectiveCloseAction?: EffectiveCloseAction,
38
+ ): boolean {
39
+ if (!entry.actions || entry.actions.has(action)) {
157
40
  return true;
158
41
  }
159
- if (action === 'close') {
160
- if (mode === 'modal' && entry.actions.has('hideModal')) {
161
- return true;
162
- }
163
- if (mode === 'present' && entry.actions.has('dismiss')) {
164
- return true;
165
- }
166
- if (mode === 'normal' && entry.actions.has('pop')) {
167
- return true;
168
- }
169
- }
170
- return false;
42
+ return (
43
+ (action === 'close' || action === 'back') &&
44
+ Boolean(effectiveCloseAction && entry.actions.has(effectiveCloseAction))
45
+ );
171
46
  }
172
47
 
173
48
  function runGuardedChain(
@@ -175,10 +50,13 @@ function runGuardedChain(
175
50
  action: LeaveAction,
176
51
  source: BeforeRemoveSource,
177
52
  matching: BeforeRemoveEntry[],
53
+ isEntryActive: (entry: BeforeRemoveEntry) => boolean,
54
+ onEntryApproved: (entry: BeforeRemoveEntry) => void,
178
55
  executeFinalProceed: () => Promise<DispatchResult>,
56
+ holdSceneIds: Iterable<string>,
179
57
  ): Promise<DispatchResult> {
180
58
  let finalPromise: Promise<DispatchResult> | null = null;
181
- const runFinal = (): Promise<DispatchResult> => {
59
+ const runFinal = () => {
182
60
  if (!finalPromise) {
183
61
  finalPromise = executeFinalProceed();
184
62
  }
@@ -189,19 +67,45 @@ function runGuardedChain(
189
67
  if (index >= matching.length) {
190
68
  return runFinal();
191
69
  }
70
+ const entry = matching[index];
71
+ if (!isEntryActive(entry)) {
72
+ return runAt(index + 1);
73
+ }
192
74
  let stepProceedPromise: Promise<DispatchResult> | null = null;
75
+ let settledWithoutProceed = false;
193
76
  const event: BeforeRemoveEvent = {
194
77
  sceneId,
195
78
  action,
196
79
  source,
197
80
  proceed: () => {
81
+ if (settledWithoutProceed) {
82
+ if (__DEV__) {
83
+ console.warn(
84
+ `[hybrid-navigation] event.proceed() was called after the beforeRemove listener for scene "${sceneId}" already settled. Return a Promise (use async/await) while awaiting confirmation.`,
85
+ );
86
+ }
87
+ return Promise.resolve({
88
+ ok: false,
89
+ code: 'intercepted',
90
+ sceneId,
91
+ message: 'Navigation prevented by beforeRemove guard.',
92
+ });
93
+ }
198
94
  if (!stepProceedPromise) {
199
- stepProceedPromise = runAt(index + 1);
95
+ onEntryApproved(entry);
96
+ const releaseHold = lifecycleHandler.holdVisible(holdSceneIds);
97
+ stepProceedPromise = runAt(index + 1).finally(releaseHold);
200
98
  }
201
99
  return stepProceedPromise;
202
100
  },
203
101
  };
204
- await matching[index].listener(event);
102
+ try {
103
+ await entry.listener(event);
104
+ } finally {
105
+ if (!stepProceedPromise) {
106
+ settledWithoutProceed = true;
107
+ }
108
+ }
205
109
  if (stepProceedPromise) {
206
110
  return await stepProceedPromise;
207
111
  }
@@ -218,86 +122,72 @@ function runGuardedChain(
218
122
 
219
123
  export default class LeaveGuardHandler {
220
124
  private listeners = new Map<string, Set<BeforeRemoveEntry>>();
221
- private nativeEnabledScenes = new Set<string>();
125
+ private exitHandlerScenes = new Set<string>();
126
+ private nativePolicies = new Map<string, string>();
127
+ private activeNativeBackScenes = new Set<string>();
222
128
  private rootGeneration = 0;
223
- private dispatchFn?: (
224
- sceneId: string,
225
- action: string,
226
- params: DispatchParams,
227
- ) => Promise<DispatchResult>;
228
129
 
229
- setDispatcher(
230
- dispatcher: (
231
- sceneId: string,
232
- action: string,
233
- params: DispatchParams,
234
- ) => Promise<DispatchResult>,
130
+ handleNativeBeforeRemoveRequests(
131
+ onNativeBack: (sceneId: string) => Promise<DispatchResult>,
235
132
  ) {
236
- this.dispatchFn = dispatcher;
133
+ NativeEvent.onBeforeRemoveRequest(({ sceneId }) => {
134
+ if (this.activeNativeBackScenes.has(sceneId)) {
135
+ return;
136
+ }
137
+ this.activeNativeBackScenes.add(sceneId);
138
+ onNativeBack(sceneId)
139
+ .catch(error => {
140
+ console.warn('[hybrid-navigation] Native back dispatch failed.', error);
141
+ })
142
+ .finally(() => {
143
+ this.activeNativeBackScenes.delete(sceneId);
144
+ });
145
+ });
237
146
  }
238
147
 
239
- handleNativeBeforeRemoveRequests() {
240
- NativeEvent.onBeforeRemoveRequest(({ sceneId, action }) => {
241
- const generation = this.rootGeneration;
242
- const leaveAction = (action || 'back') as LeaveAction;
243
- const proceedClose = async (): Promise<DispatchResult> => {
244
- if (
245
- generation !== this.rootGeneration ||
246
- lifecycleHandler.getSceneState(sceneId) === 'destroyed'
247
- ) {
248
- return {
249
- ok: false,
250
- code: 'superseded',
251
- message: 'Scene or root changed before proceed.',
252
- };
148
+ setExitHandlerActive(sceneId: string, active: boolean) {
149
+ const had = this.exitHandlerScenes.has(sceneId);
150
+ if (had === active) {
151
+ return;
152
+ }
153
+ if (active) {
154
+ this.exitHandlerScenes.add(sceneId);
155
+ } else {
156
+ this.exitHandlerScenes.delete(sceneId);
157
+ }
158
+ this.syncNativePolicy(sceneId);
159
+ }
160
+
161
+ private syncNativePolicy(sceneId: string) {
162
+ const set = this.listeners.get(sceneId);
163
+ let interceptPop = false;
164
+ let interceptDismiss = this.exitHandlerScenes.has(sceneId);
165
+ if (set) {
166
+ for (const entry of set) {
167
+ if (!interceptPop && matchesAction(entry, 'back', 'pop')) {
168
+ interceptPop = true;
253
169
  }
254
- if (!this.dispatchFn) {
255
- return { ok: false, code: 'not_ready' };
170
+ if (!interceptDismiss && matchesAction(entry, 'back', 'dismiss')) {
171
+ interceptDismiss = true;
256
172
  }
257
- return this.dispatchFn(sceneId, 'close', {
258
- target: 'self',
259
- [BYPASS_PROP]: true,
260
- });
261
- };
262
-
263
- const set = this.listeners.get(sceneId);
264
- const matching = set
265
- ? Array.from(set).filter(entry => matchesAction(entry, leaveAction))
266
- : [];
267
- if (matching.length === 0) {
268
- // 异步标志位尚未同步到原生时若刚好触发侧滑/返回键,重新同步关掉原生标志并直接放行退场,避免吞掉返回操作。
269
- this.syncNativeEnabled(sceneId);
270
- if (!this.nativeEnabledScenes.has(sceneId)) {
271
- NativeNavigation.setBeforeRemoveEnabled(sceneId, false);
173
+ if (interceptPop && interceptDismiss) {
174
+ break;
272
175
  }
273
- void proceedClose().catch(error => {
274
- console.warn('[hybrid-navigation] Native back dispatch failed.', error);
275
- });
276
- return;
277
176
  }
278
- void runGuardedChain(sceneId, leaveAction, 'back', matching, proceedClose).catch(error => {
279
- console.warn('[hybrid-navigation] Native back guard failed.', error);
280
- });
281
- });
282
- }
177
+ }
283
178
 
284
- private syncNativeEnabled(sceneId: string) {
285
- const set = this.listeners.get(sceneId);
286
- const shouldEnable =
287
- Boolean(set) &&
288
- Array.from(set!).some(entry => matchesAction(entry, 'back'));
289
- const isEnabled = this.nativeEnabledScenes.has(sceneId);
290
- if (shouldEnable === isEnabled) {
179
+ const nextKey = `${interceptPop ? 1 : 0}:${interceptDismiss ? 1 : 0}`;
180
+ const prevKey = this.nativePolicies.get(sceneId) ?? '0:0';
181
+ if (nextKey === prevKey) {
291
182
  return;
292
183
  }
293
- if (shouldEnable) {
294
- this.nativeEnabledScenes.add(sceneId);
295
- NativeNavigation.setBeforeRemoveEnabled(sceneId, true);
184
+ if (nextKey === '0:0') {
185
+ this.nativePolicies.delete(sceneId);
296
186
  } else {
297
- this.nativeEnabledScenes.delete(sceneId);
298
- if (lifecycleHandler.getSceneState(sceneId) !== 'destroyed') {
299
- NativeNavigation.setBeforeRemoveEnabled(sceneId, false);
300
- }
187
+ this.nativePolicies.set(sceneId, nextKey);
188
+ }
189
+ if (lifecycleHandler.getSceneState(sceneId) !== 'destroyed') {
190
+ NativeNavigation.setBeforeRemovePolicy(sceneId, interceptPop, interceptDismiss);
301
191
  }
302
192
  }
303
193
 
@@ -316,7 +206,7 @@ export default class LeaveGuardHandler {
316
206
  actions: options?.actions ? new Set(options.actions) : undefined,
317
207
  };
318
208
  set.add(entry);
319
- this.syncNativeEnabled(sceneId);
209
+ this.syncNativePolicy(sceneId);
320
210
 
321
211
  return () => {
322
212
  const current = this.listeners.get(sceneId);
@@ -327,160 +217,165 @@ export default class LeaveGuardHandler {
327
217
  if (current.size === 0) {
328
218
  this.listeners.delete(sceneId);
329
219
  }
330
- this.syncNativeEnabled(sceneId);
220
+ this.syncNativePolicy(sceneId);
331
221
  };
332
222
  }
333
223
 
224
+ private async fetchRemovalPlan(
225
+ sceneId: string,
226
+ action: string,
227
+ params: DispatchParams,
228
+ pinnedDismissTarget?: 'self' | 'presented',
229
+ ): Promise<RemovalPlanWire> {
230
+ const planParams =
231
+ pinnedDismissTarget && !params.target
232
+ ? { ...params, target: pinnedDismissTarget }
233
+ : params;
234
+ try {
235
+ return await NativeNavigation.planRemoval(sceneId, action, planParams);
236
+ } catch {
237
+ return { status: 'noop', sceneIds: [] };
238
+ }
239
+ }
240
+
334
241
  middleware = async (
335
242
  sceneId: string,
336
243
  action: string,
337
244
  params: DispatchParams,
338
245
  next: (sceneId: string, action: string, params: DispatchParams) => Promise<DispatchResult>,
246
+ options?: DispatchGuardOptions,
339
247
  ): Promise<DispatchResult> => {
340
- if (params[BYPASS_PROP] || params.bypassBeforeRemove) {
248
+ if (params.bypassBeforeRemove) {
341
249
  const cleanParams: DispatchParams = { ...params };
342
- delete cleanParams[BYPASS_PROP];
343
250
  delete cleanParams.bypassBeforeRemove;
344
251
  return next(sceneId, action, cleanParams);
345
252
  }
346
253
 
347
- if (!GUARDED_ACTIONS.has(action as LeaveAction) || (this.listeners.size === 0 && !params[APPROVED_SCENES_PROP])) {
254
+ const isSwitchTabPopToRoot = action === 'switchTab' && params.popToRoot === true;
255
+ const isGuardedAction = GUARDED_ACTIONS.has(action as LeaveAction) || isSwitchTabPopToRoot;
256
+ if (!isGuardedAction || this.listeners.size === 0) {
348
257
  return next(sceneId, action, params);
349
258
  }
350
259
 
351
260
  const generation = this.rootGeneration;
352
- const leaveAction = action as LeaveAction;
353
- const approved: Set<string> =
354
- params[APPROVED_SCENES_PROP] instanceof Set ? params[APPROVED_SCENES_PROP] : new Set();
355
-
356
- let candidateSceneIds: string[] = [sceneId];
357
- if (leaveAction === 'popTo' || leaveAction === 'popToRoot') {
358
- try {
359
- const layers = (await NativeNavigation.navigationSnapshot()).layers;
360
- if (Array.isArray(layers) && layers.length > 0) {
361
- candidateSceneIds = collectRemovedStackScenes(
362
- layers,
363
- sceneId,
364
- leaveAction,
365
- typeof params.moduleName === 'string'
366
- ? params.moduleName
367
- : typeof params.to === 'string'
368
- ? params.to
369
- : undefined,
370
- Boolean(params.inclusive),
371
- );
372
- }
373
- } catch {
374
- candidateSceneIds = [sceneId];
375
- }
376
- } else if (
377
- (leaveAction === 'dismiss' || leaveAction === 'hideModal') &&
378
- params.target !== 'self'
379
- ) {
380
- try {
381
- const layers = (await NativeNavigation.navigationSnapshot()).layers;
382
- const presentedAbove = collectPresentedAboveScenes(layers, sceneId);
383
- if (presentedAbove.length > 0) {
384
- candidateSceneIds = presentedAbove;
385
- } else if (params.target === 'presented') {
386
- candidateSceneIds = [];
387
- }
388
- } catch {
389
- candidateSceneIds = params.target === 'presented' ? [] : [sceneId];
261
+ const leaveAction: LeaveAction = isSwitchTabPopToRoot
262
+ ? 'popToRoot'
263
+ : options?.source === 'back' && action === 'close'
264
+ ? 'back'
265
+ : (action as LeaveAction);
266
+ const approvedEntries = new Set<BeforeRemoveEntry>();
267
+ let pinnedDismissTarget: 'self' | 'presented' | undefined;
268
+ let expectedTopSceneId: string | undefined;
269
+
270
+ const withPinnedTarget = (): DispatchParams =>
271
+ pinnedDismissTarget && !params.target
272
+ ? { ...params, target: pinnedDismissTarget }
273
+ : params;
274
+
275
+ const resolveNext = async (): Promise<DispatchResult> => {
276
+ const plan = await this.fetchRemovalPlan(sceneId, action, params, pinnedDismissTarget);
277
+ if (generation !== this.rootGeneration) {
278
+ return { ok: false, code: 'superseded' };
390
279
  }
391
- }
392
-
393
- let guardedSceneId: string | null = null;
394
- let matching: BeforeRemoveEntry[] = [];
395
- for (const candidateId of candidateSceneIds) {
396
- if (approved.has(candidateId)) {
397
- continue;
398
- }
399
- const set = this.listeners.get(candidateId);
400
- if (!set || set.size === 0) {
401
- continue;
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
- }
280
+ if (plan.status === 'covered') {
281
+ return { ok: false, code: 'covered', message: 'Target scene is covered.' };
417
282
  }
418
- const hits = Array.from(set).filter(entry =>
419
- matchesAction(entry, leaveAction, mode),
420
- );
421
- if (hits.length > 0) {
422
- guardedSceneId = candidateId;
423
- matching = hits;
424
- break;
283
+ if (plan.status !== 'ok') {
284
+ return next(sceneId, action, withPinnedTarget());
425
285
  }
426
- }
427
-
428
- if (generation !== this.rootGeneration) {
429
- return { ok: false, code: 'superseded' };
430
- }
431
- if (!guardedSceneId || matching.length === 0) {
432
- const cleanParams: DispatchParams = { ...params };
433
- delete cleanParams[APPROVED_SCENES_PROP];
434
- return next(sceneId, action, cleanParams);
435
- }
436
286
 
437
- const isMultiScene = candidateSceneIds.length > 1;
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';
445
-
446
- return runGuardedChain(targetGuardedSceneId, leaveAction, source, matching, async () => {
447
- if (
448
- generation !== this.rootGeneration ||
449
- lifecycleHandler.getSceneState(targetGuardedSceneId) === 'destroyed'
450
- ) {
287
+ const candidates = Array.isArray(plan.sceneIds) ? plan.sceneIds : [];
288
+ if (leaveAction === 'pop' && expectedTopSceneId && !candidates.includes(expectedTopSceneId)) {
451
289
  return {
452
290
  ok: false,
453
- code: 'superseded',
454
- message: 'Scene or root changed before proceed.',
291
+ code: 'covered',
292
+ message: 'Target scene is covered before proceed.',
455
293
  };
456
294
  }
457
- if (!this.dispatchFn) {
458
- return { ok: false, code: 'not_ready' };
295
+ if (
296
+ (plan.dismissTarget === 'self' || plan.dismissTarget === 'presented') &&
297
+ !params.target
298
+ ) {
299
+ pinnedDismissTarget = plan.dismissTarget;
459
300
  }
460
- if (isMultiScene) {
461
- const nextApproved = new Set(approved);
462
- nextApproved.add(targetGuardedSceneId);
463
- return this.dispatchFn(sceneId, action, {
464
- ...params,
465
- [APPROVED_SCENES_PROP]: nextApproved,
466
- });
301
+ const effectiveCloseAction =
302
+ plan.effectiveAction === 'pop' || plan.effectiveAction === 'dismiss'
303
+ ? plan.effectiveAction
304
+ : undefined;
305
+
306
+ let guardedSceneId: string | null = null;
307
+ let matching: BeforeRemoveEntry[] = [];
308
+ for (const candidateId of candidates) {
309
+ const set = this.listeners.get(candidateId);
310
+ if (!set || set.size === 0) {
311
+ continue;
312
+ }
313
+ const hits = Array.from(set).filter(
314
+ entry =>
315
+ !approvedEntries.has(entry) &&
316
+ matchesAction(entry, leaveAction, effectiveCloseAction),
317
+ );
318
+ if (hits.length > 0) {
319
+ guardedSceneId = candidateId;
320
+ matching = hits;
321
+ break;
322
+ }
467
323
  }
468
- return this.dispatchFn(sceneId, action, {
469
- ...params,
470
- [BYPASS_PROP]: true,
471
- });
472
- });
324
+
325
+ if (!guardedSceneId) {
326
+ return next(sceneId, action, withPinnedTarget());
327
+ }
328
+
329
+ const targetGuardedSceneId = guardedSceneId;
330
+ const resolvedSource: BeforeRemoveSource =
331
+ options?.source ?? (targetGuardedSceneId !== sceneId ? 'external' : 'self');
332
+ const holdSceneIds = new Set<string>([sceneId, targetGuardedSceneId, ...candidates]);
333
+
334
+ return runGuardedChain(
335
+ targetGuardedSceneId,
336
+ leaveAction,
337
+ resolvedSource,
338
+ matching,
339
+ entry => Boolean(this.listeners.get(targetGuardedSceneId)?.has(entry)),
340
+ entry => {
341
+ approvedEntries.add(entry);
342
+ },
343
+ async () => {
344
+ if (
345
+ generation !== this.rootGeneration ||
346
+ lifecycleHandler.getSceneState(targetGuardedSceneId) === 'destroyed'
347
+ ) {
348
+ return {
349
+ ok: false,
350
+ code: 'superseded',
351
+ message: 'Scene or root changed before proceed.',
352
+ };
353
+ }
354
+ if (leaveAction === 'pop') {
355
+ expectedTopSceneId = targetGuardedSceneId;
356
+ }
357
+ return resolveNext();
358
+ },
359
+ holdSceneIds,
360
+ );
361
+ };
362
+
363
+ return resolveNext();
473
364
  };
474
365
 
475
366
  onSceneDestroyed(sceneId: string) {
476
367
  this.listeners.delete(sceneId);
477
- this.nativeEnabledScenes.delete(sceneId);
368
+ this.exitHandlerScenes.delete(sceneId);
369
+ this.nativePolicies.delete(sceneId);
370
+ this.activeNativeBackScenes.delete(sceneId);
478
371
  }
479
372
 
480
373
  onRootReset() {
481
374
  this.rootGeneration += 1;
482
375
  this.listeners.clear();
483
- this.nativeEnabledScenes.clear();
376
+ this.exitHandlerScenes.clear();
377
+ this.nativePolicies.clear();
378
+ this.activeNativeBackScenes.clear();
484
379
  }
485
380
  }
486
381