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
@@ -1,13 +1,6 @@
1
1
  import NativeNavigation from '../NativeNavigation';
2
- import { resultHandler } from './ResultEventHandler';
3
- const INTERCEPT_CHECKED_PROP = '__hbdInterceptChecked';
4
- const INTERNAL_DISPATCH_PROPS = [
5
- INTERCEPT_CHECKED_PROP,
6
- 'onCovered',
7
- 'bypassBeforeRemove',
8
- '__hbdBypassBeforeRemove',
9
- '__hbdApprovedBeforeRemoveScenes',
10
- ];
2
+ import { leaveGuardHandler, BEFORE_REMOVE_SOURCE_PROP } from './LeaveGuardHandler';
3
+ import { closeWithExitHandler } from './SceneExitHandler';
11
4
  const VALID_DISPATCH_CODES = new Set([
12
5
  'ok',
13
6
  'intercepted',
@@ -28,25 +21,20 @@ export function normalizeDispatchResult(wire) {
28
21
  : wire.ok
29
22
  ? 'ok'
30
23
  : 'invalid_action';
31
- const result = { ok: Boolean(wire.ok), code };
32
- if (wire.message) {
33
- result.message = wire.message;
34
- }
35
- if (wire.sceneId) {
36
- result.sceneId = wire.sceneId;
37
- }
38
- return result;
24
+ return {
25
+ ok: Boolean(wire.ok),
26
+ code,
27
+ ...(wire.message && { message: wire.message }),
28
+ ...(wire.sceneId && { sceneId: wire.sceneId }),
29
+ };
39
30
  }
40
31
  export default class DispatchCommandHandler {
41
32
  interceptors = [];
42
- systemMiddlewares = [];
43
- addMiddleware(middleware) {
44
- this.systemMiddlewares.push(middleware);
45
- }
46
- removeMiddleware(middleware) {
47
- this.systemMiddlewares = this.systemMiddlewares.filter(item => item !== middleware);
33
+ async dispatch(sceneId, action, params) {
34
+ return leaveGuardHandler.middleware(sceneId, action, params, this.dispatchApproved);
48
35
  }
49
- interceptorMiddleware = async (sceneId, action, params, next) => {
36
+ dispatchApproved = async (sceneId, action, params) => {
37
+ const { [BEFORE_REMOVE_SOURCE_PROP]: _source, ...nativeParams } = params;
50
38
  const { from, to, props } = params;
51
39
  const intercepted = await this.intercept(action, {
52
40
  sceneId,
@@ -57,42 +45,12 @@ export default class DispatchCommandHandler {
57
45
  if (intercepted) {
58
46
  return { ok: false, code: 'intercepted' };
59
47
  }
60
- return next(sceneId, action, { ...params, [INTERCEPT_CHECKED_PROP]: true });
48
+ const dispatchNative = async () => normalizeDispatchResult(await NativeNavigation.dispatch(sceneId, action, nativeParams));
49
+ const closingOwnLayer = params.target === 'self' && (action === 'dismiss' || action === 'hideModal');
50
+ return action === 'close' || closingOwnLayer
51
+ ? closeWithExitHandler(sceneId, dispatchNative)
52
+ : dispatchNative();
61
53
  };
62
- async dispatchRaw(sceneId, action, params) {
63
- if (!params[INTERCEPT_CHECKED_PROP]) {
64
- const { from, to, props } = params;
65
- const intercepted = await this.intercept(action, {
66
- sceneId,
67
- from,
68
- to,
69
- props,
70
- });
71
- if (intercepted) {
72
- return { ok: false, code: 'intercepted' };
73
- }
74
- }
75
- const nativeParams = { ...params };
76
- for (const key of INTERNAL_DISPATCH_PROPS) {
77
- delete nativeParams[key];
78
- }
79
- if (nativeParams.result !== undefined) {
80
- nativeParams.result = resultHandler.normalizePendingResult(nativeParams.result);
81
- }
82
- const wire = await NativeNavigation.dispatch(sceneId, action, nativeParams);
83
- return normalizeDispatchResult(wire);
84
- }
85
- async dispatch(sceneId, action, params) {
86
- const chain = this.systemMiddlewares.slice();
87
- const invoke = (cursor, currentSceneId, currentAction, currentParams) => {
88
- if (cursor < chain.length) {
89
- const middleware = chain[cursor];
90
- return middleware(currentSceneId, currentAction, currentParams, (s, a, p) => invoke(cursor + 1, s, a, p));
91
- }
92
- return this.dispatchRaw(currentSceneId, currentAction, currentParams);
93
- };
94
- return invoke(0, sceneId, action, params);
95
- }
96
54
  async intercept(action, params) {
97
55
  for (const interceptor of this.interceptors.slice()) {
98
56
  const result = interceptor(action, params);
@@ -109,8 +67,5 @@ export default class DispatchCommandHandler {
109
67
  removeInterceptor(interceptor) {
110
68
  this.interceptors = this.interceptors.filter(item => item !== interceptor);
111
69
  }
112
- clearInterceptors() {
113
- this.interceptors = [];
114
- }
115
70
  }
116
71
  export const dispatchHandler = new DispatchCommandHandler();
@@ -1,10 +1,9 @@
1
- import type { BuildInLayout, DispatchResult, Layout, SetRootOptions } from '../Route';
1
+ import type { DispatchResult, Layout, SetRootOptions } from '../Route';
2
2
  export type RootLayoutListener = () => void;
3
3
  export default class LayoutCommandHandler {
4
4
  private listeners;
5
5
  handleRootLayoutChange(onWillSetRoot?: () => void): void;
6
- setRoot(layout: BuildInLayout | Layout, options?: SetRootOptions): Promise<DispatchResult>;
6
+ setRoot(layout: Layout, options?: SetRootOptions): Promise<DispatchResult>;
7
7
  addRootLayoutUpdateListener(willSetRoot?: RootLayoutListener, didSetRoot?: RootLayoutListener): () => void;
8
- clearListeners(): void;
9
8
  }
10
9
  export declare const layoutHandler: LayoutCommandHandler;
@@ -28,8 +28,5 @@ export default class LayoutCommandHandler {
28
28
  this.listeners = this.listeners.filter(item => item !== record);
29
29
  };
30
30
  }
31
- clearListeners() {
32
- this.listeners = [];
33
- }
34
31
  }
35
32
  export const layoutHandler = new LayoutCommandHandler();
@@ -1,6 +1,6 @@
1
- import type { BeforeRemoveListener, BeforeRemoveOptions, DispatchResult, RouteGraph } from '../Route';
1
+ import type { BeforeRemoveListener, BeforeRemoveOptions, DispatchResult } from '../Route';
2
2
  import type { DispatchParams } from './DispatchCommandHandler';
3
- export declare function collectRemovedStackScenes(layers: RouteGraph[], sceneId: string, action: 'popTo' | 'popToRoot', targetModuleOrSceneId?: string, inclusive?: boolean): string[];
3
+ export declare const BEFORE_REMOVE_SOURCE_PROP = "__hbdBeforeRemoveSource";
4
4
  export default class LeaveGuardHandler {
5
5
  private listeners;
6
6
  private nativeEnabledScenes;
@@ -1,7 +1,29 @@
1
1
  import NativeEvent from '../NativeEvent';
2
2
  import NativeNavigation from '../NativeNavigation';
3
- import { containsScene, findSceneInGraph } from '../routeGraph';
3
+ import { isScreenGraph } from '../router/screen';
4
4
  import { lifecycleHandler } from './LifecycleEventHandler';
5
+ function containsScene(graph, sceneId) {
6
+ if (graph.sceneId === sceneId) {
7
+ return true;
8
+ }
9
+ return Boolean(graph.children?.some(child => containsScene(child, sceneId)));
10
+ }
11
+ function findSceneInGraph(graph, predicate) {
12
+ if (isScreenGraph(graph)) {
13
+ return predicate(graph) ? graph : null;
14
+ }
15
+ if (!graph.children) {
16
+ return null;
17
+ }
18
+ for (const child of graph.children) {
19
+ const found = findSceneInGraph(child, predicate);
20
+ if (found) {
21
+ return found;
22
+ }
23
+ }
24
+ return null;
25
+ }
26
+ export const BEFORE_REMOVE_SOURCE_PROP = '__hbdBeforeRemoveSource';
5
27
  const GUARDED_ACTIONS = new Set([
6
28
  'pop',
7
29
  'popTo',
@@ -13,6 +35,9 @@ const GUARDED_ACTIONS = new Set([
13
35
  ]);
14
36
  const BYPASS_PROP = '__hbdBypassBeforeRemove';
15
37
  const APPROVED_SCENES_PROP = '__hbdApprovedBeforeRemoveScenes';
38
+ function isBeforeRemoveSource(value) {
39
+ return value === 'back' || value === 'self' || value === 'external';
40
+ }
16
41
  function collectScreenIds(graph, out) {
17
42
  if (graph.layout === 'screen') {
18
43
  out.push(graph.sceneId);
@@ -26,29 +51,14 @@ function collectScreenIds(graph, out) {
26
51
  }
27
52
  }
28
53
  function findContainingStack(graph, sceneId) {
29
- if (graph.layout === 'stack' && Array.isArray(graph.children)) {
30
- for (const child of graph.children) {
31
- const nested = findContainingStack(child, sceneId);
32
- if (nested) {
33
- return nested;
34
- }
35
- }
36
- if (graph.children.some(child => containsScene(child, sceneId))) {
37
- return graph;
38
- }
39
- }
40
- if (!graph.children) {
41
- return null;
42
- }
43
- for (const child of graph.children) {
44
- const found = findContainingStack(child, sceneId);
45
- if (found) {
46
- return found;
47
- }
54
+ for (const child of graph.children ?? []) {
55
+ if (!containsScene(child, sceneId))
56
+ continue;
57
+ return findContainingStack(child, sceneId) ?? (graph.layout === 'stack' ? graph : null);
48
58
  }
49
59
  return null;
50
60
  }
51
- export function collectRemovedStackScenes(layers, sceneId, action, targetModuleOrSceneId, inclusive = false) {
61
+ function collectRemovedStackScenes(layers, sceneId, action, targetModuleOrSceneId, inclusive = false) {
52
62
  let stack = null;
53
63
  for (let i = layers.length - 1; i >= 0; i--) {
54
64
  stack = findContainingStack(layers[i], sceneId);
@@ -57,31 +67,37 @@ export function collectRemovedStackScenes(layers, sceneId, action, targetModuleO
57
67
  }
58
68
  }
59
69
  if (!stack || !Array.isArray(stack.children) || stack.children.length <= 1) {
60
- return [sceneId];
61
- }
62
- const fromIndex = stack.children.findIndex(child => containsScene(child, sceneId));
63
- if (fromIndex <= 0) {
64
- return [sceneId];
70
+ return [];
65
71
  }
72
+ const topIndex = stack.children.length - 1;
66
73
  let stopIndex = 0;
67
74
  if (action === 'popTo') {
68
75
  if (!targetModuleOrSceneId) {
69
- return [sceneId];
76
+ return [];
70
77
  }
71
- const targetIndex = stack.children.findIndex(child => child.sceneId === targetModuleOrSceneId ||
72
- containsScene(child, targetModuleOrSceneId) ||
73
- Boolean(findSceneInGraph(child, node => node.moduleName === targetModuleOrSceneId)));
74
- if (targetIndex < 0 || targetIndex >= fromIndex) {
75
- return [sceneId];
78
+ // Match native iOS/Android top-down lookup; router.open dispatches popTo on the target sceneId,
79
+ // so removal always starts from the stack top (topIndex), not from the dispatching sceneId.
80
+ let targetIndex = -1;
81
+ for (let i = topIndex; i >= 0; i--) {
82
+ const child = stack.children[i];
83
+ if (child.sceneId === targetModuleOrSceneId ||
84
+ containsScene(child, targetModuleOrSceneId) ||
85
+ Boolean(findSceneInGraph(child, node => node.moduleName === targetModuleOrSceneId))) {
86
+ targetIndex = i;
87
+ break;
88
+ }
89
+ }
90
+ if (targetIndex < 0) {
91
+ return [];
76
92
  }
77
93
  // Match native iOS/Android behavior: inclusive && targetIndex > 0 pops targetIndex itself.
78
94
  stopIndex = inclusive && targetIndex > 0 ? targetIndex - 1 : targetIndex;
79
95
  }
80
96
  const removed = [];
81
- for (let i = fromIndex; i > stopIndex; i--) {
97
+ for (let i = topIndex; i > stopIndex; i--) {
82
98
  collectScreenIds(stack.children[i], removed);
83
99
  }
84
- return removed.length > 0 ? removed : [sceneId];
100
+ return removed;
85
101
  }
86
102
  function collectPresentedAboveScenes(layers, sceneId) {
87
103
  if (!Array.isArray(layers) || layers.length <= 1) {
@@ -97,15 +113,14 @@ function collectPresentedAboveScenes(layers, sceneId) {
97
113
  }
98
114
  return removed;
99
115
  }
100
- function matchesAction(entry, action, sceneId) {
116
+ function matchesAction(entry, action, mode) {
101
117
  if (!entry.actions) {
102
118
  return true;
103
119
  }
104
120
  if (entry.actions.has(action)) {
105
121
  return true;
106
122
  }
107
- if (action === 'close' && sceneId) {
108
- const mode = lifecycleHandler.getSceneInfo(sceneId)?.mode;
123
+ if (action === 'close') {
109
124
  if (mode === 'modal' && entry.actions.has('hideModal')) {
110
125
  return true;
111
126
  }
@@ -118,7 +133,7 @@ function matchesAction(entry, action, sceneId) {
118
133
  }
119
134
  return false;
120
135
  }
121
- function runGuardedChain(sceneId, action, matching, executeFinalProceed) {
136
+ function runGuardedChain(sceneId, action, source, matching, executeFinalProceed) {
122
137
  let finalPromise = null;
123
138
  const runFinal = () => {
124
139
  if (!finalPromise) {
@@ -134,6 +149,7 @@ function runGuardedChain(sceneId, action, matching, executeFinalProceed) {
134
149
  const event = {
135
150
  sceneId,
136
151
  action,
152
+ source,
137
153
  proceed: () => {
138
154
  if (!stepProceedPromise) {
139
155
  stepProceedPromise = runAt(index + 1);
@@ -193,10 +209,14 @@ export default class LeaveGuardHandler {
193
209
  if (!this.nativeEnabledScenes.has(sceneId)) {
194
210
  NativeNavigation.setBeforeRemoveEnabled(sceneId, false);
195
211
  }
196
- void proceedClose();
212
+ void proceedClose().catch(error => {
213
+ console.warn('[hybrid-navigation] Native back dispatch failed.', error);
214
+ });
197
215
  return;
198
216
  }
199
- runGuardedChain(sceneId, leaveAction, matching, proceedClose);
217
+ void runGuardedChain(sceneId, leaveAction, 'back', matching, proceedClose).catch(error => {
218
+ console.warn('[hybrid-navigation] Native back guard failed.', error);
219
+ });
200
220
  });
201
221
  }
202
222
  syncNativeEnabled(sceneId) {
@@ -249,15 +269,16 @@ export default class LeaveGuardHandler {
249
269
  delete cleanParams.bypassBeforeRemove;
250
270
  return next(sceneId, action, cleanParams);
251
271
  }
252
- if (!GUARDED_ACTIONS.has(action) || this.listeners.size === 0) {
272
+ if (!GUARDED_ACTIONS.has(action) || (this.listeners.size === 0 && !params[APPROVED_SCENES_PROP])) {
253
273
  return next(sceneId, action, params);
254
274
  }
275
+ const generation = this.rootGeneration;
255
276
  const leaveAction = action;
256
277
  const approved = params[APPROVED_SCENES_PROP] instanceof Set ? params[APPROVED_SCENES_PROP] : new Set();
257
278
  let candidateSceneIds = [sceneId];
258
279
  if (leaveAction === 'popTo' || leaveAction === 'popToRoot') {
259
280
  try {
260
- const layers = await NativeNavigation.routeGraph();
281
+ const layers = (await NativeNavigation.navigationSnapshot()).layers;
261
282
  if (Array.isArray(layers) && layers.length > 0) {
262
283
  candidateSceneIds = collectRemovedStackScenes(layers, sceneId, leaveAction, typeof params.moduleName === 'string'
263
284
  ? params.moduleName
@@ -273,7 +294,7 @@ export default class LeaveGuardHandler {
273
294
  else if ((leaveAction === 'dismiss' || leaveAction === 'hideModal') &&
274
295
  params.target !== 'self') {
275
296
  try {
276
- const layers = await NativeNavigation.routeGraph();
297
+ const layers = (await NativeNavigation.navigationSnapshot()).layers;
277
298
  const presentedAbove = collectPresentedAboveScenes(layers, sceneId);
278
299
  if (presentedAbove.length > 0) {
279
300
  candidateSceneIds = presentedAbove;
@@ -296,22 +317,43 @@ export default class LeaveGuardHandler {
296
317
  if (!set || set.size === 0) {
297
318
  continue;
298
319
  }
299
- const hits = Array.from(set).filter(entry => matchesAction(entry, leaveAction, candidateId));
320
+ let mode;
321
+ const needsMode = leaveAction === 'close' && Array.from(set).some(({ actions }) => actions && !actions.has('close') &&
322
+ (actions.has('pop') || actions.has('dismiss') || actions.has('hideModal')));
323
+ if (needsMode) {
324
+ const { layers } = await NativeNavigation.navigationSnapshot();
325
+ for (const layer of layers) {
326
+ const scene = findSceneInGraph(layer, node => node.sceneId === candidateId);
327
+ if (scene) {
328
+ mode = scene.mode;
329
+ break;
330
+ }
331
+ }
332
+ }
333
+ const hits = Array.from(set).filter(entry => matchesAction(entry, leaveAction, mode));
300
334
  if (hits.length > 0) {
301
335
  guardedSceneId = candidateId;
302
336
  matching = hits;
303
337
  break;
304
338
  }
305
339
  }
340
+ if (generation !== this.rootGeneration) {
341
+ return { ok: false, code: 'superseded' };
342
+ }
306
343
  if (!guardedSceneId || matching.length === 0) {
307
344
  const cleanParams = { ...params };
308
345
  delete cleanParams[APPROVED_SCENES_PROP];
309
346
  return next(sceneId, action, cleanParams);
310
347
  }
311
348
  const isMultiScene = candidateSceneIds.length > 1;
312
- const generation = this.rootGeneration;
313
349
  const targetGuardedSceneId = guardedSceneId;
314
- return runGuardedChain(targetGuardedSceneId, leaveAction, matching, async () => {
350
+ const explicitSource = params[BEFORE_REMOVE_SOURCE_PROP];
351
+ const source = isBeforeRemoveSource(explicitSource)
352
+ ? explicitSource
353
+ : targetGuardedSceneId !== sceneId
354
+ ? 'external'
355
+ : 'self';
356
+ return runGuardedChain(targetGuardedSceneId, leaveAction, source, matching, async () => {
315
357
  if (generation !== this.rootGeneration ||
316
358
  lifecycleHandler.getSceneState(targetGuardedSceneId) === 'destroyed') {
317
359
  return {
@@ -1,20 +1,12 @@
1
- import type { SceneInfo, SceneLifecycleState, Visibility } from '../Route';
1
+ import type { SceneLifecycleState } from '../Route';
2
2
  export type SceneLifecycleListener = (state: SceneLifecycleState, prevState: SceneLifecycleState) => void;
3
- export type GlobalSceneLifecycleListener = (sceneId: string, state: SceneLifecycleState, prevState: SceneLifecycleState, info?: SceneInfo) => void;
4
- export type VisibilityEventListener = (visibility: Visibility) => void;
5
- export type GlobalVisibilityEventListener = (sceneId: string, visibility: Visibility, info?: SceneInfo) => void;
3
+ export type GlobalSceneLifecycleListener = (sceneId: string, state: SceneLifecycleState, prevState: SceneLifecycleState) => void;
6
4
  export default class LifecycleEventHandler {
7
5
  private sceneStates;
8
- private sceneInfos;
9
6
  private destroyedScenes;
10
7
  private lifecycleListeners;
11
8
  private globalLifecycleListeners;
12
- private visibilityListeners;
13
- private globalVisibilityListeners;
14
9
  handleSceneLifecycle(onSceneDestroyed?: (sceneId: string) => void): void;
15
- getSceneInfo(sceneId: string): SceneInfo | undefined;
16
- onRootReset(): void;
17
- resetForTesting(): void;
18
10
  private markSceneDestroyed;
19
11
  getSceneState(sceneId: string): SceneLifecycleState;
20
12
  cleanupScene(sceneId: string): void;
@@ -22,9 +14,5 @@ export default class LifecycleEventHandler {
22
14
  removeLifecycleListener(sceneId: string, listener: SceneLifecycleListener): void;
23
15
  addGlobalLifecycleListener(listener: GlobalSceneLifecycleListener): void;
24
16
  removeGlobalLifecycleListener(listener: GlobalSceneLifecycleListener): void;
25
- addGlobalVisibilityEventListener(listener: GlobalVisibilityEventListener): void;
26
- removeGlobalVisibilityEventListener(listener: GlobalVisibilityEventListener): void;
27
- addVisibilityEventListener(sceneId: string, listener: VisibilityEventListener): void;
28
- removeVisibilityEventListener(sceneId: string, listener: VisibilityEventListener): void;
29
17
  }
30
18
  export declare const lifecycleHandler: LifecycleEventHandler;
@@ -5,68 +5,33 @@ const VALID_STATES = new Set([
5
5
  'invisible',
6
6
  'destroyed',
7
7
  ]);
8
- const VALID_MODES = new Set(['modal', 'present', 'normal']);
9
8
  function normalizeLifecycleState(raw) {
10
9
  if (VALID_STATES.has(raw)) {
11
10
  return raw;
12
11
  }
13
12
  return 'created';
14
13
  }
15
- function normalizeLayoutMode(raw, fallback = 'normal') {
16
- if (raw && VALID_MODES.has(raw)) {
17
- return raw;
18
- }
19
- return fallback;
20
- }
21
14
  const MAX_DESTROYED_SCENES = 2000;
22
15
  export default class LifecycleEventHandler {
23
16
  sceneStates = new Map();
24
- sceneInfos = new Map();
25
17
  destroyedScenes = new Set();
26
18
  lifecycleListeners = {};
27
19
  globalLifecycleListeners = [];
28
- visibilityListeners = {};
29
- globalVisibilityListeners = [];
30
20
  handleSceneLifecycle(onSceneDestroyed) {
31
- NativeEvent.onSceneStateChange(({ sceneId, state, prevState, moduleName, mode, presentingId }) => {
21
+ NativeEvent.onSceneStateChange(({ sceneId, state, prevState }) => {
32
22
  const next = normalizeLifecycleState(state);
33
23
  const prev = normalizeLifecycleState(prevState);
34
24
  if (next !== 'destroyed') {
35
25
  this.destroyedScenes.delete(sceneId);
36
26
  }
37
27
  this.sceneStates.set(sceneId, next);
38
- const prevInfo = this.sceneInfos.get(sceneId);
39
- const info = {
40
- sceneId,
41
- moduleName: moduleName ?? prevInfo?.moduleName,
42
- mode: normalizeLayoutMode(mode, prevInfo?.mode ?? 'normal'),
43
- presentingId: presentingId !== undefined ? presentingId : (prevInfo?.presentingId ?? null),
44
- state: next,
45
- };
46
- this.sceneInfos.set(sceneId, info);
47
- const visibilityChange = next === 'visible'
48
- ? 'visible'
49
- : prev === 'visible' && (next === 'invisible' || next === 'destroyed')
50
- ? 'invisible'
51
- : null;
52
- if (visibilityChange) {
53
- this.globalVisibilityListeners
54
- .slice()
55
- .forEach(listener => listener(sceneId, visibilityChange, info));
56
- }
57
28
  this.globalLifecycleListeners
58
29
  .slice()
59
- .forEach(listener => listener(sceneId, next, prev, info));
30
+ .forEach(listener => listener(sceneId, next, prev));
60
31
  const sceneListeners = this.lifecycleListeners[sceneId];
61
32
  if (sceneListeners) {
62
33
  sceneListeners.slice().forEach(listener => listener(next, prev));
63
34
  }
64
- if (visibilityChange) {
65
- const visListeners = this.visibilityListeners[sceneId];
66
- if (visListeners) {
67
- visListeners.slice().forEach(listener => listener(visibilityChange));
68
- }
69
- }
70
35
  if (next === 'destroyed') {
71
36
  this.markSceneDestroyed(sceneId);
72
37
  onSceneDestroyed?.(sceneId);
@@ -74,21 +39,6 @@ export default class LifecycleEventHandler {
74
39
  }
75
40
  });
76
41
  }
77
- getSceneInfo(sceneId) {
78
- return this.sceneInfos.get(sceneId);
79
- }
80
- onRootReset() {
81
- // Lifecycle state maps are updated by native destroyed events.
82
- }
83
- resetForTesting() {
84
- this.sceneStates.clear();
85
- this.sceneInfos.clear();
86
- this.destroyedScenes.clear();
87
- this.lifecycleListeners = {};
88
- this.globalLifecycleListeners = [];
89
- this.visibilityListeners = {};
90
- this.globalVisibilityListeners = [];
91
- }
92
42
  markSceneDestroyed(sceneId) {
93
43
  this.destroyedScenes.delete(sceneId);
94
44
  this.destroyedScenes.add(sceneId);
@@ -111,9 +61,7 @@ export default class LifecycleEventHandler {
111
61
  }
112
62
  cleanupScene(sceneId) {
113
63
  this.sceneStates.delete(sceneId);
114
- this.sceneInfos.delete(sceneId);
115
64
  delete this.lifecycleListeners[sceneId];
116
- delete this.visibilityListeners[sceneId];
117
65
  }
118
66
  addLifecycleListener(sceneId, listener) {
119
67
  if (!this.lifecycleListeners[sceneId]) {
@@ -140,30 +88,5 @@ export default class LifecycleEventHandler {
140
88
  removeGlobalLifecycleListener(listener) {
141
89
  this.globalLifecycleListeners = this.globalLifecycleListeners.filter(l => l !== listener);
142
90
  }
143
- addGlobalVisibilityEventListener(listener) {
144
- this.globalVisibilityListeners.push(listener);
145
- }
146
- removeGlobalVisibilityEventListener(listener) {
147
- this.globalVisibilityListeners = this.globalVisibilityListeners.filter(l => l !== listener);
148
- }
149
- addVisibilityEventListener(sceneId, listener) {
150
- if (!this.visibilityListeners[sceneId]) {
151
- this.visibilityListeners[sceneId] = [];
152
- }
153
- this.visibilityListeners[sceneId].push(listener);
154
- }
155
- removeVisibilityEventListener(sceneId, listener) {
156
- const list = this.visibilityListeners[sceneId];
157
- if (!list) {
158
- return;
159
- }
160
- const next = list.filter(l => l !== listener);
161
- if (next.length > 0) {
162
- this.visibilityListeners[sceneId] = next;
163
- }
164
- else {
165
- delete this.visibilityListeners[sceneId];
166
- }
167
- }
168
91
  }
169
92
  export const lifecycleHandler = new LifecycleEventHandler();
@@ -1,6 +1,5 @@
1
1
  import type { CancelReason, NavigationResult, ResultMap } from '../Route';
2
2
  export declare const RESULT_CANCEL: number, RESULT_OK: number, RESULT_BLOCK: number;
3
- export type ResultType = unknown;
4
3
  export type ResultEventListener<T = unknown> = (result: NavigationResult<T>) => void;
5
4
  export type PreparedResult<T = unknown> = {
6
5
  promise: Promise<NavigationResult<T>>;
@@ -105,9 +105,6 @@ export default class ResultEventHandler {
105
105
  if (code < RESULT_OK) {
106
106
  console.warn('`resultCode` can only be `RESULT_OK`, `RESULT_CANCEL` or an integer greater than 0.');
107
107
  }
108
- if (__DEV__ && code === RESULT_CANCEL && data !== null && data !== undefined) {
109
- console.warn('[hybrid-navigation] `RESULT_CANCEL` ignores `data` because `RESULT_CANCEL` always resolves as `{ status: "cancel" }`. Pass `null` or use `RESULT_OK` to return data.');
110
- }
111
108
  if (data !== null && (typeof data !== 'object' || Array.isArray(data))) {
112
109
  console.warn('`setResult` data must be a plain object or null.');
113
110
  return { code, data: null };
@@ -0,0 +1,3 @@
1
+ import type { DispatchResult, SceneExitHandler } from '../Route';
2
+ export declare function registerExitHandler(sceneId: string, handler: SceneExitHandler): () => void;
3
+ export declare function closeWithExitHandler(sceneId: string, close: () => Promise<DispatchResult>): Promise<DispatchResult>;
@@ -0,0 +1,76 @@
1
+ import NativeNavigation from '../NativeNavigation';
2
+ import { isSceneCoveredInLayers } from '../sceneCoverage';
3
+ const handlers = new Map();
4
+ const pending = new Map();
5
+ export function registerExitHandler(sceneId, handler) {
6
+ const stack = handlers.get(sceneId) ?? [];
7
+ stack.push(handler);
8
+ handlers.set(sceneId, stack);
9
+ return () => {
10
+ const index = stack.indexOf(handler);
11
+ if (index >= 0)
12
+ stack.splice(index, 1);
13
+ if (!stack.length && handlers.get(sceneId) === stack)
14
+ handlers.delete(sceneId);
15
+ };
16
+ }
17
+ async function playExit(handler) {
18
+ const animation = handler.onExit();
19
+ const timeout = handler.exitTimeoutMs ?? 1200;
20
+ if (!animation || timeout <= 0)
21
+ return animation;
22
+ let timer;
23
+ try {
24
+ await Promise.race([
25
+ animation,
26
+ new Promise((_, reject) => {
27
+ timer = setTimeout(() => reject(new Error('Scene exit animation timed out.')), timeout);
28
+ }),
29
+ ]);
30
+ }
31
+ finally {
32
+ clearTimeout(timer);
33
+ }
34
+ }
35
+ async function exitAndClose(sceneId, handler, close) {
36
+ const { layers } = await NativeNavigation.navigationSnapshot();
37
+ if (isSceneCoveredInLayers(layers, sceneId, 'close'))
38
+ return { ok: false, code: 'covered' };
39
+ if (!handlers.get(sceneId)?.includes(handler))
40
+ return close();
41
+ function restore(reason) {
42
+ if (handlers.get(sceneId)?.includes(handler))
43
+ handler.onRestore?.(reason);
44
+ }
45
+ try {
46
+ await playExit(handler);
47
+ }
48
+ catch (error) {
49
+ restore('exit_error');
50
+ return { ok: false, code: 'invalid_action', message: String(error) };
51
+ }
52
+ // Native closeSelf rechecks coverage before committing the supplied result.
53
+ let result;
54
+ try {
55
+ result = await close();
56
+ }
57
+ catch (error) {
58
+ restore('invalid_action');
59
+ throw error;
60
+ }
61
+ if (!result.ok)
62
+ restore(result.code);
63
+ return result;
64
+ }
65
+ export function closeWithExitHandler(sceneId, close) {
66
+ const existing = pending.get(sceneId);
67
+ if (existing)
68
+ return existing;
69
+ const stack = handlers.get(sceneId);
70
+ const handler = stack?.[stack.length - 1];
71
+ if (!handler)
72
+ return close();
73
+ const request = exitAndClose(sceneId, handler, close).finally(() => pending.delete(sceneId));
74
+ pending.set(sceneId, request);
75
+ return request;
76
+ }
package/dist/hooks.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Navigator } from './Navigator';
2
- import type { BeforeRemoveListener, BeforeRemoveOptions, RouteName, SceneLifecycleState } from './Route';
2
+ import type { BeforeRemoveListener, BeforeRemoveOptions, RouteName, SceneExitHandler, SceneLifecycleState } from './Route';
3
3
  export type VisibleEffectCallback = () => void | (() => void);
4
4
  export declare function useNavigator<Name extends RouteName = RouteName>(): Navigator<Name>;
5
5
  export declare function useSceneState(): SceneLifecycleState;
6
- export declare function useIsVisible(): boolean;
6
+ export declare function useSceneExitHandler(handler: SceneExitHandler | null | undefined): void;
7
7
  export declare function useBeforeRemove(enabled: boolean, onBeforeRemove: BeforeRemoveListener, options?: BeforeRemoveOptions): void;
8
8
  export declare function useVisibleEffect(callback: VisibleEffectCallback): void;