@baukit/navigation 0.7.2 → 0.7.4

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