-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathButton.tsx
499 lines (476 loc) · 13.5 KB
/
Button.tsx
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
import * as React from 'react';
import {
AccessibilityRole,
Animated,
ColorValue,
GestureResponderEvent,
Platform,
PressableAndroidRippleConfig,
StyleProp,
StyleSheet,
TextStyle,
View,
ViewStyle,
} from 'react-native';
import color from 'color';
import { ButtonMode, getButtonColors } from './utils';
import { useInternalTheme } from '../../core/theming';
import type { $Omit, ThemeProp } from '../../types';
import { forwardRef } from '../../utils/forwardRef';
import hasTouchHandler from '../../utils/hasTouchHandler';
import { splitStyles } from '../../utils/splitStyles';
import ActivityIndicator from '../ActivityIndicator';
import Icon, { IconSource } from '../Icon';
import Surface from '../Surface';
import TouchableRipple from '../TouchableRipple/TouchableRipple';
import Text from '../Typography/Text';
export type Props = $Omit<React.ComponentProps<typeof Surface>, 'mode'> & {
/**
* Mode of the button. You can change the mode to adjust the styling to give it desired emphasis.
* - `text` - flat button without background or outline, used for the lowest priority actions, especially when presenting multiple options.
* - `outlined` - button with an outline without background, typically used for important, but not primary action – represents medium emphasis.
* - `contained` - button with a background color, used for important action, have the most visual impact and high emphasis.
* - `elevated` - button with a background color and elevation, used when absolutely necessary e.g. button requires visual separation from a patterned background. @supported Available in v5.x with theme version 3
* - `contained-tonal` - button with a secondary background color, an alternative middle ground between contained and outlined buttons. @supported Available in v5.x with theme version 3
*/
mode?: 'text' | 'outlined' | 'contained' | 'elevated' | 'contained-tonal';
/**
* Whether the color is a dark color. A dark button will render light text and vice-versa. Only applicable for:
* * `contained` mode for theme version 2
* * `contained`, `contained-tonal` and `elevated` modes for theme version 3.
*/
dark?: boolean;
/**
* Use a compact look, useful for `text` buttons in a row.
*/
compact?: boolean;
/**
* @deprecated Deprecated in v5.x - use `buttonColor` or `textColor` instead.
* Custom text color for flat button, or background color for contained button.
*/
color?: string;
/**
* Custom button's background color.
*/
buttonColor?: string;
/**
* Custom button's text color.
*/
textColor?: string;
/**
* Color of the ripple effect.
*/
rippleColor?: ColorValue;
/**
* Whether to show a loading indicator.
*/
loading?: boolean;
/**
* Icon to display for the `Button`.
*/
icon?: IconSource;
/**
* Whether the button is disabled. A disabled button is greyed out and `onPress` is not called on touch.
*/
disabled?: boolean;
/**
* Label text of the button.
*/
children: React.ReactNode;
/**
* Make the label text uppercased. Note that this won't work if you pass React elements as children.
*/
uppercase?: boolean;
/**
* Type of background drawabale to display the feedback (Android).
* https://reactnative.dev/docs/pressable#rippleconfig
*/
background?: PressableAndroidRippleConfig;
/**
* Accessibility label for the button. This is read by the screen reader when the user taps the button.
*/
accessibilityLabel?: string;
/**
* Accessibility hint for the button. This is read by the screen reader when the user taps the button.
*/
accessibilityHint?: string;
/**
* Accessibility role for the button. The "button" role is set by default.
*/
accessibilityRole?: AccessibilityRole;
/**
* Function to execute on press.
*/
onPress?: (e: GestureResponderEvent) => void;
/**
* Function to execute as soon as the touchable element is pressed and invoked even before onPress.
*/
onPressIn?: (e: GestureResponderEvent) => void;
/**
* Function to execute as soon as the touch is released even before onPress.
*/
onPressOut?: (e: GestureResponderEvent) => void;
/**
* Function to execute on long press.
*/
onLongPress?: (e: GestureResponderEvent) => void;
/**
* The number of milliseconds a user must touch the element before executing `onLongPress`.
*/
delayLongPress?: number;
/**
* Style of button's inner content.
* Use this prop to apply custom height and width and to set the icon on the right with `flexDirection: 'row-reverse'`.
*/
contentStyle?: StyleProp<ViewStyle>;
/**
* Specifies the largest possible scale a text font can reach.
*/
maxFontSizeMultiplier?: number;
/**
* Label text number Of Lines of the button.
*/
numberOfLines?: number;
style?: Animated.WithAnimatedValue<StyleProp<ViewStyle>>;
/**
* Style for the button text.
*/
labelStyle?: StyleProp<TextStyle>;
/**
* @optional
*/
theme?: ThemeProp;
/**
* Reference for the touchable
*/
touchableRef?: React.RefObject<View>;
/**
* testID to be used on tests.
*/
testID?: string;
};
/**
* A button is component that the user can press to trigger an action.
*
* ## Usage
* ```js
* import * as React from 'react';
* import { Button } from 'react-native-paper';
*
* const MyComponent = () => (
* <Button icon="camera" mode="contained" onPress={() => console.log('Pressed')}>
* Press me
* </Button>
* );
*
* export default MyComponent;
* ```
*/
const Button = (
{
disabled,
compact,
mode = 'text',
dark,
loading,
icon,
buttonColor: customButtonColor,
textColor: customTextColor,
rippleColor: customRippleColor,
children,
accessibilityLabel,
accessibilityHint,
accessibilityRole = 'button',
onPress,
onPressIn,
onPressOut,
onLongPress,
delayLongPress,
numberOfLines,
style,
theme: themeOverrides,
uppercase: uppercaseProp,
contentStyle,
labelStyle,
testID = 'button',
accessible,
background,
maxFontSizeMultiplier,
touchableRef,
...rest
}: Props,
ref: React.ForwardedRef<View>
) => {
const theme = useInternalTheme(themeOverrides);
const isMode = React.useCallback(
(modeToCompare: ButtonMode) => {
return mode === modeToCompare;
},
[mode]
);
const { roundness, isV3, animation } = theme;
const uppercase = uppercaseProp ?? !theme.isV3;
const hasPassedTouchHandler = hasTouchHandler({
onPress,
onPressIn,
onPressOut,
onLongPress,
});
const isElevationEntitled =
!disabled && (isV3 ? isMode('elevated') : isMode('contained'));
const initialElevation = isV3 ? 1 : 2;
const activeElevation = isV3 ? 2 : 8;
const { current: elevation } = React.useRef<Animated.Value>(
new Animated.Value(isElevationEntitled ? initialElevation : 0)
);
React.useEffect(() => {
elevation.setValue(isElevationEntitled ? initialElevation : 0);
}, [isElevationEntitled, elevation, initialElevation]);
const handlePressIn = (e: GestureResponderEvent) => {
onPressIn?.(e);
if (isV3 ? isMode('elevated') : isMode('contained')) {
const { scale } = animation;
Animated.timing(elevation, {
toValue: activeElevation,
duration: 200 * scale,
useNativeDriver:
Platform.OS === 'web' ||
Platform.constants.reactNativeVersion.minor <= 72,
}).start();
}
};
const handlePressOut = (e: GestureResponderEvent) => {
onPressOut?.(e);
if (isV3 ? isMode('elevated') : isMode('contained')) {
const { scale } = animation;
Animated.timing(elevation, {
toValue: initialElevation,
duration: 150 * scale,
useNativeDriver:
Platform.OS === 'web' ||
Platform.constants.reactNativeVersion.minor <= 72,
}).start();
}
};
const flattenedStyles = (StyleSheet.flatten(style) || {}) as ViewStyle;
const [, borderRadiusStyles] = splitStyles(
flattenedStyles,
(style) => style.startsWith('border') && style.endsWith('Radius')
);
const borderRadius = (isV3 ? 5 : 1) * roundness;
const iconSize = isV3 ? 18 : 16;
const NumberOfLines = numberOfLines ? numberOfLines : 1;
const { backgroundColor, borderColor, textColor, borderWidth } =
getButtonColors({
customButtonColor,
customTextColor,
theme,
mode,
disabled,
dark,
});
const rippleColor =
customRippleColor || color(textColor).alpha(0.12).rgb().string();
const touchableStyle = {
...borderRadiusStyles,
borderRadius: borderRadiusStyles.borderRadius ?? borderRadius,
};
const buttonStyle = {
backgroundColor,
borderColor,
borderWidth,
...touchableStyle,
};
const { color: customLabelColor, fontSize: customLabelSize } =
StyleSheet.flatten(labelStyle) || {};
const font = isV3 ? theme.fonts.labelLarge : theme.fonts.medium;
const textStyle = {
color: textColor,
...font,
};
const iconStyle =
StyleSheet.flatten(contentStyle)?.flexDirection === 'row-reverse'
? [
styles.iconReverse,
isV3 && styles[`md3IconReverse${compact ? 'Compact' : ''}`],
isV3 &&
isMode('text') &&
styles[`md3IconReverseTextMode${compact ? 'Compact' : ''}`],
]
: [
styles.icon,
isV3 && styles[`md3Icon${compact ? 'Compact' : ''}`],
isV3 &&
isMode('text') &&
styles[`md3IconTextMode${compact ? 'Compact' : ''}`],
];
return (
<Surface
{...rest}
ref={ref}
testID={`${testID}-container`}
style={
[
styles.button,
compact && styles.compact,
buttonStyle,
style,
!isV3 && !disabled && { elevation },
] as ViewStyle
}
{...(isV3 && { elevation: elevation })}
>
<TouchableRipple
borderless
background={background}
onPress={onPress}
onLongPress={onLongPress}
onPressIn={hasPassedTouchHandler ? handlePressIn : undefined}
onPressOut={hasPassedTouchHandler ? handlePressOut : undefined}
delayLongPress={delayLongPress}
accessibilityLabel={accessibilityLabel}
accessibilityHint={accessibilityHint}
accessibilityRole={accessibilityRole}
accessibilityState={{ disabled }}
accessible={accessible}
disabled={disabled}
rippleColor={rippleColor}
style={touchableStyle}
testID={testID}
theme={theme}
ref={touchableRef}
>
<View style={[styles.content, contentStyle]}>
{icon && loading !== true ? (
<View style={iconStyle} testID={`${testID}-icon-container`}>
<Icon
source={icon}
size={customLabelSize ?? iconSize}
color={
typeof customLabelColor === 'string'
? customLabelColor
: textColor
}
/>
</View>
) : null}
{loading ? (
<ActivityIndicator
size={customLabelSize ?? iconSize}
color={
typeof customLabelColor === 'string'
? customLabelColor
: textColor
}
style={iconStyle}
/>
) : null}
<Text
variant="labelLarge"
selectable={false}
numberOfLines={NumberOfLines}
testID={`${testID}-text`}
style={[
styles.label,
!isV3 && styles.md2Label,
isV3 &&
(isMode('text')
? icon || loading
? styles.md3LabelTextAddons
: styles.md3LabelText
: styles.md3Label),
compact && styles.compactLabel,
uppercase && styles.uppercaseLabel,
textStyle,
labelStyle,
]}
maxFontSizeMultiplier={maxFontSizeMultiplier}
>
{children}
</Text>
</View>
</TouchableRipple>
</Surface>
);
};
const styles = StyleSheet.create({
button: {
minWidth: 64,
borderStyle: 'solid',
},
compact: {
minWidth: 'auto',
},
content: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
icon: {
marginLeft: 12,
marginRight: -4,
},
iconReverse: {
marginRight: 12,
marginLeft: -4,
},
/* eslint-disable react-native/no-unused-styles */
md3Icon: {
marginLeft: 16,
marginRight: -16,
},
md3IconCompact: {
marginLeft: 8,
marginRight: 0,
},
md3IconReverse: {
marginLeft: -16,
marginRight: 16,
},
md3IconReverseCompact: {
marginLeft: 0,
marginRight: 8,
},
md3IconTextMode: {
marginLeft: 12,
marginRight: -8,
},
md3IconTextModeCompact: {
marginLeft: 6,
marginRight: 0,
},
md3IconReverseTextMode: {
marginLeft: -8,
marginRight: 12,
},
md3IconReverseTextModeCompact: {
marginLeft: 0,
marginRight: 6,
},
/* eslint-enable react-native/no-unused-styles */
label: {
textAlign: 'center',
marginVertical: 9,
marginHorizontal: 16,
},
md2Label: {
letterSpacing: 1,
},
compactLabel: {
marginHorizontal: 8,
},
uppercaseLabel: {
textTransform: 'uppercase',
},
md3Label: {
marginVertical: 10,
marginHorizontal: 24,
},
md3LabelText: {
marginHorizontal: 12,
},
md3LabelTextAddons: {
marginHorizontal: 16,
},
});
export default forwardRef(Button);