@sigx/lynx-navigation 0.2.0 → 0.4.1

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 (67) hide show
  1. package/README.md +128 -8
  2. package/dist/components/EntryScope.d.ts.map +1 -1
  3. package/dist/components/EntryScope.js +8 -2
  4. package/dist/components/EntryScope.js.map +1 -1
  5. package/dist/components/Layer.d.ts +34 -0
  6. package/dist/components/Layer.d.ts.map +1 -0
  7. package/dist/components/Layer.js +66 -0
  8. package/dist/components/Layer.js.map +1 -0
  9. package/dist/components/Screen.d.ts +6 -6
  10. package/dist/components/Screen.d.ts.map +1 -1
  11. package/dist/components/Screen.js +13 -9
  12. package/dist/components/Screen.js.map +1 -1
  13. package/dist/components/Stack.d.ts +41 -16
  14. package/dist/components/Stack.d.ts.map +1 -1
  15. package/dist/components/Stack.js +90 -54
  16. package/dist/components/Stack.js.map +1 -1
  17. package/dist/components/TabBar.d.ts +18 -19
  18. package/dist/components/TabBar.d.ts.map +1 -1
  19. package/dist/components/TabBar.js +21 -21
  20. package/dist/components/TabBar.js.map +1 -1
  21. package/dist/components/Tabs.d.ts.map +1 -1
  22. package/dist/components/Tabs.js +15 -1
  23. package/dist/components/Tabs.js.map +1 -1
  24. package/dist/hooks/use-linking-nav.js.map +1 -1
  25. package/dist/hooks/use-nav-internal.d.ts +19 -1
  26. package/dist/hooks/use-nav-internal.d.ts.map +1 -1
  27. package/dist/hooks/use-nav-internal.js +11 -0
  28. package/dist/hooks/use-nav-internal.js.map +1 -1
  29. package/dist/hooks/use-screen-chrome.d.ts +19 -0
  30. package/dist/hooks/use-screen-chrome.d.ts.map +1 -0
  31. package/dist/hooks/use-screen-chrome.js +102 -0
  32. package/dist/hooks/use-screen-chrome.js.map +1 -0
  33. package/dist/index.d.ts +2 -0
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +1 -0
  36. package/dist/index.js.map +1 -1
  37. package/dist/internal/layer-plan.d.ts +69 -0
  38. package/dist/internal/layer-plan.d.ts.map +1 -0
  39. package/dist/internal/layer-plan.js +102 -0
  40. package/dist/internal/layer-plan.js.map +1 -0
  41. package/dist/internal/screen-width.d.ts +9 -7
  42. package/dist/internal/screen-width.d.ts.map +1 -1
  43. package/dist/internal/screen-width.js +15 -13
  44. package/dist/internal/screen-width.js.map +1 -1
  45. package/dist/navigator/core.d.ts +2 -1
  46. package/dist/navigator/core.d.ts.map +1 -1
  47. package/dist/navigator/core.js +13 -2
  48. package/dist/navigator/core.js.map +1 -1
  49. package/dist/url/format.js.map +1 -1
  50. package/package.json +13 -11
  51. package/src/components/EntryScope.tsx +13 -2
  52. package/src/components/Layer.tsx +96 -0
  53. package/src/components/Screen.tsx +11 -9
  54. package/src/components/Stack.tsx +136 -92
  55. package/src/components/TabBar.tsx +21 -21
  56. package/src/components/Tabs.tsx +15 -1
  57. package/src/hooks/use-nav-internal.ts +22 -1
  58. package/src/hooks/use-screen-chrome.ts +122 -0
  59. package/src/index.ts +2 -0
  60. package/src/internal/layer-plan.ts +187 -0
  61. package/src/internal/screen-width.ts +22 -14
  62. package/src/navigator/core.ts +14 -3
  63. package/dist/components/ScreenContainer.d.ts +0 -18
  64. package/dist/components/ScreenContainer.d.ts.map +0 -1
  65. package/dist/components/ScreenContainer.js +0 -77
  66. package/dist/components/ScreenContainer.js.map +0 -1
  67. package/src/components/ScreenContainer.tsx +0 -114
@@ -5,11 +5,8 @@ import {
5
5
  onUnmounted,
6
6
  untrack,
7
7
  useSharedValue,
8
- type ComponentFactory,
9
8
  type Define,
10
- type SharedValue,
11
9
  } from '@sigx/lynx';
