@td-design/react-native
Version:
react-native UI组件库
87 lines • 2.82 kB
JavaScript
import React, { forwardRef, useMemo } from 'react';
import { StyleSheet, TouchableWithoutFeedback } from 'react-native';
import Animated, { useAnimatedStyle } from 'react-native-reanimated';
import { useTheme } from '@shopify/restyle';
import Box from '../box';
import helpers from '../helpers';
import Text from '../text';
import { mix, mixColor } from '../utils/redash';
import useSwitch from './useSwitch';
const {
px
} = helpers;
const SWITCH_WIDTH = px(50);
const Switch = /*#__PURE__*/forwardRef((_ref2,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_ref) => {
let {
checked = false,
disabled = false,
onChange,
activeBackground,
showText = false,
onText = '开',
offText = '关',
width = SWITCH_WIDTH
} = _ref2;
const theme = useTheme();
const {
progress,
toggle
} = useSwitch({
onChange,
checked
});
const HEIGHT = width / 2;
const HANDLER_SIZE = HEIGHT;
const handlerStyle = useAnimatedStyle(() => ({
borderWidth: 1,
borderColor: mixColor(progress.value, disabled ? theme.colors.disabled : theme.colors.gray50, disabled ? theme.colors.primary400 : activeBackground ?? theme.colors.primary200),
transform: [{
translateX: mix(progress.value, 0, width / 2)
}]
}));
const containerStyle = useAnimatedStyle(() => ({
backgroundColor: mixColor(progress.value, disabled ? theme.colors.disabled : theme.colors.gray50, disabled ? theme.colors.primary400 : activeBackground ?? theme.colors.primary200)
}));
const styles = StyleSheet.create({
content: {
width,
height: HEIGHT,
borderRadius: HEIGHT,
justifyContent: 'center'
},
handler: {
width: HANDLER_SIZE,
height: HANDLER_SIZE,
borderRadius: HANDLER_SIZE,
backgroundColor: disabled ? theme.colors.gray50 : theme.colors.white,
justifyContent: 'center',
alignItems: 'center'
},
text: {
fontSize: HANDLER_SIZE / 2,
color: theme.colors.primary200
}
});
const Content = useMemo(() => {
return /*#__PURE__*/React.createElement(Animated.View, {
style: [styles.content, containerStyle]
}, /*#__PURE__*/React.createElement(Animated.View, {
style: [styles.handler, handlerStyle]
}, showText ? checked ? /*#__PURE__*/React.createElement(Text, {
style: styles.text
}, offText) : /*#__PURE__*/React.createElement(Text, {
style: styles.text
}, onText) : /*#__PURE__*/React.createElement(Box, null)));
}, [checked, disabled, showText, onText, offText, containerStyle, handlerStyle]);
if (disabled) {
return Content;
}
return /*#__PURE__*/React.createElement(TouchableWithoutFeedback, {
onPress: toggle
}, Content);
});
Switch.displayName = 'Switch';
export default Switch;
//# sourceMappingURL=index.js.map