import React, { forwardRef, useMemo } from 'react'; import ECharts from './ECharts'; import propTypes from 'prop-types'; import _ from 'lodash'; const isCategory = (category) => category !== undefined; const isArea = (lineType) => lineType === 'area'; const LineChart = forwardRef((props, ref) => { const { category, lineType, smooth, dataSource, title } = props; const option = useMemo(() => { const titleCfg = typeof title === 'string' ? { show: true, text } : { show: false }; const xAxis = isCategory(category) ? { type: 'category', data: category, } : { type: 'time', }; const hasUnitItem = dataSource.find((item) => item.unit); const yAxis = !!hasUnitItem ? { name: `(${hasUnitItem.unit})` } : {}; const series = dataSource.map((item, index) => { const config = _.omit(item, ['type']); const itemStyle = isArea(lineType) ? { areaStyle: {}, } : {}; return { type: 'line', smooth, ...itemStyle, ...config, }; }); return { xAxis, yAxis, series, title: titleCfg }; }, [category, smooth, lineType, dataSource, title]); const restProps = _.omit(props, ['category', 'lineType', 'smooth', 'dataSource', 'title']); return <ECharts ref={ref} option={option} {...restProps} />; }); LineChart.PropTypes = { smooth: propTypes.boolean, lineType: propTypes.oneOf(['line', 'area']), category: propTypes.array, dataSource: propTypes.objectOf({ name: propTypes.string, data: propTypes.array, unit: propTypes.unit, }), title: propTypes.string || propTypes.object, }; LineChart.defaultProps = { smooth: true, lineType: 'line', }; export default LineChart;