UNPKG

2.77 kBJavaScriptView Raw
1import React, { useEffect, useState } from 'react';
2import { View } from 'react-native';
3import normalizeColor from 'react-native-web/src/modules/normalizeColor';
4const NativeLinearGradient = ({ colors, locations, startPoint, endPoint, ...props }) => {
5 const [layout, setLayout] = useState(null);
6 const [gradientColors, setGradientColors] = useState([]);
7 const [pseudoAngle, setPseudoAngle] = useState(0);
8 useEffect(() => {
9 const getControlPoints = () => {
10 let correctedStartPoint = [0, 0];
11 if (Array.isArray(startPoint)) {
12 correctedStartPoint = [
13 startPoint[0] != null ? startPoint[0] : 0.0,
14 startPoint[1] != null ? startPoint[1] : 0.0,
15 ];
16 }
17 let correctedEndPoint = [0.0, 1.0];
18 if (Array.isArray(endPoint)) {
19 correctedEndPoint = [
20 endPoint[0] != null ? endPoint[0] : 0.0,
21 endPoint[1] != null ? endPoint[1] : 1.0,
22 ];
23 }
24 return [correctedStartPoint, correctedEndPoint];
25 };
26 const [start, end] = getControlPoints();
27 const { width = 1, height = 1 } = layout || {};
28 start[0] *= width;
29 end[0] *= width;
30 start[1] *= height;
31 end[1] *= height;
32 const py = end[1] - start[1];
33 const px = end[0] - start[0];
34 setPseudoAngle(90 + (Math.atan2(py, px) * 180) / Math.PI);
35 }, [startPoint, endPoint]);
36 useEffect(() => {
37 const nextGradientColors = colors.map((color, index) => {
38 const hexColor = normalizeColor(color);
39 let output = hexColor;
40 if (locations && locations[index]) {
41 const location = Math.max(0, Math.min(1, locations[index]));
42 // Convert 0...1 to 0...100
43 const percentage = location * 100;
44 output += ` ${percentage}%`;
45 }
46 return output;
47 });
48 setGradientColors(nextGradientColors);
49 }, [colors, locations]);
50 const colorStyle = gradientColors.join(',');
51 const backgroundImage = `linear-gradient(${pseudoAngle}deg, ${colorStyle})`;
52 // TODO: Bacon: In the future we could consider adding `backgroundRepeat: "no-repeat"`. For more
53 // browser support.
54 return (<View {...props} style={[
55 props.style,
56 // @ts-ignore: [ts] Property 'backgroundImage' does not exist on type 'ViewStyle'.
57 { backgroundImage },
58 ]} onLayout={event => {
59 setLayout(event.nativeEvent.layout);
60 if (props.onLayout) {
61 props.onLayout(event);
62 }
63 }}/>);
64};
65export default NativeLinearGradient;
66//# sourceMappingURL=NativeLinearGradient.web.js.map
\No newline at end of file