/
line.js
73 lines (63 loc) · 1.58 KB
/
line.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* global Chart */
/**
* Internal dependencies.
*/
import { getLabelWithTypeCondition, toolTipBaseConfig } from './utils';
/**
* Render a line chart.
*
* @param {Object} config Global chart config.
* @return {Chart}
*/
export const render = ( config ) => {
const {
dates,
options,
data,
target,
} = config;
// Convert dataset x-axis values to moment() objects.
_.each( data.datasets, ( dataset ) => {
_.each( dataset.data, ( pair, index ) => {
if ( ! dates.hour_by_hour ) {
pair.x = moment( pair.x ).utcOffset( 0 ).format( 'LLL' );
} else {
pair.x = moment( pair.x ).utcOffset( dates.utc_offset ).format( 'LLL' );
}
} );
} );
// Set min and max moment() values for the x-axis.
// @todo Not sure this is the correct way to be setting this?
_.each( options.scales.xAxes, ( xaxis ) => {
if ( ! dates.day_by_day ) {
xaxis.time.unit = 'month';
}
xaxis.time.min = moment( dates.start.date );
xaxis.time.max = moment( dates.end.date );
} );
// Config tooltips.
config.options.tooltips = tooltipConfig( config );
// Render
return new Chart( document.getElementById( target ), config );
};
/**
* Get custom tooltip config for line charts.
*
* @param {Object} config Global chart config.
* @return {Object}
*/
export const tooltipConfig = ( config ) => ( {
...toolTipBaseConfig,
callbacks: {
/**
* Generate a label.
*
* @param {Object} t
* @param {Object} d
*/
label: function( t, d ) {
const label = getLabelWithTypeCondition( t.yLabel, config );
return `${ d.datasets[ t.datasetIndex ].label }: ${ label }`;
},
},
} );