@baukit/navigation 0.7.3 → 0.8.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.
package/src/native.tsx CHANGED
@@ -19,6 +19,9 @@ import {
19
19
  View,
20
20
  useWindowDimensions,
21
21
  type GestureResponderEvent,
22
+ type LayoutChangeEvent,
23
+ type NativeScrollEvent,
24
+ type NativeSyntheticEvent,
22
25
  type StyleProp,
23
26
  type ViewStyle,
24
27
  type TextStyle,
@@ -37,6 +40,11 @@ import {
37
40
  import {
38
41
  getNavigationLayout,
39
42
  getNavigationBarHeight,
43
+ getNavigationBarVisualHeight,
44
+ getNavigationBarLineHeight,
45
+ NAVIGATION_BAR_DIMENSIONS,
46
+ type NavigationBarMetrics,
47
+ type NavigationSlots,
40
48
  NAVIGATION_DIMENSIONS,
41
49
  navigationMatches,
42
50
  nextSectionHref,
@@ -69,6 +77,7 @@ export interface NavigationTheme {
69
77
  readonly background: string;
70
78
  readonly text: string;
71
79
  readonly muted: string;
80
+ readonly danger: string;
72
81
  readonly activeBackground: string;
73
82
  readonly activeText: string;
74
83
  readonly ancestorText: string;
@@ -78,15 +87,28 @@ export interface NavigationTheme {
78
87
  readonly spacing: number;
79
88
  readonly typography?: NavigationTypography;
80
89
  }
90
+ function barMetrics(theme?: NavigationTheme): NavigationBarMetrics {
91
+ return {
92
+ ...(theme === undefined ? {} : { spacing: theme.spacing }),
93
+ ...(theme?.typography?.barFontSize === undefined
94
+ ? {}
95
+ : { fontSize: theme.typography.barFontSize }),
96
+ ...(theme?.typography?.lineHeight === undefined
97
+ ? {}
98
+ : { lineHeight: theme.typography.lineHeight }),
99
+ };
100
+ }
81
101
  function textStyle(theme: NavigationTheme, selected = false, bar = false): TextStyle {
82
102
  const typography = theme.typography;
83
103
  return {
84
104
  fontFamily: typography?.fontFamily,
85
- fontSize: bar ? (typography?.barFontSize ?? 11) : (typography?.fontSize ?? 14),
105
+ fontSize: bar
106
+ ? (typography?.barFontSize ?? NAVIGATION_BAR_DIMENSIONS.labelFontSize)
107
+ : (typography?.fontSize ?? 14),
86
108
  fontWeight: selected
87
109
  ? (typography?.activeFontWeight ?? '700')
88
110
  : (typography?.fontWeight ?? '400'),
89
- lineHeight: typography?.lineHeight,
111
+ lineHeight: bar ? getNavigationBarLineHeight(barMetrics(theme)) : typography?.lineHeight,
90
112
  letterSpacing: typography?.letterSpacing,
91
113
  };
92
114
  }
@@ -137,7 +159,7 @@ function FocusablePressable({
137
159
  Platform.OS === 'android'
138
160
  ? NAVIGATION_DIMENSIONS.androidTarget
139
161
  : NAVIGATION_DIMENSIONS.target,
140
- borderWidth: 3,
162
+ borderWidth: NAVIGATION_BAR_DIMENSIONS.targetBorder,
141
163
  borderColor: focused
142
164
  ? selected
143
165
  ? theme.activeText
@@ -270,9 +292,16 @@ function Target({
270
292
  </FocusablePressable>
271
293
  );
272
294
  }
273
- function Decorative({ children }: { readonly children: ReactNode }) {
295
+ function Decorative({
296
+ children,
297
+ style,
298
+ }: {
299
+ readonly children: ReactNode;
300
+ readonly style?: StyleProp<ViewStyle>;
301
+ }) {
274
302
  return (
275
303
  <View
304
+ style={style}
276
305
  accessible={false}
277
306
  accessibilityElementsHidden
278
307
  importantForAccessibility="no-hide-descendants"
@@ -319,6 +348,30 @@ function Menu({
319
348
  const closeRef = useRef<View>(null);
320
349
  const pendingFocus = useRef<(() => void) | null>(null);
321
350
  const presented = useRef(false);
351
+ const pendingSelection = useRef<(() => void) | null>(null);
352
+ const finishSelection = useCallback(() => {
353
+ const selection = pendingSelection.current;
354
+ pendingSelection.current = null;
355
+ selection?.();
356
+ }, []);
357
+ useEffect(() => {
358
+ if (visible) {
359
+ pendingSelection.current = null;
360
+ return;
361
+ }
362
+ if (Platform.OS === 'ios' || pendingSelection.current === null) return;
363
+ // Android removes an unanimated Modal in the close commit and has no onDismiss event.
364
+ const frame = requestAnimationFrame(finishSelection);
365
+ return () => {
366
+ cancelAnimationFrame(frame);
367
+ };
368
+ }, [visible, finishSelection]);
369
+ useEffect(
370
+ () => () => {
371
+ pendingSelection.current = null;
372
+ },
373
+ [],
374
+ );
322
375
  const [webPresented, setWebPresented] = useState(false);
323
376
  const [webPosition, setWebPosition] = useState<ViewStyle>();
324
377
  const deferFocus = useCallback((task: () => void) => {
@@ -458,7 +511,7 @@ function Menu({
458
511
  <FocusablePressable
459
512
  theme={theme}
460
513
  selected={entry === activeEntry}
461
- {...{ dataSet: { active: entry === activeEntry ? 'page' : 'false' } }}
514
+ {...{ dataSet: { active: entry === activeEntry ? 'page' : 'false', tone: entry.tone } }}
462
515
  {...roving.itemProps(index)}
463
516
  key={entry.id}
464
517
  accessibilityRole="menuitem"
@@ -470,22 +523,35 @@ function Menu({
470
523
  disabled={entry.disabled}
471
524
  {...(entry.href === undefined ? {} : webLink(entry.href, entry === activeEntry))}
472
525
  onPress={(event) => {
473
- if (isModifiedPress(event)) return;
526
+ if (isModifiedPress(event) || pendingSelection.current !== null) return;
527
+ event.preventDefault();
528
+ pendingSelection.current =
529
+ entry.href !== undefined
530
+ ? () => {
531
+ onNavigate(entry.href);
532
+ }
533
+ : entry.onSelect;
474
534
  closeAndRestore();
475
- if (entry.href !== undefined) follow(entry.href, event, onNavigate);
476
- else entry.onSelect();
477
535
  }}
478
536
  style={[
479
537
  styles.menuItem,
480
538
  {
481
539
  paddingHorizontal: theme.spacing,
482
- backgroundColor: entry === activeEntry ? theme.activeBackground : theme.background,
540
+ backgroundColor:
541
+ entry === activeEntry && entry.tone !== 'danger'
542
+ ? theme.activeBackground
543
+ : theme.background,
483
544
  },
484
545
  ]}
485
546
  >
486
547
  <Text
487
548
  style={{
488
- color: entry === activeEntry ? theme.activeText : theme.text,
549
+ color:
550
+ entry.tone === 'danger'
551
+ ? theme.danger
552
+ : entry === activeEntry
553
+ ? theme.activeText
554
+ : theme.text,
489
555
  ...textStyle(theme, entry === activeEntry),
490
556
  }}
491
557
  >
@@ -514,6 +580,9 @@ function Menu({
514
580
  transparent
515
581
  animationType="none"
516
582
  onRequestClose={onClose}
583
+ onDismiss={() => {
584
+ if (!visible) finishSelection();
585
+ }}
517
586
  onShow={() => {
518
587
  if (!visible) return;
519
588
  presented.current = true;
@@ -529,25 +598,31 @@ function Menu({
529
598
  );
530
599
  }
531
600
 
601
+ function compactVisualStyle(fontScale: number): ViewStyle {
602
+ return { height: getNavigationBarVisualHeight(fontScale), justifyContent: 'center' };
603
+ }
604
+
532
605
  function Avatar({
533
606
  profile,
534
607
  active,
535
608
  theme,
609
+ style,
536
610
  }: {
537
611
  readonly profile: NavigationProfile;
538
612
  readonly active: boolean;
539
613
  readonly theme: NavigationTheme;
614
+ readonly style?: StyleProp<ViewStyle>;
540
615
  }) {
541
616
  const [failedUrl, setFailedUrl] = useState<string>();
542
617
  if (profile.renderAvatar !== undefined) {
543
618
  return (
544
- <Decorative>
619
+ <Decorative style={style}>
545
620
  {profile.renderAvatar({ active, size: NAVIGATION_DIMENSIONS.avatar })}
546
621
  </Decorative>
547
622
  );
548
623
  }
549
624
  return (
550
- <Decorative>
625
+ <Decorative style={style}>
551
626
  {profile.imageUrl !== undefined && failedUrl !== profile.imageUrl ? (
552
627
  <Image
553
628
  source={{ uri: profile.imageUrl }}
@@ -558,7 +633,9 @@ function Avatar({
558
633
  />
559
634
  ) : (
560
635
  <View style={[styles.avatar, { backgroundColor: theme.activeBackground }]}>
561
- <Text style={{ ...textStyle(theme), color: theme.activeText }}>{profile.initials}</Text>
636
+ <Text allowFontScaling={false} style={{ ...textStyle(theme), color: theme.activeText }}>
637
+ {profile.initials}
638
+ </Text>
562
639
  </View>
563
640
  )}
564
641
  </Decorative>
@@ -577,6 +654,12 @@ interface ProfileProps {
577
654
  readonly pathname: string;
578
655
  readonly onNavigate: Navigate;
579
656
  readonly roving: ReturnType<ReturnType<typeof useRovingMenu>['itemProps']>;
657
+ readonly onLayout?: (event: LayoutChangeEvent) => void;
658
+ }
659
+ function profileIsActive(profile: NavigationProfile, pathname: string): boolean {
660
+ return profile.href !== undefined
661
+ ? navigationMatches({ id: 'profile', label: profile.label, href: profile.href }, pathname)
662
+ : resolveActiveMenuEntry(profile.menu, pathname) !== null;
580
663
  }
581
664
  function Profile({
582
665
  profile,
@@ -590,13 +673,16 @@ function Profile({
590
673
  pathname,
591
674
  onNavigate,
592
675
  roving,
676
+ onLayout,
593
677
  }: 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;
678
+ const { fontScale } = useWindowDimensions();
679
+ const active = profileIsActive(profile, pathname);
598
680
  return (
599
- <View style={bar ? styles.barSection : styles.profile} testID="navigation-profile">
681
+ <View
682
+ style={bar ? styles.barSection : styles.profile}
683
+ testID="navigation-profile"
684
+ onLayout={onLayout}
685
+ >
600
686
  <Target
601
687
  label={profile.label}
602
688
  subtitle={profile.subtitle}
@@ -614,18 +700,68 @@ function Profile({
614
700
  else onOpen();
615
701
  }}
616
702
  >
617
- <Avatar profile={profile} active={active} theme={theme} />
703
+ <Avatar
704
+ profile={profile}
705
+ active={active}
706
+ theme={theme}
707
+ style={bar ? compactVisualStyle(fontScale) : undefined}
708
+ />
618
709
  </Target>
619
710
  </View>
620
711
  );
621
712
  }
622
713
 
623
- export function useNavigationBarHeight(bottomInset = 0): number {
714
+ export function useNavigationBarHeight(
715
+ bottomInset = 0,
716
+ theme?: NavigationTheme,
717
+ slotHeight = 0,
718
+ ): number {
624
719
  const { fontScale } = useWindowDimensions();
625
- return getNavigationBarHeight(fontScale, bottomInset);
720
+ return getNavigationBarHeight(fontScale, bottomInset, { ...barMetrics(theme), slotHeight });
721
+ }
722
+
723
+ function useCompactBarScroll(selectedIndex: number) {
724
+ const ref = useRef<ScrollView>(null);
725
+ const viewport = useRef(0);
726
+ const content = useRef(0);
727
+ const offset = useRef(0);
728
+ const frames = useRef(new Map<number, { x: number; width: number }>());
729
+ const revealSelected = useCallback(() => {
730
+ const frame = frames.current.get(selectedIndex);
731
+ if (frame === undefined || viewport.current === 0 || content.current === 0) return;
732
+ if (frame.x >= offset.current && frame.x + frame.width <= offset.current + viewport.current)
733
+ return;
734
+ const x = Math.max(
735
+ 0,
736
+ Math.min(frame.x + (frame.width - viewport.current) / 2, content.current - viewport.current),
737
+ );
738
+ ref.current?.scrollTo({ x, animated: false });
739
+ offset.current = x;
740
+ }, [selectedIndex]);
741
+ useEffect(revealSelected, [revealSelected]);
742
+ return {
743
+ scrollProps: {
744
+ ref,
745
+ onLayout: (event: LayoutChangeEvent) => {
746
+ viewport.current = event.nativeEvent.layout.width;
747
+ revealSelected();
748
+ },
749
+ onContentSizeChange: (width: number) => {
750
+ content.current = width;
751
+ revealSelected();
752
+ },
753
+ onScroll: (event: NativeSyntheticEvent<NativeScrollEvent>) => {
754
+ offset.current = event.nativeEvent.contentOffset.x;
755
+ },
756
+ },
757
+ itemLayout: (index: number) => (event: LayoutChangeEvent) => {
758
+ frames.current.set(index, event.nativeEvent.layout);
759
+ revealSelected();
760
+ },
761
+ };
626
762
  }
627
763
 
628
- export interface AppNavigationProps extends CollapseProps {
764
+ export interface AppNavigationProps extends CollapseProps, NavigationSlots {
629
765
  readonly items: readonly NavigationItem<NavigationIcon>[];
630
766
  readonly profile?: NavigationProfile;
631
767
  readonly pathname: string;
@@ -652,6 +788,7 @@ export function AppNavigation(props: AppNavigationProps) {
652
788
  collapseLabel,
653
789
  expandLabel,
654
790
  } = props;
791
+ const [slotHeight, setSlotHeight] = useState(0);
655
792
  const [profileOpen, setProfileOpen] = useState(false);
656
793
  const profileTriggerRef = useRef<View>(null);
657
794
  const profileMenuId = useId();
@@ -661,6 +798,19 @@ export function AppNavigation(props: AppNavigationProps) {
661
798
  const bar = getNavigationLayout(props.width ?? dimensions.width) === 'bar';
662
799
  const state = useNavigationState(items, pathname, props);
663
800
  const collapsed = !bar && state.collapsed;
801
+ const slotState = { layout: bar ? ('bar' as const) : ('rail' as const), collapsed };
802
+ const brand = props.renderBrand?.(slotState);
803
+ const accessory = props.renderAccessory?.(slotState);
804
+ const hasBrand = brand != null && typeof brand !== 'boolean';
805
+ const hasAccessory = accessory != null && typeof accessory !== 'boolean';
806
+ const hasSlots = hasBrand || hasAccessory;
807
+ const barHeight = getNavigationBarHeight(dimensions.fontScale, insets.bottom, {
808
+ ...barMetrics(theme),
809
+ slotHeight: hasSlots ? slotHeight : 0,
810
+ });
811
+ useEffect(() => {
812
+ if (bar) props.onBarHeightChange?.(barHeight);
813
+ }, [bar, barHeight, props.onBarHeightChange]);
664
814
  const id = useId();
665
815
  const visible = items.flatMap((item) =>
666
816
  !bar && !collapsed && state.openIds.includes(item.id)
@@ -670,13 +820,17 @@ export function AppNavigation(props: AppNavigationProps) {
670
820
  const activeId = visible.some((item) => item.id === state.active.subItem?.id)
671
821
  ? state.active.subItem?.id
672
822
  : state.active.item?.id;
823
+ const profileActive = profile !== undefined && profileIsActive(profile, pathname);
824
+ const compactScroll = useCompactBarScroll(
825
+ bar ? (profileActive ? items.length : items.findIndex((item) => item.id === activeId)) : -1,
826
+ );
673
827
  const roving = useRovingMenu({
674
828
  active: true,
675
829
  options: [
676
830
  ...visible.map((item) => ({
677
831
  selected: item.id === activeId,
678
832
  })),
679
- ...(profile === undefined ? [] : [{}]),
833
+ ...(profile === undefined ? [] : [{ selected: profileActive }]),
680
834
  ],
681
835
  });
682
836
  const renderBackground = (backgroundProps: OverlayBackgroundProps = {}) => (
@@ -693,7 +847,9 @@ export function AppNavigation(props: AppNavigationProps) {
693
847
  borderColor: theme.border,
694
848
  paddingBottom: insets.bottom ?? 0,
695
849
  ...(bar
696
- ? { minHeight: getNavigationBarHeight(dimensions.fontScale, insets.bottom) }
850
+ ? {
851
+ minHeight: barHeight,
852
+ }
697
853
  : {}),
698
854
  paddingLeft: insets.left ?? 0,
699
855
  paddingRight: insets.right ?? 0,
@@ -705,6 +861,30 @@ export function AppNavigation(props: AppNavigationProps) {
705
861
  props.style,
706
862
  ]}
707
863
  >
864
+ {hasSlots ? (
865
+ <View
866
+ testID="navigation-slots"
867
+ style={[
868
+ styles.slots,
869
+ bar && styles.barSlots,
870
+ { padding: theme.spacing, gap: theme.spacing },
871
+ ]}
872
+ onLayout={(event) => {
873
+ if (bar) setSlotHeight(event.nativeEvent.layout.height);
874
+ }}
875
+ >
876
+ {!hasBrand ? null : (
877
+ <View testID="navigation-brand" style={[styles.slot, bar && styles.barBrand]}>
878
+ {brand}
879
+ </View>
880
+ )}
881
+ {!hasAccessory ? null : (
882
+ <View testID="navigation-accessory" style={styles.slot}>
883
+ {accessory}
884
+ </View>
885
+ )}
886
+ </View>
887
+ ) : null}
708
888
  {!bar ? (
709
889
  <Target
710
890
  label={collapsed ? expandLabel : collapseLabel}
@@ -721,10 +901,23 @@ export function AppNavigation(props: AppNavigationProps) {
721
901
  </Target>
722
902
  ) : null}
723
903
  <ScrollView
904
+ {...(bar ? compactScroll.scrollProps : {})}
905
+ testID="navigation-items"
724
906
  horizontal={bar}
725
- scrollEnabled={!bar}
907
+ scrollEnabled
726
908
  showsHorizontalScrollIndicator={false}
727
- style={bar ? styles.barItems : styles.railItems}
909
+ style={
910
+ bar
911
+ ? [
912
+ styles.barItems,
913
+ {
914
+ height:
915
+ getNavigationBarHeight(dimensions.fontScale, 0, barMetrics(theme)) -
916
+ NAVIGATION_BAR_DIMENSIONS.border,
917
+ },
918
+ ]
919
+ : styles.railItems
920
+ }
728
921
  contentContainerStyle={bar ? styles.barContent : undefined}
729
922
  >
730
923
  {items.map((item, index) => {
@@ -737,6 +930,7 @@ export function AppNavigation(props: AppNavigationProps) {
737
930
  key={item.id}
738
931
  style={bar ? styles.barSection : undefined}
739
932
  testID={`navigation-section-${item.id}`}
933
+ onLayout={bar ? compactScroll.itemLayout(index) : undefined}
740
934
  >
741
935
  <Target
742
936
  label={item.label}
@@ -754,7 +948,9 @@ export function AppNavigation(props: AppNavigationProps) {
754
948
  else follow(href, event, onNavigate);
755
949
  }}
756
950
  >
757
- <Decorative>{item.icon({ active, size: 24 })}</Decorative>
951
+ <Decorative style={bar ? compactVisualStyle(dimensions.fontScale) : undefined}>
952
+ {item.icon({ active, size: NAVIGATION_BAR_DIMENSIONS.icon })}
953
+ </Decorative>
758
954
  </Target>
759
955
  {!bar && open && children.length > 0 ? (
760
956
  <View
@@ -803,6 +999,7 @@ export function AppNavigation(props: AppNavigationProps) {
803
999
  pathname={pathname}
804
1000
  onNavigate={onNavigate}
805
1001
  roving={roving.itemProps(visible.length)}
1002
+ onLayout={compactScroll.itemLayout(items.length)}
806
1003
  />
807
1004
  ) : null}
808
1005
  </ScrollView>
@@ -929,21 +1126,25 @@ const styles = StyleSheet.create({
929
1126
  labelGroup: { minWidth: 0, flexShrink: 1 },
930
1127
  menuProfile: { padding: 8 },
931
1128
  target: {
932
- padding: 8,
1129
+ padding: NAVIGATION_BAR_DIMENSIONS.targetPadding,
933
1130
  },
934
1131
  railTarget: { flexDirection: 'row', alignItems: 'center' },
935
1132
  collapsedTarget: { justifyContent: 'center' },
936
1133
  barTarget: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flex: 1 },
937
1134
  bar: {
938
- flexDirection: 'row',
939
- minHeight: NAVIGATION_DIMENSIONS.bar,
940
- borderTopWidth: 1,
1135
+ flexDirection: 'column',
1136
+ minHeight: NAVIGATION_DIMENSIONS.nativeBar,
1137
+ borderTopWidth: NAVIGATION_BAR_DIMENSIONS.border,
941
1138
  width: '100%',
942
1139
  },
943
1140
  rail: { borderRightWidth: 1, height: '100%' },
1141
+ slots: { flexShrink: 0 },
1142
+ barSlots: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
1143
+ slot: { minWidth: 0, flexShrink: 1 },
1144
+ barBrand: { flexShrink: 0 },
944
1145
  railItems: { flex: 1 },
945
- barItems: { width: '100%' },
946
- barContent: { flexDirection: 'row', flexGrow: 1 },
1146
+ barItems: { width: '100%', flexGrow: 0, flexShrink: 0 },
1147
+ barContent: { flexDirection: 'row', flexGrow: 1, minWidth: '100%' },
947
1148
  barSection: { flex: 1, minWidth: NAVIGATION_DIMENSIONS.target },
948
1149
  children: { marginLeft: 20, paddingLeft: 8, borderLeftWidth: 1 },
949
1150
  profile: { position: 'relative', marginTop: 'auto', paddingTop: 8, borderTopWidth: 1 },