1import PropTypes from 'prop-types';
2import React from 'react';
3import { ColorPropType, View, ViewPropTypes, processColor } from 'react-native';
4
5import NativeLinearGradient from './NativeLinearGradient';
6
7type Props = {
8  colors: string[];
9  locations?: number[] | null;
10  start?: Point | null;
11  end?: Point | null;
12} & React.ComponentProps<typeof View>;
13
14type Point = { x: number; y: number } | [number, number];
15
16export 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={colors.map(processColor)}
37        locations={locations}
38        startPoint={_normalizePoint(start)}
39        endPoint={_normalizePoint(end)}
40      />
41    );
42  }
43}
44
45function _normalizePoint(point: Point | null | undefined): [number, number] | undefined {
46  if (!point) {
47    return undefined;
48  }
49
50  if (Array.isArray(point) && point.length !== 2) {
51    console.warn('start and end props for LinearGradient must be of the format [x,y] or {x, y}');
52    return undefined;
53  }
54
55  return Array.isArray(point) ? point : [point.x, point.y];
56}
57