12
- import { Suspense, isLazyComponent } from '@sigx/lynx';
13
10
  import { createNavigatorState } from '../navigator/core.js';
14
11
  import { useNav, type Nav } from '../hooks/use-nav.js';
15
12
  import {
@@ -19,9 +16,9 @@ import {
19
16
  type NavInternals,
20
17
  } from '../hooks/use-nav-internal.js';
21
18
  import type { Presentation, StackEntry } from '../types.js';
22
- import { ScreenContainer } from './ScreenContainer.js';
19
+ import { animationVariant, computeLayers, isOverlayPresentation } from '../internal/layer-plan.js';
23
20
  import { EdgeBackHandle } from './EdgeBackHandle.js';
24
- import { EntryScope } from './EntryScope.js';
21
+ import { Layer } from './Layer.js';
25
22
  import { useTabScreenName, useTabs } from './Tabs.js';
26
23
 
27
24
  type StackProps =
@@ -42,7 +39,19 @@ type StackProps =
42
39
  /** Initial params for the nested-stack base entry. */
43
40
  & Define.Prop<'initialParams', Record<string, unknown>>
44
41
  /** Initial search for the nested-stack base entry. */
45
- & Define.Prop<'initialSearch', Record<string, unknown>>;
42
+ & Define.Prop<'initialSearch', Record<string, unknown>>
43
+ /**
44
+ * Optional chrome rendered *above* the active screen, **inside this
45
+ * Stack's nav scope**. The intended use is `<Header />`, which needs
46
+ * to resolve `useNav()` to the per-stack nav (not the enclosing one)
47
+ * so it can react to pushes inside this stack — e.g. show a back
48
+ * button when a card is pushed onto a per-tab stack.
49
+ *
50
+ * Without this, a `<Header />` placed as a sibling of `<Stack>`
51
+ * would see the enclosing nav and never update when pushes happen
52
+ * inside the nested stack.
53
+ */
54
+ & Define.Slot<'default'>;
46
55
 
47
56
  let _nestedKeyCounter = 0;
48
57
 
@@ -74,22 +83,33 @@ let _nestedKeyCounter = 0;
74
83
  * walks to root and overlays the whole UI. `replace` stays strictly local
75
84
  * (asymmetric with `push`) so a modal `replace` never wipes the root stack.
76
85
  *
77
- * **Render strategy** (same in both modes):
78
- * - **Idle**: just the top entry, full-bleed, no transform. The screen
79
- * component mounts directly so it can use its own layout (no extra
80
- * absolute positioning that would break percentage heights).
81
- * - **Transitioning**: two `<ScreenContainer>` instances stacked
82
- * absolutely, each with an MT-driven `translateX` that reads from the
83
- * navigator's progress `SharedValue`. The host's BG thread doesn't tick
84
- * per frame — `useAnimatedStyle` runs the interpolation entirely on MT.
86
+ * **Render strategy.** Stack always emits the same JSX shape — a
87
+ * relative wrapper containing one `<Layer>` per entry returned by
88
+ * `computeLayers(stack, transition, progress)`. Each Layer is an
89
+ * absolutely-positioned host view with optional MT-bound translate
90
+ * animation. The pure layer-plan function decides:
85
91
  *
86
- * `key={top.key}` keeps the idle render's component instance stable across
87
- * unrelated re-renders. During transitions, composite keys
88
- * (`${entry.key}-${role}-${kind}`) ensure a fresh mount per role/kind pair
89
- * so the `useAnimatedStyle` binding is set with the right input/output
90
- * ranges.
92
+ * - **Idle.** Topmost non-overlay base + any overlays above it. All
93
+ * static (no transform). Overlays (`modal` / `fullScreen` /
94
+ * `transparent-modal`) keep their underneath mounted; cards
95
+ * replace their underneath in the base layer.
96
+ * - **Card transition.** Both top and underneath animate (slide-in
97
+ * + parallax). After settle, idle rules apply — the underneath
98
+ * unmounts because the new top is the sole base.
99
+ * - **Overlay transition.** The full idle layer stack up through
100
+ * the underneath stays static; only the animated top has a
101
+ * transform. After settle, the overlay either joins the static
102
+ * idle stack (push) or unmounts (pop).
103
+ *
104
+ * Layer keys are `layer-${entry.key}-${animationVariant}`. The variant
105
+ * suffix forces a remount when an entry transitions from animated to
106
+ * static (or vice versa) — `useAnimatedStyle` binds once at setup and
107
+ * can't switch its mapper at runtime. Modal underneath layers never
108
+ * animate, so their key is stable across the modal lifecycle and the
109
+ * subtree's state (per-tab Stack navigators, scroll positions,
110
+ * in-flight inputs) survives.
91
111
  */
