vault/ui/app/components/clients/line-chart.js
Jordan Reimer d4766766f2
Ember Upgrade to 4.4 (#17086)
* runs ember-cli-update to 4.4.0

* updates yarn.lock

* updates dependencies causing runtime errors (#17135)

* Inject Store Service When Accessed Implicitly (#17345)

* adds codemod for injecting store service

* adds custom babylon parser with decorators-legacy plugin for jscodeshift transforms

* updates inject-store-service codemod to only look for .extend object expressions and adds recast options

* runs inject-store-service codemod on js files

* replace query-params helper with hash (#17404)

* Updates/removes dependencies throwing errors in Ember 4.4 (#17396)

* updates ember-responsive to latest

* updates ember-composable-helpers to latest and uses includes helper since contains was removed

* updates ember-concurrency to latest

* updates ember-cli-clipboard to latest

* temporary workaround for toolbar-link component throwing errors for using params arg with LinkTo

* adds missing store injection to auth configure route

* fixes issue with string-list component throwing error for accessing prop in same computation

* fixes non-iterable query params issue in mfa methods controller

* refactors field-to-attrs to handle belongsTo rather than fragments

* converts mount-config fragment to belongsTo on auth-method model

* removes ember-api-actions and adds tune method to auth-method adapter

* converts cluster replication attributes from fragment to relationship

* updates ember-data, removes ember-data-fragments and updates yarn to latest

* removes fragments from secret-engine model

* removes fragment from test-form-model

* removes commented out code

* minor change to inject-store-service codemod and runs again on js files

* Remove LinkTo positional params (#17421)

* updates ember-cli-page-object to latest version

* update toolbar-link to support link-to args and not positional params

* adds replace arg to toolbar-link component

* Clean up js lint errors (#17426)

* replaces assert.equal to assert.strictEqual

* update eslint no-console to error and disables invididual intended uses of console

* cleans up hbs lint warnings (#17432)

* Upgrade bug and test fixes (#17500)

* updates inject-service codemod to take arg for service name and runs for flashMessages service

* fixes hbs lint error after merging main

* fixes flash messages

* updates more deps

* bug fixes

* test fixes

* updates ember-cli-content-security-policy and prevents default form submission throwing errors

* more bug and test fixes

* removes commented out code

* fixes issue with code-mirror modifier sending change event on setup causing same computation error

* Upgrade Clean Up (#17543)

* updates deprecation workflow and filter

* cleans up build errors, removes unused ivy-codemirror and sass and updates ember-cli-sass and node-sass to latest

* fixes control groups test that was skipped after upgrade

* updates control group service tests

* addresses review feedback

* updates control group service handleError method to use router.currentURL rather that transition.intent.url

* adds changelog entry
2022-10-18 09:46:02 -06:00

197 lines
6.6 KiB
JavaScript

import Component from '@glimmer/component';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { max } from 'd3-array';
// eslint-disable-next-line no-unused-vars
import { select, selectAll, node } from 'd3-selection';
import { axisLeft, axisBottom } from 'd3-axis';
import { scaleLinear, scalePoint } from 'd3-scale';
import { line } from 'd3-shape';
import {
LIGHT_AND_DARK_BLUE,
UPGRADE_WARNING,
SVG_DIMENSIONS,
formatNumbers,
} from 'vault/utils/chart-helpers';
import { parseAPITimestamp, formatChartDate } from 'core/utils/date-formatters';
import { formatNumber } from 'core/helpers/format-number';
/**
* @module LineChart
* LineChart components are used to display data in a line plot with accompanying tooltip
*
* @example
* ```js
* <LineChart @dataset={{dataset}} @upgradeData={{this.versionHistory}}/>
* ```
* @param {string} xKey - string denoting key for x-axis data (data[xKey]) of dataset
* @param {string} yKey - string denoting key for y-axis data (data[yKey]) of dataset
* @param {array} upgradeData - array of objects containing version history from the /version-history endpoint
* @param {string} [noDataMessage] - custom empty state message that displays when no dataset is passed to the chart
*/
export default class LineChart extends Component {
@tracked tooltipTarget = '';
@tracked tooltipMonth = '';
@tracked tooltipTotal = '';
@tracked tooltipNew = '';
@tracked tooltipUpgradeText = '';
get yKey() {
return this.args.yKey || 'clients';
}
get xKey() {
return this.args.xKey || 'month';
}
get upgradeData() {
const upgradeData = this.args.upgradeData;
if (!upgradeData) return null;
if (!Array.isArray(upgradeData)) {
console.debug('upgradeData must be an array of objects containing upgrade history'); // eslint-disable-line
return null;
} else if (!Object.keys(upgradeData[0]).includes('timestampInstalled')) {
// eslint-disable-next-line
console.debug(
`upgrade must be an object with the following key names: ['id', 'previousVersion', 'timestampInstalled']`
);
return null;
} else {
return upgradeData?.map((versionData) => {
return {
[this.xKey]: parseAPITimestamp(versionData.timestampInstalled, 'M/yy'),
...versionData,
};
});
}
}
@action removeTooltip() {
this.tooltipTarget = null;
}
@action
renderChart(element, [chartData]) {
const dataset = chartData;
const filteredData = dataset.filter((e) => Object.keys(e).includes(this.yKey)); // months with data will contain a 'clients' key (otherwise only a timestamp)
const domainMax = max(filteredData.map((d) => d[this.yKey]));
const chartSvg = select(element);
chartSvg.attr('viewBox', `-50 20 600 ${SVG_DIMENSIONS.height}`); // set svg dimensions
// clear out DOM before appending anything
chartSvg.selectAll('g').remove().exit().data(filteredData).enter();
// DEFINE AXES SCALES
const yScale = scaleLinear().domain([0, domainMax]).range([0, 100]).nice();
const yAxisScale = scaleLinear().domain([0, domainMax]).range([SVG_DIMENSIONS.height, 0]).nice();
// use full dataset (instead of filteredData) so x-axis spans months with and without data
const xScale = scalePoint()
.domain(dataset.map((d) => d[this.xKey]))
.range([0, SVG_DIMENSIONS.width])
.padding(0.2);
// CUSTOMIZE AND APPEND AXES
const yAxis = axisLeft(yAxisScale)
.ticks(4)
.tickPadding(10)
.tickSizeInner(-SVG_DIMENSIONS.width) // makes grid lines length of svg
.tickFormat(formatNumbers);
const xAxis = axisBottom(xScale).tickSize(0);
yAxis(chartSvg.append('g').attr('data-test-line-chart', 'y-axis-labels'));
xAxis(
chartSvg
.append('g')
.attr('transform', `translate(0, ${SVG_DIMENSIONS.height + 10})`)
.attr('data-test-line-chart', 'x-axis-labels')
);
chartSvg.selectAll('.domain').remove();
const findUpgradeData = (datum) => {
return this.upgradeData
? this.upgradeData.find((upgrade) => upgrade[this.xKey] === datum[this.xKey])
: null;
};
// VERSION UPGRADE INDICATOR
chartSvg
.append('g')
.selectAll('circle')
.data(filteredData)
.enter()
.append('circle')
.attr('class', 'upgrade-circle')
.attr('data-test-line-chart', (d) => `upgrade-${d[this.xKey]}`)
.attr('fill', UPGRADE_WARNING)
.style('opacity', (d) => (findUpgradeData(d) ? '1' : '0'))
.attr('cy', (d) => `${100 - yScale(d[this.yKey])}%`)
.attr('cx', (d) => xScale(d[this.xKey]))
.attr('r', 10);
// PATH BETWEEN PLOT POINTS
const lineGenerator = line()
.x((d) => xScale(d[this.xKey]))
.y((d) => yAxisScale(d[this.yKey]));
chartSvg
.append('g')
.append('path')
.attr('fill', 'none')
.attr('stroke', LIGHT_AND_DARK_BLUE[1])
.attr('stroke-width', 0.5)
.attr('d', lineGenerator(filteredData));
// LINE PLOTS (CIRCLES)
chartSvg
.append('g')
.selectAll('circle')
.data(filteredData)
.enter()
.append('circle')
.attr('data-test-line-chart', 'plot-point')
.attr('cy', (d) => `${100 - yScale(d[this.yKey])}%`)
.attr('cx', (d) => xScale(d[this.xKey]))
.attr('r', 3.5)
.attr('fill', LIGHT_AND_DARK_BLUE[0])
.attr('stroke', LIGHT_AND_DARK_BLUE[1])
.attr('stroke-width', 1.5);
// LARGER HOVER CIRCLES
chartSvg
.append('g')
.selectAll('circle')
.data(filteredData)
.enter()
.append('circle')
.attr('class', 'hover-circle')
.style('cursor', 'pointer')
.style('opacity', '0')
.attr('cy', (d) => `${100 - yScale(d[this.yKey])}%`)
.attr('cx', (d) => xScale(d[this.xKey]))
.attr('r', 10);
const hoverCircles = chartSvg.selectAll('.hover-circle');
// MOUSE EVENT FOR TOOLTIP
hoverCircles.on('mouseover', (data) => {
// TODO: how to generalize this?
this.tooltipMonth = formatChartDate(data[this.xKey]);
this.tooltipTotal = formatNumber([data[this.yKey]]) + ' total clients';
this.tooltipNew = (formatNumber([data?.new_clients[this.yKey]]) || '0') + ' new clients';
this.tooltipUpgradeText = '';
let upgradeInfo = findUpgradeData(data);
if (upgradeInfo) {
let { id, previousVersion } = upgradeInfo;
this.tooltipUpgradeText = `Vault was upgraded
${previousVersion ? 'from ' + previousVersion : ''} to ${id}`;
}
let node = hoverCircles.filter((plot) => plot[this.xKey] === data[this.xKey]).node();
this.tooltipTarget = node;
});
}
}