@momo-kits/animated-tooltip 0.169.15 → 0.169.16-beta.15

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/index.tsx CHANGED
@@ -5,56 +5,77 @@ import React, {
5
5
  useEffect,
6
6
  useImperativeHandle,
7
7
  useMemo,
8
- useReducer,
9
8
  useRef,
10
9
  useState,
11
10
  } from 'react';
11
+ import { Animated, Dimensions, Easing, Modal, View } from 'react-native';
12
12
  import {
13
- Animated,
14
- Easing,
15
- TouchableWithoutFeedback,
16
- useWindowDimensions,
17
- View,
18
- } from 'react-native';
19
- import {
13
+ ApplicationContext,
20
14
  MiniAppContext,
21
15
  ScreenContext,
22
- Spacing,
23
- useTooltipPortal,
24
16
  } from '@momo-kits/foundation';
25
17
  import styles from './styles';
26
18
  import { TooltipPlacement, TooltipProps, TooltipRef } from './types';
27
- import { usePreloadMeasure } from './usePreloadMeasure';
28
- import { getPlacementStyle, getTooltipArrowStyle } from './utils';
19
+ import {
20
+ getFlippedPosition,
21
+ getPlacementStyle,
22
+ getTooltipArrowStyle,
23
+ TOOLTIP_OFFSET,
24
+ } from './utils';
29
25
  import { renderTooltipContent } from './renderButtons';
30
26
 
31
- type Frame = { x: number; y: number; width: number; height: number };
32
-
33
- const EMPTY_FRAME: Frame = { x: 0, y: 0, width: 0, height: 0 };
34
27
  const ANIMATION_DURATION = 180;
35
- const TOOLTIP_OFFSET = Spacing.S;
36
- const ARROW_SIZE = 6;
37
28
  const SLIDE_DISTANCE = 4;
29
+ const MODAL_KIT_PROPS = { isModalKit: true };
30
+
31
+ const MAX_SETTLE_FRAMES = 60;
38
32
 
