@momo-kits/foundation 0.169.19-beta.3 → 0.169.19-beta.5

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.
@@ -17,6 +17,7 @@ import BackgroundImageView from './BackgroundImageView';
17
17
  import { type AnimatedCompatValue } from '../utils';
18
18
  import { useNormalizedSharedValue } from '../hooks';
19
19
  import { useScreenLayout } from '../../Layout';
20
+ import { getHeaderMargin } from '../../Layout/utils';
20
21
  import {
21
22
  HeaderBarMetrics,
22
23
  type HeaderContentLayout,
@@ -70,8 +71,11 @@ const HeaderExtendHeader: React.FC<{
70
71
  const layout = useScreenLayout();
71
72
  const headerLayout = useHeaderLayout(contentLayout);
72
73
  // collapsed into the bar, the search follows back and the right cluster into the
73
- // frame; both already sit `sidePadding` from the edge on large iOS windows
74
- const frameShift = headerLayout.frameInset - sidePadding;
74
+ // frame, or the side margin React Navigation adds on large iOS windows (the larger)
75
+ let frameShift = headerLayout.frameInset - sidePadding;
76
+ if (!layout.sideBar) {
77
+ frameShift = Math.max(frameShift, getHeaderMargin(layout.width));
78
+ }
75
79
 
76
80
  const backLeft = buttonSize + sidePadding + titleGap;
77
81
  const defaultLeft = layout.sideBar ? SCREEN_PADDING : backLeft;
@@ -1,4 +1,4 @@
1
- import { BackHandler, useWindowDimensions, View } from 'react-native';
1
+ import { BackHandler, StyleSheet, View } from 'react-native';
2
2
  import type { HeaderBackProps } from '../types';
3
3
  import React, { useCallback, useContext, useEffect } from 'react';
4
4
  import { ApplicationContext, MiniAppContext } from '../../Context';
@@ -8,12 +8,11 @@ import { SideBarButton } from './SideBarButton';
8
8
  import Animated from 'react-native-reanimated';
9
9
  import { useSideBarItemStyle } from '../../Layout/utils';
10
10
  import { useSideBarCounterStyle } from './DuoQuickReturnHeader';
11
- import { getHeaderRowInset } from '../headerLayout';
11
+ import { HeaderBarMetrics } from '../headerLayout';
12
12
 
13
13
  /**
14
14
  * Header back button, also bound to the Android hardware back. `preventBack`
15
15
  * confirms in a popup first; the iPhone Duo side bar uses the 48pt side bar button.
16
- * In the bar it sits `sidePadding` from the window edge on every iPhone width.
17
16
  */
18
17
  const HeaderLeft: React.FC<HeaderBackProps> = ({
19
18
  tintColor,
@@ -26,7 +25,6 @@ const HeaderLeft: React.FC<HeaderBackProps> = ({
26
25
  const { navigator } = useContext(ApplicationContext);
27
26
  const sideBarStyle = useSideBarItemStyle('left', 0);
28
27
  const counterStyle = useSideBarCounterStyle();
29
- const { width } = useWindowDimensions();
30
28
 
31
29
  const goBack = useCallback(() => {
32
30
  const canGoBack = navigator?.ref?.current?.canGoBack?.();
@@ -100,7 +98,7 @@ const HeaderLeft: React.FC<HeaderBackProps> = ({
100
98
  }
101
99
 
102
100
  return (
103
- <View style={{ marginLeft: getHeaderRowInset(width) }}>
101
+ <View style={styles.headerLeft}>
104
102
  <NavigationButton
105
103
  accessibilityLabel="btn_navigation_back"
106
104
  icon="arrow-back"
@@ -111,4 +109,10 @@ const HeaderLeft: React.FC<HeaderBackProps> = ({
111
109
  );
112
110
  };
113
111
 
112
+ const styles = StyleSheet.create({
113
+ headerLeft: {
114
+ marginLeft: HeaderBarMetrics.sidePadding,
115
+ },
116
+ });
117
+
114
118
  export { HeaderLeft };
@@ -2,7 +2,7 @@ import { Platform, StyleSheet } from 'react-native';
2
2
  import { Colors, Spacing } from '../../Consts';
3
3
  import { HeaderBarMetrics } from '../headerLayout';
4
4
 
5
- const { buttonSize, pillWidth, pillHeight } = HeaderBarMetrics;
5
+ const { buttonSize, pillWidth, pillHeight, sidePadding } = HeaderBarMetrics;
6
6
 
7
7
  export const styles = StyleSheet.create({
8
8
  navigationButton: {
@@ -48,6 +48,7 @@ export const styles = StyleSheet.create({
48
48
  flexDirection: 'row',
49
49
  justifyContent: 'center',
50
50
  alignItems: 'center',
51
+ paddingRight: sidePadding,
51
52
  },
52
53
  toolkitContainer: {
53
54
  height: pillHeight,
@@ -133,6 +134,9 @@ export const styles = StyleSheet.create({
133
134
  },
134
135
  }),
135
136
  },
137
+ onBoarding: {
138
+ marginRight: Spacing.M,
139
+ },
136
140
  toolkitWide: {
137
141
  width: pillWidth,
138
142
  },
@@ -1,16 +1,10 @@
1
1
  import React, { useCallback, useContext, useEffect } from 'react';
2
- import {
3
- type LayoutChangeEvent,
4
- TouchableOpacity,
5
- useWindowDimensions,
6
- View,
7
- } from 'react-native';
2
+ import { type LayoutChangeEvent, TouchableOpacity, View } from 'react-native';
8
3
  import { NavigationRouteContext } from '@react-navigation/native';
9
4
  import { ApplicationContext } from '../../Context';
10
5
  import { Text } from '../../Text';
11
6
  import Animated from 'react-native-reanimated';
12
- import { getHeaderMargin, useSideBarItemStyle } from '../../Layout/utils';
13
- import { getHeaderRowInset } from '../headerLayout';
7
+ import { useSideBarItemStyle } from '../../Layout/utils';
14
8
  import { useSideBarCounterStyle } from './DuoQuickReturnHeader';
15
9
  import { HeaderToolkitAction } from './HeaderToolkitAction';
16
10
  import { styles } from './HeaderRight.styles';
@@ -19,8 +13,7 @@ import { setHeaderRightWidth } from './useHeaderRightWidth';
19
13
  /**
20
14
  * Header right slot: a custom `headerRight` render function, the onboarding skip
21
15
  * button, or the toolkit (stacked vertically in the floating iPhone Duo side bar).
22
- * The bar toolkit sits `sidePadding` from the window edge and reports its width
23
- * from that edge so header searches stop short of it.
16
+ * The bar toolkit reports its width so header searches stop short of it.
24
17
  */
25
18
  const HeaderRight: React.FC<any> = props => {
26
19
  const { translate } = useContext(ApplicationContext);
@@ -29,18 +22,14 @@ const HeaderRight: React.FC<any> = props => {
29
22
  const sideBarStyle = useSideBarItemStyle('right', 1);
30
23
  const counterStyle = useSideBarCounterStyle();
31
24
  const routeKey = useContext(NavigationRouteContext)?.key;
32
- const { width } = useWindowDimensions();
33
- const rowMargin = getHeaderMargin(width);
34
- const rowInset = getHeaderRowInset(width);
35
25
 
36
26
  const handleToolkitLayout = useCallback(
37
27
  (event: LayoutChangeEvent) => {
38
28
  if (routeKey) {
39
- const toolkitWidth = event.nativeEvent.layout.width + rowMargin;
40
- setHeaderRightWidth(routeKey, toolkitWidth);
29
+ setHeaderRightWidth(routeKey, event.nativeEvent.layout.width);
41
30
  }
42
31
  },
43
- [routeKey, rowMargin],
32
+ [routeKey],
44
33
  );
45
34
 
46
35
  useEffect(() => {
@@ -57,7 +46,7 @@ const HeaderRight: React.FC<any> = props => {
57
46
 
58
47
  if (useOnBoarding && onPress) {
59
48
  return (
60
- <TouchableOpacity onPress={onPress} style={{ marginRight: rowInset }}>
49
+ <TouchableOpacity onPress={onPress} style={styles.onBoarding}>
61
50
  <Text typography={'action_s_bold'}>
62
51
  {buttonOnBoarding || translate?.('skip')}
63
52
  </Text>
@@ -81,10 +70,7 @@ const HeaderRight: React.FC<any> = props => {
81
70
  }
82
71
 
83
72
  return (
84
- <View
85
- style={[styles.headerRightButton, { paddingRight: rowInset }]}
86
- onLayout={handleToolkitLayout}
87
- >
73
+ <View style={styles.headerRightButton} onLayout={handleToolkitLayout}>
88
74
  <HeaderToolkitAction {...props.headerRight} tintColor={props.tintColor} />
89
75
  </View>
90
76
  );
@@ -8,6 +8,7 @@ import { ApplicationContext, MiniAppContext } from '../../Context';
8
8
  import { Text } from '../../Text';
9
9
  import { useNormalizedSharedValue } from '../hooks';
10
10
  import { useScreenLayout } from '../../Layout';
11
+ import { getHeaderMargin } from '../../Layout/utils';
11
12
  import { HeaderBarMetrics } from '../headerLayout';
12
13
  import { useHeaderRightWidth } from './useHeaderRightWidth';
13
14
 
@@ -46,9 +47,10 @@ const SearchHeader = React.forwardRef<InputRef, SearchHeaderProps>(
46
47
  const headerRightWidth = props?.headerRightWidth ?? defaultRightWidth;
47
48
 
48
49
  // iPhone Duo side bar holds back: the search shares the content width with the buttons only
49
- // back ends at leftPosition and the measured right cluster counts from the window
50
- // edge, so the large iOS header row margin is already netted out on both sides
51
- const rowWidth = layout.width - leftPosition - sidePadding;
50
+ // large iOS windows: React Navigation narrows the header row by a margin each side
51
+ const headerMargin = getHeaderMargin(layout.width);
52
+ const rowWidth =
53
+ layout.width - leftPosition - sidePadding - headerMargin * 2;
52
54
  let searchMaxWidth = rowWidth - headerRightWidth;
53
55
  if (layout.sideBar) {
54
56
  searchMaxWidth = layout.contentWidth - Spacing.M * 2 - headerRightWidth;
@@ -16,8 +16,8 @@ const subscribe = (listener: () => void) => {
16
16
  };
17
17
 
18
18
  /**
19
- * Records how far a route's header right reaches in from the window edge, side
20
- * padding included; `undefined` clears it when the header right unmounts.
19
+ * Records the laid out width of a route's header right, side padding included;
20
+ * `undefined` clears it when the header right unmounts.
21
21
  */
22
22
  const setHeaderRightWidth = (routeKey: string, width?: number) => {
23
23
  if (widths.get(routeKey) === width) {
@@ -69,7 +69,7 @@ describe('getHeaderFrameOptions', () => {
69
69
  isDuo: false,
70
70
  contentLayout,
71
71
  });
72
- return { layout, isDuo: false, edgePadding: NO_EDGE };
72
+ return { layout, isDuo: false, headerMargin: 0, edgePadding: NO_EDGE };
73
73
  };
74
74
 
75
75
  it('leaves the options alone when contentLayout is unset', () => {
@@ -103,6 +103,7 @@ describe('getHeaderFrameOptions', () => {
103
103
  const options = getHeaderFrameOptions({
104
104
  layout,
105
105
  isDuo: true,
106
+ headerMargin: 0,
106
107
  edgePadding: DUO_EDGE,
107
108
  contentLayout: 'stretch',
108
109
  });
@@ -85,6 +85,8 @@ type EdgePadding = { left: number; right: number };
85
85
  type HeaderFrameInput = {
86
86
  layout: HeaderLayout;
87
87
  isDuo: boolean;
88
+ // side margin @react-navigation/elements already adds to the row
89
+ headerMargin: number;
88
90
  // padding of the plain row containers: the iPhone Duo status bar clearance, else 0
89
91
  edgePadding: EdgePadding;
90
92
  contentLayout?: HeaderContentLayout;
@@ -121,14 +123,6 @@ const getHeaderLayout = ({
121
123
  };
122
124
  };
123
125
 
124
- /**
125
- * Inset from the React Navigation header row that puts an item `sidePadding` from
126
- * the window edge: large iOS windows already inset that row by `getHeaderMargin`.
127
- */
128
- const getHeaderRowInset = (width: number) => {
129
- return HeaderBarMetrics.sidePadding - getHeaderMargin(width);
130
- };
131
-
132
126
  /**
133
127
  * Widest a title can be between back and the right cluster of the header row.
134
128
  */
@@ -195,6 +189,7 @@ const getEdgeFrameOptions = (
195
189
  const getHeaderFrameOptions = ({
196
190
  layout,
197
191
  isDuo,
192
+ headerMargin,
198
193
  edgePadding,
199
194
  contentLayout,
200
195
  }: HeaderFrameInput): StackNavigationOptions | undefined => {
@@ -204,11 +199,12 @@ const getHeaderFrameOptions = ({
204
199
  if (contentLayout !== 'stretch' || isDuo) {
205
200
  return getEdgeFrameOptions(edgePadding);
206
201
  }
207
- // back and toolkit already net out the header row margin of large iOS windows
202
+ // the header content row already sits this far in on large iOS windows
208
203
  const shift = layout.frameInset - layout.sidePadding;
204
+ const containerShift = Math.max(0, shift - headerMargin);
209
205
  return {
210
- headerLeftContainerStyle: { paddingLeft: shift },
211
- headerRightContainerStyle: { paddingRight: shift },
206
+ headerLeftContainerStyle: { paddingLeft: containerShift },
207
+ headerRightContainerStyle: { paddingRight: containerShift },
212
208
  headerTitleContainerStyle: {
213
209
  ...TITLE_CONTAINER_RESET,
214
210
  left: layout.titleGap,
@@ -229,15 +225,17 @@ const useHeaderFrameOptions = (
229
225
  const rowOptions = getHeaderRowOptions(screenLayout);
230
226
  const edgeLeft = rowOptions.headerLeftContainerStyle?.paddingLeft ?? 0;
231
227
  const edgeRight = rowOptions.headerRightContainerStyle?.paddingRight ?? 0;
228
+ const headerMargin = getHeaderMargin(screenLayout.width);
232
229
  const isDuo = isIPhoneDuo();
233
230
  return useMemo(() => {
234
231
  return getHeaderFrameOptions({
235
232
  layout,
236
233
  isDuo,
234
+ headerMargin,
237
235
  edgePadding: { left: edgeLeft, right: edgeRight },
238
236
  contentLayout,
239
237
  });
240
- }, [contentLayout, isDuo, layout, edgeLeft, edgeRight]);
238
+ }, [contentLayout, isDuo, layout, headerMargin, edgeLeft, edgeRight]);
241
239
  };
242
240
 
243
241
  export type { HeaderContentLayout, HeaderLayout };
@@ -249,7 +247,6 @@ export {
249
247
  getHeaderFrameOptions,
250
248
  getHeaderLayout,
251
249
  getSearchHeaderHeight,
252
- getHeaderRowInset,
253
250
  getTitleBudget,
254
251
  useHeaderLayout,
255
252
  useHeaderFrameOptions,
@@ -6,6 +6,7 @@ import {
6
6
  ScreenContext,
7
7
  TrackingScopeContext,
8
8
  } from '../Context';
9
+ import { useCountComponent } from '../ComponentCounter/hooks';
9
10
  import {
10
11
  type AnimatedCompatValue,
11
12
  type NavigationTreeState,
@@ -27,6 +28,8 @@ const useComponentId = (componentName: string, accessibilityLabel?: string) => {
27
28
 
28
29
  const scope = scopeName ? `${scopeName}/` : '';
29
30
 
31
+ useCountComponent(screen.screenName ?? 'unknown', componentName);
32
+
30
33
  const componentId = useMemo(() => {
31
34
  if (accessibilityLabel) {
32
35
  return accessibilityLabel;
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { Dimensions, Platform } from 'react-native';
2
+ import { Platform } from 'react-native';
3
3
  import {
4
4
  CardStyleInterpolators,
5
5
  type StackCardInterpolatedStyle,
@@ -13,11 +13,7 @@ import { HeaderBackground } from './Components/HeaderBackground';
13
13
  import { HeaderLeft } from './Components/HeaderLeft';
14
14
  import { HeaderRight } from './Components/HeaderRight';
15
15
  import { HeaderTitle, TitleCustom } from './Components/HeaderTitle';
16
- import {
17
- getHeaderRowInset,
18
- HeaderBarMetrics,
19
- TITLE_CONTAINER_RESET,
20
- } from './headerLayout';
16
+ import { HeaderBarMetrics, TITLE_CONTAINER_RESET } from './headerLayout';
21
17
  import type { HeaderTitleProps, NavigationOptions } from './types';
22
18
 
23
19
  const CARD_SHADOW_OPACITY = 0.3;
@@ -148,9 +144,8 @@ const exportHeaderTitle = (
148
144
  };
149
145
 
150
146
  /**
151
- * React Navigation options from screen params: design system header left, title
152
- * (`sidePadding` from the window edge with hidden back) and right, and swipe back
153
- * off for screens that own their back flow.
147
+ * React Navigation options from screen params: design system header left,
148
+ * title and right, and swipe back off for screens that own their back flow.
154
149
  */
155
150
  const getOptions = (
156
151
  params: NavigationOptions,
@@ -172,11 +167,9 @@ const getOptions = (
172
167
  };
173
168
  if (params.hiddenBack) {
174
169
  headerLeft = null;
175
- // options are static, so the window width is read once when they are built
176
- const { width } = Dimensions.get('window');
177
170
  options.headerTitleContainerStyle = {
178
171
  ...TITLE_CONTAINER_RESET,
179
- left: getHeaderRowInset(width),
172
+ left: HeaderBarMetrics.sidePadding,
180
173
  };
181
174
  }
182
175
  options = {
@@ -0,0 +1,227 @@
1
+ import React from 'react';
2
+ import { act, create, type ReactTestRenderer } from 'react-test-renderer';
3
+ import { useComponentCounts, useCountComponent } from '../hooks';
4
+
5
+ type Counts = Record<string, number>;
6
+
7
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
8
+ true;
9
+
10
+ let screenSeed = 0;
11
+ const nextScreen = () => {
12
+ screenSeed += 1;
13
+ return `screen-${screenSeed}`;
14
+ };
15
+
16
+ const Probe: React.FC<{ screen: string; name: string }> = ({
17
+ screen,
18
+ name,
19
+ }) => {
20
+ useCountComponent(screen, name);
21
+ return null;
22
+ };
23
+
24
+ const Reader: React.FC<{ screen: string; read: (counts: Counts) => void }> = ({
25
+ screen,
26
+ read,
27
+ }) => {
28
+ read(useComponentCounts(screen));
29
+ return null;
30
+ };
31
+
32
+ type Probes = { screen: string; name: string }[];
33
+
34
+ const mount = (watched: string, probes: Probes) => {
35
+ let latest: Counts = {};
36
+ const read = (counts: Counts) => {
37
+ latest = counts;
38
+ };
39
+ const tree = (list: Probes) => (
40
+ <>
41
+ <Reader screen={watched} read={read} />
42
+ {list.map((probe, index) => (
43
+ <Probe key={index} screen={probe.screen} name={probe.name} />
44
+ ))}
45
+ </>
46
+ );
47
+ let renderer: ReactTestRenderer | undefined;
48
+ act(() => {
49
+ renderer = create(tree(probes));
50
+ });
51
+ return {
52
+ counts: () => latest,
53
+ update: (list: Probes) => {
54
+ act(() => renderer?.update(tree(list)));
55
+ },
56
+ unmount: () => {
57
+ act(() => renderer?.unmount());
58
+ },
59
+ };
60
+ };
61
+
62
+ const same = (screen: string, name: string, size: number): Probes => {
63
+ return Array.from({ length: size }, () => ({ screen, name }));
64
+ };
65
+
66
+ describe('useCountComponent: counting mounts', () => {
67
+ it.each(Array.from({ length: 10 }, (_, index) => index + 1))(
68
+ 'counts %i mounted components of one type',
69
+ size => {
70
+ const screen = nextScreen();
71
+ const view = mount(screen, same(screen, 'Button', size));
72
+ expect(view.counts()).toEqual({ Button: size });
73
+ view.unmount();
74
+ },
75
+ );
76
+
77
+ it('reports nothing for a screen without components', () => {
78
+ const screen = nextScreen();
79
+ const view = mount(screen, []);
80
+ expect(view.counts()).toEqual({});
81
+ view.unmount();
82
+ });
83
+ });
84
+
85
+ describe('useCountComponent: unmount cleanup', () => {
86
+ it.each([1, 2, 3, 4, 5])('clears %i components on unmount', size => {
87
+ const screen = nextScreen();
88
+ const view = mount(screen, same(screen, 'Switch', size));
89
+ view.unmount();
90
+ const reader = mount(screen, []);
91
+ expect(reader.counts()).toEqual({});
92
+ reader.unmount();
93
+ });
94
+
95
+ it.each([2, 3, 4, 5])(
96
+ 'drops one of %i components when it is removed',
97
+ size => {
98
+ const screen = nextScreen();
99
+ const view = mount(screen, same(screen, 'Tag', size));
100
+ view.update(same(screen, 'Tag', size - 1));
101
+ expect(view.counts()).toEqual({ Tag: size - 1 });
102
+ view.unmount();
103
+ },
104
+ );
105
+
106
+ it('removes the entry instead of leaving a zero', () => {
107
+ const screen = nextScreen();
108
+ const view = mount(screen, same(screen, 'Tag', 1));
109
+ view.update([]);
110
+ expect(Object.keys(view.counts())).toEqual([]);
111
+ view.unmount();
112
+ });
113
+ });
114
+
115
+ describe('useCountComponent: grouping by type', () => {
116
+ it.each([
117
+ ['Button/Pay', 'Button'],
118
+ ['Button/Cancel', 'Button'],
119
+ ['Tag/Label', 'Tag'],
120
+ ['Input/Money/Amount', 'Input'],
121
+ ['Switch', 'Switch'],
122
+ ])('counts "%s" under "%s"', (name, type) => {
123
+ const screen = nextScreen();
124
+ const view = mount(screen, same(screen, name, 1));
125
+ expect(view.counts()).toEqual({ [type]: 1 });
126
+ view.unmount();
127
+ });
128
+
129
+ it.each([2, 3, 4, 5, 6])(
130
+ 'merges %i differently labelled buttons into one entry',
131
+ size => {
132
+ const screen = nextScreen();
133
+ const probes = Array.from({ length: size }, (_, index) => ({
134
+ screen,
135
+ name: `Button/Label ${index}`,
136
+ }));
137
+ const view = mount(screen, probes);
138
+ expect(view.counts()).toEqual({ Button: size });
139
+ view.unmount();
140
+ },
141
+ );
142
+
143
+ it('keeps the count when a label changes but the type does not', () => {
144
+ const screen = nextScreen();
145
+ const view = mount(screen, same(screen, 'Button/A', 2));
146
+ view.update(same(screen, 'Button/B', 2));
147
+ expect(view.counts()).toEqual({ Button: 2 });
148
+ view.unmount();
149
+ });
150
+
151
+ it('moves the count when the type changes', () => {
152
+ const screen = nextScreen();
153
+ const view = mount(screen, same(screen, 'Button/A', 1));
154
+ view.update(same(screen, 'Tag/A', 1));
155
+ expect(view.counts()).toEqual({ Tag: 1 });
156
+ view.unmount();
157
+ });
158
+ });
159
+
160
+ describe('useCountComponent: mixed types', () => {
161
+ const sizes = [0, 1, 2, 3];
162
+ const pairs = sizes.flatMap(buttons => sizes.map(tags => [buttons, tags]));
163
+
164
+ it.each(pairs)('%i buttons with %i tags', (buttons, tags) => {
165
+ const screen = nextScreen();
166
+ const probes = [
167
+ ...same(screen, 'Button/x', buttons),
168
+ ...same(screen, 'Tag/y', tags),
169
+ ];
170
+ const view = mount(screen, probes);
171
+ const expected: Counts = {};
172
+ if (buttons > 0) {
173
+ expected.Button = buttons;
174
+ }
175
+ if (tags > 0) {
176
+ expected.Tag = tags;
177
+ }
178
+ expect(view.counts()).toEqual(expected);
179
+ view.unmount();
180
+ });
181
+ });
182
+
183
+ describe('useCountComponent: screen isolation', () => {
184
+ it.each([1, 2, 3])('keeps %i other screens out of the count', others => {
185
+ const screen = nextScreen();
186
+ const probes = [
187
+ ...same(screen, 'Button', 2),
188
+ ...Array.from({ length: others }, () => ({
189
+ screen: nextScreen(),
190
+ name: 'Button',
191
+ })),
192
+ ];
193
+ const view = mount(screen, probes);
194
+ expect(view.counts()).toEqual({ Button: 2 });
195
+ view.unmount();
196
+ });
197
+
198
+ it('counts the same screen from separate roots together', () => {
199
+ const screen = nextScreen();
200
+ const first = mount(screen, same(screen, 'Tag', 1));
201
+ const second = mount(screen, same(screen, 'Tag', 2));
202
+ expect(second.counts()).toEqual({ Tag: 3 });
203
+ first.unmount();
204
+ second.unmount();
205
+ });
206
+ });
207
+
208
+ describe('useComponentCounts: snapshot stability', () => {
209
+ it('returns the same object between unrelated renders', () => {
210
+ const screen = nextScreen();
211
+ const seen: Counts[] = [];
212
+ const view = mount(screen, same(screen, 'Tag', 1));
213
+ seen.push(view.counts());
214
+ view.update(same(screen, 'Tag', 1));
215
+ seen.push(view.counts());
216
+ expect(seen[1]).toBe(seen[0]);
217
+ view.unmount();
218
+ });
219
+
220
+ it('returns a stable empty object for an unknown screen', () => {
221
+ const first = mount(nextScreen(), []);
222
+ const second = mount(nextScreen(), []);
223
+ expect(first.counts()).toBe(second.counts());
224
+ first.unmount();
225
+ second.unmount();
226
+ });
227
+ });
@@ -0,0 +1,249 @@
1
+ import {
2
+ type Fiber,
3
+ countViews,
4
+ getInstanceFiber,
5
+ getScopeRoot,
6
+ } from '../utils';
7
+
8
+ const HOST = 5;
9
+ const TEXT = 6;
10
+ const COMPOSITE = 0;
11
+ const KIT_CONTEXT = { name: 'ComponentContext' };
12
+ const OTHER_CONTEXT = { name: 'OtherContext' };
13
+
14
+ type Spec = {
15
+ tag?: number;
16
+ type?: unknown;
17
+ children?: Spec[];
18
+ capture?: (fiber: Fiber) => void;
19
+ };
20
+
21
+ const build = (spec: Spec, parent: Fiber | null = null): Fiber => {
22
+ const fiber: Fiber = {
23
+ tag: spec.tag ?? COMPOSITE,
24
+ type: spec.type ?? null,
25
+ child: null,
26
+ sibling: null,
27
+ return: parent,
28
+ alternate: null,
29
+ };
30
+ let previous: Fiber | null = null;
31
+ (spec.children ?? []).forEach(childSpec => {
32
+ const child = build(childSpec, fiber);
33
+ if (previous) {
34
+ previous.sibling = child;
35
+ } else {
36
+ fiber.child = child;
37
+ }
38
+ previous = child;
39
+ });
40
+ spec.capture?.(fiber);
41
+ return fiber;
42
+ };
43
+
44
+ const host = (...children: Spec[]): Spec => ({ tag: HOST, children });
45
+ const kit = (...children: Spec[]): Spec => ({
46
+ type: KIT_CONTEXT,
47
+ children,
48
+ });
49
+ const hosts = (count: number): Spec[] => {
50
+ return Array.from({ length: count }, () => host());
51
+ };
52
+ const root = (...children: Spec[]) => build(host(...children));
53
+ const count = (rootFiber: Fiber, skip: Fiber | null = null) => {
54
+ return countViews(rootFiber, KIT_CONTEXT, skip);
55
+ };
56
+
57
+ describe('countViews: flat host views', () => {
58
+ it.each(Array.from({ length: 21 }, (_, index) => index))(
59
+ 'counts %i sibling views as not kit',
60
+ size => {
61
+ expect(count(root(...hosts(size)))).toEqual({ total: size, kit: 0 });
62
+ },
63
+ );
64
+ });
65
+
66
+ describe('countViews: views inside a kit provider', () => {
67
+ it.each(Array.from({ length: 15 }, (_, index) => index + 1))(
68
+ 'counts %i views under one kit provider as kit',
69
+ size => {
70
+ expect(count(root(kit(...hosts(size))))).toEqual({
71
+ total: size,
72
+ kit: size,
73
+ });
74
+ },
75
+ );
76
+
77
+ it('recognises a provider exposing the context through _context', () => {
78
+ const provider: Spec = {
79
+ type: { _context: KIT_CONTEXT },
80
+ children: hosts(2),
81
+ };
82
+ expect(count(root(provider))).toEqual({ total: 2, kit: 2 });
83
+ });
84
+
85
+ it('recognises a provider that is the context itself', () => {
86
+ expect(count(root(kit(host(), host(), host())))).toEqual({
87
+ total: 3,
88
+ kit: 3,
89
+ });
90
+ });
91
+
92
+ it('ignores providers of another context', () => {
93
+ const other: Spec = { type: OTHER_CONTEXT, children: hosts(4) };
94
+ expect(count(root(other))).toEqual({ total: 4, kit: 0 });
95
+ });
96
+ });
97
+
98
+ describe('countViews: nesting depth', () => {
99
+ const chain = (depth: number): Spec => {
100
+ let spec = host();
101
+ for (let level = 1; level < depth; level += 1) {
102
+ spec = host(spec);
103
+ }
104
+ return spec;
105
+ };
106
+
107
+ it.each(Array.from({ length: 12 }, (_, index) => index + 1))(
108
+ 'counts a host chain %i levels deep',
109
+ depth => {
110
+ expect(count(root(chain(depth)))).toEqual({ total: depth, kit: 0 });
111
+ },
112
+ );
113
+
114
+ it('counts a kit subtree nested inside a kit subtree once per view', () => {
115
+ expect(count(root(kit(host(kit(host(host()))))))).toEqual({
116
+ total: 3,
117
+ kit: 3,
118
+ });
119
+ });
120
+ });
121
+
122
+ describe('countViews: kit and non-kit mix', () => {
123
+ const sizes = [0, 1, 2, 3];
124
+ const pairs = sizes.flatMap(plain => sizes.map(inKit => [plain, inKit]));
125
+
126
+ it.each(pairs)('%i plain views next to %i kit views', (plain, inKit) => {
127
+ const tree = root(...hosts(plain), kit(...hosts(inKit)));
128
+ expect(count(tree)).toEqual({ total: plain + inKit, kit: inKit });
129
+ });
130
+
131
+ it('keeps siblings after a kit subtree out of kit', () => {
132
+ expect(count(root(kit(host()), host()))).toEqual({ total: 2, kit: 1 });
133
+ });
134
+
135
+ it('counts a plain view that wraps a kit component', () => {
136
+ expect(count(root(host(kit(host()))))).toEqual({ total: 2, kit: 1 });
137
+ });
138
+ });
139
+
140
+ describe('countViews: tags that are not host views', () => {
141
+ it('ignores text instances', () => {
142
+ expect(count(root({ tag: TEXT }, host()))).toEqual({ total: 1, kit: 0 });
143
+ });
144
+
145
+ it('ignores composite wrappers but counts their host children', () => {
146
+ const wrapper: Spec = { tag: COMPOSITE, children: hosts(2) };
147
+ expect(count(root(wrapper))).toEqual({ total: 2, kit: 0 });
148
+ });
149
+
150
+ it('returns zero for an empty root', () => {
151
+ expect(count(root())).toEqual({ total: 0, kit: 0 });
152
+ });
153
+ });
154
+
155
+ describe('countViews: skipped subtree', () => {
156
+ it.each([0, 1, 2, 3, 4])('skips a subtree with %i descendants', size => {
157
+ let skipped: Fiber | null = null;
158
+ const badge: Spec = {
159
+ tag: HOST,
160
+ children: hosts(size),
161
+ capture: fiber => {
162
+ skipped = fiber;
163
+ },
164
+ };
165
+ const tree = root(host(), badge, host());
166
+ expect(count(tree, skipped)).toEqual({ total: 2, kit: 0 });
167
+ });
168
+
169
+ it('skips a fiber through its alternate', () => {
170
+ let skipped: Fiber | null = null;
171
+ const badge: Spec = {
172
+ tag: HOST,
173
+ children: hosts(2),
174
+ capture: fiber => {
175
+ skipped = fiber;
176
+ },
177
+ };
178
+ const tree = root(host(), badge);
179
+ const current = tree.child?.sibling as Fiber;
180
+ const alternate = { ...current, alternate: skipped };
181
+ tree.child!.sibling = alternate;
182
+ expect(count(tree, skipped)).toEqual({ total: 1, kit: 0 });
183
+ });
184
+
185
+ it('counts everything when nothing is skipped', () => {
186
+ expect(count(root(host(), host(host())), null)).toEqual({
187
+ total: 3,
188
+ kit: 0,
189
+ });
190
+ });
191
+ });
192
+
193
+ describe('getInstanceFiber', () => {
194
+ const fiber = build(host());
195
+ const devFiber = build(host());
196
+
197
+ it('returns null for null', () => {
198
+ expect(getInstanceFiber(null)).toBeNull();
199
+ });
200
+
201
+ it('returns null for an object without a handle', () => {
202
+ expect(getInstanceFiber({})).toBeNull();
203
+ });
204
+
205
+ it('reads __internalInstanceHandle', () => {
206
+ expect(getInstanceFiber({ __internalInstanceHandle: fiber })).toBe(fiber);
207
+ });
208
+
209
+ it('falls back to the dev handle', () => {
210
+ const owner = { _internalFiberInstanceHandleDEV: devFiber };
211
+ expect(getInstanceFiber(owner)).toBe(devFiber);
212
+ });
213
+
214
+ it('prefers __internalInstanceHandle over the dev handle', () => {
215
+ const owner = {
216
+ __internalInstanceHandle: fiber,
217
+ _internalFiberInstanceHandleDEV: devFiber,
218
+ };
219
+ expect(getInstanceFiber(owner)).toBe(fiber);
220
+ });
221
+ });
222
+
223
+ describe('getScopeRoot', () => {
224
+ it('returns null for null', () => {
225
+ expect(getScopeRoot(null)).toBeNull();
226
+ });
227
+
228
+ it('returns null when there is no host ancestor', () => {
229
+ const tree = build({ children: [{ children: [{}] }] });
230
+ expect(getScopeRoot(tree.child?.child ?? null)).toBeNull();
231
+ });
232
+
233
+ it('returns the direct host parent', () => {
234
+ const tree = build(host(host()));
235
+ expect(getScopeRoot(tree.child)).toBe(tree);
236
+ });
237
+
238
+ it('skips composite parents up to the nearest host', () => {
239
+ const tree = build(host({ children: [{ children: [host()] }] }));
240
+ const leaf = tree.child?.child?.child ?? null;
241
+ expect(getScopeRoot(leaf)).toBe(tree);
242
+ });
243
+
244
+ it('returns the nearest host, not the topmost', () => {
245
+ const tree = build(host(host(host())));
246
+ const leaf = tree.child?.child ?? null;
247
+ expect(getScopeRoot(leaf)).toBe(tree.child);
248
+ });
249
+ });
@@ -0,0 +1,44 @@
1
+ import { useEffect, useSyncExternalStore } from 'react';
2
+
3
+ type Counts = Record<string, number>;
4
+ type Snapshot = Record<string, Counts>;
5
+
6
+ const EMPTY_COUNTS: Counts = {};
7
+ const listeners = new Set<() => void>();
8
+ let snapshot: Snapshot = {};
9
+
10
+ const changeCount = (screenName: string, componentName: string, delta: number) => {
11
+ const current = snapshot[screenName] ?? EMPTY_COUNTS;
12
+ const value = (current[componentName] ?? 0) + delta;
13
+ const nextScreen = { ...current, [componentName]: value };
14
+ if (value <= 0) {
15
+ delete nextScreen[componentName];
16
+ }
17
+ snapshot = { ...snapshot, [screenName]: nextScreen };
18
+ listeners.forEach(listener => listener());
19
+ };
20
+
21
+ const subscribe = (listener: () => void) => {
22
+ listeners.add(listener);
23
+ return () => {
24
+ listeners.delete(listener);
25
+ };
26
+ };
27
+
28
+ /** Registers one mounted kit component under its screen, removed on unmount. */
29
+ const useCountComponent = (screenName: string, componentName: string) => {
30
+ useEffect(() => {
31
+ const type = componentName.split('/')[0];
32
+ changeCount(screenName, type, 1);
33
+ return () => changeCount(screenName, type, -1);
34
+ }, [screenName, componentName]);
35
+ };
36
+
37
+ /** Live per-component counts of the kit components mounted on a screen. */
38
+ const useComponentCounts = (screenName: string): Counts => {
39
+ return useSyncExternalStore(subscribe, () => {
40
+ return snapshot[screenName] ?? EMPTY_COUNTS;
41
+ });
42
+ };
43
+
44
+ export { useCountComponent, useComponentCounts };
@@ -0,0 +1,57 @@
1
+ import React, { FC, useContext, useEffect, useRef, useState } from 'react';
2
+ import { Text, TouchableOpacity, View } from 'react-native';
3
+ import { ComponentContext, ScreenContext } from '../Context';
4
+ import { useComponentCounts } from './hooks';
5
+ import {
6
+ type ViewCounts,
7
+ countViews,
8
+ getInstanceFiber,
9
+ getScopeRoot,
10
+ } from './utils';
11
+ import styles from './styles';
12
+
13
+ /** Floating badge with the kit components and native views on this screen. */
14
+ const ComponentCounterBadge: FC = () => {
15
+ const screen = useContext<any>(ScreenContext);
16
+ const counts = useComponentCounts(screen.screenName ?? 'unknown');
17
+ const [isExpanded, setExpanded] = useState(false);
18
+ const [views, setViews] = useState<ViewCounts>({ total: 0, kit: 0 });
19
+ const containerRef = useRef<View>(null);
20
+
21
+ const scanViews = () => {
22
+ const self = getInstanceFiber(containerRef.current);
23
+ const root = getScopeRoot(self);
24
+ if (root) {
25
+ setViews(countViews(root, ComponentContext, self));
26
+ }
27
+ };
28
+
29
+ useEffect(scanViews, [counts, isExpanded]);
30
+
31
+ const entries = Object.entries(counts).sort((a, b) => b[1] - a[1]);
32
+ const total = entries.reduce((sum, [, count]) => sum + count, 0);
33
+
34
+ return (
35
+ <View ref={containerRef} style={styles.container} pointerEvents="box-none">
36
+ <TouchableOpacity
37
+ style={styles.badge}
38
+ onPress={() => {
39
+ scanViews();
40
+ setExpanded(!isExpanded);
41
+ }}>
42
+ <Text style={styles.title}>{`Views: ${views.total}`}</Text>
43
+ <Text style={styles.row}>{`In kit: ${views.kit}`}</Text>
44
+ <Text style={styles.row}>
45
+ {`Not kit: ${views.total - views.kit}`}
46
+ </Text>
47
+ <Text style={styles.title}>{`Kit components: ${total}`}</Text>
48
+ {isExpanded &&
49
+ entries.map(([name, count]) => (
50
+ <Text key={name} style={styles.row}>{`${name}: ${count}`}</Text>
51
+ ))}
52
+ </TouchableOpacity>
53
+ </View>
54
+ );
55
+ };
56
+
57
+ export { ComponentCounterBadge };
@@ -0,0 +1,25 @@
1
+ import { StyleSheet } from 'react-native';
2
+ import { Colors, Radius, Spacing } from '../Consts';
3
+
4
+ export default StyleSheet.create({
5
+ container: {
6
+ position: 'absolute',
7
+ right: Spacing.M,
8
+ bottom: Spacing.Size3XL,
9
+ alignItems: 'flex-end',
10
+ },
11
+ badge: {
12
+ backgroundColor: Colors.black_17,
13
+ borderRadius: Radius.S,
14
+ paddingHorizontal: Spacing.M,
15
+ paddingVertical: Spacing.S,
16
+ },
17
+ title: {
18
+ color: Colors.black_01,
19
+ fontWeight: '600',
20
+ },
21
+ row: {
22
+ color: Colors.black_01,
23
+ marginTop: Spacing.XXS,
24
+ },
25
+ });
@@ -0,0 +1,73 @@
1
+ type Fiber = {
2
+ tag: number;
3
+ type: unknown;
4
+ child: Fiber | null;
5
+ sibling: Fiber | null;
6
+ return: Fiber | null;
7
+ alternate: Fiber | null;
8
+ };
9
+
10
+ type FiberOwner = {
11
+ __internalInstanceHandle?: Fiber;
12
+ _internalFiberInstanceHandleDEV?: Fiber;
13
+ };
14
+
15
+ type ViewCounts = { total: number; kit: number };
16
+
17
+ const HOST_COMPONENT_TAG = 5;
18
+
19
+ const getInstanceFiber = (instance: unknown): Fiber | null => {
20
+ const owner = instance as FiberOwner | null;
21
+ const fiber = owner?.__internalInstanceHandle;
22
+ return fiber ?? owner?._internalFiberInstanceHandleDEV ?? null;
23
+ };
24
+
25
+ const getScopeRoot = (fiber: Fiber | null): Fiber | null => {
26
+ let node = fiber?.return ?? null;
27
+ while (node && node.tag !== HOST_COMPONENT_TAG) {
28
+ node = node.return;
29
+ }
30
+ return node;
31
+ };
32
+
33
+ const isProviderOf = (fiber: Fiber, context: unknown) => {
34
+ const providerContext = (fiber.type as { _context?: unknown })?._context;
35
+ return fiber.type === context || providerContext === context;
36
+ };
37
+
38
+ const isSkipped = (fiber: Fiber, skip: Fiber | null) => {
39
+ return !!skip && (fiber === skip || fiber.alternate === skip);
40
+ };
41
+
42
+ /**
43
+ * Native views under `root`, ignoring the `skip` subtree. Views below a
44
+ * `context` provider (the one every kit component wraps itself in) count as kit.
45
+ */
46
+ const countViews = (
47
+ root: Fiber,
48
+ context: unknown,
49
+ skip: Fiber | null,
50
+ ): ViewCounts => {
51
+ const counts: ViewCounts = { total: 0, kit: 0 };
52
+
53
+ const visit = (first: Fiber | null, isInKit: boolean) => {
54
+ let node = first;
55
+ while (node) {
56
+ if (!isSkipped(node, skip)) {
57
+ const isKit = isInKit || isProviderOf(node, context);
58
+ if (node.tag === HOST_COMPONENT_TAG) {
59
+ counts.total += 1;
60
+ counts.kit += isKit ? 1 : 0;
61
+ }
62
+ visit(node.child, isKit);
63
+ }
64
+ node = node.sibling;
65
+ }
66
+ };
67
+
68
+ visit(root.child, false);
69
+ return counts;
70
+ };
71
+
72
+ export type { Fiber, ViewCounts };
73
+ export { getInstanceFiber, getScopeRoot, countViews };
@@ -13,11 +13,8 @@ import {
13
13
  SearchHeader,
14
14
  } from '../Application';
15
15
  import { DuoGlassBackground } from '../Application/Components/DuoGlassBackground';
16
- import {
17
- getHeaderRowInset,
18
- type HeaderContentLayout,
19
- TITLE_CONTAINER_RESET,
20
- } from '../Application/headerLayout';
16
+ import { type HeaderContentLayout } from '../Application/headerLayout';
17
+ import { getHeaderMargin } from './utils';
21
18
  import { useHeaderBarOptions } from './useHeaderBarOptions';
22
19
  import { HeaderType } from './types';
23
20
 
@@ -245,11 +242,10 @@ export const useScreenHeader = ({
245
242
  // the search field spans the content, clear of the side bar and status bar
246
243
  // clusters; kept as numbers so the setter below stays stable
247
244
  let searchWidth = layout.width - Spacing.M * 2;
248
- // past back, or at the row start when back is hidden or floats in the side bar
249
- const rowStartLeft = getHeaderRowInset(layout.width);
250
- const searchLeft = layout.sideBar ? rowStartLeft : Spacing.M;
245
+ let searchLeft = Spacing.M;
251
246
  if (layout.sideBar) {
252
247
  searchWidth = layout.contentWidth - Spacing.M * 2;
248
+ searchLeft = Spacing.M - getHeaderMargin(layout.width);
253
249
  }
254
250
  const clearance = layout.statusBarClearance;
255
251
  if (clearance) {
@@ -263,18 +259,25 @@ export const useScreenHeader = ({
263
259
  const setSearchHeader = useCallback(
264
260
  (params: SearchHeaderProps) => {
265
261
  searchHeaderParams.current = params;
266
- const hasBack = !params?.hiddenBack;
267
262
  const options: StackNavigationOptions = {
268
263
  ...searchOptions,
269
264
  headerRight: undefined,
270
265
  headerTitleContainerStyle: {
271
- ...TITLE_CONTAINER_RESET,
272
266
  width: searchWidth,
273
267
  maxWidth: searchWidth,
274
- left: hasBack ? searchLeft : rowStartLeft,
268
+ marginLeft: 0,
269
+ marginEnd: 0,
270
+ marginStart: 0,
271
+ marginHorizontal: 0,
272
+ marginVertical: 0,
273
+ margin: 0,
274
+ left: searchLeft,
275
275
  },
276
276
  headerLeft: (props: any) => {
277
- return hasBack && <HeaderLeft {...props} floating />;
277
+ if (params?.hiddenBack) {
278
+ return null;
279
+ }
280
+ return <HeaderLeft {...props} floating />;
278
281
  },
279
282
  headerTitle: () => (
280
283
  <SearchHeader {...params} animatedValue={sharedValue} />
@@ -283,14 +286,7 @@ export const useScreenHeader = ({
283
286
 
284
287
  navigation?.instance?.setOptions(options);
285
288
  },
286
- [
287
- navigation?.instance,
288
- sharedValue,
289
- searchOptions,
290
- searchWidth,
291
- searchLeft,
292
- rowStartLeft,
293
- ],
289
+ [navigation?.instance, sharedValue, searchOptions, searchWidth, searchLeft],
294
290
  );
295
291
 
296
292
  useEffect(() => {
package/index.ts CHANGED
@@ -13,6 +13,7 @@ export * from './Text';
13
13
  export * from './Text/types';
14
14
  export * from './Button';
15
15
  export * from './Application';
16
+ export * from './ComponentCounter';
16
17
  export * from './Application/types';
17
18
  export * from './Icon';
18
19
  export * from './Icon/types';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@momo-kits/foundation",
3
- "version": "0.169.19-beta.3",
3
+ "version": "0.169.19-beta.5",
4
4
  "description": "React Native Component Kits",
5
5
  "main": "index.ts",
6
6
  "scripts": {},