open-nomad/ui/app/components/line-chart.js

329 lines
8.2 KiB
JavaScript
Raw Normal View History

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
2020-08-04 02:22:03 +00:00
import { assert } from '@ember/debug';
2018-09-07 16:59:02 +00:00
import { run } from '@ember/runloop';
import d3 from 'd3-selection';
import d3Scale from 'd3-scale';
import d3Axis from 'd3-axis';
import d3Array from 'd3-array';
import d3Format from 'd3-format';
import d3TimeFormat from 'd3-time-format';
import styleString from 'nomad-ui/utils/properties/glimmer-style-string';
import uniquely from 'nomad-ui/utils/properties/uniquely';
2018-09-07 16:59:02 +00:00
// Returns a new array with the specified number of points linearly
// distributed across the bounds
const lerp = ([low, high], numPoints) => {
const step = (high - low) / (numPoints - 1);
const arr = [];
for (var i = 0; i < numPoints; i++) {
arr.push(low + step * i);
}
return arr;
};
// Round a number or an array of numbers
const nice = val => (val instanceof Array ? val.map(nice) : Math.round(val));
const defaultXScale = (data, yAxisOffset, xProp, timeseries) => {
const scale = timeseries ? d3Scale.scaleTime() : d3Scale.scaleLinear();
const domain = data.length ? d3Array.extent(data, d => d[xProp]) : [0, 1];
scale.rangeRound([10, yAxisOffset]).domain(domain);
return scale;
};
const defaultYScale = (data, xAxisOffset, yProp) => {
let max = d3Array.max(data, d => d[yProp]) || 1;
if (max > 1) {
max = nice(max);
}
return d3Scale
.scaleLinear()
.rangeRound([xAxisOffset, 10])
.domain([0, max]);
};
export default class LineChart extends Component {
/** Args
data = null;
xProp = null;
yProp = null;
curve = 'linear';
title = 'Line Chart';
description = null;
timeseries = false;
chartClass = 'is-primary';
activeAnnotation = null;
onAnnotationClick() {}
xFormat;
yFormat;
xScale;
yScale;
*/
@tracked width = 0;
@tracked height = 0;
@tracked isActive = false;
@tracked activeDatum = null;
@tracked tooltipPosition = null;
@tracked element = null;
@uniquely('title') titleId;
@uniquely('desc') descriptionId;
get xProp() {
return this.args.xProp || 'time';
}
get yProp() {
return this.args.yProp || 'value';
}
get data() {
return this.args.data || [];
}
get curve() {
return this.args.curve || 'linear';
}
get chartClass() {
return this.args.chartClass || 'is-primary';
}
2018-09-07 16:59:02 +00:00
@action
xFormat(timeseries) {
if (this.args.xFormat) return this.args.xFormat;
return timeseries ? d3TimeFormat.timeFormat('%b %d, %H:%M') : d3Format.format(',');
}
2018-09-07 16:59:02 +00:00
@action
yFormat() {
if (this.args.yFormat) return this.args.yFormat;
return d3Format.format(',.2~r');
}
2018-09-07 16:59:02 +00:00
get activeDatumLabel() {
2019-03-26 07:46:44 +00:00
const datum = this.activeDatum;
2018-09-07 16:59:02 +00:00
if (!datum) return undefined;
2018-09-07 16:59:02 +00:00
2019-03-26 07:46:44 +00:00
const x = datum[this.xProp];
return this.xFormat(this.args.timeseries)(x);
}
2018-09-07 16:59:02 +00:00
get activeDatumValue() {
2019-03-26 07:46:44 +00:00
const datum = this.activeDatum;
2018-09-07 16:59:02 +00:00
if (!datum) return undefined;
2018-09-07 16:59:02 +00:00
2019-03-26 07:46:44 +00:00
const y = datum[this.yProp];
2018-09-07 16:59:02 +00:00
return this.yFormat()(y);
}
2018-09-07 16:59:02 +00:00
2020-08-04 02:22:03 +00:00
get curveMethod() {
const mappings = {
linear: 'curveLinear',
stepAfter: 'curveStepAfter',
};
assert(`Provided curve "${this.curve}" is not an allowed curve type`, mappings[this.curve]);
return mappings[this.curve];
}
@styleString
get tooltipStyle() {
return this.tooltipPosition;
}
get xScale() {
const fn = this.args.xScale || defaultXScale;
return fn(this.data, this.yAxisOffset, this.xProp, this.args.timeseries);
}
2018-09-07 16:59:02 +00:00
get xRange() {
const { xProp, data } = this;
const range = d3Array.extent(data, d => d[xProp]);
const formatter = this.xFormat(this.args.timeseries);
return range.map(formatter);
}
get yRange() {
2019-03-26 07:46:44 +00:00
const yProp = this.yProp;
const range = d3Array.extent(this.data, d => d[yProp]);
const formatter = this.yFormat();
return range.map(formatter);
}
get yScale() {
const fn = this.args.yScale || defaultYScale;
return fn(this.data, this.xAxisOffset, this.yProp);
}
2018-09-07 16:59:02 +00:00
get xAxis() {
const formatter = this.xFormat(this.args.timeseries);
2018-09-07 16:59:02 +00:00
return d3Axis
.axisBottom()
2019-03-26 07:46:44 +00:00
.scale(this.xScale)
2018-09-07 16:59:02 +00:00
.ticks(5)
.tickFormat(formatter);
}
2018-09-07 16:59:02 +00:00
get yTicks() {
2019-03-26 07:46:44 +00:00
const height = this.xAxisOffset;
2018-09-07 16:59:02 +00:00
const tickCount = Math.ceil(height / 120) * 2 + 1;
2019-03-26 07:46:44 +00:00
const domain = this.yScale.domain();
const ticks = lerp(domain, tickCount);
return domain[1] - domain[0] > 1 ? nice(ticks) : ticks;
}
2018-09-07 16:59:02 +00:00
get yAxis() {
2018-09-07 16:59:02 +00:00
const formatter = this.yFormat();
return d3Axis
.axisRight()
2019-03-26 07:46:44 +00:00
.scale(this.yScale)
.tickValues(this.yTicks)
2018-09-07 16:59:02 +00:00
.tickFormat(formatter);
}
2018-09-07 16:59:02 +00:00
get yGridlines() {
2018-09-07 16:59:02 +00:00
// The first gridline overlaps the x-axis, so remove it
2019-03-26 07:46:44 +00:00
const [, ...ticks] = this.yTicks;
2018-09-07 16:59:02 +00:00
return d3Axis
.axisRight()
2019-03-26 07:46:44 +00:00
.scale(this.yScale)
2018-09-07 16:59:02 +00:00
.tickValues(ticks)
2019-03-26 07:46:44 +00:00
.tickSize(-this.yAxisOffset)
2018-09-07 16:59:02 +00:00
.tickFormat('');
}
2018-09-07 16:59:02 +00:00
get xAxisHeight() {
// Avoid divide by zero errors by always having a height
if (!this.element) return 1;
2018-09-07 16:59:02 +00:00
const axis = this.element.querySelector('.x-axis');
return axis && axis.getBBox().height;
}
2018-09-07 16:59:02 +00:00
get yAxisWidth() {
// Avoid divide by zero errors by always having a width
if (!this.element) return 1;
2018-09-07 16:59:02 +00:00
const axis = this.element.querySelector('.y-axis');
return axis && axis.getBBox().width;
}
2018-09-07 16:59:02 +00:00
get xAxisOffset() {
2019-03-26 07:46:44 +00:00
return this.height - this.xAxisHeight;
}
2018-09-07 16:59:02 +00:00
get yAxisOffset() {
2019-03-26 07:46:44 +00:00
return this.width - this.yAxisWidth;
}
2018-09-07 16:59:02 +00:00
@action
onInsert(element) {
this.element = element;
2018-09-07 16:59:02 +00:00
this.updateDimensions();
const canvas = d3.select(this.element.querySelector('.hover-target'));
2018-09-07 16:59:02 +00:00
const updateActiveDatum = this.updateActiveDatum.bind(this);
const chart = this;
canvas.on('mouseenter', function() {
const mouseX = d3.mouse(this)[0];
chart.latestMouseX = mouseX;
updateActiveDatum(mouseX);
run.schedule('afterRender', chart, () => (chart.isActive = true));
2018-09-07 16:59:02 +00:00
});
canvas.on('mousemove', function() {
const mouseX = d3.mouse(this)[0];
chart.latestMouseX = mouseX;
2018-09-07 16:59:02 +00:00
updateActiveDatum(mouseX);
});
canvas.on('mouseleave', () => {
run.schedule('afterRender', this, () => (this.isActive = false));
this.activeDatum = null;
2018-09-07 16:59:02 +00:00
});
}
2018-09-07 16:59:02 +00:00
updateActiveDatum(mouseX) {
2019-03-26 07:46:44 +00:00
const { xScale, xProp, yScale, yProp, data } = this;
2018-09-07 16:59:02 +00:00
if (!data || !data.length) return;
2018-09-07 16:59:02 +00:00
// Map the mouse coordinate to the index in the data array
const bisector = d3Array.bisector(d => d[xProp]).left;
const x = xScale.invert(mouseX);
const index = bisector(data, x, 1);
// The data point on either side of the cursor
const dLeft = data[index - 1];
const dRight = data[index];
let datum;
// If there is only one point, it's the activeDatum
if (dLeft && !dRight) {
datum = dLeft;
} else {
// Pick the closer point
datum = x - dLeft[xProp] > dRight[xProp] - x ? dRight : dLeft;
}
2018-09-07 16:59:02 +00:00
this.activeDatum = datum;
this.tooltipPosition = {
2018-09-07 16:59:02 +00:00
left: xScale(datum[xProp]),
top: yScale(datum[yProp]) - 10,
};
}
2018-09-07 16:59:02 +00:00
// The renderChart method should only ever be responsible for runtime calculations
// and appending d3 created elements to the DOM (such as axes).
renderChart() {
// There is nothing to do if the element hasn't been inserted yet
if (!this.element) return;
// Create the axes to get the dimensions of the resulting
2018-09-07 16:59:02 +00:00
// svg elements
this.mountD3Elements();
run.next(() => {
// Since each axis depends on the dimension of the other
// axis, the axes themselves are recomputed and need to
// be re-rendered.
this.mountD3Elements();
2019-03-26 07:46:44 +00:00
if (this.isActive) {
this.updateActiveDatum(this.latestMouseX);
2018-09-07 16:59:02 +00:00
}
});
}
2018-09-07 16:59:02 +00:00
mountD3Elements() {
2019-03-26 07:46:44 +00:00
if (!this.isDestroyed && !this.isDestroying) {
d3.select(this.element.querySelector('.x-axis')).call(this.xAxis);
d3.select(this.element.querySelector('.y-axis')).call(this.yAxis);
d3.select(this.element.querySelector('.y-gridlines')).call(this.yGridlines);
}
}
2018-09-07 16:59:02 +00:00
annotationClick(annotation) {
this.args.onAnnotationClick && this.args.onAnnotationClick(annotation);
}
2018-09-07 16:59:02 +00:00
@action
2018-09-07 16:59:02 +00:00
updateDimensions() {
2020-05-26 21:05:45 +00:00
const $svg = this.element.querySelector('svg');
2018-09-07 16:59:02 +00:00
this.height = $svg.clientHeight;
this.width = $svg.clientWidth;
2018-09-07 16:59:02 +00:00
this.renderChart();
}
}