39
- /** Whether two measured frames have the same origin and size. */
40
- const isSameFrame = (a: Frame, b: Frame) => {
41
- const isSameOrigin = a.x === b.x && a.y === b.y;
42
- const isSameSize = a.width === b.width && a.height === b.height;
43
- return isSameOrigin && isSameSize;
33
+ type Frame = { x: number; y: number; width: number; height: number };
34
+
35
+ let closeActiveTooltip: (() => void) | null = null;
36
+
37
+ const isOnScreen = ({ x, y, width, height }: Frame) => {
38
+ const window = Dimensions.get('window');
39
+ const isInX = x + width > 0 && x < window.width;
40
+ return isInX && y + height > 0 && y < window.height;
41
+ };
42
+
43
+ const measureSettled = (
44
+ getView: () => View | null,
45
+ isStale: () => boolean,
46
+ onSettled: (frame: Frame) => void,
47
+ previous?: Frame,
48
+ framesLeft = MAX_SETTLE_FRAMES,
49
+ ) => {
50
+ const view = getView();
51
+ if (!view || isStale()) {
52
+ return;
53
+ }
54
+ view.measureInWindow((x, y, width, height) => {
55
+ if (isStale()) {
56
+ return;
57
+ }
58
+ const frame = { x, y, width, height };
59
+ const isSame = previous?.x === x && previous?.y === y;
60
+ const isSettled = isSame && isOnScreen(frame);
61
+ if (isSettled || framesLeft <= 0) {
62
+ onSettled(frame);
63
+ return;
64
+ }
65
+ requestAnimationFrame(() => {
66
+ measureSettled(getView, isStale, onSettled, frame, framesLeft - 1);
67
+ });
68
+ });
44
69
  };
45
70
 
46
- /**
47
- * Wraps children as the anchor and shows a bubble through the foundation
48
- * tooltip portal. Opened and closed only through the ref (show/hide).
49
- */
50
71
  const Tooltip = forwardRef<TooltipRef, TooltipProps>(function Tooltip(
51
72
  {
52
73
  children,
53
74
  title,
54
75
  description,
55
- buttons = [],
56
76
  placement = 'top',
57
77
  align = 'center',
78
+ shouldFlip = false,
58
79
  accessibilityLabel,
59
80
  onVisibleChange,
60
81
  onPressClose,
@@ -62,17 +83,13 @@ const Tooltip = forwardRef<TooltipRef, TooltipProps>(function Tooltip(
62
83
  },
63
84
  ref,
64
85
  ) {
86
+ const { theme } = useContext(ApplicationContext);
65
87
  const app = useContext<any>(MiniAppContext);
66
88
  const screen = useContext<any>(ScreenContext);
67
- const screenWidth = useWindowDimensions().width;
68
89
  const [tooltipSize, setTooltipSize] = useState({ width: 0, height: 0 });
69
90
 
70
- const portal = useTooltipPortal();
71
- const portalId = useRef(
72
- `tooltip-${Math.random().toString(36).substr(2, 9)}`,
73
- ).current;
74
-
75
91
  const anchorRef = useRef<View>(null);
92
+ const hostRef = useRef<View>(null);
76
93
 
77
94
  const [anchorPosition, setAnchorPosition] = useState({
78
95
  x: 0,
@@ -81,11 +98,10 @@ const Tooltip = forwardRef<TooltipRef, TooltipProps>(function Tooltip(
81
98
  height: 0,
82
99
  });
83
100
 
84
- // Portal content is positioned relative to the host, not the window.
85
- const [hostPosition, setHostPosition] = useState({
86
- x: 0,
87
- y: 0,
88
- });
101
+ const [hostPosition, setHostPosition] = useState<{
102
+ x: number;
103
+ y: number;
104
+ } | null>(null);
89
105
 
90
106
  const componentName = 'Tooltip';
91
107
  const componentId = useMemo(() => {
@@ -96,32 +112,29 @@ const Tooltip = forwardRef<TooltipRef, TooltipProps>(function Tooltip(
96
112
  return `${app.appId}/${app.code}/${screen.screenName}/${componentName}`;
97
113
  }, [accessibilityLabel, app, screen, componentName]);
98
114
 
99
- // Visibility lives in a ref read by the effects; forceUpdate re-renders.
115
+ const [isVisible, setIsVisible] = useState(false);
100
116
  const isVisibleRef = useRef(false);
101
- const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
117
+ const isMountedRef = useRef(false);
118
+ const showToken = useRef(0);
119
+ const onVisibleChangeRef = useRef(onVisibleChange);
120
+ onVisibleChangeRef.current = onVisibleChange;
102
121
  const animatedValue = useRef(new Animated.Value(0)).current;
103
- const showTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
104
122
  const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
105
123
 
106
- const clearTimers = () => {
107
- if (showTimer.current) {
108
- clearTimeout(showTimer.current);
109
- }
124
+ const clearHideTimer = useCallback(() => {
110
125
  if (hideTimer.current) {
111
126
  clearTimeout(hideTimer.current);
127
+ hideTimer.current = null;
112
128
  }
113
- };
129
+ }, []);
114
130
 
115
- const setVisibility = useCallback(
116
- (nextVisible: boolean) => {
117
- if (isVisibleRef.current !== nextVisible) {
118
- isVisibleRef.current = nextVisible;
119
- forceUpdate();
120
- onVisibleChange?.(nextVisible);
121
- }
122
- },
123
- [onVisibleChange],
124
- );
131
+ const setVisibility = useCallback((nextVisible: boolean) => {
132
+ if (isVisibleRef.current !== nextVisible) {
133
+ isVisibleRef.current = nextVisible;
134
+ setIsVisible(nextVisible);
135
+ onVisibleChangeRef.current?.(nextVisible);
136
+ }
137
+ }, []);
125
138
 
126
139
  const animate = useCallback(
127
140
  (nextVisible: boolean) => {
@@ -135,114 +148,100 @@ const Tooltip = forwardRef<TooltipRef, TooltipProps>(function Tooltip(
135
148
  [animatedValue],
136
149
  );
137
150
 
138
- useEffect(() => {
139
- // Wait for onLayout on first show so the bubble does not jump into place.
140
- const hasSize = tooltipSize.width > 0 || tooltipSize.height > 0;
141
- if (isVisibleRef.current && !hasSize) {
142
- return;
151
+ const hideNow = useCallback(() => {
152
+ showToken.current += 1;
153
+ clearHideTimer();
154
+ animatedValue.stopAnimation();
155
+ animatedValue.setValue(0);
156
+ setHostPosition(null);
157
+ setVisibility(false);
158
+ if (closeActiveTooltip === hideNow) {
159
+ closeActiveTooltip = null;
143
160
  }
144
- animate(isVisibleRef.current);
145
- }, [tooltipSize, animate]);
146
-
147
- usePreloadMeasure({
148
- hostRef: portal.hostRef,
149
- anchorRef,
150
- setHostPosition,
151
- setAnchorPosition,
152
- });
161
+ }, [animatedValue, clearHideTimer, setVisibility]);
153
162
 
163
+ const hasSize = tooltipSize.width > 0 || tooltipSize.height > 0;
164
+ const isReady = isVisible && hasSize && hostPosition !== null;
154
165
  useEffect(() => {
155
- if (!isVisibleRef.current) {
156
- setAnchorPosition({ x: 0, y: 0, width: 0, height: 0 });
157
- setHostPosition({ x: 0, y: 0 });
158
- return;
166
+ if (isReady) {
167
+ animate(true);
159
168
  }
160
-
161
- let rafId: number | null = null;
162
- let lastPosition = { x: 0, y: 0, width: 0, height: 0 };
163
- let lastHostPosition = { x: 0, y: 0 };
164
- let isMounted = true;
165
- let isActive = true;
166
-
167
- const measureAnchor = () => {
168
- if (!isMounted || !isActive || !anchorRef.current) {
169
- return;
170
- }
171
-
172
- if (portal.hostRef?.current) {
173
- portal.hostRef.current.measureInWindow((hostX, hostY) => {
174
- if (!isMounted || !isActive) return;
175
-
176
- if (hostX !== lastHostPosition.x || hostY !== lastHostPosition.y) {
177
- lastHostPosition = { x: hostX, y: hostY };
178
- setHostPosition({ x: hostX, y: hostY });
179
- }
180
- });
181
- }
182
-
183
- anchorRef.current.measureInWindow((x, y, width, height) => {
184
- if (!isMounted || !isActive) return;
185
-
186
- if (!isSameFrame({ x, y, width, height }, lastPosition)) {
187
- lastPosition = { x, y, width, height };
188
- setAnchorPosition({ x, y, width, height });
189
- }
190
- });
191
- };
192
-
193
- // Measure once on the next frame, after layout settles (no polling).
194
- rafId = requestAnimationFrame(measureAnchor);
195
-
196
- return () => {
197
- isMounted = false;
198
- isActive = false;
199
-
200
- if (rafId !== null) {
201
- cancelAnimationFrame(rafId);
202
- rafId = null;
203
- }
204
- };
205
- }, [portal.hostRef]);
169
+ }, [isReady, animate]);
206
170
 
207
171
  useEffect(() => {
172
+ isMountedRef.current = true;
208
173
  return () => {
209
- clearTimers();
174
+ isMountedRef.current = false;
175
+ clearHideTimer();
210
176
  animatedValue.stopAnimation();
177
+ if (closeActiveTooltip === hideNow) {
178
+ closeActiveTooltip = null;
179
+ }
211
180
  };
212
- }, [animatedValue]);
181
+ }, [animatedValue, clearHideTimer, hideNow]);
213
182
 
214
183
  const handleShow = useCallback(() => {
215
- clearTimers();
216
- showTimer.current = setTimeout(() => {
217
- if (portal.hostRef?.current) {
218
- portal.hostRef.current.measureInWindow((hostX, hostY) => {
219
- setHostPosition({ x: hostX, y: hostY });
220
- });
221
- }
222
-
223
- // Show only once the anchor is measured so the bubble opens in place.
224
- anchorRef.current?.measureInWindow((x, y, width, height) => {
225
- setAnchorPosition({ x, y, width, height });
184
+ clearHideTimer();
185
+ if (closeActiveTooltip && closeActiveTooltip !== hideNow) {
186
+ closeActiveTooltip();
187
+ }
188
+ closeActiveTooltip = hideNow;
189
+ showToken.current += 1;
190
+ const token = showToken.current;
191
+
192
+ const isStale = () => !isMountedRef.current || token !== showToken.current;
193
+
194
+ measureSettled(
195
+ () => anchorRef.current,
196
+ isStale,
197
+ frame => {
198
+ setAnchorPosition(frame);
199
+ if (isVisibleRef.current) {
200
+ animate(true);
201
+ }
226
202
  setVisibility(true);
227
- });
228
- }, ANIMATION_DURATION);
229
- }, [portal.hostRef, setVisibility]);
203
+ },
204
+ );
205
+ }, [animate, clearHideTimer, hideNow, setVisibility]);
230
206
 
231
207
  const handleHide = useCallback(() => {
232
- clearTimers();
233
- hideTimer.current = setTimeout(
234
- () => setVisibility(false),
235
- ANIMATION_DURATION,
236
- );
237
- }, [setVisibility]);
208
+ clearHideTimer();
209
+ showToken.current += 1;
210
+ animate(false);
211
+ hideTimer.current = setTimeout(hideNow, ANIMATION_DURATION);
212
+ }, [animate, clearHideTimer, hideNow]);
213
+
214
+ const handlePressClose = useCallback(() => {
215
+ handleHide();
216
+ onPressClose?.();
217
+ }, [handleHide, onPressClose]);
218
+
219
+ const handleHostLayout = useCallback(() => {
220
+ hostRef.current?.measureInWindow((x, y) => {
221
+ setHostPosition({ x, y });
222
+ });
223
+ }, []);
238
224
 
239
225
  useImperativeHandle(ref, () => ({ show: handleShow, hide: handleHide }), [
240
226
  handleHide,
241
227
  handleShow,
242
228
  ]);
243
229
 
244
- const isVertical = placement === 'top' || placement === 'bottom';
245
- const isBeforeAnchor = placement === 'top' || placement === 'left';
230
+ const shown = useMemo(() => {
231
+ if (!shouldFlip || !hasSize) {
232
+ return { placement, align };
233
+ }
234
+ return getFlippedPosition({
235
+ anchorPosition,
236
+ tooltipSize,
237
+ placement,
238
+ align,
239
+ });
240
+ }, [shouldFlip, hasSize, anchorPosition, tooltipSize, placement, align]);
241
+
242
+ const isVertical = shown.placement === 'top' || shown.placement === 'bottom';
243
+ const isBeforeAnchor =
244
+ shown.placement === 'top' || shown.placement === 'left';
246
245
  const slideFrom = isBeforeAnchor ? SLIDE_DISTANCE : -SLIDE_DISTANCE;
247
246
  const slide = animatedValue.interpolate({
248
247
  inputRange: [0, 1],
@@ -250,103 +249,67 @@ const Tooltip = forwardRef<TooltipRef, TooltipProps>(function Tooltip(
250
249
  });
251
250
  const translate = isVertical ? { translateY: slide } : { translateX: slide };
252
251
 
252
+ const hostX = hostPosition?.x ?? 0;
253
+ const hostY = hostPosition?.y ?? 0;
253
254
  const placementStyle = useMemo(() => {
254
255
  return getPlacementStyle({
255
256
  anchorPosition,
256
257
  tooltipSize,
257
- placement,
258
- align,
259
- hostX: hostPosition.x,
260
- hostY: hostPosition.y,
258
+ placement: shown.placement,
259
+ align: shown.align,
260
+ hostX,
261
+ hostY,
261
262
  offset: TOOLTIP_OFFSET,
262
263
  });
263
- }, [
264
- anchorPosition,
265
- tooltipSize,
266
- placement,
267
- hostPosition.y,
268
- hostPosition.x,
269
- align,
270
- ]);
264
+ }, [anchorPosition, tooltipSize, shown, hostY, hostX]);
271
265
 
272
- const renderContent = () => {
273
- return renderTooltipContent({
274
- title,
275
- description,
276
- buttons,
277
- screenWidth,
278
- onPressClose,
279
- });
280
- };
281
-
282
- const getArrowStyle = () => {
283
- return getTooltipArrowStyle({
284
- arrowSize: ARROW_SIZE,
285
- align,
286
- placement,
287
- tooltipSize,
288
- });
289
- };
290
-
291
- useEffect(() => {
292
- let isActive = true;
293
-
294
- if (!isVisibleRef.current) {
295
- portal.unregister(portalId, true); // Immediate cleanup when hiding
296
- return;
297
- }
298
-
299
- const hasMeasurement = !isSameFrame(anchorPosition, EMPTY_FRAME);
300
- if (!hasMeasurement) {
301
- return;
302
- }
303
-
304
- const content = (
305
- <>
306
- <TouchableWithoutFeedback onPress={handleHide}>
307
- <View style={styles.backdrop} />
308
- </TouchableWithoutFeedback>
309
-
310
- <Animated.View
311
- pointerEvents="auto"
312
- style={[
313
- {
314
- maxWidth: screenWidth - Spacing.M * 2,
315
- },
316
- containerStyle,
317
- styles.tooltip,
318
- placementStyle,
319
- {
320
- opacity: animatedValue,
321
- transform: [translate],
322
- },
323
- ]}
324
- onLayout={event => {
325
- if (isActive) {
326
- setTooltipSize(event.nativeEvent.layout);
327
- }
328
- }}
329
- >
330
- {renderContent()}
331
- <View style={getArrowStyle()} />
332
- </Animated.View>
333
- </>
334
- );
335
-
336
- portal.register(portalId, content);
337
-
338
- return () => {
339
- isActive = false;
340
- portal.unregister(portalId, true);
341
- };
342
- // eslint-disable-next-line react-hooks/exhaustive-deps -- re-register only when visibility or geometry changes
343
- }, [isVisibleRef.current, anchorPosition, placement, align, tooltipSize]);
266
+ const bubbleColor = theme.colors.interactive.primary;
267
+ const arrowStyle = getTooltipArrowStyle({
268
+ align: shown.align,
269
+ placement: shown.placement,
270
+ tooltipSize,
271
+ color: bubbleColor,
272
+ });
344
273
 
345
274
  return (
346
275
  <View style={styles.container} accessibilityLabel={componentId}>
347
276
  <View ref={anchorRef} style={styles.anchorView}>
348
277
  {children}
349
278
  </View>
279
+ <Modal
280
+ visible={isVisible}
281
+ transparent
282
+ animationType="none"
283
+ statusBarTranslucent
284
+ navigationBarTranslucent
285
+ onRequestClose={handleHide}
286
+ {...MODAL_KIT_PROPS}
287
+ >
288
+ <View ref={hostRef} style={styles.host} onLayout={handleHostLayout}>
289
+ <View style={styles.backdrop} onTouchStart={handleHide} />
290
+ <Animated.View
291
+ pointerEvents="auto"
292
+ style={[
293
+ containerStyle,
294
+ styles.tooltip,
295
+ placementStyle,
296
+ {
297
+ backgroundColor: bubbleColor,
298
+ opacity: animatedValue,
299
+ transform: [translate],
300
+ },
301
+ ]}
302
+ onLayout={event => setTooltipSize(event.nativeEvent.layout)}
303
+ >
304
+ {renderTooltipContent({
305
+ title,
306
+ description,
307
+ onPressClose: handlePressClose,
308
+ })}
309
+ <View style={arrowStyle} />
310
+ </Animated.View>
311
+ </View>
312
+ </Modal>
350
313
  </View>
351
314
  );
352
315
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@momo-kits/animated-tooltip",
3
- "version": "0.169.15",
3
+ "version": "0.169.16-beta.15",
4
4
  "private": false,
5
5
  "main": "index.tsx",
6
6
  "dependencies": {},
package/renderButtons.tsx CHANGED
@@ -1,131 +1,39 @@
1
1
  import React from 'react';
2
2
  import { TouchableOpacity, View } from 'react-native';
3
- import { Colors, Icon, Spacing, Text } from '@momo-kits/foundation';
3
+ import { Colors, Icon, Text } from '@momo-kits/foundation';
4
4
  import styles from './styles';
5
- import { TooltipButton } from './types';
6
- import { IconButton, PrimaryButton, SecondaryButton } from './TooltipButtons';
7
5
 
8
- /**
9
- * Right-aligned action row. With two buttons the first is the primary, on the
10
- * right; buttons with `icon` render as icon buttons (a pair only if both do).
11
- */
12
- export const renderTooltipButtons = (buttons: TooltipButton[]) => {
13
- if (!buttons.length) {
14
- return null;
15
- }
6
+ const CLOSE_ICON_SIZE = 20;
7
+ const CLOSE_HIT_SLOP = 12;
16
8
 
17
- if (buttons.length === 1) {
18
- const btn = buttons[0];
19
- const onPress = btn.onPress ?? (() => {});
20
- return (
21
- <View style={styles.buttonsRow}>
22
- <View
23
- style={[
24
- styles.button,
25
- btn.icon ? styles.iconButton : styles.textButton,
26
- ]}
27
- >
28
- {btn.icon ? (
29
- <IconButton icon={btn.icon} onPress={onPress} />
30
- ) : (
31
- <PrimaryButton title={btn.title || ''} onPress={onPress} />
32
- )}
33
- </View>
34
- </View>
35
- );
36
- }
37
-
38
- if (buttons.length === 2) {
39
- const [first, second] = buttons;
40
- const firstPress = first.onPress ?? (() => {});
41
- const secondPress = second.onPress ?? (() => {});
42
- const bothIcon = !!first.icon && !!second.icon;
43
-
44
- return (
45
- <View style={styles.buttonsRow}>
46
- {bothIcon ? (
47
- <View style={styles.buttonRowContainer}>
48
- <IconButton
49
- icon={second.icon as string}
50
- onPress={secondPress}
51
- style={styles.buttonSpacing}
52
- />
53
- <IconButton icon={first.icon as string} onPress={firstPress} />
54
- </View>
55
- ) : (
56
- <View style={styles.buttonRowContainer}>
57
- <SecondaryButton
58
- title={second.title || ''}
59
- onPress={secondPress}
60
- style={styles.buttonSpacing}
61
- />
62
- <PrimaryButton title={first.title || ''} onPress={firstPress} />
63
- </View>
64
- )}
65
- </View>
66
- );
67
- }
68
-
69
- return (
70
- <View style={styles.buttonsRow}>
71
- {buttons.map((btn, idx) => {
72
- const isIcon = !!btn.icon;
73
- const key = btn.title || btn.icon || `${idx}`;
74
- const onPress = btn.onPress ?? (() => {});
75
-
76
- return (
77
- <View
78
- key={key}
79
- style={[
80
- styles.button,
81
- isIcon ? styles.iconButton : styles.textButton,
82
- ]}
83
- >
84
- {isIcon ? (
85
- <IconButton icon={btn.icon as string} onPress={onPress} />
86
- ) : (
87
- <PrimaryButton title={btn.title || ''} onPress={onPress} />
88
- )}
89
- </View>
90
- );
91
- })}
92
- </View>
93
- );
94
- };
95
-
96
- /** Bubble body: required title, optional description, close icon and actions. */
97
9
  export const renderTooltipContent = ({
98
10
  title,
99
11
  description,
100
- buttons,
101
- screenWidth,
102
12
  onPressClose,
103
13
  }: {
104
- title: string;
14
+ title?: string;
105
15
  description?: string;
106
- buttons: TooltipButton[];
107
- screenWidth: number;
108
16
  onPressClose?: () => void;
109
17
  }) => {
110
18
  return (
111
19
  <View style={styles.content}>
112
20
  <View style={styles.contentHeader}>
113
- <View
114
- style={[
115
- styles.contentTextContainer,
116
- {
117
- maxWidth: screenWidth - Spacing.M * 2 - 48,
118
- },
119
- ]}
120
- >
121
- <Text typography={'header_s_semibold'} color={Colors.black_01}>
122
- {title}
123
- </Text>
21
+ <View style={styles.contentTextContainer}>
22
+ {title ? (
23
+ <Text
24
+ typography={'header_s_semibold'}
25
+ color={Colors.black_01}
26
+ numberOfLines={1}
27
+ >
28
+ {title}
29
+ </Text>
30
+ ) : null}
124
31
  {description ? (
125
32
  <Text
126
- typography={'description_default_regular'}
33
+ typography={'body_default_regular'}
127
34
  color={Colors.black_01}
128
- style={styles.description}
35
+ numberOfLines={2}
36
+ style={title ? styles.description : undefined}
129
37
  >
130
38
  {description}
131
39
  </Text>
@@ -133,13 +41,21 @@ export const renderTooltipContent = ({
133
41
  </View>
134
42
  <TouchableOpacity
135
43
  onPress={onPressClose}
136
- hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
44
+ hitSlop={{
45
+ top: CLOSE_HIT_SLOP,
46
+ bottom: CLOSE_HIT_SLOP,
47
+ left: CLOSE_HIT_SLOP,
48
+ right: CLOSE_HIT_SLOP,
49
+ }}
137
50
  style={styles.closeIconSpacing}
138
51
  >
139
- <Icon source={'navigation_close'} size={20} color={Colors.black_01} />
52
+ <Icon
53
+ source={'navigation_close'}
54
+ size={CLOSE_ICON_SIZE}
55
+ color={Colors.black_01}
56
+ />
140
57
  </TouchableOpacity>
141
58
  </View>
142
- {renderTooltipButtons(buttons)}
143
59
  </View>
144
60
  );
145
61
  };
package/styles.ts CHANGED
@@ -1,14 +1,16 @@
1
1
  import { StyleSheet } from 'react-native';
2
2
  import { Colors, Radius, Spacing } from '@momo-kits/foundation';
3
3
 
4
+ const TOOLTIP_WIDTH = 220;
5
+
4
6
  export default StyleSheet.create({
5
7
  container: {
6
8
  position: 'relative',
7
9
  },
8
10
  tooltip: {
9
11
  position: 'absolute',
12
+ width: TOOLTIP_WIDTH,
10
13
  padding: Spacing.M,
11
- backgroundColor: Colors.blue_03,
12
14
  borderRadius: Radius.S,
13
15
  },
14
16
  text: {
@@ -25,52 +27,18 @@ export default StyleSheet.create({
25
27
  description: {
26
28
  marginTop: Spacing.XS,
27
29
  },
28
- buttonsRow: {
29
- marginTop: Spacing.M,
30
- flexDirection: 'row',
31
- flexWrap: 'wrap',
32
- justifyContent: 'flex-end',
33
- },
34
- button: {
35
- marginRight: Spacing.XXS,
36
- marginBottom: Spacing.XXS,
37
- },
38
- textButton: {},
39
- iconButton: {},
40
- buttonRowContainer: {
41
- flexDirection: 'row',
42
- alignItems: 'center',
43
- },
44
- buttonSpacing: {
45
- marginRight: Spacing.S,
46
- },
47
30
  contentHeader: {
48
31
  flexDirection: 'row',
49
32
  },
50
33
  closeIconSpacing: {
51
34
  marginLeft: Spacing.S,
52
35
  },
53
- secondaryButtonContainer: {
54
- paddingHorizontal: Spacing.M,
55
- paddingVertical: Spacing.S,
56
- },
57
- iconButtonContainer: {
58
- borderRadius: Radius.XL,
59
- backgroundColor: Colors.black_01,
60
- alignItems: 'center',
61
- justifyContent: 'center',
62
- },
63
36
  anchorView: {
64
37
  alignSelf: 'flex-start',
65
38
  },
66
39
  contentTextContainer: {
67
- minWidth: 100,
68
- },
69
- backdrop: {
70
- position: 'absolute',
71
- top: -9999,
72
- left: -9999,
73
- right: -9999,
74
- bottom: -9999,
40
+ flex: 1,
75
41
  },
42
+ host: StyleSheet.absoluteFillObject,
43
+ backdrop: StyleSheet.absoluteFillObject,
76
44
  });
package/types.ts CHANGED
@@ -22,13 +22,13 @@ export type TooltipProps = {
22
22
  /**
23
23
  * Title displayed at the top of the tooltip.
24
24
  */
25
- title: string;
25
+ title?: string;
26
26
  /**
27
27
  * Description text shown under the title.
28
28
  */
29
29
  description?: string;
30
30
  /**
31
- * Action buttons rendered at the bottom of the tooltip.
31
+ * @deprecated Ignored: the tooltip no longer renders action buttons.
32
32
  */
33
33
  buttons?: TooltipButton[];
34
34
  /**
@@ -41,6 +41,12 @@ export type TooltipProps = {
41
41
  * @default 'center'
42
42
  */
43
43
  align?: 'start' | 'center' | 'end';
44
+ /**
45
+ * Flips to the opposite side or align when the bubble would leave the window
46
+ * and the alternative fits. Off by default, so the tooltip stays where set.
47
+ * @default false
48
+ */
49
+ shouldFlip?: boolean;
44
50
  /**
45
51
  * Accessibility label for the component.
46
52
  */
@@ -50,7 +56,7 @@ export type TooltipProps = {
50
56
  */
51
57
  onVisibleChange?: (visible: boolean) => void;
52
58
  /**
53
- * Triggered when the close button (X) is pressed.
59
+ * Called after the close button (X) hides the tooltip.
54
60
  */
55
61
  onPressClose?: () => void;
56
62
 
package/utils.ts CHANGED
@@ -1,14 +1,115 @@
1
- import { ViewStyle } from 'react-native';
2
- import { Colors, Spacing } from '@momo-kits/foundation';
1
+ import { Dimensions, ViewStyle } from 'react-native';
2
+ import { Spacing } from '@momo-kits/foundation';
3
3
  import styles from './styles';
4
4
  import { TooltipPlacement, TooltipProps } from './types';
5
5
 
6
6
  type Align = NonNullable<TooltipProps['align']>;
7
+ type Frame = { x: number; y: number; width: number; height: number };
8
+ type Size = { width: number; height: number };
9
+
10
+ const ARROW_WIDTH = 12;
11
+ const ARROW_HEIGHT = 6;
12
+ const ARROW_GAP = Spacing.XS;
13
+ const ARROW_EDGE_INSET = Spacing.M + ARROW_WIDTH / 2;
14
+ const TOOLTIP_OFFSET = ARROW_HEIGHT + ARROW_GAP;
15
+ const PLACEMENT_FALLBACKS: Record<TooltipPlacement, TooltipPlacement[]> = {
16
+ top: ['top', 'bottom', 'right', 'left'],
17
+ bottom: ['bottom', 'top', 'right', 'left'],
18
+ left: ['left', 'right', 'top', 'bottom'],
19
+ right: ['right', 'left', 'top', 'bottom'],
20
+ };
21
+
22
+ const getCrossAxisStart = (
23
+ anchorCenter: number,
24
+ tooltipLength: number,
25
+ align: Align,
26
+ ) => {
27
+ if (align === 'start') {
28
+ return anchorCenter - ARROW_EDGE_INSET;
29
+ }
30
+ if (align === 'end') {
31
+ return anchorCenter - (tooltipLength - ARROW_EDGE_INSET);
32
+ }
33
+ return anchorCenter - tooltipLength / 2;
34
+ };
35
+
36
+ const hasMainAxisRoom = (
37
+ anchor: Frame,
38
+ size: Size,
39
+ placement: TooltipPlacement,
40
+ ) => {
41
+ const window = Dimensions.get('window');
42
+ if (placement === 'top') {
43
+ return anchor.y - size.height - TOOLTIP_OFFSET >= 0;
44
+ }
45
+ if (placement === 'left') {
46
+ return anchor.x - size.width - TOOLTIP_OFFSET >= 0;
47
+ }
48
+ if (placement === 'bottom') {
49
+ const bubbleEnd = anchor.y + anchor.height + TOOLTIP_OFFSET + size.height;
50
+ return bubbleEnd <= window.height;
51
+ }
52
+ const bubbleEnd = anchor.x + anchor.width + TOOLTIP_OFFSET + size.width;
53
+ return bubbleEnd <= window.width;
54
+ };
55
+
56
+ const hasCrossAxisRoom = (
57
+ anchor: Frame,
58
+ size: Size,
59
+ placement: TooltipPlacement,
60
+ align: Align,
61
+ ) => {
62
+ const window = Dimensions.get('window');
63
+ const isVertical = placement === 'top' || placement === 'bottom';
64
+ const center = isVertical
65
+ ? anchor.x + anchor.width / 2
66
+ : anchor.y + anchor.height / 2;
67
+ const length = isVertical ? size.width : size.height;
68
+ const limit = isVertical ? window.width : window.height;
69
+ const start = getCrossAxisStart(center, length, align);
70
+ return start >= 0 && start + length <= limit;
71
+ };
72
+
73
+ const getAlignCandidates = (align: Align): Align[] => {
74
+ if (align === 'start') {
75
+ return ['start', 'end', 'center'];
76
+ }
77
+ if (align === 'end') {
78
+ return ['end', 'start', 'center'];
79
+ }
80
+ return ['center', 'start', 'end'];
81
+ };
82
+
83
+ export const getFlippedPosition = ({
84
+ anchorPosition,
85
+ tooltipSize,
86
+ placement,
87
+ align,
88
+ }: {
89
+ anchorPosition: Frame;
90
+ tooltipSize: Size;
91
+ placement: TooltipPlacement;
92
+ align: Align;
93
+ }): { placement: TooltipPlacement; align: Align } => {
94
+ for (const candidate of PLACEMENT_FALLBACKS[placement]) {
95
+ if (!hasMainAxisRoom(anchorPosition, tooltipSize, candidate)) {
96
+ continue;
97
+ }
98
+ const fittingAlign = getAlignCandidates(align).find(alignCandidate => {
99
+ return hasCrossAxisRoom(
100
+ anchorPosition,
101
+ tooltipSize,
102
+ candidate,
103
+ alignCandidate,
104
+ );
105
+ });
106
+ if (fittingAlign) {
107
+ return { placement: candidate, align: fittingAlign };
108
+ }
109
+ }
110
+ return { placement, align };
111
+ };
7
112
 
8
- /**
9
- * Top/left of the bubble inside the portal host: the anchor's window frame
10
- * minus the host origin, pushed out by offset and aligned start/center/end.
11
- */
12
113
  export const getPlacementStyle = ({
13
114
  anchorPosition,
14
115
  tooltipSize,
@@ -34,20 +135,16 @@ export const getPlacementStyle = ({
34
135
  const { x, y, width, height } = anchorPosition;
35
136
  const { width: tooltipWidth, height: tooltipHeight } = tooltipSize;
36
137
 
37
- let position: { top?: number; left?: number; right?: number } = {};
138
+ const position: { top?: number; left?: number; right?: number } = {};
38
139
 
39
140
  if (placement === 'top') {
40
141
  position.top = y - tooltipHeight - offset - hostY;
41
142
  } else if (placement === 'bottom') {
42
143
  position.top = y + height + offset - hostY;
43
144
  } else {
44
- if (align === 'start') {
45
- position.top = y - hostY;
46
- } else if (align === 'end') {
47
- position.top = y + height - tooltipHeight - hostY;
48
- } else {
49
- position.top = y + height / 2 - tooltipHeight / 2 - hostY;
50
- }
145
+ const anchorCenterY = y + height / 2;
146
+ position.top =
147
+ getCrossAxisStart(anchorCenterY, tooltipHeight, align) - hostY;
51
148
  }
52
149
 
53
150
  if (placement === 'left') {
@@ -55,89 +152,98 @@ export const getPlacementStyle = ({
55
152
  } else if (placement === 'right') {
56
153
  position.left = x + width + offset - hostX;
57
154
  } else {
58
- if (align === 'start') {
59
- position.left = x - hostX;
60
- } else if (align === 'end') {
61
- position.left = x + width - tooltipWidth - hostX;
62
- } else {
63
- position.left = x + width / 2 - tooltipWidth / 2 - hostX;
64
- }
155
+ const anchorCenterX = x + width / 2;
156
+ position.left =
157
+ getCrossAxisStart(anchorCenterX, tooltipWidth, align) - hostX;
65
158
  }
66
159
 
67
160
  return position;
68
161
  };
69
162
 
70
- /**
71
- * Rotated-square arrow on the bubble edge that faces the anchor, aligned the
72
- * same way as the bubble.
73
- */
74
163
  export const getTooltipArrowStyle = ({
75
- arrowSize,
76
164
  align,
77
165
  placement,
78
166
  tooltipSize,
167
+ color,
79
168
  }: {
80
- arrowSize: number;
81
169
  align: Align;
82
170
  placement: TooltipPlacement;
83
171
  tooltipSize: { width: number; height: number };
84
- }): object[] => {
85
- const size = arrowSize;
86
- const common = [
87
- styles.arrow,
88
- {
89
- width: size * 2,
90
- height: size * 2,
91
- backgroundColor: Colors.blue_03,
92
- transform: [{ rotate: '45deg' }],
93
- borderRadius: size / 2,
94
- },
95
- ];
96
- const inset = size + Spacing.M;
97
- const centerTop = (tooltipSize.height || 0) / 2 - size;
172
+ color: string;
173
+ }): ViewStyle[] => {
174
+ const half = ARROW_WIDTH / 2;
175
+ const edgeStart = ARROW_EDGE_INSET - half;
176
+ const centerTop = (tooltipSize.height || 0) / 2 - half;
98
177
  let horizontalAlign: ViewStyle = { alignSelf: 'center' };
99
178
  let verticalAlign: ViewStyle = { top: centerTop };
100
179
  if (align === 'start') {
101
- horizontalAlign = { left: inset };
102
- verticalAlign = { top: inset };
180
+ horizontalAlign = { left: edgeStart };
181
+ verticalAlign = { top: edgeStart };
103
182
  } else if (align === 'end') {
104
- horizontalAlign = { right: inset };
105
- verticalAlign = { bottom: inset };
183
+ horizontalAlign = { right: edgeStart };
184
+ verticalAlign = { bottom: edgeStart };
106
185
  }
107
186
 
187
+ const sides: ViewStyle = {
188
+ borderLeftWidth: half,
189
+ borderRightWidth: half,
190
+ borderLeftColor: 'transparent',
191
+ borderRightColor: 'transparent',
192
+ };
193
+ const ends: ViewStyle = {
194
+ borderTopWidth: half,
195
+ borderBottomWidth: half,
196
+ borderTopColor: 'transparent',
197
+ borderBottomColor: 'transparent',
198
+ };
199
+
108
200
  switch (placement) {
109
201
  case 'top':
110
202
  return [
111
- ...common,
203
+ styles.arrow,
204
+ sides,
112
205
  {
113
- bottom: -(size - 1),
114
- ...horizontalAlign,
206
+ borderTopWidth: ARROW_HEIGHT,
207
+ borderTopColor: color,
208
+ bottom: -ARROW_HEIGHT,
115
209
  },
210
+ horizontalAlign,
116
211
  ];
117
212
  case 'bottom':
118
213
  return [
119
- ...common,
214
+ styles.arrow,
215
+ sides,
120
216
  {
121
- top: -(size - 1),
122
- ...horizontalAlign,
217
+ borderBottomWidth: ARROW_HEIGHT,
218
+ borderBottomColor: color,
219
+ top: -ARROW_HEIGHT,
123
220
  },
221
+ horizontalAlign,
124
222
  ];
125
223
  case 'left':
126
224
  return [
127
- ...common,
225
+ styles.arrow,
226
+ ends,
128
227
  {
129
- right: -(size - 1),
130
- ...verticalAlign,
228
+ borderLeftWidth: ARROW_HEIGHT,
229
+ borderLeftColor: color,
230
+ right: -ARROW_HEIGHT,
131
231
  },
232
+ verticalAlign,
132
233
  ];
133
234
  case 'right':
134
235
  default:
135
236
  return [
136
- ...common,
237
+ styles.arrow,
238
+ ends,
137
239
  {
138
- left: -(size - 1),
139
- ...verticalAlign,
240
+ borderRightWidth: ARROW_HEIGHT,
241
+ borderRightColor: color,
242
+ left: -ARROW_HEIGHT,
140
243
  },
244
+ verticalAlign,
141
245
  ];
142
246
  }
143
247
  };
248
+
249
+ export { TOOLTIP_OFFSET };
@@ -1,57 +0,0 @@
1
- import React, { FC } from 'react';
2
- import { TouchableOpacity } from 'react-native';
3
- import {
4
- Button,
5
- ButtonProps,
6
- Colors,
7
- Icon,
8
- IconButtonProps,
9
- Text,
10
- useScaleSize,
11
- } from '@momo-kits/foundation';
12
- import styles from './styles';
13
-
14
- /** Main tooltip action: a medium foundation Button of type secondary. */
15
- const PrimaryButton: FC<ButtonProps> = ({ title, onPress }) => {
16
- return (
17
- <Button
18
- full={false}
19
- title={title}
20
- onPress={onPress}
21
- type={'secondary'}
22
- size={'medium'}
23
- />
24
- );
25
- };
26
-
27
- /** Text-only action shown left of the primary in a two-button row. */
28
- const SecondaryButton: FC<ButtonProps> = ({ title, onPress, style }) => {
29
- return (
30
- <TouchableOpacity
31
- style={[styles.secondaryButtonContainer, style]}
32
- onPress={onPress}
33
- >
34
- <Text color={Colors.black_01} typography={'action_s_bold'}>
35
- {title}
36
- </Text>
37
- </TouchableOpacity>
38
- );
39
- };
40
-
41
- /** 36pt (scaled) icon-only action. */
42
- const IconButton: FC<IconButtonProps> = ({ icon, onPress, style }) => {
43
- return (
44
- <TouchableOpacity
45
- onPress={onPress}
46
- style={[
47
- { width: useScaleSize(36), height: useScaleSize(36) },
48
- styles.iconButtonContainer,
49
- style,
50
- ]}
51
- >
52
- <Icon source={icon} />
53
- </TouchableOpacity>
54
- );
55
- };
56
-
57
- export { PrimaryButton, SecondaryButton, IconButton };
@@ -1,35 +0,0 @@
1
- import { RefObject, useEffect } from 'react';
2
- import { View } from 'react-native';
3
-
4
- type Position = { x: number; y: number; width: number; height: number };
5
-
6
- /** Measures host and anchor once after mount so the first show() opens fast. */
7
- export const usePreloadMeasure = ({
8
- hostRef,
9
- anchorRef,
10
- setHostPosition,
11
- setAnchorPosition,
12
- }: {
13
- hostRef?: RefObject<View | null> | null;
14
- anchorRef: RefObject<View | null>;
15
- setHostPosition: (position: { x: number; y: number }) => void;
16
- setAnchorPosition: (position: Position) => void;
17
- }) => {
18
- useEffect(() => {
19
- const timer = setTimeout(() => {
20
- if (hostRef?.current) {
21
- hostRef.current.measureInWindow((hostX, hostY) => {
22
- setHostPosition({ x: hostX, y: hostY });
23
- });
24
- }
25
-
26
- anchorRef.current?.measureInWindow((x, y, width, height) => {
27
- if (x !== 0 || y !== 0 || width !== 0 || height !== 0) {
28
- setAnchorPosition({ x, y, width, height });
29
- }
30
- });
31
- }, 0);
32
-
33
- return () => clearTimeout(timer);
34
- }, [hostRef, anchorRef, setHostPosition, setAnchorPosition]);
35
- };