Allow custom options for charts

This commit is contained in:
Thomas Nordquist
2019-06-17 16:37:13 +02:00
parent 2296143883
commit 0f9c2cd36f
10 changed files with 367 additions and 39 deletions

View File

@@ -1,6 +1,7 @@
import * as React from 'react'
import DateFormatter from '../helper/DateFormatter'
import { default as ReactResizeDetector } from 'react-resize-detector'
import { PlotCurveTypes } from '../../reducers/Charts'
import { Theme, withTheme } from '@material-ui/core'
import 'react-vis/dist/style.css'
const { XYPlot, LineMarkSeries, Hint, XAxis, YAxis, HorizontalGridLines } = require('react-vis')
@@ -9,6 +10,25 @@ const abbreviate = require('number-abbreviate')
interface Props {
data: Array<{ x: number; y: number }>
theme: Theme
interpolation?: PlotCurveTypes
range?: [number?, number?]
}
function mapCurveType(type: PlotCurveTypes | undefined) {
switch (type) {
case 'curve':
return 'curveMonotoneX'
case 'linear':
return 'curveLinear'
case 'cubic_basis_spline':
return 'curveBasis'
case 'step_after':
return 'curveStepAfter'
case 'step_before':
return 'curveStepBefore'
default:
return 'curveMonotoneX'
}
}
export default withTheme((props: Props) => {
@@ -31,12 +51,16 @@ export default withTheme((props: Props) => {
setTooltip({ value })
}, [])
const data = props.data
return React.useMemo(() => {
const data = props.data
const calculatedDomain = domainForData(data)
let yDomain: [number, number] = props.range
? [props.range[0] || calculatedDomain[0], props.range[1] || calculatedDomain[1]]
: calculatedDomain
return (
<div style={{ height: '150px', overflow: 'hidden' }}>
<XYPlot width={width} height={180}>
<XYPlot width={width} height={180} yDomain={yDomain}>
<HorizontalGridLines />
<XAxis />
<YAxis width={45} tickFormat={(num: number) => abbreviate(num)} />
@@ -50,12 +74,35 @@ export default withTheme((props: Props) => {
onValueMouseOut={hideTooltip}
size={3}
data={data}
curve="curveMonotoneX"
curve={mapCurveType(props.interpolation)}
/>
{tooltip.value ? <Hint format={hintFormatter} value={tooltip.value} /> : null}
</XYPlot>
<ReactResizeDetector handleWidth={true} onResize={detectResize} />
</div>
)
}, [width, data, tooltip])
}, [width, props.data, tooltip, props.interpolation, props.range])
})
function domainForData(data: Array<{ x: number; y: number }>): [number, number] {
let max = data[0].y
let min = data[0].y
data.forEach(d => {
if (max < d.y) {
max = d.y
}
if (min > d.y) {
min = d.y
}
})
if ((max === 1 || max === 0) && (min === 1 || min === 0)) {
return [0, 1]
}
if (min === max) {
return [min - 0.5 * min, min + 0.5 * min]
}
return [min, max]
}