1 | import PropTypes from 'prop-types';
|
2 | import React from 'react';
|
3 | import { ColorPropType, Platform, View, ViewPropTypes, processColor } from 'react-native';
|
4 |
|
5 | import NativeLinearGradient from './NativeLinearGradient';
|
6 |
|
7 | type Props = {
|
8 | colors: string[];
|
9 | locations?: number[] | null;
|
10 | start?: Point | null;
|
11 | end?: Point | null;
|
12 | } & React.ComponentProps<typeof View>;
|
13 |
|
14 | type Point = { x: number; y: number } | [number, number];
|
15 |
|
16 | export default class LinearGradient extends React.Component<Props> {
|
17 | static propTypes = {
|
18 | ...ViewPropTypes,
|
19 | colors: PropTypes.arrayOf(ColorPropType).isRequired,
|
20 | locations: PropTypes.arrayOf(PropTypes.number),
|
21 | start: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.object]),
|
22 | end: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.object]),
|
23 | };
|
24 |
|
25 | render() {
|
26 | let { colors, locations, start, end, ...props } = this.props;
|
27 |
|
28 | if (locations && colors.length !== locations.length) {
|
29 | console.warn('LinearGradient colors and locations props should be arrays of the same length');
|
30 | locations = locations.slice(0, colors.length);
|
31 | }
|
32 |
|
33 | return (
|
34 | <NativeLinearGradient
|
35 | {...props}
|
36 | colors={Platform.select({
|
37 | web: colors as any,
|
38 | default: colors.map(processColor),
|
39 | })}
|
40 | locations={locations}
|
41 | startPoint={_normalizePoint(start)}
|
42 | endPoint={_normalizePoint(end)}
|
43 | />
|
44 | );
|
45 | }
|
46 | }
|
47 |
|
48 | function _normalizePoint(point: Point | null | undefined): [number, number] | undefined {
|
49 | if (!point) {
|
50 | return undefined;
|
51 | }
|
52 |
|
53 | if (Array.isArray(point) && point.length !== 2) {
|
54 | console.warn('start and end props for LinearGradient must be of the format [x,y] or {x, y}');
|
55 | return undefined;
|
56 | }
|
57 |
|
58 | return Array.isArray(point) ? point : [point.x, point.y];
|
59 | }
|