-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathTouchableRipple.tsx
More file actions
349 lines (311 loc) · 9.96 KB
/
TouchableRipple.tsx
File metadata and controls
349 lines (311 loc) · 9.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import * as React from 'react';
import {
ColorValue,
GestureResponderEvent,
Platform,
StyleProp,
StyleSheet,
View,
ViewStyle,
} from 'react-native';
import color from 'color';
import type { PressableProps, PressableStateCallbackType } from './Pressable';
import { Pressable } from './Pressable';
import { getTouchableRippleColors } from './utils';
import { Settings, SettingsContext } from '../../core/settings';
import { useInternalTheme } from '../../core/theming';
import type { ThemeProp } from '../../types';
import { forwardRef } from '../../utils/forwardRef';
import hasTouchHandler from '../../utils/hasTouchHandler';
export type Props = PressableProps & {
/**
* Whether to render the ripple outside the view bounds.
*/
borderless?: boolean;
/**
* Type of background drawabale to display the feedback (Android).
* https://reactnative.dev/docs/pressable#rippleconfig
*/
background?: Object;
/**
* Whether to start the ripple at the center (Web).
*/
centered?: boolean;
/**
* Whether to prevent interaction with the touchable.
*/
disabled?: boolean;
/**
* Function to execute on press. If not set, will cause the touchable to be disabled.
*/
onPress?: (e: GestureResponderEvent) => void;
/**
* Function to execute on long press.
*/
onLongPress?: (e: GestureResponderEvent) => void;
/**
* Debounce time in milliseconds to prevent rapid successive presses.
* When set, subsequent onPress calls within this time window will be ignored.
*/
debounce?: number;
/**
* Function to execute immediately when a touch is engaged, before `onPressOut` and `onPress`.
*/
onPressIn?: (e: GestureResponderEvent) => void;
/**
* Function to execute when a touch is released.
*/
onPressOut?: (e: GestureResponderEvent) => void;
/**
* Color of the ripple effect (Android >= 5.0 and Web).
*/
rippleColor?: ColorValue;
/**
* Color of the underlay for the highlight effect (Android < 5.0 and iOS).
*/
underlayColor?: string;
/**
* Content of the `TouchableRipple`.
*/
children:
| ((state: PressableStateCallbackType) => React.ReactNode)
| React.ReactNode;
style?:
| StyleProp<ViewStyle>
| ((state: PressableStateCallbackType) => StyleProp<ViewStyle>)
| undefined;
/**
* @optional
*/
theme?: ThemeProp;
};
/**
* A wrapper for views that should respond to touches.
* Provides a material "ink ripple" interaction effect for supported platforms (>= Android Lollipop).
* On unsupported platforms, it falls back to a highlight effect.
*
* ## Usage
* ```js
* import * as React from 'react';
* import { View } from 'react-native';
* import { Text, TouchableRipple } from 'react-native-paper';
*
* const MyComponent = () => (
* <TouchableRipple
* onPress={() => console.log('Pressed')}
* rippleColor="rgba(0, 0, 0, .32)"
* debounce={300} // Prevent double-clicks within 300ms
* >
* <Text>Press anywhere</Text>
* </TouchableRipple>
* );
*
* export default MyComponent;
* ```
*
* @extends Pressable props https://reactnative.dev/docs/Pressable#props
*/
const TouchableRipple = (
{
style,
background: _background,
borderless = false,
disabled: disabledProp,
rippleColor,
underlayColor: _underlayColor,
children,
theme: themeOverrides,
debounce,
...rest
}: Props,
ref: React.ForwardedRef<View>
) => {
const theme = useInternalTheme(themeOverrides);
const { calculatedRippleColor } = getTouchableRippleColors({
theme,
rippleColor,
});
const hoverColor = color(calculatedRippleColor).fade(0.5).rgb().string();
const { rippleEffectEnabled } = React.useContext<Settings>(SettingsContext);
const { onPress, onLongPress, onPressIn, onPressOut } = rest;
const lastPressTime = React.useRef<number>(0);
const debouncedOnPress = React.useCallback(
(e: GestureResponderEvent) => {
if (!onPress) return;
if (debounce && debounce > 0) {
const now = Date.now();
if (now - lastPressTime.current < debounce) {
return; // Ignore this press as it's within the debounce window
}
lastPressTime.current = now;
}
onPress(e);
},
[onPress, debounce]
);
const handlePressIn = React.useCallback(
(e: any) => {
onPressIn?.(e);
if (rippleEffectEnabled) {
const { centered } = rest;
const button = e.currentTarget;
const style = window.getComputedStyle(button);
const dimensions = button.getBoundingClientRect();
let touchX;
let touchY;
const { changedTouches, touches } = e.nativeEvent;
const touch = touches?.[0] ?? changedTouches?.[0];
// If centered or it was pressed using keyboard - enter or space
if (centered || !touch) {
touchX = dimensions.width / 2;
touchY = dimensions.height / 2;
} else {
touchX = touch.locationX ?? e.pageX;
touchY = touch.locationY ?? e.pageY;
}
// Get the size of the button to determine how big the ripple should be
const size = centered
? // If ripple is always centered, we don't need to make it too big
Math.min(dimensions.width, dimensions.height) * 1.5
: // Otherwise make it twice as big so clicking on one end spreads ripple to other
Math.max(dimensions.width, dimensions.height) * 2;
// Create a container for our ripple effect so we don't need to change the parent's style
const container = document.createElement('span');
container.setAttribute('data-paper-ripple', '');
Object.assign(container.style, {
position: 'absolute',
pointerEvents: 'none',
top: '0',
left: '0',
right: '0',
bottom: '0',
borderTopLeftRadius: style.borderTopLeftRadius,
borderTopRightRadius: style.borderTopRightRadius,
borderBottomRightRadius: style.borderBottomRightRadius,
borderBottomLeftRadius: style.borderBottomLeftRadius,
overflow: centered ? 'visible' : 'hidden',
});
// Create span to show the ripple effect
const ripple = document.createElement('span');
Object.assign(ripple.style, {
position: 'absolute',
pointerEvents: 'none',
backgroundColor: calculatedRippleColor,
borderRadius: '50%',
/* Transition configuration */
transitionProperty: 'transform opacity',
transitionDuration: `${Math.min(size * 1.5, 350)}ms`,
transitionTimingFunction: 'linear',
transformOrigin: 'center',
/* We'll animate these properties */
transform: 'translate3d(-50%, -50%, 0) scale3d(0.1, 0.1, 0.1)',
opacity: '0.5',
// Position the ripple where cursor was
left: `${touchX}px`,
top: `${touchY}px`,
width: `${size}px`,
height: `${size}px`,
});
// Finally, append it to DOM
container.appendChild(ripple);
button.appendChild(container);
// rAF runs in the same frame as the event handler
// Use double rAF to ensure the transition class is added in next frame
// This will make sure that the transition animation is triggered
requestAnimationFrame(() => {
requestAnimationFrame(() => {
Object.assign(ripple.style, {
transform: 'translate3d(-50%, -50%, 0) scale3d(1, 1, 1)',
opacity: '1',
});
});
});
}
},
[onPressIn, rest, rippleEffectEnabled, calculatedRippleColor]
);
const handlePressOut = React.useCallback(
(e: any) => {
onPressOut?.(e);
if (rippleEffectEnabled) {
const containers = e.currentTarget.querySelectorAll(
'[data-paper-ripple]'
) as HTMLElement[];
requestAnimationFrame(() => {
requestAnimationFrame(() => {
containers.forEach((container) => {
const ripple = container.firstChild as HTMLSpanElement;
Object.assign(ripple.style, {
transitionDuration: '250ms',
opacity: 0,
});
// Finally remove the span after the transition
setTimeout(() => {
const { parentNode } = container;
if (parentNode) {
parentNode.removeChild(container);
}
}, 500);
});
});
});
}
},
[onPressOut, rippleEffectEnabled]
);
const hasPassedTouchHandler = hasTouchHandler({
onPress,
onLongPress,
onPressIn,
onPressOut,
});
const disabled = disabledProp || !hasPassedTouchHandler;
return (
<Pressable
{...rest}
ref={ref}
onPress={debouncedOnPress}
onPressIn={handlePressIn}
onPressOut={handlePressOut}
disabled={disabled}
style={(state: PressableStateCallbackType) => [
styles.touchable,
borderless && styles.borderless,
// focused state is not ready yet: https://github.com/necolas/react-native-web/issues/1849
// state.focused && { backgroundColor: ___ },
state.hovered && { backgroundColor: hoverColor },
disabled && styles.disabled,
typeof style === 'function' ? style(state) : style,
]}
>
{(state: PressableStateCallbackType) =>
React.Children.only(
typeof children === 'function' ? children(state) : children
)
}
</Pressable>
);
};
/**
* Whether ripple effect is supported.
*/
TouchableRipple.supported = true;
const styles = StyleSheet.create({
touchable: {
position: 'relative',
...(Platform.OS === 'web' && {
cursor: 'pointer',
transition: '150ms background-color',
}),
},
disabled: {
...(Platform.OS === 'web' && {
cursor: 'auto',
}),
},
borderless: {
overflow: 'hidden',
},
});
const Component = forwardRef(TouchableRipple);
export default Component as typeof Component & { supported: boolean };