@baukit/navigation 0.7.2 → 0.7.3

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