92
- export const Stack = component<StackProps>(({ props }) => {
112
+ export const Stack = component<StackProps>(({ props, slots }) => {
93
113
  // Capture enclosing scope's nav + routes + internals BEFORE any of the
94
114
  // defineProvide calls below override them for descendants. These are
95
115
  // always the "outer" values regardless of whether this Stack is bound
@@ -226,89 +246,113 @@ export const Stack = component<StackProps>(({ props }) => {
226
246
  internals = parentInternals;
227
247
  }
228
248
 
249
+ // Per-stack chrome (slots.default) renders *inside* this Stack's
250
+ // nav scope so a `<Header />` placed there resolves `useNav()` to
251
+ // the per-stack nav. Wrapping the active body in a flex-column
252
+ // with the slot above does that without disturbing layer-fill
253
+ // semantics — the slot takes natural height, the body keeps
254
+ // flex-fill.
255
+ const flexColumnFill = {
256
+ flexGrow: 1,
257
+ flexShrink: 1,
258
+ flexBasis: 0,
259
+ minHeight: 0,
260
+ display: 'flex',
261
+ flexDirection: 'column',
262
+ } as const;
263
+
229
264
  return () => {
230
- const transition = nav.transition;
231
- const top = nav.current;
265
+ const chrome = slots.default?.();
266
+ const layers = computeLayers(nav.stack, nav.transition, internals.progress);
232
267
 
233
- if (!transition) {
234
- const route = routes[top.route];
235
- if (!route) return null;
236
- const Comp = route.component as unknown as ComponentFactory<
237
- Record<string, unknown>,
238
- unknown,
239
- unknown
240
- >;
241
- if (typeof Comp !== 'function') return null;
242
- const params = top.params as Record<string, unknown>;
243
- // Wrap lazy routes that declare a `fallback` in <Suspense> so the
244
- // chunk-load shows the user-provided spinner instead of throwing
245
- // up to the nearest outer boundary (which may be wrong layer or
246
- // missing entirely).
247
- const body = isLazyComponent(Comp) && route.fallback
248
- ? (
249
- <Suspense fallback={route.fallback as never}>
250
- <Comp {...params} />
251
- </Suspense>
252
- )
253
- : <Comp {...params} />;
254
- // When canGoBack and edge-swipe is enabled, overlay the gesture
255
- // handle so the user can pan from the left edge to start a back
256
- // transition. `position: absolute` doesn't disturb the screen's
257
- // own layout — the handle only intercepts touches in the leftmost
258
- // 20px, and only when they pan rightward past `MIN_DISTANCE`.
259
- if (nav.canGoBack && internals.edgeSwipeEnabled) {
260
- return (
261
- <view
262
- style={{
263
- position: 'relative',
264
- width: '100%',
265
- height: '100%',
266
- }}
267
- >
268
- <EntryScope key={top.key} entry={top}>
269
- {body}
270
- </EntryScope>
271
- <EdgeBackHandle key="edge-back" />
272
- </view>
273
- );
274
- }
275
- return (
276
- <EntryScope key={top.key} entry={top}>
277
- {body}
278
- </EntryScope>
279
- );
280
- }
268
+ const renderLayerNode = (layer: typeof layers[number] | undefined) =>
269
+ layer ? (
270
+ <Layer
271
+ key={`layer-${layer.entry.key}-${animationVariant(layer.animation)}`}
272
+ entry={layer.entry}
273
+ routes={routes}
274
+ animation={layer.animation}
275
+ />
276
+ ) : null;
277
+ // sigx's reconciler treats a single array-valued JSX child as
278
+ // one "slot": when the array's *length* changes between
279
+ // renders, keyed children inside can be remounted even if
280
+ // their keys are stable. To make stacked-overlay state
281
+ // preservation work (modal A still mounted after modal B
282
+ // pushes on top), each layer is emitted as its own separate
283
+ // JSX child slot rather than as an array. The slots are
284
+ // position-stable across renders — the only thing that
285
+ // changes is a slot turning from `null` to a Layer (mount) or
286
+ // vice versa (unmount). MAX_LAYERS caps the supported stack
287
+ // depth; in practice apps rarely stack more than 2-3 overlays.
288
+ // If you hit the cap, increase the constant — the unrolled
289
+ // shape is just verbose, not algorithmically limited.
281
290
 
282
- // Cast progress: TransitionState carries it as `unknown` to avoid
283
- // pinning the contract to `@sigx/lynx`'s SharedValue at the type
284
- // level; here at the runtime boundary we know it's a SharedValue<number>.
285
- const progress = transition.progress as SharedValue<number>;
291
+ // Edge-swipe handle on top, gated on:
292
+ // - `internals.edgeSwipeEnabled` opt-out flag (also off
293
+ // when the navigator has no progress SharedValue, i.e.
294
+ // animations disabled no in-flight gesture to animate).
295
+ // - `nav.canGoBack` — something to pop back to.
296
+ // - `!nav.transition` — no animation already running.
297
+ // - The current top is a card (not an overlay). Edge-swipe
298
+ // is the iOS-style horizontal pop gesture for card stacks;
299
+ // using it to dismiss a modal would be the wrong axis +
300
+ // the wrong dismissal semantic.
301
+ //
302
+ // The handle only intercepts touches in the leftmost 20px and
303
+ // ignores small drags, so placing it last (highest z) doesn't
304
+ // disturb screen touches.
305
+ const top = nav.current;
306
+ const edgeHandle = (
307
+ internals.edgeSwipeEnabled
308
+ && nav.canGoBack
309
+ && !nav.transition
310
+ && !isOverlayPresentation(top.presentation)
311
+ )
312
+ ? <EdgeBackHandle key="edge-back" />
313
+ : null;
286
314
 
287
- return (
315
+ const body = (
288
316
  <view
289
317
  style={{
290
318
  position: 'relative',
291
319
  width: '100%',
292
- height: '100%',
320
+ // Flex-fill so the layer container has a real
321
+ // height — `<Layer>`s anchor via `position:
322
+ // absolute; top/right/bottom/left: 0`, which
323
+ // needs a sized relative parent.
324
+ ...flexColumnFill,
325
+ // Clip any animated layer that translates off-
326
+ // screen so the slide doesn't bleed past the
327
+ // Stack's bounds.
293
328
  overflow: 'hidden',
294
329
  }}
295
330
  >
296
- <ScreenContainer
297
- key={`${transition.underneathEntry.key}-underneath-${transition.kind}`}
298
- entry={transition.underneathEntry}
299
- routes={routes}
300
- role="underneath"
301
- kind={transition.kind}
302
- progress={progress}
303
- />
304
- <ScreenContainer
305
- key={`${transition.topEntry.key}-top-${transition.kind}`}
306
- entry={transition.topEntry}
307
- routes={routes}
308
- role="top"
309
- kind={transition.kind}
310
- progress={progress}
311
- />
331
+ {renderLayerNode(layers[0])}
332
+ {renderLayerNode(layers[1])}
333
+ {renderLayerNode(layers[2])}
334
+ {renderLayerNode(layers[3])}
335
+ {renderLayerNode(layers[4])}
336
+ {renderLayerNode(layers[5])}
337
+ {renderLayerNode(layers[6])}
338
+ {renderLayerNode(layers[7])}
339
+ {renderLayerNode(layers[8])}
340
+ {renderLayerNode(layers[9])}
341
+ {renderLayerNode(layers[10])}
342
+ {renderLayerNode(layers[11])}
343
+ {renderLayerNode(layers[12])}
344
+ {renderLayerNode(layers[13])}
345
+ {renderLayerNode(layers[14])}
346
+ {renderLayerNode(layers[15])}
347
+ {edgeHandle}
348
+ </view>
349
+ );
350
+
351
+ if (chrome == null) return body as never;
352
+ return (
353
+ <view style={flexColumnFill}>
354
+ {chrome}
355
+ <view style={flexColumnFill}>{body}</view>
312
356
  </view>
313
357
  );
314
358
  };
@@ -1,29 +1,28 @@
1
1
  /**
2
- * `<TabBar>` — default chrome for `<Tabs>`.
2
+ * `<TabBar>` — headless default chrome for `<Tabs>`.
3
3
  *
4
- * Renders a row of tab buttons reading from the enclosing `useTabs()`
5
- * navigator. Active tab is highlighted via the `active` prop on each
6
- * default button (consumers can re-style via `renderTab`).
4
+ * Renders the active-tab buttons reading from the enclosing `useTabs()`
5
+ * navigator. Intentionally **unstyled** this lives in the (theme-less)
6
+ * navigation package, so it ships pure structure + accessibility wiring.
7
+ * Themed chrome belongs in a UI-kit package: see `<NavTabBar />` in
8
+ * `@sigx/lynx-daisyui` for the daisy-themed equivalent.
7
9
  *
8
- * Customization knobs:
10
+ * Use this directly only if you want to handle styling yourself via the
11
+ * `renderTab` prop. For a "looks like a tab bar out of the box" component,
12
+ * pull `<NavTabBar />` from `@sigx/lynx-daisyui` (or your own UI kit).
13
+ *
14
+ * Customization:
9
15
  * - `renderTab`: a function `(info, ctx) => JSX` that fully replaces the
10
16
  * default button rendering for each tab. `ctx.active` tells the
11
17
  * consumer whether this tab is currently focused; `ctx.onPress`
12
- * activates the tab.
13
- *
14
- * Accessibility:
15
- * - Each default button gets `accessibility-label` from
16
- * `info.accessibilityLabel ?? info.label ?? info.name`.
17
- * - Each default button gets `accessibility-element="true"` so screen
18
- * readers see the whole pill, not just the inner `<text>`.
19
- * - Each default button gets `accessibility-trait="button"` and a
20
- * `selected` flag on the active one so VoiceOver/TalkBack announces
21
- * focus state on tab switch.
18
+ * activates the tab. **Recommended** for any visual treatment.
22
19
  *
23
- * Placement: mount inside `<Tabs>` alongside the `<Tabs.Screen>`s. Order
24
- * matters visually (place above or below the screen bodies depending on
25
- * the layout), and `<Tabs.Screen>` bodies all stack with `display:flex` so
26
- * the TabBar should be at a deterministic position in the JSX.
20
+ * Accessibility (baked into the default button — the one structural
21
+ * concern this component keeps):
22
+ * - `accessibility-label` from `info.accessibilityLabel ?? info.label ?? info.name`.
23
+ * - `accessibility-element="true"` so screen readers see the whole pill.
24
+ * - `accessibility-trait="button"` and a `selected` flag on the active
25
+ * one so VoiceOver/TalkBack announces focus state on tab switch.
27
26
  */
28
27
  import {
29
28
  component,
@@ -46,8 +45,9 @@ type TabBarProps =
46
45
  /**
47
46
  * Default per-tab button. Plain `<view>` with a `<text>` inside, an
48
47
  * `accessibility-*` cluster for screen readers, and a tap handler. No
49
- * styling beyond a minimal active-state marker — consumers that want
50
- * branded chrome pass `renderTab`.
48
+ * styling beyond a minimal active-state opacity hint — consumers that
49
+ * want branded chrome pass `renderTab` or use a UI-kit-provided tab bar
50
+ * (e.g. `<NavTabBar />` from `@sigx/lynx-daisyui`).
51
51
  */
52
52
  const DefaultTabButton = component<
53
53
  & Define.Prop<'info', TabInfo, true>
@@ -208,13 +208,27 @@ const TabsScreen = component<TabsScreenProps>(({ props, slots }) => {
208
208
  // `display: none` keeps the body mounted so per-tab state survives
209
209
  // tab switches. Read activeSignal here so re-activating triggers a
210
210
  // re-render with display restored.
211
+ //
212
+ // Flex-fill long-form (`flex-grow/shrink/basis`) instead of
213
+ // `height: '100%'`. The percentage form only resolves against an
214
+ // explicit parent height, which means consumers had to wrap us
215
+ // in a `flexFill + height: '100%'` view to make us visible — and
216
+ // every Lynx app got that wrong (myself included) until we hit
217
+ // it on the showcase. With flex-fill we just take whatever space
218
+ // our parent flex container gives us; the parent only needs to
219
+ // be a flex column with a known height (e.g. SafeAreaView, which
220
+ // now defaults to that).
211
221
  const active = registrar.activeSignal.value === name;
212
222
  return (
213
223
  <view
214
224
  style={{
215
225
  display: active ? 'flex' : 'none',
226
+ flexDirection: 'column',
216
227
  width: '100%',
217
- height: '100%',
228
+ flexGrow: 1,
229
+ flexShrink: 1,
230
+ flexBasis: 0,
231
+ minHeight: 0,
218
232
  }}
219
233
  >
220
234
  {slots.default?.()}
@@ -19,6 +19,20 @@ export const useCurrentEntry = defineInjectable<StackEntry>(() => {
19
19
  );
20
20
  });
21
21
 
22
+ /**
23
+ * Soft companion to {@link useCurrentEntry} — returns the current scope's
24
+ * entry if any, `null` when called outside an `<EntryScope>` instead of
25
+ * throwing. Provided alongside the strict version by `<EntryScope>`.
26
+ *
27
+ * Used by chrome consumers (`useScreenChrome`) where "no scoped entry"
28
+ * is a legitimate state (a Stack chrome slot lives outside the screen's
29
+ * EntryScope) and the caller wants to soft-fallback to the navigator's
30
+ * destination entry rather than crash.
31
+ */
32
+ export const useCurrentEntryOptional = defineInjectable<StackEntry | null>(
33
+ () => null,
34
+ );
35
+
22
36
  /**
23
37
  * Internal injectable: the route registry passed into `<NavigationRoot>`.
24
38
  * Components (Stack, Screen) read this to look up route definitions by name.
@@ -64,7 +78,14 @@ export interface NavInternals {
64
78
  */
65
79
  readonly screens: {
66
80
  register(registry: ScreenRegistry): void;
67
- unregister(entryKey: string): void;
81
+ /**
82
+ * Identity-checked: only removes the entry if `registry` is the
83
+ * one currently registered under its `entry.key`. A no-op when
84
+ * a newer registry has already taken that slot (which happens
85
+ * at the transition→idle handoff, where a fresh `<EntryScope>`
86
+ * for the same entry mounts before the old one's unmount fires).
87
+ */
88
+ unregister(registry: ScreenRegistry): void;
68
89
  get(entryKey: string): ScreenRegistry | undefined;
69
90
  };
70
91
  }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * `useScreenChrome` — reactive read of the currently-focused screen's
3
+ * options + slot fills, plus navigation helpers a header would need
4
+ * (canGoBack, pop).
5
+ *
6
+ * The built-in `<Header />` reads this same data via internal hooks.
7
+ * `useScreenChrome` exposes it as a public API so theme packages
8
+ * (`@sigx/lynx-daisyui`, custom designs) can build their own header
9
+ * components without depending on internal modules.
10
+ *
11
+ * Resolution rules:
12
+ *
13
+ * - **Inside a screen body** (i.e. inside an EntryScope whose entry is
14
+ * on the nearest `useNav()`'s stack), bind to **this entry's**
15
+ * registry. Useful for modal screens that render their own
16
+ * NavHeader inside — the chrome slides with the sheet.
17
+ * - **Outside any matching EntryScope** (slot of `<Stack>`, persistent
18
+ * root-level Header, etc.), bind to the *destination* entry of the
19
+ * current nav state — what the navigator is settling on once the
20
+ * in-flight transition completes. Push: the new top (already at
21
+ * nav.current). Pop: the entry being revealed
22
+ * (`transition.underneathEntry`), *not* the one being animated off.
23
+ * Using the destination means the bar reflects what the user is
24
+ * navigating *to*, immediately, with no end-of-animation snap.
25
+ *
26
+ * Every property is a getter — reading inside a render / `computed`
27
+ * subscribes to the underlying signal, so consumers re-render when
28
+ * title / slots change.
29
+ */
30
+ import { useNav } from './use-nav.js';
31
+ import { useCurrentEntryOptional, useNavInternals } from './use-nav-internal.js';
32
+ import type { ScreenSlotFills, StackEntry } from '../types.js';
33
+
34
+ export interface ScreenChrome {
35
+ /** Resolved screen title — `options.title` (string or getter) or the route name as fallback. Reactive. */
36
+ readonly title: string;
37
+ /** Whether the header should render. Defaults to true unless the screen set `headerShown: false`. Reactive. */
38
+ readonly headerShown: boolean;
39
+ /** True when the current stack has more than one entry — i.e. there's something to pop back to. Reactive. */
40
+ readonly canGoBack: boolean;
41
+ /** Pop the top entry. No-op when `!canGoBack`. */
42
+ pop(): void;
43
+ /** Full header override slot, if `<Screen.Header>` was set. Render its return value in place of the default layout. */
44
+ readonly header: ScreenSlotFills['header'] | undefined;
45
+ /** Left-aligned slot (typically a back button). Reactive. */
46
+ readonly headerLeft: ScreenSlotFills['headerLeft'] | undefined;
47
+ /** Right-aligned slot (typically actions). Reactive. */
48
+ readonly headerRight: ScreenSlotFills['headerRight'] | undefined;
49
+ }
50
+
51
+ export function useScreenChrome(): ScreenChrome {
52
+ const nav = useNav();
53
+ const internals = useNavInternals();
54
+
55
+ // The candidate "scoped" entry, if we happen to be rendered inside
56
+ // an EntryScope. May belong to a DIFFERENT nav than `nav` — e.g.
57
+ // when NavHeader is placed in a per-tab `<Stack>`'s chrome slot,
58
+ // it sees the outer (root) EntryScope's entry but its `useNav()`
59
+ // returns the inner per-tab nav. We only honor the pin when the
60
+ // entry is actually on this nav's stack; otherwise we're crossing
61
+ // scopes and the destination-entry path is correct.
62
+ //
63
+ // `useCurrentEntryOptional` is the soft companion to
64
+ // `useCurrentEntry` — it returns `null` outside any EntryScope
65
+ // rather than throwing, which is the right semantic for a chrome
66
+ // consumer that *might* be a Stack slot.
67
+ const candidate: StackEntry | null = useCurrentEntryOptional();
68
+
69
+ const getDestinationEntry = (): StackEntry => {
70
+ const t = nav.transition;
71
+ if (t) {
72
+ return t.kind === 'pop' ? t.underneathEntry : t.topEntry;
73
+ }
74
+ return nav.current;
75
+ };
76
+
77
+ const getEntry = (): StackEntry => {
78
+ if (candidate) {
79
+ const stack = nav.stack;
80
+ if (stack.some((e) => e.key === candidate!.key)) {
81
+ return candidate;
82
+ }
83
+ }
84
+ return getDestinationEntry();
85
+ };
86
+
87
+ return {
88
+ get title() {
89
+ const entry = getEntry();
90
+ const reg = internals.screens.get(entry.key);
91
+ const t = reg?.options.title;
92
+ if (typeof t === 'function') return t();
93
+ if (typeof t === 'string') return t;
94
+ return entry.route;
95
+ },
96
+ get headerShown() {
97
+ const reg = internals.screens.get(getEntry().key);
98
+ return reg?.options.headerShown !== false;
99
+ },
100
+ get canGoBack() {
101
+ const entry = getEntry();
102
+ const stack = nav.stack;
103
+ const idx = stack.findIndex((e) => e.key === entry.key);
104
+ return idx > 0;
105
+ },
106
+ pop() {
107
+ nav.pop();
108
+ },
109
+ get header() {
110
+ const reg = internals.screens.get(getEntry().key);
111
+ return reg?.slots.header;
112
+ },
113
+ get headerLeft() {
114
+ const reg = internals.screens.get(getEntry().key);
115
+ return reg?.slots.headerLeft;
116
+ },
117
+ get headerRight() {
118
+ const reg = internals.screens.get(getEntry().key);
119
+ return reg?.slots.headerRight;
120
+ },
121
+ };
122
+ }
package/src/index.ts CHANGED
@@ -16,6 +16,8 @@ export { useLinkingNav } from './hooks/use-linking-nav.js';
16
16
  export type { UseLinkingNavOptions } from './hooks/use-linking-nav.js';
17
17
  export { useIsFocused, useFocusEffect } from './hooks/use-focus.js';
18
18
  export { useScreenOptions } from './hooks/use-screen-options.js';
19
+ export { useScreenChrome } from './hooks/use-screen-chrome.js';
20
+ export type { ScreenChrome } from './hooks/use-screen-chrome.js';
19
21
  export {
20
22
  useNavSerializer,
21
23
  NAV_SNAPSHOT_VERSION,