@baukit/navigation 0.18.3 → 0.19.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 (70) hide show
  1. package/dist/index.d.ts.map +1 -1
  2. package/dist/index.js +19 -14
  3. package/dist/index.js.map +1 -1
  4. package/dist/native-menu.d.ts +22 -0
  5. package/dist/native-menu.d.ts.map +1 -0
  6. package/dist/native-menu.js +226 -0
  7. package/dist/native-menu.js.map +1 -0
  8. package/dist/native-primitives.d.ts +51 -0
  9. package/dist/native-primitives.d.ts.map +1 -0
  10. package/dist/native-primitives.js +125 -0
  11. package/dist/native-primitives.js.map +1 -0
  12. package/dist/native-profile.d.ts +34 -0
  13. package/dist/native-profile.d.ts.map +1 -0
  14. package/dist/native-profile.js +67 -0
  15. package/dist/native-profile.js.map +1 -0
  16. package/dist/native-section-picker.d.ts +14 -0
  17. package/dist/native-section-picker.d.ts.map +1 -0
  18. package/dist/native-section-picker.js +46 -0
  19. package/dist/native-section-picker.js.map +1 -0
  20. package/dist/native-styles.d.ts +106 -0
  21. package/dist/native-styles.d.ts.map +1 -0
  22. package/dist/native-styles.js +50 -0
  23. package/dist/native-styles.js.map +1 -0
  24. package/dist/native-theme.d.ts +49 -0
  25. package/dist/native-theme.d.ts.map +1 -0
  26. package/dist/native-theme.js +56 -0
  27. package/dist/native-theme.js.map +1 -0
  28. package/dist/native.d.ts +9 -52
  29. package/dist/native.d.ts.map +1 -1
  30. package/dist/native.js +148 -536
  31. package/dist/native.js.map +1 -1
  32. package/dist/use-navigation-state.d.ts +9 -8
  33. package/dist/use-navigation-state.d.ts.map +1 -1
  34. package/dist/use-navigation-state.js +3 -2
  35. package/dist/use-navigation-state.js.map +1 -1
  36. package/dist/web-link.d.ts +20 -0
  37. package/dist/web-link.d.ts.map +1 -0
  38. package/dist/web-link.js +23 -0
  39. package/dist/web-link.js.map +1 -0
  40. package/dist/web-menu.d.ts +19 -0
  41. package/dist/web-menu.d.ts.map +1 -0
  42. package/dist/web-menu.js +96 -0
  43. package/dist/web-menu.js.map +1 -0
  44. package/dist/web-profile.d.ts +16 -0
  45. package/dist/web-profile.d.ts.map +1 -0
  46. package/dist/web-profile.js +58 -0
  47. package/dist/web-profile.js.map +1 -0
  48. package/dist/web-section-picker.d.ts +13 -0
  49. package/dist/web-section-picker.d.ts.map +1 -0
  50. package/dist/web-section-picker.js +71 -0
  51. package/dist/web-section-picker.js.map +1 -0
  52. package/dist/web.d.ts +7 -25
  53. package/dist/web.d.ts.map +1 -1
  54. package/dist/web.js +113 -257
  55. package/dist/web.js.map +1 -1
  56. package/package.json +7 -7
  57. package/src/index.ts +22 -16
  58. package/src/native-menu.tsx +436 -0
  59. package/src/native-primitives.tsx +308 -0
  60. package/src/native-profile.tsx +153 -0
  61. package/src/native-section-picker.tsx +102 -0
  62. package/src/native-styles.ts +50 -0
  63. package/src/native-theme.ts +108 -0
  64. package/src/native.tsx +355 -1086
  65. package/src/use-navigation-state.ts +20 -5
  66. package/src/web-link.tsx +51 -0
  67. package/src/web-menu.tsx +220 -0
  68. package/src/web-profile.tsx +201 -0
  69. package/src/web-section-picker.tsx +128 -0
  70. package/src/web.tsx +256 -598
package/src/native.tsx CHANGED
@@ -1,1198 +1,467 @@
1
+ import { useEffect, useId, useRef, useState, type ReactNode, type RefObject } from 'react';
1
2
  import {
2
- useEffect,
3
- useCallback,
4
- useLayoutEffect,
5
- useId,
6
- useRef,
7
- useState,
8
- type ComponentPropsWithRef,
9
- type ReactNode,
10
- } from 'react';
11
- import {
12
- Image,
13
- Modal,
14
- Platform,
15
- Pressable,
16
3
  ScrollView,
17
- StyleSheet,
18
4
  Text,
19
5
  View,
20
6
  useWindowDimensions,
21
- type GestureResponderEvent,
22
- type LayoutChangeEvent,
23
- type NativeScrollEvent,
24
- type NativeSyntheticEvent,
25
7
  type StyleProp,
26
8
  type ViewStyle,
27
- type TextStyle,
28
9
  } from 'react-native';
29
- import {
30
- announce,
31
- asFocusTarget,
32
- hostElement,
33
- type RovingMenuKeyEvent,
34
- type OverlayBackgroundProps,
35
- useAriaHiddenInert,
36
- useOverlayA11y,
37
- useReducedMotionPreference,
38
- useRovingMenu,
39
- } from '@baukit/a11y-core';
10
+ import { type OverlayBackgroundProps, useAriaHiddenInert, useRovingMenu } from '@baukit/a11y-core';
40
11
  import {
41
12
  getNavigationLayout,
42
13
  getNavigationBarHeight,
43
- getNavigationBarVisualHeight,
44
- getNavigationBarLineHeight,
45
14
  NAVIGATION_BAR_DIMENSIONS,
46
- type NavigationBarMetrics,
47
15
  type NavigationSlots,
48
16
  NAVIGATION_DIMENSIONS,
49
- navigationMatches,
50
17
  nextSectionHref,
51
- resolveActiveNavigation,
52
- resolveActiveMenuEntry,
53
18
  validateNavigation,
54
19
  type NavigationItem,
55
20
  type NavigationProfile,
56
- type NavigationProfileMenuEntry,
21
+ type NavigationSubItem,
57
22
  } from './index.js';
58
- import { useNavigationState, type CollapseProps } from './use-navigation-state.js';
23
+ import { Menu } from './native-menu.js';
24
+ import { compactVisualStyle, Decorative, follow, Target } from './native-primitives.js';
25
+ import {
26
+ Profile,
27
+ profileIsActive,
28
+ useCompactBarScroll,
29
+ type CompactBarScroll,
30
+ } from './native-profile.js';
31
+ import { styles } from './native-styles.js';
32
+ import {
33
+ barMetrics,
34
+ textStyle,
35
+ type Navigate,
36
+ type NavigationIcon,
37
+ type NavigationInsets,
38
+ type NavigationTheme,
39
+ } from './native-theme.js';
40
+ import {
41
+ useNavigationState,
42
+ type CollapseProps,
43
+ type NavigationStateHandle,
44
+ } from './use-navigation-state.js';
45
+ import { useNavigationBarHeight as profileBarHeight } from './native-profile.js';
46
+ import { SectionPicker as Picker } from './native-section-picker.js';
59
47
 
