-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathSwitch.tsx
54 lines (46 loc) · 1.65 KB
/
Switch.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
import React, {useEffect, useRef} from 'react';
import {Animated} from 'react-native';
import useThemeStyles from '@hooks/useThemeStyles';
import useNativeDriver from '@libs/useNativeDriver';
import CONST from '@src/CONST';
import PressableWithFeedback from './Pressable/PressableWithFeedback';
type SwitchProps = {
/** Whether the switch is toggled to the on position */
isOn: boolean;
/** Callback to fire when the switch is toggled */
onToggle: (isOn: boolean) => void;
/** Accessibility label for the switch */
accessibilityLabel: string;
};
const OFFSET_X = {
OFF: 0,
ON: 20,
};
function Switch({isOn, onToggle, accessibilityLabel}: SwitchProps) {
const styles = useThemeStyles();
const offsetX = useRef(new Animated.Value(isOn ? OFFSET_X.ON : OFFSET_X.OFF));
useEffect(() => {
Animated.timing(offsetX.current, {
toValue: isOn ? OFFSET_X.ON : OFFSET_X.OFF,
duration: 300,
useNativeDriver,
}).start();
}, [isOn]);
return (
<PressableWithFeedback
style={[styles.switchTrack, !isOn && styles.switchInactive]}
onPress={() => onToggle(!isOn)}
onLongPress={() => onToggle(!isOn)}
role={CONST.ROLE.SWITCH}
aria-checked={isOn}
accessibilityLabel={accessibilityLabel}
// disable hover dim for switch
hoverDimmingValue={1}
pressDimmingValue={0.8}
>
<Animated.View style={[styles.switchThumb, styles.switchThumbTransformation(offsetX.current)]} />
</PressableWithFeedback>
);
}
Switch.displayName = 'Switch';
export default Switch;