@momo-kits/foundation 0.169.4-beta.7 → 0.169.4-beta.8

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.
@@ -18,6 +18,7 @@ import Animated, {
18
18
  } from 'react-native-reanimated';
19
19
  import { scheduleOnRN } from 'react-native-worklets';
20
20
  import { DUO_ORIENTATIONS, styles } from './BottomSheet.styles';
21
+ import { AdoptionProbe } from './KitAdoption';
21
22
  import {
22
23
  useBottomSheetLayout,
23
24
  useDuoKeyboardLift,
@@ -173,11 +174,16 @@ const BottomSheet: React.FC<BottomSheetParams> = props => {
173
174
  );
174
175
 
175
176
  const screen = (
176
- <Screen
177
- {...props}
178
- {...props.route.params}
179
- onRequestClose={onRequestClose}
180
- />
177
+ <AdoptionProbe
178
+ screenName={Screen?.name || 'Invalid'}
179
+ navigation={props.navigation}
180
+ >
181
+ <Screen
182
+ {...props}
183
+ {...props.route.params}
184
+ onRequestClose={onRequestClose}
185
+ />
186
+ </AdoptionProbe>
181
187
  );
182
188
 
183
189
  return (
@@ -46,9 +46,6 @@ export const styles = StyleSheet.create({
46
46
  width: TabBarMetrics.ctaSize,
47
47
  height: TabBarMetrics.ctaSize,
48
48
  borderRadius: TabBarMetrics.ctaSize / 2,
49
- // Figma Icon Button border: white 60% hairline
50
- borderWidth: 1,
51
- borderColor: `rgba(255, 255, 255, ${TabBarMetrics.ctaBorderOpacity})`,
52
49
  alignItems: 'center',
53
50
  justifyContent: 'center',
54
51
  },
@@ -17,7 +17,7 @@ import { CurvedContainer } from './CurvedContainer';
17
17
  import { ActiveIndicator } from './ActiveIndicator';
18
18
  import { getHorizontalBarWidth, TabBarMetrics, TabBarMotion } from './metrics';
19
19
  import { getTabItems, TabItem } from './tabItems';
20
- import { CappedScaleText } from './TabBarIcon';
20
+ import { FixedScaleText } from './TabBarIcon';
21
21
  import { styles } from './BottomTabBar.styles';
22
22
 
23
23
  type Props = BottomTabBarProps & {
@@ -114,7 +114,7 @@ const CenterAction: React.FC<{
114
114
  </Animated.View>
115
115
  <View style={styles.ctaLabel}>
116
116
  {fixedFontScale ? (
117
- <CappedScaleText>{labelText}</CappedScaleText>
117
+ <FixedScaleText>{labelText}</FixedScaleText>
118
118
  ) : (
119
119
  labelText
120
120
  )}
@@ -194,17 +194,21 @@ const HorizontalTabBar: React.FC<{
194
194
  return renderItems(items);
195
195
  };
196
196
 
197
+ const customContainer = withCta && floatingButton?.container;
198
+
197
199
  return (
198
200
  <View
199
201
  style={[styles.container, { width }]}
200
202
  accessibilityLabel={'bottom_tab_bar'}
201
203
  >
202
- <CurvedContainer
203
- width={width}
204
- height={TabBarMetrics.height}
205
- radius={TabBarMetrics.height / 2}
206
- notchCenterX={withCta ? width / 2 : undefined}
207
- />
204
+ {customContainer || (
205
+ <CurvedContainer
206
+ width={width}
207
+ height={TabBarMetrics.height}
208
+ radius={TabBarMetrics.height / 2}
209
+ notchCenterX={withCta ? width / 2 : undefined}
210
+ />
211
+ )}
208
212
  <View style={styles.content}>
209
213
  <ActiveIndicator
210
214
  axis={'x'}
@@ -237,8 +241,6 @@ export default function BottomTabBar(props: Props) {
237
241
  window.height,
238
242
  insets.left,
239
243
  insets.right,
240
- state.routes.length,
241
- withCta,
242
244
  );
243
245
 
244
246
  return (
@@ -256,7 +258,6 @@ export default function BottomTabBar(props: Props) {
256
258
  ]}
257
259
  >
258
260
  <HorizontalTabBar
259
- fixedFontScale
260
261
  items={getTabItems(props)}
261
262
  width={width}
262
263
  floatingButton={floatingButton}
@@ -3,7 +3,7 @@ import { StyleSheet } from 'react-native';
3
3
  import Svg, { Defs, FeGaussianBlur, Filter, Path } from 'react-native-svg';
4
4
  import { Colors } from '../../Consts';
5
5
  import { ApplicationContext } from '../../Context';
6
- import { NOTCH_CURVES, NOTCH_HALF_WIDTH, TabBarMetrics } from './metrics';
6
+ import { NOTCH_CURVES, NOTCH_HALF_WIDTH } from './metrics';
7
7
 
8
8
  type Props = {
9
9
  width: number;
@@ -137,13 +137,7 @@ const CurvedContainer: React.FC<Props> = ({
137
137
  filter={'url(#keyShadow)'}
138
138
  />
139
139
  )}
140
- <Path
141
- d={path}
142
- fill={theme.colors.background.surface}
143
- fillOpacity={TabBarMetrics.backgroundOpacity}
144
- stroke={theme.colors.border.default}
145
- strokeWidth={1}
146
- />
140
+ <Path d={path} fill={theme.colors.background.surface} />
147
141
  </Svg>
148
142
  );
149
143
  };
@@ -10,10 +10,10 @@ import Animated, {
10
10
  useSharedValue,
11
11
  withTiming,
12
12
  } from 'react-native-reanimated';
13
- import { CappedScaleText, TabBarIcon } from './TabBarIcon';
13
+ import { FixedScaleText, TabBarIcon } from './TabBarIcon';
14
14
  import { Text } from '../../Text';
15
15
  import { MiniAppContext } from '../../Context';
16
- import { Colors } from '../../Consts';
16
+ import { Colors, Spacing } from '../../Consts';
17
17
  import { TabBarMetrics, TabBarMotion } from './metrics';
18
18
 
19
19
  type IconRenderer = (props: {
@@ -98,7 +98,7 @@ const TabItemContent: React.FC<TabItemContentProps> = ({
98
98
  />
99
99
  </View>
100
100
  {!hideLabel &&
101
- (fixedFontScale ? <CappedScaleText>{text}</CappedScaleText> : text)}
101
+ (fixedFontScale ? <FixedScaleText>{text}</FixedScaleText> : text)}
102
102
  </>
103
103
  );
104
104
  };
@@ -147,7 +147,7 @@ const styles = StyleSheet.create({
147
147
  minWidth: 1,
148
148
  alignItems: 'center',
149
149
  justifyContent: 'center',
150
- gap: TabBarMetrics.itemIconLabelGap,
150
+ gap: Spacing.XXS,
151
151
  },
152
152
  slot: {
153
153
  height: TabBarMetrics.indicatorHeight,
@@ -166,11 +166,6 @@ const styles = StyleSheet.create({
166
166
  },
167
167
  labelBox: {
168
168
  alignSelf: 'stretch',
169
- // fixed to the design line height so a capped-scale label overflows downward and the
170
- // icon above it stays put
171
- height: TabBarMetrics.labelHeight,
172
- justifyContent: 'flex-start',
173
- overflow: 'visible',
174
169
  },
175
170
  label: {
176
171
  textAlign: 'center',
@@ -13,7 +13,7 @@ import { TabItemContent } from './CustomBottomTabItem';
13
13
  import { CurvedContainer } from './CurvedContainer';
14
14
  import { TabBarMetrics } from './metrics';
15
15
  import { getTabItems, TabItem } from './tabItems';
16
- import { CappedScaleText } from './TabBarIcon';
16
+ import { FixedScaleText } from './TabBarIcon';
17
17
  import { usePressLift } from './usePressLift';
18
18
  import { ActiveIndicator } from './ActiveIndicator';
19
19
  import {
@@ -116,7 +116,7 @@ const RailCenterAction: React.FC<{ floatingButton: FloatingButtonProps }> = ({
116
116
  <CtaIcon icon={floatingButton.icon} />
117
117
  </Animated.View>
118
118
  <View style={styles.railCtaLabel}>
119
- <CappedScaleText>
119
+ <FixedScaleText>
120
120
  <Text
121
121
  numberOfLines={1}
122
122
  typography={'label_xs_medium'}
@@ -124,7 +124,7 @@ const RailCenterAction: React.FC<{ floatingButton: FloatingButtonProps }> = ({
124
124
  >
125
125
  {floatingButton.label}
126
126
  </Text>
127
- </CappedScaleText>
127
+ </FixedScaleText>
128
128
  {floatingButton.labelContent && (
129
129
  <View pointerEvents={'none'} style={styles.railCtaLabelOverlay}>
130
130
  {floatingButton.labelContent}
@@ -3,11 +3,7 @@ import React from 'react';
3
3
  import { useWindowDimensions, View } from 'react-native';
4
4
  import { useScreenLayout } from '../../Layout/utils';
5
5
  import { FloatingButtonProps } from '../types';
6
- import {
7
- getSystemIndicatorHeight,
8
- hasCenterAction,
9
- HorizontalTabBar,
10
- } from './BottomTabBar';
6
+ import { getSystemIndicatorHeight, HorizontalTabBar } from './BottomTabBar';
11
7
  import { getHorizontalBarWidth, TabBarMetrics } from './metrics';
12
8
  import { getTabItems } from './tabItems';
13
9
  import { DuoRailTabBar } from './DuoRailTabBar';
@@ -38,7 +34,6 @@ const DuoFloatingTabBar: React.FC<DuoTabBarProps> = props => {
38
34
  const { insets } = useScreenLayout();
39
35
  const { width, height } = useWindowDimensions();
40
36
  const { floatingButton, activeTintColor, inactiveTintColor } = props;
41
- const tabItems = getTabItems(props);
42
37
 
43
38
  return (
44
39
  <View
@@ -50,15 +45,8 @@ const DuoFloatingTabBar: React.FC<DuoTabBarProps> = props => {
50
45
  >
51
46
  <HorizontalTabBar
52
47
  fixedFontScale
53
- items={tabItems}
54
- width={getHorizontalBarWidth(
55
- width,
56
- height,
57
- insets.left,
58
- insets.right,
59
- tabItems.length,
60
- hasCenterAction(floatingButton, tabItems.length),
61
- )}
48
+ items={getTabItems(props)}
49
+ width={getHorizontalBarWidth(width, height, insets.left, insets.right)}
62
50
  floatingButton={floatingButton}
63
51
  activeTintColor={activeTintColor}
64
52
  inactiveTintColor={inactiveTintColor}
@@ -71,30 +71,6 @@ export const FixedScaleText: React.FC<{ children: React.ReactNode }> = ({
71
71
  );
72
72
  };
73
73
 
74
- // the tab labels follow the OS/host font scale but never grow past this, so the fixed-height
75
- // container and the notch stay aligned
76
- const TAB_LABEL_MAX_SCALE = 1.2;
77
-
78
- /**
79
- * caps the label scale at `TAB_LABEL_MAX_SCALE`: it keeps following the host/OS font scale but
80
- * stops growing past 1.2× so it fits the fixed bar geometry
81
- */
82
- export const CappedScaleText: React.FC<{ children: React.ReactNode }> = ({
83
- children,
84
- }) => {
85
- const context = useContext<any>(MiniAppContext);
86
- return (
87
- <MiniAppContext.Provider
88
- value={{
89
- ...context,
90
- fontScale: { ...context?.fontScale, maxScaleRate: TAB_LABEL_MAX_SCALE },
91
- }}
92
- >
93
- {children}
94
- </MiniAppContext.Provider>
95
- );
96
- };
97
-
98
74
  /**
99
75
  * numbers use the error color, text the warning color (Figma Badge round numeric / text)
100
76
  */
@@ -9,36 +9,23 @@ import { Colors, Radius, Spacing } from '../../Consts';
9
9
  * - vertical: iPhone Duo rail, center action under the container
10
10
  */
11
11
  const TabBarMetrics = {
12
- height: 60,
12
+ height: 68,
13
13
  margin: Spacing.S,
14
- paddingVertical: Spacing.XS,
14
+ paddingVertical: Spacing.S,
15
15
  paddingHorizontal: Spacing.M,
16
- itemGap: 1,
17
- // gap between the icon slot and the label inside a tab (Figma: none)
18
- itemIconLabelGap: 0,
19
- // .Nav/Background: no backdrop blur, so use the Figma Blur=Off spec (opacity 95%, no blur) plus the 1px
20
- // border — nearly solid, matching the frosted sample; surface keeps dark-mode support
21
- backgroundOpacity: 0.95,
22
- // white 60% hairline around the center action button (Figma Icon Button border)
23
- ctaBorderOpacity: 0.6,
16
+ itemGap: Spacing.XS,
24
17
  iconSize: 24,
25
18
  // active indicator behind the icon: 24 icon + XS·M padding
26
19
  indicatorPaddingVertical: Spacing.XS,
27
20
  indicatorPaddingHorizontal: Spacing.M,
28
21
  indicatorRadius: Radius.XL,
29
22
  indicatorHeight: 32,
30
- // label_s_medium line height: the label box keeps this height so a scaled label grows
31
- // downward instead of pushing the icon up
32
- labelHeight: 18,
33
23
  // home indicator / gesture bar area under the container
34
24
  systemIndicatorHeight: 24,
35
25
  // unfolded foldables (short side from 600, the smallest in the spec) use 65% of the short
36
26
  // side, centered; phones and folded outer displays fill the window
37
27
  foldableMinShortSide: 600,
38
28
  foldableWidthRatio: 0.65,
39
- // a 2-tab bar doesn't stretch to the full width: each item is this fixed width and the bar is
40
- // sized to its content, centered (Figma Navigation · 2 Tab: item 100, bar ~225)
41
- twoTabItemWidth: 100,
42
29
  ctaSlotWidth: 92,
43
30
  ctaSize: 48,
44
31
  // the icon sits 10 inside the 48 button (prototype .cta: 28 icon), 12 inside the 52 rail one
@@ -149,17 +136,7 @@ const getHorizontalBarWidth = (
149
136
  height: number,
150
137
  insetLeft: number,
151
138
  insetRight: number,
152
- itemCount: number,
153
- hasCta: boolean,
154
139
  ) => {
155
- // 2 tabs (no center action) stay content-sized and centered instead of filling the window
156
- if (itemCount === 2 && !hasCta) {
157
- return (
158
- TabBarMetrics.twoTabItemWidth * 2 +
159
- TabBarMetrics.paddingHorizontal * 2 +
160
- TabBarMetrics.itemGap
161
- );
162
- }
163
140
  const shortSide = Math.min(width, height);
164
141
  if (shortSide >= TabBarMetrics.foldableMinShortSide) {
165
142
  return shortSide * TabBarMetrics.foldableWidthRatio;
@@ -0,0 +1,119 @@
1
+ import React, { useState, useSyncExternalStore } from 'react';
2
+ import { Share, TouchableOpacity, View } from 'react-native';
3
+ import { useSafeAreaInsets } from 'react-native-safe-area-context';
4
+
5
+ import { Colors, Spacing } from '../../Consts';
6
+ import { Text } from '../../Text';
7
+ import { adoptionStore } from './AdoptionStore';
8
+ import { styles } from './styles';
9
+ import type { ScreenSnapshot } from './types';
10
+
11
+ /** Subscribes a React listener to the adoption store. Stable identity for useSyncExternalStore. */
12
+ const subscribeToStore = (listener: () => void): (() => void) =>
13
+ adoptionStore.subscribe(listener);
14
+
15
+ const getLatestSnapshot = (): ScreenSnapshot | undefined =>
16
+ adoptionStore.getLatest();
17
+
18
+ const getScreenCount = (): number => adoptionStore.getAll().length;
19
+
20
+ /** Share of classified nodes that are app-authored kit: K / (K + R + O). */
21
+ const getAdoptionRate = (snapshot: ScreenSnapshot): number => {
22
+ const { K, R, O } = snapshot.counts;
23
+ const total = K + R + O;
24
+ return total === 0 ? 0 : K / total;
25
+ };
26
+
27
+ const formatSummary = (snapshot: ScreenSnapshot | undefined): string => {
28
+ if (!snapshot) return 'Kit adoption: chưa có dữ liệu';
29
+ const { K, R, O } = snapshot.counts;
30
+ const percent = Math.round(getAdoptionRate(snapshot) * 100);
31
+ return `Kit ${percent}% · K${K} R${R} O${O}`;
32
+ };
33
+
34
+ const handleRemeasure = (): void => {
35
+ adoptionStore.remeasureActive();
36
+ };
37
+
38
+ const handleShare = (): void => {
39
+ Share.share({ message: JSON.stringify(adoptionStore.getAll()) }).catch(
40
+ () => undefined,
41
+ );
42
+ };
43
+
44
+ const handleClear = (): void => {
45
+ adoptionStore.clear();
46
+ };
47
+
48
+ /**
49
+ * Dev-only floating badge showing the latest screen's kit adoption. Tap to
50
+ * expand actions (re-measure, share JSON, clear). Renders nothing in release builds.
51
+ */
52
+ const AdoptionBadge: React.FC = () => {
53
+ const insets = useSafeAreaInsets();
54
+ const [isExpanded, setExpanded] = useState(false);
55
+ const latest = useSyncExternalStore(subscribeToStore, getLatestSnapshot);
56
+ const screenCount = useSyncExternalStore(subscribeToStore, getScreenCount);
57
+
58
+ if (!__DEV__) return null;
59
+
60
+ const handleToggle = (): void => setExpanded(prev => !prev);
61
+
62
+ return (
63
+ <View
64
+ pointerEvents="box-none"
65
+ style={[styles.wrapper, { top: insets.top + Spacing.S }]}
66
+ >
67
+ <TouchableOpacity
68
+ accessibilityRole="button"
69
+ onPress={handleToggle}
70
+ style={styles.badge}
71
+ >
72
+ <Text typography="label_xs_medium" color={Colors.black_01}>
73
+ {formatSummary(latest)}
74
+ </Text>
75
+ {latest ? (
76
+ <Text typography="description_xs_regular" color={Colors.black_01}>
77
+ {latest.screen_name}
78
+ </Text>
79
+ ) : null}
80
+ </TouchableOpacity>
81
+ {isExpanded ? (
82
+ <View style={styles.panel}>
83
+ <Text typography="label_xs_medium" color={Colors.black_17}>
84
+ {`Đã đo ${screenCount} màn hình`}
85
+ </Text>
86
+ <TouchableOpacity
87
+ accessibilityRole="button"
88
+ onPress={handleRemeasure}
89
+ style={styles.action}
90
+ >
91
+ <Text typography="label_xs_medium" color={Colors.blue_03}>
92
+ Đo lại
93
+ </Text>
94
+ </TouchableOpacity>
95
+ <TouchableOpacity
96
+ accessibilityRole="button"
97
+ onPress={handleShare}
98
+ style={styles.action}
99
+ >
100
+ <Text typography="label_xs_medium" color={Colors.blue_03}>
101
+ Share JSON
102
+ </Text>
103
+ </TouchableOpacity>
104
+ <TouchableOpacity
105
+ accessibilityRole="button"
106
+ onPress={handleClear}
107
+ style={styles.actionOutline}
108
+ >
109
+ <Text typography="label_xs_medium" color={Colors.black_17}>
110
+ Xoá
111
+ </Text>
112
+ </TouchableOpacity>
113
+ </View>
114
+ ) : null}
115
+ </View>
116
+ );
117
+ };
118
+
119
+ export { AdoptionBadge };
@@ -0,0 +1,145 @@
1
+ import React from 'react';
2
+ import { InteractionManager, Platform } from 'react-native';
3
+
4
+ import { MiniAppContext } from '../../Context';
5
+ import { adoptionStore } from './AdoptionStore';
6
+ import { SETTLE_MS } from './constants';
7
+ import type {
8
+ FiberLike,
9
+ KitRegistries,
10
+ ScreenSnapshot,
11
+ WalkResult,
12
+ } from './types';
13
+ import {
14
+ createRegistries,
15
+ getAppId,
16
+ getCurrentFiber,
17
+ walkScreen,
18
+ } from './utils';
19
+
20
+ type NavigationLike = {
21
+ addListener?: (event: string, callback: () => void) => () => void;
22
+ };
23
+
24
+ type ProbeProps = {
25
+ screenName: string;
26
+ navigation?: NavigationLike;
27
+ children: React.ReactNode;
28
+ };
29
+
30
+ let registriesCache: KitRegistries | undefined;
31
+
32
+ /**
33
+ * Kit and RN identity sets, built on first use. Lazy require breaks the cycle
34
+ * between the foundation index and the Application screens that render this probe.
35
+ */
36
+ const getRegistries = (): KitRegistries => {
37
+ if (!registriesCache) {
38
+ const kitModule = require('../../index') as Record<string, unknown>;
39
+ const rnModule = require('react-native') as Record<string, unknown>;
40
+ registriesCache = createRegistries([kitModule], rnModule);
41
+ }
42
+ return registriesCache;
43
+ };
44
+
45
+ /** Foundation version from its package.json, or undefined if it cannot be read. */
46
+ const readFoundationVersion = (): string | undefined => {
47
+ try {
48
+ const pkg = require('../../package.json') as { version?: string };
49
+ return pkg.version;
50
+ } catch {
51
+ return undefined;
52
+ }
53
+ };
54
+
55
+ const createErrorResult = (): WalkResult => ({
56
+ counts: { K: 0, R: 0, O: 0 },
57
+ kit: {},
58
+ rn: {},
59
+ other: {},
60
+ top_transparent: [],
61
+ fibers: 0,
62
+ truncated: false,
63
+ status: 'error',
64
+ });
65
+
66
+ /** Stops the walk at nested probes so each screen is measured on its own. */
67
+ const isProbeFiber = (fiber: FiberLike): boolean =>
68
+ fiber.type === AdoptionProbeDev;
69
+
70
+ /** Passes children through with no measurement. Used in release builds. */
71
+ const PassThrough = (props: ProbeProps): React.JSX.Element => (
72
+ <>{props.children}</>
73
+ );
74
+
75
+ /**
76
+ * Dev-only wrapper around a screen. Measures the screen's fiber tree after
77
+ * the first interactions settle, and again on focus. Release builds use PassThrough.
78
+ */
79
+ class AdoptionProbeDev extends React.Component<ProbeProps> {
80
+ static contextType = MiniAppContext;
81
+
82
+ private timer: ReturnType<typeof setTimeout> | undefined;
83
+ private interaction: { cancel: () => void } | undefined;
84
+ private unsubscribeFocus: (() => void) | undefined;
85
+
86
+ componentDidMount(): void {
87
+ adoptionStore.setActive(this.measure);
88
+ this.unsubscribeFocus = this.props.navigation?.addListener?.(
89
+ 'focus',
90
+ this.handleFocus,
91
+ );
92
+ this.interaction = InteractionManager.runAfterInteractions(() => {
93
+ this.timer = setTimeout(this.measure, SETTLE_MS);
94
+ });
95
+ }
96
+
97
+ componentWillUnmount(): void {
98
+ if (this.timer !== undefined) clearTimeout(this.timer);
99
+ this.interaction?.cancel();
100
+ this.unsubscribeFocus?.();
101
+ adoptionStore.clearActive(this.measure);
102
+ }
103
+
104
+ render(): React.ReactNode {
105
+ return this.props.children;
106
+ }
107
+
108
+ private handleFocus = (): void => {
109
+ adoptionStore.setActive(this.measure);
110
+ };
111
+
112
+ private measure = (): void => {
113
+ const startedAt = Date.now();
114
+ let result: WalkResult;
115
+ try {
116
+ const self = getCurrentFiber(
117
+ (this as unknown as { _reactInternals: FiberLike })._reactInternals,
118
+ );
119
+ const root = self.child;
120
+ if (!root) return;
121
+ result = walkScreen(root, getRegistries(), isProbeFiber);
122
+ } catch {
123
+ result = createErrorResult();
124
+ }
125
+ this.save(result, startedAt);
126
+ };
127
+
128
+ private save(result: WalkResult, startedAt: number): void {
129
+ const snapshot: ScreenSnapshot = {
130
+ ...result,
131
+ app_id: getAppId(this.context),
132
+ screen_name: this.props.screenName,
133
+ foundation_version: readFoundationVersion(),
134
+ platform: Platform.OS,
135
+ ts: Date.now(),
136
+ walk_ms: Date.now() - startedAt,
137
+ };
138
+ adoptionStore.save(snapshot);
139
+ }
140
+ }
141
+
142
+ const AdoptionProbe = __DEV__ ? AdoptionProbeDev : PassThrough;
143
+
144
+ export type { NavigationLike, ProbeProps };
145
+ export { AdoptionProbe, AdoptionProbeDev };
@@ -0,0 +1,80 @@
1
+ import type { ScreenSnapshot } from './types';
2
+
3
+ type Listener = () => void;
4
+ type Measure = () => void;
5
+
6
+ /** Total classified nodes in a snapshot, used to keep the richer measurement. */
7
+ const getTotal = (snapshot: ScreenSnapshot): number =>
8
+ snapshot.counts.K + snapshot.counts.R + snapshot.counts.O;
9
+
10
+ const getKey = (snapshot: ScreenSnapshot): string =>
11
+ `${snapshot.app_id}/${snapshot.screen_name}`;
12
+
13
+ /**
14
+ * In-memory, dev-only store of per-screen snapshots. Keeps one snapshot per
15
+ * app and screen (the one with the most nodes) and holds the active measurer.
16
+ */
17
+ class AdoptionStore {
18
+ private snapshots = new Map<string, ScreenSnapshot>();
19
+ private listeners = new Set<Listener>();
20
+ private latestKey: string | undefined;
21
+ private activeMeasure: Measure | undefined;
22
+
23
+ /** Stores a snapshot unless the stored one for the same screen is larger. */
24
+ save(snapshot: ScreenSnapshot): void {
25
+ const key = getKey(snapshot);
26
+ const existing = this.snapshots.get(key);
27
+ if (!existing || getTotal(existing) <= getTotal(snapshot)) {
28
+ this.snapshots.set(key, snapshot);
29
+ }
30
+ this.latestKey = key;
31
+ this.notify();
32
+ }
33
+
34
+ getAll(): ScreenSnapshot[] {
35
+ return Array.from(this.snapshots.values());
36
+ }
37
+
38
+ /** The screen saved most recently, or undefined when nothing is saved. */
39
+ getLatest(): ScreenSnapshot | undefined {
40
+ return this.latestKey === undefined
41
+ ? undefined
42
+ : this.snapshots.get(this.latestKey);
43
+ }
44
+
45
+ clear(): void {
46
+ this.snapshots.clear();
47
+ this.latestKey = undefined;
48
+ this.notify();
49
+ }
50
+
51
+ /** Registers a change listener and returns its unsubscribe function. */
52
+ subscribe(listener: Listener): () => void {
53
+ this.listeners.add(listener);
54
+ return () => {
55
+ this.listeners.delete(listener);
56
+ };
57
+ }
58
+
59
+ setActive(measure: Measure): void {
60
+ this.activeMeasure = measure;
61
+ }
62
+
63
+ /** Clears the active measurer only if it is still the given one. */
64
+ clearActive(measure: Measure): void {
65
+ if (this.activeMeasure === measure) this.activeMeasure = undefined;
66
+ }
67
+
68
+ remeasureActive(): void {
69
+ this.activeMeasure?.();
70
+ }
71
+
72
+ private notify(): void {
73
+ this.listeners.forEach(listener => listener());
74
+ }
75
+ }
76
+
77
+ const adoptionStore = new AdoptionStore();
78
+
79
+ export type { Listener, Measure };
80
+ export { AdoptionStore, adoptionStore };