60
- export interface NavigationIconState {
61
- readonly active: boolean;
62
- readonly size: number;
63
- }
64
- export type NavigationIcon = (state: NavigationIconState) => ReactNode;
65
- export interface NavigationTypography {
66
- readonly fontFamily?: string;
67
- readonly activeFontFamily?: string;
68
- readonly fontSize?: number;
69
- readonly barFontSize?: number;
70
- readonly subtitleFontSize?: number;
71
- readonly fontWeight?: TextStyle['fontWeight'];
72
- readonly activeFontWeight?: TextStyle['fontWeight'];
73
- readonly lineHeight?: number;
74
- readonly letterSpacing?: number;
48
+ export type {
49
+ Navigate,
50
+ NavigationIcon,
51
+ NavigationIconState,
52
+ NavigationInsets,
53
+ NavigationTheme,
54
+ NavigationTypography,
55
+ } from './native-theme.js';
56
+ // A local binding keeps the export a plain property, so Jest can spy on it like before the split.
57
+ export const useNavigationBarHeight: typeof profileBarHeight = profileBarHeight;
58
+
59
+ export interface AppNavigationProps extends CollapseProps, NavigationSlots {
60
+ readonly items: readonly NavigationItem<NavigationIcon>[];
61
+ readonly profile?: NavigationProfile;
62
+ readonly pathname: string;
63
+ readonly onNavigate: Navigate;
64
+ readonly theme: NavigationTheme;
65
+ readonly width?: number;
66
+ readonly insets?: NavigationInsets;
67
+ readonly label: string;
68
+ readonly collapseLabel: string;
69
+ readonly expandLabel: string;
70
+ readonly closeLabel: string;
71
+ readonly style?: ViewStyle;
75
72
  }
76
73
 
77
- export interface NavigationTheme {
78
- readonly background: string;
79
- readonly text: string;
80
- readonly muted: string;
81
- readonly danger: string;
82
- readonly activeBackground: string;
83
- readonly activeText: string;
84
- readonly ancestorText: string;
85
- readonly border: string;
86
- readonly focus: string;
87
- readonly radius: number;
88
- readonly spacing: number;
89
- readonly typography?: NavigationTypography;
74
+ const CHILD_ICON_SIZE = 20;
75
+
76
+ interface SlotContent {
77
+ readonly brand: ReactNode;
78
+ readonly accessory: ReactNode;
79
+ readonly hasBrand: boolean;
80
+ readonly hasAccessory: boolean;
90
81
  }
91
- function barMetrics(theme?: NavigationTheme): NavigationBarMetrics {
92
- return {
93
- ...(theme === undefined ? {} : { spacing: theme.spacing }),
94
- ...(theme?.typography?.barFontSize === undefined
95
- ? {}
96
- : { fontSize: theme.typography.barFontSize }),
97
- ...(theme?.typography?.lineHeight === undefined
98
- ? {}
99
- : { lineHeight: theme.typography.lineHeight }),
100
- };
82
+
83
+ function rendersSomething(node: ReactNode): boolean {
84
+ return node !== null && node !== undefined && typeof node !== 'boolean';
101
85
  }
102
- function textStyle(theme: NavigationTheme, selected = false, bar = false): TextStyle {
103
- const typography = theme.typography;
86
+
87
+ function useSlotContent(props: AppNavigationProps, bar: boolean, collapsed: boolean): SlotContent {
88
+ const slotState = { layout: bar ? ('bar' as const) : ('rail' as const), collapsed };
89
+ const brand = props.renderBrand?.(slotState);
90
+ const accessory = props.renderAccessory?.(slotState);
104
91
  return {
105
- fontFamily: selected
106
- ? (typography?.activeFontFamily ?? typography?.fontFamily)
107
- : typography?.fontFamily,
108
- fontSize: bar
109
- ? (typography?.barFontSize ?? NAVIGATION_BAR_DIMENSIONS.labelFontSize)
110
- : (typography?.fontSize ?? 14),
111
- fontWeight: selected
112
- ? (typography?.activeFontWeight ?? '700')
113
- : (typography?.fontWeight ?? '400'),
114
- lineHeight: bar ? getNavigationBarLineHeight(barMetrics(theme)) : typography?.lineHeight,
115
- letterSpacing: typography?.letterSpacing,
92
+ brand,
93
+ accessory,
94
+ hasBrand: rendersSomething(brand),
95
+ hasAccessory: rendersSomething(accessory),
116
96
  };
117
97
  }
118
98
 
119
- export interface NavigationInsets {
120
- readonly top?: number;
121
- readonly bottom?: number;
122
- readonly left?: number;
123
- readonly right?: number;
99
+ function useBarHeightReport(
100
+ bar: boolean,
101
+ barHeight: number,
102
+ onBarHeightChange: ((height: number) => void) | undefined,
103
+ ): void {
104
+ useEffect(() => {
105
+ if (bar) onBarHeightChange?.(barHeight);
106
+ }, [bar, barHeight, onBarHeightChange]);
124
107
  }
125
- export type Navigate = (href: string, options?: { readonly replace: boolean }) => void;
126
108
 
127
- type FocusablePressableProps = Omit<ComponentPropsWithRef<typeof Pressable>, 'style'> & {
128
- readonly theme: NavigationTheme;
129
- readonly selected?: boolean;
130
- readonly unfocusedBorderColor?: string;
131
- readonly style?: StyleProp<ViewStyle>;
132
- };
133
- function showsFocusRing(event: NativeSyntheticEvent<unknown>): boolean {
134
- if (Platform.OS !== 'web') return true;
135
- const target: unknown = (event.nativeEvent as { target?: unknown } | undefined)?.target;
136
- return !(target instanceof Element) || target.matches(':focus-visible');
137
- }
138
- function FocusablePressable({
139
- theme,
140
- selected = false,
141
- unfocusedBorderColor,
142
- style,
143
- onFocus,
144
- onBlur,
145
- ...props
146
- }: FocusablePressableProps) {
147
- const [focused, setFocused] = useState(false);
148
- return (
149
- <Pressable
150
- {...props}
151
- onFocus={(event) => {
152
- setFocused(showsFocusRing(event));
153
- onFocus?.(event);
154
- }}
155
- onBlur={(event) => {
156
- setFocused(false);
157
- onBlur?.(event);
158
- }}
159
- style={[
160
- style,
161
- {
162
- minHeight:
163
- Platform.OS === 'android'
164
- ? NAVIGATION_DIMENSIONS.androidTarget
165
- : NAVIGATION_DIMENSIONS.target,
166
- minWidth:
167
- Platform.OS === 'android'
168
- ? NAVIGATION_DIMENSIONS.androidTarget
169
- : NAVIGATION_DIMENSIONS.target,
170
- borderWidth: NAVIGATION_BAR_DIMENSIONS.targetBorder,
171
- borderColor: focused
172
- ? selected
173
- ? theme.activeText
174
- : theme.focus
175
- : (unfocusedBorderColor ?? 'transparent'),
176
- },
177
- ]}
178
- />
179
- );
109
+ interface NavigationModel {
110
+ readonly props: AppNavigationProps;
111
+ readonly insets: NavigationInsets;
112
+ readonly bar: boolean;
113
+ readonly collapsed: boolean;
114
+ readonly fontScale: number;
115
+ readonly barHeight: number;
116
+ readonly state: NavigationStateHandle<NavigationIcon>;
117
+ readonly id: string;
118
+ readonly visible: readonly (NavigationItem<NavigationIcon> | NavigationSubItem<NavigationIcon>)[];
119
+ readonly roving: ReturnType<typeof useRovingMenu>;
120
+ readonly compactScroll: CompactBarScroll;
121
+ readonly slots: SlotContent;
122
+ readonly setSlotHeight: (height: number) => void;
123
+ readonly profileOpen: boolean;
124
+ readonly setProfileOpen: (open: boolean) => void;
125
+ readonly profileTriggerRef: RefObject<View | null>;
126
+ readonly profileMenuId: string;
180
127
  }
181
128
 
182
- function isModifiedPress(event: GestureResponderEvent): boolean {
183
- const native: unknown = event.nativeEvent;
184
- if (typeof native !== 'object' || native === null) return false;
185
- return (
186
- ('button' in native && native.button !== undefined && native.button !== 0) ||
187
- ('metaKey' in native && native.metaKey === true) ||
188
- ('ctrlKey' in native && native.ctrlKey === true) ||
189
- ('shiftKey' in native && native.shiftKey === true) ||
190
- ('altKey' in native && native.altKey === true)
129
+ function visibleItems(
130
+ items: readonly NavigationItem<NavigationIcon>[],
131
+ expanded: boolean,
132
+ openIds: readonly string[],
133
+ ): (NavigationItem<NavigationIcon> | NavigationSubItem<NavigationIcon>)[] {
134
+ return items.flatMap((item) =>
135
+ expanded && openIds.includes(item.id) ? [item, ...(item.children ?? [])] : [item],
191
136
  );
192
137
  }
193
- function webLink(href: string, active: boolean) {
194
- return Platform.OS === 'web'
195
- ? { href, 'aria-current': active ? ('page' as const) : undefined }
196
- : {};
197
- }
198
- function follow(href: string, event: GestureResponderEvent, onNavigate: Navigate) {
199
- if (isModifiedPress(event)) return;
200
- event.preventDefault();
201
- onNavigate(href);
138
+
139
+ function compactSelectedIndex(
140
+ items: readonly NavigationItem<NavigationIcon>[],
141
+ activeId: string | undefined,
142
+ profileActive: boolean,
143
+ ): number {
144
+ return profileActive ? items.length : items.findIndex((item) => item.id === activeId);
202
145
  }
203
146
 
204
- interface TargetProps {
205
- readonly label: string;
206
- readonly subtitle?: string | undefined;
207
- readonly selected?: boolean;
208
- readonly ancestor?: boolean;
209
- readonly expanded?: boolean;
210
- readonly controls?: string;
211
- readonly menu?: boolean;
212
- readonly href?: string;
213
- readonly onPress: (event: GestureResponderEvent) => void;
214
- readonly theme: NavigationTheme;
215
- readonly bar?: boolean;
216
- readonly collapsed?: boolean;
217
- readonly children: ReactNode;
218
- readonly roving?: ReturnType<ReturnType<typeof useRovingMenu>['itemProps']>;
219
- readonly triggerRef?: React.RefObject<View | null>;
220
- readonly testID?: string;
147
+ function useAppNavigationModel(props: AppNavigationProps): NavigationModel {
148
+ const { items, profile, pathname, theme, insets = {} } = props;
149
+ const [slotHeight, setSlotHeight] = useState(0);
150
+ const [profileOpen, setProfileOpen] = useState(false);
151
+ const profileTriggerRef = useRef<View>(null);
152
+ const profileMenuId = useId();
153
+ validateNavigation(items, profile);
154
+ useAriaHiddenInert();
155
+ const dimensions = useWindowDimensions();
156
+ const bar = getNavigationLayout(props.width ?? dimensions.width) === 'bar';
157
+ const state = useNavigationState(items, pathname, props);
158
+ const collapsed = !bar && state.collapsed;
159
+ const slots = useSlotContent(props, bar, collapsed);
160
+ const barHeight = getNavigationBarHeight(dimensions.fontScale, insets.bottom, {
161
+ ...barMetrics(theme),
162
+ slotHeight: slots.hasBrand || slots.hasAccessory ? slotHeight : 0,
163
+ });
164
+ useBarHeightReport(bar, barHeight, props.onBarHeightChange);
165
+ const id = useId();
166
+ const visible = visibleItems(items, !bar && !collapsed, state.openIds);
167
+ const activeId = visible.some((item) => item.id === state.active.subItem?.id)
168
+ ? state.active.subItem?.id
169
+ : state.active.item?.id;
170
+ const profileActive = profile !== undefined && profileIsActive(profile, pathname);
171
+ const compactScroll = useCompactBarScroll(
172
+ bar ? compactSelectedIndex(items, activeId, profileActive) : -1,
173
+ );
174
+ const roving = useRovingMenu({
175
+ active: true,
176
+ options: [
177
+ ...visible.map((item) => ({ selected: item.id === activeId })),
178
+ ...(profile === undefined ? [] : [{ selected: profileActive }]),
179
+ ],
180
+ });
181
+ return {
182
+ props,
183
+ insets,
184
+ bar,
185
+ collapsed,
186
+ fontScale: dimensions.fontScale,
187
+ barHeight,
188
+ state,
189
+ id,
190
+ visible,
191
+ roving,
192
+ compactScroll,
193
+ slots,
194
+ setSlotHeight,
195
+ profileOpen,
196
+ setProfileOpen,
197
+ profileTriggerRef,
198
+ profileMenuId,
199
+ };
221
200
  }
222
- function Target({
223
- label,
224
- subtitle,
225
- selected = false,
226
- ancestor = false,
227
- expanded,
228
- controls,
229
- menu,
230
- href,
231
- onPress,
232
- theme,
233
- bar = false,
234
- collapsed = false,
235
- children,
236
- roving,
237
- triggerRef,
238
- testID,
239
- }: TargetProps) {
201
+
202
+ function SlotsView({ model }: { readonly model: NavigationModel }): ReactNode {
203
+ const { bar, slots, props } = model;
240
204
  return (
241
- <FocusablePressable
242
- theme={theme}
243
- selected={selected && !ancestor}
244
- {...{ dataSet: { active: selected ? (ancestor ? 'ancestor' : 'page') : 'false' } }}
245
- {...roving}
246
- {...(href === undefined ? {} : webLink(href, selected))}
247
- {...(Platform.OS === 'web'
248
- ? {
249
- title: collapsed ? label : undefined,
250
- 'aria-controls': controls,
251
- 'aria-haspopup': menu ? ('menu' as const) : undefined,
252
- }
253
- : {})}
254
- accessibilityLabel={subtitle === undefined ? label : `${label}, ${subtitle}`}
255
- accessibilityRole={href === undefined ? 'button' : 'link'}
256
- accessibilityState={{ selected, ...(expanded === undefined ? {} : { expanded }) }}
257
- ref={(node) => {
258
- roving?.ref(node);
259
- if (triggerRef !== undefined) triggerRef.current = node;
260
- }}
261
- onPress={onPress}
262
- testID={testID}
205
+ <View
206
+ testID="navigation-slots"
263
207
  style={[
264
- styles.target,
265
- bar ? styles.barTarget : styles.railTarget,
266
- collapsed && styles.collapsedTarget,
267
- {
268
- borderRadius: theme.radius,
269
- gap: theme.spacing,
270
- backgroundColor: selected && !ancestor ? theme.activeBackground : theme.background,
271
- },
208
+ styles.slots,
209
+ bar && styles.barSlots,
210
+ { padding: props.theme.spacing, gap: props.theme.spacing },
272
211
  ]}
212
+ onLayout={(event) => {
213
+ if (bar) model.setSlotHeight(event.nativeEvent.layout.height);
214
+ }}
273
215
  >
274
- {children}
275
- {!collapsed ? (
276
- <View style={styles.labelGroup}>
277
- <Text
278
- numberOfLines={1}
279
- style={{
280
- ...textStyle(theme, selected && !ancestor, bar),
281
- color: ancestor ? theme.ancestorText : selected ? theme.activeText : theme.text,
282
- }}
283
- >
284
- {label}
285
- </Text>
286
- {!bar && subtitle !== undefined ? (
287
- <Text
288
- numberOfLines={1}
289
- style={{
290
- ...textStyle(theme),
291
- color: theme.muted,
292
- fontSize: theme.typography?.subtitleFontSize ?? 12,
293
- }}
294
- >
295
- {subtitle}
296
- </Text>
297
- ) : null}
216
+ {!slots.hasBrand ? null : (
217
+ <View testID="navigation-brand" style={[styles.slot, bar && styles.barBrand]}>
218
+ {slots.brand}
219
+ </View>
220
+ )}
221
+ {!slots.hasAccessory ? null : (
222
+ <View testID="navigation-accessory" style={styles.slot}>
223
+ {slots.accessory}
298
224
  </View>
299
- ) : null}
300
- </FocusablePressable>
225
+ )}
226
+ </View>
301
227
  );
302
228
  }
303
- function Decorative({
304
- children,
305
- style,
306
- }: {
307
- readonly children: ReactNode;
308
- readonly style?: StyleProp<ViewStyle>;
309
- }) {
229
+
230
+ function CollapseToggle({ model }: { readonly model: NavigationModel }): ReactNode {
231
+ const { collapsed, props } = model;
310
232
  return (
311
- <View
312
- style={style}
313
- accessible={false}
314
- accessibilityElementsHidden
315
- importantForAccessibility="no-hide-descendants"
316
- aria-hidden
233
+ <Target
234
+ label={collapsed ? props.expandLabel : props.collapseLabel}
235
+ expanded={!collapsed}
236
+ collapsed
237
+ theme={props.theme}
238
+ onPress={() => {
239
+ model.state.setCollapsed(!collapsed);
240
+ }}
317
241
  >
318
- {children}
319
- </View>
242
+ <Decorative>
243
+ <Text style={{ ...textStyle(props.theme), color: props.theme.text }}>
244
+ {collapsed ? '›' : '‹'}
245
+ </Text>
246
+ </Decorative>
247
+ </Target>
320
248
  );
321
249
  }
322
250
 
323
- const MENU_WIDTH = 280;
324
- const MENU_EDGE = 8;
325
-
326
- interface MenuProps {
327
- readonly subtitle?: string | undefined;
328
- readonly renderBackground: (props: OverlayBackgroundProps) => ReactNode;
329
- readonly entries: readonly NavigationProfileMenuEntry[];
330
- readonly label: string;
331
- readonly closeLabel: string;
332
- readonly pathname: string;
333
- readonly visible: boolean;
334
- readonly onClose: () => void;
335
- readonly onNavigate: Navigate;
336
- readonly triggerRef: React.RefObject<View | null>;
337
- readonly theme: NavigationTheme;
338
- readonly id: string;
339
- readonly insets?: NavigationInsets | undefined;
340
- }
341
- function menuModalPadding(insets: NavigationInsets = {}): ViewStyle {
342
- const native = Platform.OS !== 'web';
343
- const edge = (inset: number | undefined) => MENU_EDGE + (native ? (inset ?? 0) : 0);
344
- return {
345
- paddingTop: edge(insets.top),
346
- paddingBottom: edge(insets.bottom),
347
- paddingLeft: edge(insets.left),
348
- paddingRight: edge(insets.right),
349
- };
350
- }
351
- function Menu({
352
- subtitle,
353
- renderBackground,
354
- entries,
355
- label,
356
- closeLabel,
357
- pathname,
358
- visible,
359
- onClose,
360
- onNavigate,
361
- triggerRef,
362
- theme,
363
- id,
364
- insets,
365
- }: MenuProps) {
366
- const activeEntry = resolveActiveMenuEntry(entries, pathname);
367
- const containerRef = useRef<View>(null);
368
- const closeRef = useRef<View>(null);
369
- const pendingFocus = useRef<(() => void) | null>(null);
370
- const presented = useRef(false);
371
- const pendingSelection = useRef<(() => void) | null>(null);
372
- const finishSelection = useCallback(() => {
373
- const selection = pendingSelection.current;
374
- pendingSelection.current = null;
375
- selection?.();
376
- }, []);
377
- useEffect(() => {
378
- if (visible) {
379
- pendingSelection.current = null;
380
- return;
381
- }
382
- if (Platform.OS === 'ios' || pendingSelection.current === null) return;
383
- // Android removes an unanimated Modal in the close commit and has no onDismiss event.
384
- const frame = requestAnimationFrame(finishSelection);
385
- return () => {
386
- cancelAnimationFrame(frame);
387
- };
388
- }, [visible, finishSelection]);
389
- useEffect(
390
- () => () => {
391
- pendingSelection.current = null;
392
- },
393
- [],
394
- );
395
- const [webPresented, setWebPresented] = useState(false);
396
- const [webPosition, setWebPosition] = useState<ViewStyle>();
397
- const deferFocus = useCallback((task: () => void) => {
398
- if (presented.current) task();
399
- else pendingFocus.current = task;
400
- return {
401
- cancel: () => {
402
- pendingFocus.current = null;
403
- presented.current = false;
404
- },
405
- };
406
- }, []);
407
- const roving = useRovingMenu({
408
- active: visible,
409
- options: entries.map((entry) => ({
410
- disabled: entry.disabled,
411
- selected: entry === activeEntry,
412
- })),
413
- });
414
- const { containerProps, backgroundProps } = useOverlayA11y({
415
- active: visible && (Platform.OS !== 'web' || webPresented),
416
- deferFocus,
417
- containerRef,
418
- triggerRef,
419
- initialFocusRef: roving.activeIndex === null ? closeRef : roving.initialFocusRef,
420
- onEscape: onClose,
421
- });
422
- const { reducedMotion, resolved } = useReducedMotionPreference();
423
- const motion = !resolved ? 'unresolved' : reducedMotion ? 'reduced' : 'standard';
424
- useEffect(() => {
425
- if (visible) return;
426
- presented.current = false;
427
- setWebPresented(false);
428
- }, [visible]);
429
- useLayoutEffect(() => {
430
- if (!visible || Platform.OS !== 'web') return;
431
- function positionMenu() {
432
- const trigger = hostElement(triggerRef);
433
- if (!(trigger instanceof HTMLElement)) return;
434
- const rect = trigger.getBoundingClientRect();
435
- const width = Math.min(MENU_WIDTH, window.innerWidth - 2 * MENU_EDGE);
436
- const below = window.innerHeight - rect.bottom;
437
- const above = rect.top >= below;
438
- setWebPosition({
439
- position: 'absolute',
440
- left: Math.max(MENU_EDGE, Math.min(rect.left, window.innerWidth - width - MENU_EDGE)),
441
- width,
442
- maxHeight: Math.max(
443
- NAVIGATION_DIMENSIONS.target,
444
- (above ? rect.top : below) - 2 * MENU_EDGE,
445
- ),
446
- ...(above
447
- ? { bottom: window.innerHeight - rect.top + MENU_EDGE }
448
- : { top: rect.bottom + MENU_EDGE }),
449
- });
450
- }
451
- positionMenu();
452
- window.addEventListener('resize', positionMenu);
453
- window.addEventListener('scroll', positionMenu, true);
454
- return () => {
455
- window.removeEventListener('resize', positionMenu);
456
- window.removeEventListener('scroll', positionMenu, true);
457
- };
458
- }, [visible, triggerRef]);
459
- useEffect(() => {
460
- if (!visible || Platform.OS !== 'web') return;
461
- function outside(event: PointerEvent) {
462
- const menu = hostElement(containerRef);
463
- const trigger = hostElement(triggerRef);
464
- if (
465
- !(event.target instanceof Node) ||
466
- (menu instanceof Node && menu.contains(event.target)) ||
467
- (trigger instanceof Node && trigger.contains(event.target))
468
- )
469
- return;
470
- onClose();
471
- }
472
- document.addEventListener('pointerdown', outside);
473
- return () => {
474
- document.removeEventListener('pointerdown', outside);
475
- };
476
- }, [visible, triggerRef, onClose, roving.activeIndex, roving.initialFocusRef]);
477
- function closeAndRestore() {
478
- onClose();
479
- if (Platform.OS === 'web') asFocusTarget(triggerRef)?.focus();
480
- }
481
- const menu = (
251
+ function SectionChildren({
252
+ model,
253
+ item,
254
+ groupId,
255
+ }: {
256
+ readonly model: NavigationModel;
257
+ readonly item: NavigationItem<NavigationIcon>;
258
+ readonly groupId: string;
259
+ }): ReactNode {
260
+ const { state, roving, visible, props } = model;
261
+ return (
482
262
  <View
483
- {...containerProps}
484
- {...{
485
- onKeyDown: (event: RovingMenuKeyEvent) => {
486
- if (event.nativeEvent.key === 'Escape') {
487
- event.preventDefault();
488
- closeAndRestore();
489
- }
490
- if (Platform.OS === 'web' && event.nativeEvent.key === 'Tab') closeAndRestore();
491
- },
492
- }}
493
- ref={containerRef}
494
- accessibilityViewIsModal={Platform.OS !== 'web'}
495
- accessibilityLabel={subtitle === undefined ? label : `${label}, ${subtitle}`}
496
- role="menu"
497
- nativeID={id}
498
- testID="navigation-menu"
499
- style={[
500
- styles.menu,
501
- {
502
- backgroundColor: theme.background,
503
- borderColor: theme.border,
504
- borderRadius: theme.radius,
505
- },
506
- Platform.OS === 'web' && webPosition,
507
- ]}
508
- {...{ dataSet: { motion } }}
263
+ nativeID={groupId}
264
+ role="group"
265
+ accessibilityLabel={item.label}
266
+ style={[styles.children, { borderColor: props.theme.border }]}
509
267
  >
510
- {subtitle === undefined ? null : (
511
- <Decorative>
512
- <View style={styles.menuProfile}>
513
- <Text numberOfLines={1} style={{ ...textStyle(theme), color: theme.text }}>
514
- {label}
515
- </Text>
516
- <Text
517
- numberOfLines={1}
518
- style={{
519
- ...textStyle(theme),
520
- color: theme.muted,
521
- fontSize: theme.typography?.subtitleFontSize ?? 12,
522
- }}
523
- >
524
- {subtitle}
525
- </Text>
526
- </View>
527
- </Decorative>
528
- )}
529
- <ScrollView>
530
- {entries.map((entry, index) => (
531
- <FocusablePressable
532
- theme={theme}
533
- selected={entry === activeEntry}
534
- {...{ dataSet: { active: entry === activeEntry ? 'page' : 'false', tone: entry.tone } }}
535
- {...roving.itemProps(index)}
536
- key={entry.id}
537
- accessibilityRole="menuitem"
538
- accessibilityLabel={entry.label}
539
- accessibilityState={{
540
- disabled: entry.disabled === true,
541
- selected: entry === activeEntry,
542
- }}
543
- disabled={entry.disabled}
544
- {...(entry.href === undefined ? {} : webLink(entry.href, entry === activeEntry))}
268
+ {(item.children ?? []).map((child) => {
269
+ const selected = state.active.subItem?.id === child.id;
270
+ return (
271
+ <Target
272
+ key={child.id}
273
+ label={child.label}
274
+ selected={selected}
275
+ href={child.href}
276
+ theme={props.theme}
277
+ roving={roving.itemProps(visible.indexOf(child))}
545
278
  onPress={(event) => {
546
- if (isModifiedPress(event) || pendingSelection.current !== null) return;
547
- event.preventDefault();
548
- pendingSelection.current =
549
- entry.href !== undefined
550
- ? () => {
551
- onNavigate(entry.href);
552
- }
553
- : entry.onSelect;
554
- closeAndRestore();
279
+ follow(child.href, event, props.onNavigate);
555
280
  }}
556
- style={[
557
- styles.menuItem,
558
- {
559
- paddingHorizontal: theme.spacing,
560
- backgroundColor:
561
- entry === activeEntry && entry.tone !== 'danger'
562
- ? theme.activeBackground
563
- : theme.background,
564
- },
565
- ]}
566
281
  >
567
- <Text
568
- style={{
569
- color:
570
- entry.tone === 'danger'
571
- ? theme.danger
572
- : entry === activeEntry
573
- ? theme.activeText
574
- : theme.text,
575
- ...textStyle(theme, entry === activeEntry),
576
- }}
577
- >
578
- {entry.label}
579
- </Text>
580
- </FocusablePressable>
581
- ))}
582
- </ScrollView>
583
- <FocusablePressable
584
- theme={theme}
585
- ref={closeRef}
586
- accessibilityRole="button"
587
- accessibilityLabel={closeLabel}
588
- onPress={closeAndRestore}
589
- style={styles.menuItem}
590
- >
591
- <Text style={{ ...textStyle(theme), color: theme.text }}>{closeLabel}</Text>
592
- </FocusablePressable>
282
+ {child.icon === undefined ? null : (
283
+ <Decorative>{child.icon({ active: selected, size: CHILD_ICON_SIZE })}</Decorative>
284
+ )}
285
+ </Target>
286
+ );
287
+ })}
593
288
  </View>
594
289
  );
595
- return (
596
- <>
597
- {renderBackground(backgroundProps)}
598
- <Modal
599
- visible={visible}
600
- transparent
601
- animationType="none"
602
- onRequestClose={onClose}
603
- onDismiss={() => {
604
- if (!visible) finishSelection();
605
- }}
606
- onShow={() => {
607
- if (!visible) return;
608
- presented.current = true;
609
- const focus = pendingFocus.current;
610
- pendingFocus.current = null;
611
- focus?.();
612
- if (Platform.OS === 'web') setWebPresented(true);
613
- }}
614
- >
615
- <View style={[styles.modal, menuModalPadding(insets)]}>{menu}</View>
616
- </Modal>
617
- </>
618
- );
619
290
  }
620
291
 
621
- function compactVisualStyle(fontScale: number): ViewStyle {
622
- return { height: getNavigationBarVisualHeight(fontScale), justifyContent: 'center' };
292
+ function sectionHref(
293
+ item: NavigationItem<NavigationIcon>,
294
+ cycle: boolean,
295
+ pathname: string,
296
+ ): string {
297
+ return cycle ? nextSectionHref(item, pathname) : item.href;
623
298
  }
624
299
 
625
- function Avatar({
626
- profile,
627
- active,
628
- theme,
629
- style,
300
+ function NavigationSection({
301
+ model,
302
+ item,
303
+ index,
630
304
  }: {
631
- readonly profile: NavigationProfile;
632
- readonly active: boolean;
633
- readonly theme: NavigationTheme;
634
- readonly style?: StyleProp<ViewStyle>;
635
- }) {
636
- const [failedUrl, setFailedUrl] = useState<string>();
637
- if (profile.renderAvatar !== undefined) {
638
- return (
639
- <Decorative style={style}>
640
- {profile.renderAvatar({ active, size: NAVIGATION_DIMENSIONS.avatar })}
641
- </Decorative>
642
- );
643
- }
644
- return (
645
- <Decorative style={style}>
646
- {profile.imageUrl !== undefined && failedUrl !== profile.imageUrl ? (
647
- <Image
648
- source={{ uri: profile.imageUrl }}
649
- onError={() => {
650
- setFailedUrl(profile.imageUrl);
651
- }}
652
- style={styles.avatar}
653
- />
654
- ) : (
655
- <View style={[styles.avatar, { backgroundColor: theme.activeBackground }]}>
656
- <Text allowFontScaling={false} style={{ ...textStyle(theme), color: theme.activeText }}>
657
- {profile.initials}
658
- </Text>
659
- </View>
660
- )}
661
- </Decorative>
662
- );
663
- }
664
-
665
- interface ProfileProps {
666
- readonly open: boolean;
667
- readonly onOpen: () => void;
668
- readonly triggerRef: React.RefObject<View | null>;
669
- readonly id: string;
670
- readonly profile: NavigationProfile;
671
- readonly theme: NavigationTheme;
672
- readonly bar: boolean;
673
- readonly collapsed: boolean;
674
- readonly pathname: string;
675
- readonly onNavigate: Navigate;
676
- readonly roving: ReturnType<ReturnType<typeof useRovingMenu>['itemProps']>;
677
- readonly onLayout?: (event: LayoutChangeEvent) => void;
678
- }
679
- function profileIsActive(profile: NavigationProfile, pathname: string): boolean {
680
- return profile.href !== undefined
681
- ? navigationMatches({ id: 'profile', label: profile.label, href: profile.href }, pathname)
682
- : resolveActiveMenuEntry(profile.menu, pathname) !== null;
683
- }
684
- function Profile({
685
- profile,
686
- open,
687
- onOpen,
688
- triggerRef,
689
- id,
690
- theme,
691
- bar,
692
- collapsed,
693
- pathname,
694
- onNavigate,
695
- roving,
696
- onLayout,
697
- }: ProfileProps) {
698
- const { fontScale } = useWindowDimensions();
699
- const active = profileIsActive(profile, pathname);
305
+ readonly model: NavigationModel;
306
+ readonly item: NavigationItem<NavigationIcon>;
307
+ readonly index: number;
308
+ }): ReactNode {
309
+ const { bar, collapsed, state, props } = model;
310
+ const active = state.active.item?.id === item.id;
311
+ const group = !bar && (item.children ?? []).length > 0;
312
+ const open = !collapsed && state.openIds.includes(item.id);
313
+ const href = sectionHref(item, bar && active, props.pathname);
314
+ const groupId = `${model.id}-${String(index)}`;
700
315
  return (
701
316
  <View
702
- style={bar ? styles.barSection : styles.profile}
703
- testID="navigation-profile"
704
- onLayout={onLayout}
317
+ style={bar ? styles.barSection : undefined}
318
+ testID={`navigation-section-${item.id}`}
319
+ onLayout={bar ? model.compactScroll.itemLayout(index) : undefined}
705
320
  >
706
321
  <Target
707
- label={profile.label}
708
- subtitle={profile.subtitle}
322
+ label={item.label}
709
323
  selected={active}
710
- theme={theme}
324
+ ancestor={active && !bar && !collapsed && state.active.subItem !== null}
325
+ theme={props.theme}
711
326
  bar={bar}
712
327
  collapsed={collapsed}
713
- roving={roving}
714
- triggerRef={triggerRef}
715
- {...(profile.href === undefined
716
- ? { expanded: open, controls: id, menu: true }
717
- : { href: profile.href })}
328
+ roving={model.roving.itemProps(model.visible.indexOf(item))}
329
+ {...(group ? { expanded: open, controls: groupId } : { href })}
718
330
  onPress={(event) => {
719
- if (profile.href !== undefined) follow(profile.href, event, onNavigate);
720
- else onOpen();
331
+ if (group) state.toggleGroup(item.id);
332
+ else follow(href, event, props.onNavigate);
721
333
  }}
722
334
  >
723
- <Avatar
724
- profile={profile}
725
- active={active}
726
- theme={theme}
727
- style={bar ? compactVisualStyle(fontScale) : undefined}
728
- />
335
+ <Decorative style={bar ? compactVisualStyle(model.fontScale) : undefined}>
336
+ {item.icon({ active, size: NAVIGATION_BAR_DIMENSIONS.icon })}
337
+ </Decorative>
729
338
  </Target>
339
+ {group && open ? <SectionChildren model={model} item={item} groupId={groupId} /> : null}
730
340
  </View>
731
341
  );
732
342
  }
733
343
 
734
- export function useNavigationBarHeight(
735
- bottomInset = 0,
736
- theme?: NavigationTheme,
737
- slotHeight = 0,
738
- ): number {
739
- const { fontScale } = useWindowDimensions();
740
- return getNavigationBarHeight(fontScale, bottomInset, { ...barMetrics(theme), slotHeight });
344
+ function ProfileTarget({
345
+ model,
346
+ profile,
347
+ }: {
348
+ readonly model: NavigationModel;
349
+ readonly profile: NavigationProfile;
350
+ }): ReactNode {
351
+ const { bar, props } = model;
352
+ return (
353
+ <Profile
354
+ profile={profile}
355
+ open={model.profileOpen}
356
+ onOpen={() => {
357
+ model.setProfileOpen(true);
358
+ }}
359
+ triggerRef={model.profileTriggerRef}
360
+ id={model.profileMenuId}
361
+ theme={props.theme}
362
+ bar={bar}
363
+ collapsed={model.collapsed}
364
+ pathname={props.pathname}
365
+ onNavigate={props.onNavigate}
366
+ roving={model.roving.itemProps(model.visible.length)}
367
+ {...(bar ? { onLayout: model.compactScroll.itemLayout(props.items.length) } : {})}
368
+ />
369
+ );
741
370
  }
742
371
 
743
- function useCompactBarScroll(selectedIndex: number) {
744
- const ref = useRef<ScrollView>(null);
745
- const viewport = useRef(0);
746
- const content = useRef(0);
747
- const offset = useRef(0);
748
- const frames = useRef(new Map<number, { x: number; width: number }>());
749
- const revealSelected = useCallback(() => {
750
- const frame = frames.current.get(selectedIndex);
751
- if (frame === undefined || viewport.current === 0 || content.current === 0) return;
752
- if (frame.x >= offset.current && frame.x + frame.width <= offset.current + viewport.current)
753
- return;
754
- const x = Math.max(
755
- 0,
756
- Math.min(frame.x + (frame.width - viewport.current) / 2, content.current - viewport.current),
757
- );
758
- ref.current?.scrollTo({ x, animated: false });
759
- offset.current = x;
760
- }, [selectedIndex]);
761
- useEffect(revealSelected, [revealSelected]);
372
+ function surfaceStyle(model: NavigationModel): ViewStyle {
373
+ const { bar, collapsed, insets, props } = model;
762
374
  return {
763
- scrollProps: {
764
- ref,
765
- onLayout: (event: LayoutChangeEvent) => {
766
- viewport.current = event.nativeEvent.layout.width;
767
- revealSelected();
768
- },
769
- onContentSizeChange: (width: number) => {
770
- content.current = width;
771
- revealSelected();
772
- },
773
- onScroll: (event: NativeSyntheticEvent<NativeScrollEvent>) => {
774
- offset.current = event.nativeEvent.contentOffset.x;
775
- },
776
- },
777
- itemLayout: (index: number) => (event: LayoutChangeEvent) => {
778
- frames.current.set(index, event.nativeEvent.layout);
779
- revealSelected();
780
- },
375
+ backgroundColor: props.theme.background,
376
+ borderColor: props.theme.border,
377
+ paddingBottom: insets.bottom ?? 0,
378
+ ...(bar ? { minHeight: model.barHeight } : {}),
379
+ paddingLeft: insets.left ?? 0,
380
+ paddingRight: insets.right ?? 0,
381
+ ...(bar
382
+ ? {}
383
+ : {
384
+ width: collapsed ? NAVIGATION_DIMENSIONS.collapsedRail : NAVIGATION_DIMENSIONS.rail,
385
+ paddingTop: insets.top ?? 0,
386
+ }),
781
387
  };
782
388
  }
783
389
 
784
- export interface AppNavigationProps extends CollapseProps, NavigationSlots {
785
- readonly items: readonly NavigationItem<NavigationIcon>[];
786
- readonly profile?: NavigationProfile;
787
- readonly pathname: string;
788
- readonly onNavigate: Navigate;
789
- readonly theme: NavigationTheme;
790
- readonly width?: number;
791
- readonly insets?: NavigationInsets;
792
- readonly label: string;
793
- readonly collapseLabel: string;
794
- readonly expandLabel: string;
795
- readonly closeLabel: string;
796
- readonly style?: ViewStyle;
390
+ function itemsStyle(model: NavigationModel): StyleProp<ViewStyle> {
391
+ if (!model.bar) return styles.railItems;
392
+ const height =
393
+ getNavigationBarHeight(model.fontScale, 0, barMetrics(model.props.theme)) -
394
+ NAVIGATION_BAR_DIMENSIONS.border;
395
+ return [styles.barItems, { height }];
797
396
  }
798
- export function AppNavigation(props: AppNavigationProps) {
799
- const {
800
- items,
801
- profile,
802
- pathname,
803
- onNavigate,
804
- theme,
805
- insets = {},
806
- label,
807
- closeLabel,
808
- collapseLabel,
809
- expandLabel,
810
- } = props;
811
- const [slotHeight, setSlotHeight] = useState(0);
812
- const [profileOpen, setProfileOpen] = useState(false);
813
- const profileTriggerRef = useRef<View>(null);
814
- const profileMenuId = useId();
815
- validateNavigation(items, profile);
816
- useAriaHiddenInert();
817
- const dimensions = useWindowDimensions();
818
- const bar = getNavigationLayout(props.width ?? dimensions.width) === 'bar';
819
- const state = useNavigationState(items, pathname, props);
820
- const collapsed = !bar && state.collapsed;
821
- const slotState = { layout: bar ? ('bar' as const) : ('rail' as const), collapsed };
822
- const brand = props.renderBrand?.(slotState);
823
- const accessory = props.renderAccessory?.(slotState);
824
- const hasBrand = brand != null && typeof brand !== 'boolean';
825
- const hasAccessory = accessory != null && typeof accessory !== 'boolean';
826
- const hasSlots = hasBrand || hasAccessory;
827
- const barHeight = getNavigationBarHeight(dimensions.fontScale, insets.bottom, {
828
- ...barMetrics(theme),
829
- slotHeight: hasSlots ? slotHeight : 0,
830
- });
831
- useEffect(() => {
832
- if (bar) props.onBarHeightChange?.(barHeight);
833
- }, [bar, barHeight, props.onBarHeightChange]);
834
- const id = useId();
835
- const visible = items.flatMap((item) =>
836
- !bar && !collapsed && state.openIds.includes(item.id)
837
- ? [item, ...(item.children ?? [])]
838
- : [item],
839
- );
840
- const activeId = visible.some((item) => item.id === state.active.subItem?.id)
841
- ? state.active.subItem?.id
842
- : state.active.item?.id;
843
- const profileActive = profile !== undefined && profileIsActive(profile, pathname);
844
- const compactScroll = useCompactBarScroll(
845
- bar ? (profileActive ? items.length : items.findIndex((item) => item.id === activeId)) : -1,
846
- );
847
- const roving = useRovingMenu({
848
- active: true,
849
- options: [
850
- ...visible.map((item) => ({
851
- selected: item.id === activeId,
852
- })),
853
- ...(profile === undefined ? [] : [{ selected: profileActive }]),
854
- ],
855
- });
856
- const renderBackground = (backgroundProps: OverlayBackgroundProps = {}) => (
397
+
398
+ function NavigationSurface({
399
+ model,
400
+ backgroundProps,
401
+ }: {
402
+ readonly model: NavigationModel;
403
+ readonly backgroundProps: OverlayBackgroundProps;
404
+ }): ReactNode {
405
+ const { bar, collapsed, props, slots } = model;
406
+ const profile = props.profile;
407
+ return (
857
408
  <View
858
409
  {...backgroundProps}
859
410
  role="navigation"
860
- accessibilityLabel={label}
411
+ accessibilityLabel={props.label}
861
412
  testID="primary-navigation"
862
413
  {...{ dataSet: { layout: bar ? 'bar' : 'rail', collapsed: String(collapsed) } }}
863
- style={[
864
- bar ? styles.bar : styles.rail,
865
- {
866
- backgroundColor: theme.background,
867
- borderColor: theme.border,
868
- paddingBottom: insets.bottom ?? 0,
869
- ...(bar
870
- ? {
871
- minHeight: barHeight,
872
- }
873
- : {}),
874
- paddingLeft: insets.left ?? 0,
875
- paddingRight: insets.right ?? 0,
876
- },
877
- !bar && {
878
- width: collapsed ? NAVIGATION_DIMENSIONS.collapsedRail : NAVIGATION_DIMENSIONS.rail,
879
- paddingTop: insets.top ?? 0,
880
- },
881
- props.style,
882
- ]}
414
+ style={[bar ? styles.bar : styles.rail, surfaceStyle(model), props.style]}
883
415
  >
884
- {hasSlots ? (
885
- <View
886
- testID="navigation-slots"
887
- style={[
888
- styles.slots,
889
- bar && styles.barSlots,
890
- { padding: theme.spacing, gap: theme.spacing },
891
- ]}
892
- onLayout={(event) => {
893
- if (bar) setSlotHeight(event.nativeEvent.layout.height);
894
- }}
895
- >
896
- {!hasBrand ? null : (
897
- <View testID="navigation-brand" style={[styles.slot, bar && styles.barBrand]}>
898
- {brand}
899
- </View>
900
- )}
901
- {!hasAccessory ? null : (
902
- <View testID="navigation-accessory" style={styles.slot}>
903
- {accessory}
904
- </View>
905
- )}
906
- </View>
907
- ) : null}
908
- {!bar ? (
909
- <Target
910
- label={collapsed ? expandLabel : collapseLabel}
911
- expanded={!collapsed}
912
- collapsed
913
- theme={theme}
914
- onPress={() => {
915
- state.setCollapsed(!collapsed);
916
- }}
917
- >
918
- <Decorative>
919
- <Text style={{ ...textStyle(theme), color: theme.text }}>{collapsed ? '›' : '‹'}</Text>
920
- </Decorative>
921
- </Target>
922
- ) : null}
416
+ {slots.hasBrand || slots.hasAccessory ? <SlotsView model={model} /> : null}
417
+ {!bar ? <CollapseToggle model={model} /> : null}
923
418
  <ScrollView
924
- {...(bar ? compactScroll.scrollProps : {})}
419
+ {...(bar ? model.compactScroll.scrollProps : {})}
925
420
  testID="navigation-items"
926
421
  horizontal={bar}
927
422
  scrollEnabled
928
423
  showsHorizontalScrollIndicator={false}
929
- style={
930
- bar
931
- ? [
932
- styles.barItems,
933
- {
934
- height:
935
- getNavigationBarHeight(dimensions.fontScale, 0, barMetrics(theme)) -
936
- NAVIGATION_BAR_DIMENSIONS.border,
937
- },
938
- ]
939
- : styles.railItems
940
- }
424
+ style={itemsStyle(model)}
941
425
  contentContainerStyle={bar ? styles.barContent : undefined}
942
426
  >
943
- {items.map((item, index) => {
944
- const active = state.active.item?.id === item.id;
945
- const children = item.children ?? [];
946
- const open = !collapsed && state.openIds.includes(item.id);
947
- const href = bar && active ? nextSectionHref(item, pathname) : item.href;
948
- return (
949
- <View
950
- key={item.id}
951
- style={bar ? styles.barSection : undefined}
952
- testID={`navigation-section-${item.id}`}
953
- onLayout={bar ? compactScroll.itemLayout(index) : undefined}
954
- >
955
- <Target
956
- label={item.label}
957
- selected={active}
958
- ancestor={active && !bar && !collapsed && state.active.subItem !== null}
959
- theme={theme}
960
- bar={bar}
961
- collapsed={collapsed}
962
- roving={roving.itemProps(visible.indexOf(item))}
963
- {...(!bar && children.length > 0
964
- ? { expanded: open, controls: `${id}-${String(index)}` }
965
- : { href })}
966
- onPress={(event) => {
967
- if (!bar && children.length > 0) state.toggleGroup(item.id);
968
- else follow(href, event, onNavigate);
969
- }}
970
- >
971
- <Decorative style={bar ? compactVisualStyle(dimensions.fontScale) : undefined}>
972
- {item.icon({ active, size: NAVIGATION_BAR_DIMENSIONS.icon })}
973
- </Decorative>
974
- </Target>
975
- {!bar && open && children.length > 0 ? (
976
- <View
977
- nativeID={`${id}-${String(index)}`}
978
- role="group"
979
- accessibilityLabel={item.label}
980
- style={[styles.children, { borderColor: theme.border }]}
981
- >
982
- {children.map((child) => {
983
- const selected = state.active.subItem?.id === child.id;
984
- return (
985
- <Target
986
- key={child.id}
987
- label={child.label}
988
- selected={selected}
989
- href={child.href}
990
- theme={theme}
991
- roving={roving.itemProps(visible.indexOf(child))}
992
- onPress={(event) => {
993
- follow(child.href, event, onNavigate);
994
- }}
995
- >
996
- {child.icon === undefined ? null : (
997
- <Decorative>{child.icon({ active: selected, size: 20 })}</Decorative>
998
- )}
999
- </Target>
1000
- );
1001
- })}
1002
- </View>
1003
- ) : null}
1004
- </View>
1005
- );
1006
- })}
1007
- {bar && profile !== undefined ? (
1008
- <Profile
1009
- profile={profile}
1010
- open={profileOpen}
1011
- onOpen={() => {
1012
- setProfileOpen(true);
1013
- }}
1014
- triggerRef={profileTriggerRef}
1015
- id={profileMenuId}
1016
- theme={theme}
1017
- bar
1018
- collapsed={false}
1019
- pathname={pathname}
1020
- onNavigate={onNavigate}
1021
- roving={roving.itemProps(visible.length)}
1022
- onLayout={compactScroll.itemLayout(items.length)}
1023
- />
1024
- ) : null}
427
+ {props.items.map((item, index) => (
428
+ <NavigationSection key={item.id} model={model} item={item} index={index} />
429
+ ))}
430
+ {bar && profile !== undefined ? <ProfileTarget model={model} profile={profile} /> : null}
1025
431
  </ScrollView>
1026
- {!bar && profile !== undefined ? (
1027
- <Profile
1028
- profile={profile}
1029
- open={profileOpen}
1030
- onOpen={() => {
1031
- setProfileOpen(true);
1032
- }}
1033
- triggerRef={profileTriggerRef}
1034
- id={profileMenuId}
1035
- theme={theme}
1036
- bar={false}
1037
- collapsed={collapsed}
1038
- pathname={pathname}
1039
- onNavigate={onNavigate}
1040
- roving={roving.itemProps(visible.length)}
1041
- />
1042
- ) : null}
432
+ {!bar && profile !== undefined ? <ProfileTarget model={model} profile={profile} /> : null}
1043
433
  </View>
1044
434
  );
435
+ }
436
+
437
+ export function AppNavigation(props: AppNavigationProps): ReactNode {
438
+ const model = useAppNavigationModel(props);
439
+ const renderBackground = (backgroundProps: OverlayBackgroundProps = {}): ReactNode => (
440
+ <NavigationSurface model={model} backgroundProps={backgroundProps} />
441
+ );
442
+ const profile = props.profile;
1045
443
  if (profile?.menu === undefined) return renderBackground();
1046
444
  return (
1047
445
  <Menu
1048
446
  renderBackground={renderBackground}
1049
447
  entries={profile.menu}
1050
- closeLabel={closeLabel}
1051
- pathname={pathname}
1052
- visible={profileOpen}
1053
- id={profileMenuId}
448
+ closeLabel={props.closeLabel}
449
+ pathname={props.pathname}
450
+ visible={model.profileOpen}
451
+ id={model.profileMenuId}
1054
452
  label={profile.label}
1055
453
  subtitle={profile.subtitle}
1056
- triggerRef={profileTriggerRef}
1057
- theme={theme}
1058
- insets={insets}
454
+ triggerRef={model.profileTriggerRef}
455
+ theme={props.theme}
456
+ insets={model.insets}
1059
457
  onClose={() => {
1060
- setProfileOpen(false);
458
+ model.setProfileOpen(false);
1061
459
  }}
1062
- onNavigate={onNavigate}
460
+ onNavigate={props.onNavigate}
1063
461
  />
1064
462
  );
1065
463
  }
1066
464
 
1067
- export interface SectionPickerProps {
1068
- readonly replace?: boolean;
1069
- readonly closeLabel: string;
1070
- readonly item: NavigationItem<NavigationIcon>;
1071
- readonly pathname: string;
1072
- readonly onNavigate: Navigate;
1073
- readonly theme: NavigationTheme;
1074
- readonly insets?: NavigationInsets;
1075
- }
1076
- export function SectionPicker({
1077
- replace = false,
1078
- item,
1079
- pathname,
1080
- onNavigate,
1081
- theme,
1082
- closeLabel,
1083
- insets,
1084
- }: SectionPickerProps) {
1085
- const [open, setOpen] = useState(false);
1086
- const triggerRef = useRef<View>(null);
1087
- const id = useId();
1088
- const active = resolveActiveNavigation([item], pathname).subItem ?? item.children?.[0];
1089
- const entries = item.children ?? [];
1090
- useEffect(() => {
1091
- setOpen(false);
1092
- }, [pathname]);
1093
- if (entries.length === 0) return null;
1094
- const renderBackground = (backgroundProps: OverlayBackgroundProps) => (
1095
- <View {...backgroundProps} role="navigation" accessibilityLabel={item.label}>
1096
- <FocusablePressable
1097
- theme={theme}
1098
- unfocusedBorderColor={theme.border}
1099
- ref={triggerRef}
1100
- {...(Platform.OS === 'web'
1101
- ? { 'aria-controls': id, 'aria-haspopup': 'menu' as const }
1102
- : {})}
1103
- accessibilityRole="button"
1104
- accessibilityLabel={`${item.label}, ${active?.label ?? ''}`}
1105
- accessibilityState={{ expanded: open }}
1106
- onPress={() => {
1107
- setOpen(true);
1108
- }}
1109
- style={[
1110
- styles.picker,
1111
- {
1112
- backgroundColor: theme.background,
1113
- borderColor: theme.border,
1114
- borderRadius: theme.radius,
1115
- padding: theme.spacing,
1116
- },
1117
- ]}
1118
- >
1119
- <View>
1120
- <Text style={{ ...textStyle(theme), color: theme.muted }}>{item.label}</Text>
1121
- <Text style={{ ...textStyle(theme), color: theme.text }}>{active?.label}</Text>
1122
- </View>
1123
- <Decorative>
1124
- <Text style={{ ...textStyle(theme), color: theme.text }}>⌄</Text>
1125
- </Decorative>
1126
- </FocusablePressable>
1127
- </View>
1128
- );
1129
- return (
1130
- <Menu
1131
- renderBackground={renderBackground}
1132
- entries={entries}
1133
- closeLabel={closeLabel}
1134
- pathname={pathname}
1135
- label={item.label}
1136
- visible={open}
1137
- id={id}
1138
- triggerRef={triggerRef}
1139
- theme={theme}
1140
- insets={insets}
1141
- onClose={() => {
1142
- setOpen(false);
1143
- }}
1144
- onNavigate={(href) => {
1145
- announce(entries.find((entry) => entry.href === href)?.label ?? item.label);
1146
- if (replace) onNavigate(href, { replace: true });
1147
- else onNavigate(href);
1148
- }}
1149
- />
1150
- );
1151
- }
1152
- const styles = StyleSheet.create({
1153
- labelGroup: { minWidth: 0, flexShrink: 1 },
1154
- menuProfile: { padding: 8 },
1155
- target: {
1156
- padding: NAVIGATION_BAR_DIMENSIONS.targetPadding,
1157
- },
1158
- railTarget: { flexDirection: 'row', alignItems: 'center' },
1159
- collapsedTarget: { justifyContent: 'center' },
1160
- barTarget: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flex: 1 },
1161
- bar: {
1162
- flexDirection: 'column',
1163
- minHeight: NAVIGATION_DIMENSIONS.nativeBar,
1164
- borderTopWidth: NAVIGATION_BAR_DIMENSIONS.border,
1165
- width: '100%',
1166
- },
1167
- rail: { borderRightWidth: 1, height: '100%' },
1168
- slots: { flexShrink: 0 },
1169
- barSlots: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
1170
- slot: { minWidth: 0, flexShrink: 1 },
1171
- barBrand: { flexShrink: 0 },
1172
- railItems: { flex: 1 },
1173
- barItems: { width: '100%', flexGrow: 0, flexShrink: 0 },
1174
- barContent: { flexDirection: 'row', flexGrow: 1, minWidth: '100%' },
1175
- barSection: { flex: 1, minWidth: NAVIGATION_DIMENSIONS.target },
1176
- children: { marginLeft: 20, paddingLeft: 8, borderLeftWidth: 1 },
1177
- profile: { position: 'relative', marginTop: 'auto', paddingTop: 8, borderTopWidth: 1 },
1178
- avatar: {
1179
- width: NAVIGATION_DIMENSIONS.avatar,
1180
- height: NAVIGATION_DIMENSIONS.avatar,
1181
- borderRadius: NAVIGATION_DIMENSIONS.avatar / 2,
1182
- alignItems: 'center',
1183
- justifyContent: 'center',
1184
- },
1185
- modal: { flex: 1, justifyContent: 'flex-end' },
1186
- menu: { borderWidth: 1, padding: 8, maxHeight: '80%' },
1187
- menuItem: {
1188
- justifyContent: 'center',
1189
- padding: 8,
1190
- },
1191
- picker: {
1192
- flexDirection: 'row',
1193
- alignItems: 'center',
1194
- justifyContent: 'space-between',
1195
- borderWidth: 1,
1196
- width: '100%',
1197
- },
1198
- });
465
+ export type { SectionPickerProps } from './native-section-picker.js';
466
+ // A local binding keeps the export a plain property, so Jest can spy on it like before the split.
467
+ export const SectionPicker: typeof Picker = Picker;