chore: formatting changes

This commit is contained in:
Arjun Choudhary 2022-11-24 12:54:27 +05:30
parent d4e78ebb05
commit f2262fac43
32 changed files with 4371 additions and 3913 deletions

View File

@ -1,10 +1,13 @@
{
"presets": [
["@babel/preset-env", {
[
"@babel/preset-env",
{
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
},
"modules": false
}]
}
]
]
}

View File

@ -8,18 +8,9 @@
"sourceType": "module"
},
"rules": {
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"unix"
],
"semi": [
"error",
"always"
],
"indent": ["error", "tab"],
"linebreak-style": ["error", "unix"],
"semi": ["error", "always"],
"no-console": [
"error",
{

View File

@ -19,9 +19,9 @@
position: relative;
/* for absolutely positioned tooltip */
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
"Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans",
"Helvetica Neue", sans-serif;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
.axis,
.chart-label {

View File

@ -1 +1,2 @@
export const CSSTEXT = ".chart-container{position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif}.chart-container .axis,.chart-container .chart-label{fill:#555b51}.chart-container .axis line,.chart-container .chart-label line{stroke:#dadada}.chart-container .dataset-units circle{stroke:#fff;stroke-width:2}.chart-container .dataset-units path{fill:none;stroke-opacity:1;stroke-width:2px}.chart-container .dataset-path{stroke-width:2px}.chart-container .path-group path{fill:none;stroke-opacity:1;stroke-width:2px}.chart-container line.dashed{stroke-dasharray:5,3}.chart-container .axis-line .specific-value{text-anchor:start}.chart-container .axis-line .y-line{text-anchor:end}.chart-container .axis-line .x-line{text-anchor:middle}.chart-container .legend-dataset-text{fill:#6c7680;font-weight:600}.graph-svg-tip{position:absolute;z-index:99999;padding:10px;font-size:12px;color:#959da5;text-align:center;background:rgba(0,0,0,.8);border-radius:3px}.graph-svg-tip ul{padding-left:0;display:flex}.graph-svg-tip ol{padding-left:0;display:flex}.graph-svg-tip ul.data-point-list li{min-width:90px;flex:1;font-weight:600}.graph-svg-tip strong{color:#dfe2e5;font-weight:600}.graph-svg-tip .svg-pointer{position:absolute;height:5px;margin:0 0 0 -5px;content:' ';border:5px solid transparent;}.graph-svg-tip.comparison{padding:0;text-align:left;pointer-events:none}.graph-svg-tip.comparison .title{display:block;padding:10px;margin:0;font-weight:600;line-height:1;pointer-events:none}.graph-svg-tip.comparison ul{margin:0;white-space:nowrap;list-style:none}.graph-svg-tip.comparison li{display:inline-block;padding:5px 10px}";
export const CSSTEXT =
".chart-container{position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif}.chart-container .axis,.chart-container .chart-label{fill:#555b51}.chart-container .axis line,.chart-container .chart-label line{stroke:#dadada}.chart-container .dataset-units circle{stroke:#fff;stroke-width:2}.chart-container .dataset-units path{fill:none;stroke-opacity:1;stroke-width:2px}.chart-container .dataset-path{stroke-width:2px}.chart-container .path-group path{fill:none;stroke-opacity:1;stroke-width:2px}.chart-container line.dashed{stroke-dasharray:5,3}.chart-container .axis-line .specific-value{text-anchor:start}.chart-container .axis-line .y-line{text-anchor:end}.chart-container .axis-line .x-line{text-anchor:middle}.chart-container .legend-dataset-text{fill:#6c7680;font-weight:600}.graph-svg-tip{position:absolute;z-index:99999;padding:10px;font-size:12px;color:#959da5;text-align:center;background:rgba(0,0,0,.8);border-radius:3px}.graph-svg-tip ul{padding-left:0;display:flex}.graph-svg-tip ol{padding-left:0;display:flex}.graph-svg-tip ul.data-point-list li{min-width:90px;flex:1;font-weight:600}.graph-svg-tip strong{color:#dfe2e5;font-weight:600}.graph-svg-tip .svg-pointer{position:absolute;height:5px;margin:0 0 0 -5px;content:' ';border:5px solid transparent;}.graph-svg-tip.comparison{padding:0;text-align:left;pointer-events:none}.graph-svg-tip.comparison .title{display:block;padding:10px;margin:0;font-weight:600;line-height:1;pointer-events:none}.graph-svg-tip.comparison ul{margin:0;white-space:nowrap;list-style:none}.graph-svg-tip.comparison li{display:inline-block;padding:5px 10px}";

View File

@ -1,11 +1,11 @@
import '../css/charts.scss';
import "../css/charts.scss";
// import MultiAxisChart from './charts/MultiAxisChart';
import PercentageChart from './charts/PercentageChart';
import PieChart from './charts/PieChart';
import Heatmap from './charts/Heatmap';
import AxisChart from './charts/AxisChart';
import DonutChart from './charts/DonutChart';
import PercentageChart from "./charts/PercentageChart";
import PieChart from "./charts/PieChart";
import Heatmap from "./charts/Heatmap";
import AxisChart from "./charts/AxisChart";
import DonutChart from "./charts/DonutChart";
const chartTypes = {
bar: AxisChart,
@ -17,9 +17,9 @@ const chartTypes = {
donut: DonutChart,
};
function getChartByType(chartType = 'line', parent, options) {
if (chartType === 'axis-mixed') {
options.type = 'line';
function getChartByType(chartType = "line", parent, options) {
if (chartType === "axis-mixed") {
options.type = "line";
return new AxisChart(parent, options);
}

View File

@ -1,8 +1,8 @@
import BaseChart from './BaseChart';
import { truncateString } from '../utils/draw-utils';
import { legendDot } from '../utils/draw';
import { round } from '../utils/helpers';
import { getExtraWidth } from '../utils/constants';
import BaseChart from "./BaseChart";
import { truncateString } from "../utils/draw-utils";
import { legendDot } from "../utils/draw";
import { round } from "../utils/helpers";
import { getExtraWidth } from "../utils/constants";
export default class AggregationChart extends BaseChart {
constructor(parent, args) {
@ -22,30 +22,38 @@ export default class AggregationChart extends BaseChart {
let maxSlices = this.config.maxSlices;
s.sliceTotals = [];
let allTotals = this.data.labels.map((label, i) => {
let allTotals = this.data.labels
.map((label, i) => {
let total = 0;
this.data.datasets.map(e => {
this.data.datasets.map((e) => {
total += e.values[i];
});
return [total, label];
}).filter(d => { return d[0] >= 0; }); // keep only positive results
})
.filter((d) => {
return d[0] >= 0;
}); // keep only positive results
let totals = allTotals;
if(allTotals.length > maxSlices) {
if (allTotals.length > maxSlices) {
// Prune and keep a grey area for rest as per maxSlices
allTotals.sort((a, b) => { return b[0] - a[0]; });
allTotals.sort((a, b) => {
return b[0] - a[0];
});
totals = allTotals.slice(0, maxSlices-1);
let remaining = allTotals.slice(maxSlices-1);
totals = allTotals.slice(0, maxSlices - 1);
let remaining = allTotals.slice(maxSlices - 1);
let sumOfRemaining = 0;
remaining.map(d => {sumOfRemaining += d[0];});
totals.push([sumOfRemaining, 'Rest']);
this.colors[maxSlices-1] = 'grey';
remaining.map((d) => {
sumOfRemaining += d[0];
});
totals.push([sumOfRemaining, "Rest"]);
this.colors[maxSlices - 1] = "grey";
}
s.labels = [];
totals.map(d => {
totals.map((d) => {
s.sliceTotals.push(round(d[0]));
s.labels.push(d[1]);
});
@ -54,13 +62,13 @@ export default class AggregationChart extends BaseChart {
this.center = {
x: this.width / 2,
y: this.height / 2
y: this.height / 2,
};
}
renderLegend() {
let s = this.state;
this.legendArea.textContent = '';
this.legendArea.textContent = "";
this.legendTotals = s.sliceTotals.slice(0, this.config.maxLegendPoints);
let count = 0;
@ -68,18 +76,22 @@ export default class AggregationChart extends BaseChart {
this.legendTotals.map((d, i) => {
let barWidth = 150;
let divisor = Math.floor(
(this.width - getExtraWidth(this.measures))/barWidth
(this.width - getExtraWidth(this.measures)) / barWidth
);
if (this.legendTotals.length < divisor) {
barWidth = this.width/this.legendTotals.length;
barWidth = this.width / this.legendTotals.length;
}
if(count > divisor) {
if (count > divisor) {
count = 0;
y += 60;
}
let x = barWidth * count + 5;
let label = this.config.truncateLegends ? truncateString(s.labels[i], barWidth/10) : s.labels[i];
let formatted = this.config.formatTooltipY ? this.config.formatTooltipY(d) : d;
let label = this.config.truncateLegends
? truncateString(s.labels[i], barWidth / 10)
: s.labels[i];
let formatted = this.config.formatTooltipY
? this.config.formatTooltipY(d)
: d;
let dot = legendDot(
x,
y,

View File

@ -1,13 +1,29 @@
import BaseChart from './BaseChart';
import { dataPrep, zeroDataPrep, getShortenedLabels } from '../utils/axis-chart-utils';
import { AXIS_LEGEND_BAR_SIZE } from '../utils/constants';
import { getComponent } from '../objects/ChartComponents';
import { getOffset, fire } from '../utils/dom';
import { calcChartIntervals, getIntervalSize, getValueRange, getZeroIndex, scale, getClosestInArray } from '../utils/intervals';
import { floatTwo } from '../utils/helpers';
import { makeOverlay, updateOverlay, legendBar } from '../utils/draw';
import { getTopOffset, getLeftOffset, MIN_BAR_PERCENT_HEIGHT, BAR_CHART_SPACE_RATIO,
LINE_CHART_DOT_SIZE } from '../utils/constants';
import BaseChart from "./BaseChart";
import {
dataPrep,
zeroDataPrep,
getShortenedLabels,
} from "../utils/axis-chart-utils";
import { AXIS_LEGEND_BAR_SIZE } from "../utils/constants";
import { getComponent } from "../objects/ChartComponents";
import { getOffset, fire } from "../utils/dom";
import {
calcChartIntervals,
getIntervalSize,
getValueRange,
getZeroIndex,
scale,
getClosestInArray,
} from "../utils/intervals";
import { floatTwo } from "../utils/helpers";
import { makeOverlay, updateOverlay, legendBar } from "../utils/draw";
import {
getTopOffset,
getLeftOffset,
MIN_BAR_PERCENT_HEIGHT,
BAR_CHART_SPACE_RATIO,
LINE_CHART_DOT_SIZE,
} from "../utils/constants";
export default class AxisChart extends BaseChart {
constructor(parent, args) {
@ -16,14 +32,14 @@ export default class AxisChart extends BaseChart {
this.barOptions = args.barOptions || {};
this.lineOptions = args.lineOptions || {};
this.type = args.type || 'line';
this.type = args.type || "line";
this.init = 1;
this.setup();
}
setMeasures() {
if(this.data.datasets.length <= 1) {
if (this.data.datasets.length <= 1) {
this.config.showLegend = 0;
this.measures.paddings.bottom = 30;
}
@ -35,10 +51,11 @@ export default class AxisChart extends BaseChart {
options.axisOptions = options.axisOptions || {};
options.tooltipOptions = options.tooltipOptions || {};
this.config.xAxisMode = options.axisOptions.xAxisMode || 'span';
this.config.yAxisMode = options.axisOptions.yAxisMode || 'span';
this.config.xAxisMode = options.axisOptions.xAxisMode || "span";
this.config.yAxisMode = options.axisOptions.yAxisMode || "span";
this.config.xIsSeries = options.axisOptions.xIsSeries || 0;
this.config.shortenYAxisNumbers = options.axisOptions.shortenYAxisNumbers || 0;
this.config.shortenYAxisNumbers =
options.axisOptions.shortenYAxisNumbers || 0;
this.config.formatTooltipX = options.tooltipOptions.formatTooltipX;
this.config.formatTooltipY = options.tooltipOptions.formatTooltipY;
@ -46,18 +63,18 @@ export default class AxisChart extends BaseChart {
this.config.valuesOverPoints = options.valuesOverPoints;
}
prepareData(data=this.data) {
prepareData(data = this.data) {
return dataPrep(data, this.type);
}
prepareFirstData(data=this.data) {
prepareFirstData(data = this.data) {
return zeroDataPrep(data);
}
calc(onlyWidthChange = false) {
this.calcXPositions();
if(!onlyWidthChange) {
this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
if (!onlyWidthChange) {
this.calcYAxisParameters(this.getAllYValues(), this.type === "line");
}
this.makeDataByIndex();
}
@ -67,9 +84,9 @@ export default class AxisChart extends BaseChart {
let labels = this.data.labels;
s.datasetLength = labels.length;
s.unitWidth = this.width/(s.datasetLength);
s.unitWidth = this.width / s.datasetLength;
// Default, as per bar, and mixed. Only line will be a special case
s.xOffset = s.unitWidth/2;
s.xOffset = s.unitWidth / 2;
// // For a pure Line Chart
// s.unitWidth = this.width/(s.datasetLength - 1);
@ -77,21 +94,19 @@ export default class AxisChart extends BaseChart {
s.xAxis = {
labels: labels,
positions: labels.map((d, i) =>
floatTwo(s.xOffset + i * s.unitWidth)
)
positions: labels.map((d, i) => floatTwo(s.xOffset + i * s.unitWidth)),
};
}
calcYAxisParameters(dataValues, withMinimum = 'false') {
calcYAxisParameters(dataValues, withMinimum = "false") {
const yPts = calcChartIntervals(dataValues, withMinimum);
const scaleMultiplier = this.height / getValueRange(yPts);
const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
const zeroLine = this.height - getZeroIndex(yPts) * intervalHeight;
this.state.yAxis = {
labels: yPts,
positions: yPts.map(d => zeroLine - d * scaleMultiplier),
positions: yPts.map((d) => zeroLine - d * scaleMultiplier),
scaleMultiplier: scaleMultiplier,
zeroLine: zeroLine,
};
@ -104,13 +119,17 @@ export default class AxisChart extends BaseChart {
calcDatasetPoints() {
let s = this.state;
let scaleAll = values => values.map(val => scale(val, s.yAxis));
let scaleAll = (values) => values.map((val) => scale(val, s.yAxis));
s.datasets = this.data.datasets.map((d, i) => {
let values = d.values;
let cumulativeYs = d.cumulativeYs || [];
return {
name: d.name && d.name.replace(/<|>|&/g, (char) => char == '&' ? '&amp;' : char == '<' ? '&lt;' : '&gt;'),
name:
d.name &&
d.name.replace(/<|>|&/g, (char) =>
char == "&" ? "&amp;" : char == "<" ? "&lt;" : "&gt;"
),
index: i,
chartType: d.chartType,
@ -125,14 +144,14 @@ export default class AxisChart extends BaseChart {
calcYExtremes() {
let s = this.state;
if(this.barOptions.stacked) {
if (this.barOptions.stacked) {
s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
return;
}
s.yExtremes = new Array(s.datasetLength).fill(9999);
s.datasets.map(d => {
s.datasets.map((d) => {
d.yPositions.map((pos, j) => {
if(pos < s.yExtremes[j]) {
if (pos < s.yExtremes[j]) {
s.yExtremes[j] = pos;
}
});
@ -141,31 +160,31 @@ export default class AxisChart extends BaseChart {
calcYRegions() {
let s = this.state;
if(this.data.yMarkers) {
this.state.yMarkers = this.data.yMarkers.map(d => {
if (this.data.yMarkers) {
this.state.yMarkers = this.data.yMarkers.map((d) => {
d.position = scale(d.value, s.yAxis);
if(!d.options) d.options = {};
if (!d.options) d.options = {};
// if(!d.label.includes(':')) {
// d.label += ': ' + d.value;
// }
return d;
});
}
if(this.data.yRegions) {
this.state.yRegions = this.data.yRegions.map(d => {
if (this.data.yRegions) {
this.state.yRegions = this.data.yRegions.map((d) => {
d.startPos = scale(d.start, s.yAxis);
d.endPos = scale(d.end, s.yAxis);
if(!d.options) d.options = {};
if (!d.options) d.options = {};
return d;
});
}
}
getAllYValues() {
let key = 'values';
let key = "values";
if(this.barOptions.stacked) {
key = 'cumulativeYs';
if (this.barOptions.stacked) {
key = "cumulativeYs";
let cumulative = new Array(this.state.datasetLength).fill(0);
this.data.datasets.map((d, i) => {
let values = this.data.datasets[i].values;
@ -173,12 +192,12 @@ export default class AxisChart extends BaseChart {
});
}
let allValueLists = this.data.datasets.map(d => d[key]);
if(this.data.yMarkers) {
allValueLists.push(this.data.yMarkers.map(d => d.value));
let allValueLists = this.data.datasets.map((d) => d[key]);
if (this.data.yMarkers) {
allValueLists.push(this.data.yMarkers.map((d) => d.value));
}
if(this.data.yRegions) {
this.data.yRegions.map(d => {
if (this.data.yRegions) {
this.data.yRegions.map((d) => {
allValueLists.push([d.end, d.start]);
});
}
@ -189,53 +208,58 @@ export default class AxisChart extends BaseChart {
setupComponents() {
let componentConfigs = [
[
'yAxis',
"yAxis",
{
mode: this.config.yAxisMode,
width: this.width,
shortenNumbers: this.config.shortenYAxisNumbers
shortenNumbers: this.config.shortenYAxisNumbers,
// pos: 'right'
},
function() {
function () {
return this.state.yAxis;
}.bind(this)
}.bind(this),
],
[
'xAxis',
"xAxis",
{
mode: this.config.xAxisMode,
height: this.height,
// pos: 'right'
},
function() {
function () {
let s = this.state;
s.xAxis.calcLabels = getShortenedLabels(this.width,
s.xAxis.labels, this.config.xIsSeries);
s.xAxis.calcLabels = getShortenedLabels(
this.width,
s.xAxis.labels,
this.config.xIsSeries
);
return s.xAxis;
}.bind(this)
}.bind(this),
],
[
'yRegions',
"yRegions",
{
width: this.width,
pos: 'right'
pos: "right",
},
function() {
function () {
return this.state.yRegions;
}.bind(this)
}.bind(this),
],
];
let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
let barDatasets = this.state.datasets.filter((d) => d.chartType === "bar");
let lineDatasets = this.state.datasets.filter(
(d) => d.chartType === "line"
);
let barsConfigs = barDatasets.map(d => {
let barsConfigs = barDatasets.map((d) => {
let index = d.index;
return [
'barGraph' + '-' + d.index,
"barGraph" + "-" + d.index,
{
index: index,
color: this.colors[index],
@ -245,23 +269,23 @@ export default class AxisChart extends BaseChart {
valuesOverPoints: this.config.valuesOverPoints,
minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
},
function() {
function () {
let s = this.state;
let d = s.datasets[index];
let stacked = this.barOptions.stacked;
let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
let barsWidth = s.unitWidth * (1 - spaceRatio);
let barWidth = barsWidth/(stacked ? 1 : barDatasets.length);
let barWidth = barsWidth / (stacked ? 1 : barDatasets.length);
let xPositions = s.xAxis.positions.map(x => x - barsWidth/2);
if(!stacked) {
xPositions = xPositions.map(p => p + barWidth * index);
let xPositions = s.xAxis.positions.map((x) => x - barsWidth / 2);
if (!stacked) {
xPositions = xPositions.map((p) => p + barWidth * index);
}
let labels = new Array(s.datasetLength).fill('');
if(this.config.valuesOverPoints) {
if(stacked && d.index === s.datasets.length - 1) {
let labels = new Array(s.datasetLength).fill("");
if (this.config.valuesOverPoints) {
if (stacked && d.index === s.datasets.length - 1) {
labels = d.cumulativeYs;
} else {
labels = d.values;
@ -269,7 +293,7 @@ export default class AxisChart extends BaseChart {
}
let offsets = new Array(s.datasetLength).fill(0);
if(stacked) {
if (stacked) {
offsets = d.yPositions.map((y, j) => y - d.cumulativeYPos[j]);
}
@ -284,14 +308,14 @@ export default class AxisChart extends BaseChart {
barsWidth: barsWidth,
barWidth: barWidth,
};
}.bind(this)
}.bind(this),
];
});
let lineConfigs = lineDatasets.map(d => {
let lineConfigs = lineDatasets.map((d) => {
let index = d.index;
return [
'lineGraph' + '-' + d.index,
"lineGraph" + "-" + d.index,
{
index: index,
color: this.colors[index],
@ -305,11 +329,13 @@ export default class AxisChart extends BaseChart {
// same for all datasets
valuesOverPoints: this.config.valuesOverPoints,
},
function() {
function () {
let s = this.state;
let d = s.datasets[index];
let minLine = s.yAxis.positions[0] < s.yAxis.zeroLine
? s.yAxis.positions[0] : s.yAxis.zeroLine;
let minLine =
s.yAxis.positions[0] < s.yAxis.zeroLine
? s.yAxis.positions[0]
: s.yAxis.zeroLine;
return {
xPositions: s.xAxis.positions,
@ -320,37 +346,43 @@ export default class AxisChart extends BaseChart {
zeroLine: minLine,
radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE,
};
}.bind(this)
}.bind(this),
];
});
let markerConfigs = [
[
'yMarkers',
"yMarkers",
{
width: this.width,
pos: 'right'
pos: "right",
},
function() {
function () {
return this.state.yMarkers;
}.bind(this)
]
}.bind(this),
],
];
componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
componentConfigs = componentConfigs.concat(
barsConfigs,
lineConfigs,
markerConfigs
);
let optionals = ['yMarkers', 'yRegions'];
let optionals = ["yMarkers", "yRegions"];
this.dataUnitComponents = [];
this.components = new Map(componentConfigs
.filter(args => !optionals.includes(args[0]) || this.state[args[0]])
.map(args => {
this.components = new Map(
componentConfigs
.filter((args) => !optionals.includes(args[0]) || this.state[args[0]])
.map((args) => {
let component = getComponent(...args);
if(args[0].includes('lineGraph') || args[0].includes('barGraph')) {
if (args[0].includes("lineGraph") || args[0].includes("barGraph")) {
this.dataUnitComponents.push(component);
}
return [args[0], component];
}));
})
);
}
makeDataByIndex() {
@ -385,14 +417,13 @@ export default class AxisChart extends BaseChart {
bindTooltip() {
// NOTE: could be in tooltip itself, as it is a given functionality for its parent
this.container.addEventListener('mousemove', (e) => {
this.container.addEventListener("mousemove", (e) => {
let m = this.measures;
let o = getOffset(this.container);
let relX = e.pageX - o.left - getLeftOffset(m);
let relY = e.pageY - o.top;
if(relY < this.height + getTopOffset(m)
&& relY > getTopOffset(m)) {
if (relY < this.height + getTopOffset(m) && relY > getTopOffset(m)) {
this.mapTooltipXPosition(relX);
} else {
this.tip.hideTip();
@ -402,7 +433,7 @@ export default class AxisChart extends BaseChart {
mapTooltipXPosition(relX) {
let s = this.state;
if(!s.yExtremes) return;
if (!s.yExtremes) return;
let index = getClosestInArray(relX, s.xAxis.positions, true);
if (index >= 0) {
@ -411,7 +442,7 @@ export default class AxisChart extends BaseChart {
this.tip.setValues(
dbi.xPos + this.tip.offset.x,
dbi.yExtreme + this.tip.offset.y,
{name: dbi.formattedLabel, value: ''},
{ name: dbi.formattedLabel, value: "" },
dbi.values,
index
);
@ -422,8 +453,8 @@ export default class AxisChart extends BaseChart {
renderLegend() {
let s = this.data;
if(s.datasets.length > 1) {
this.legendArea.textContent = '';
if (s.datasets.length > 1) {
this.legendArea.textContent = "";
s.datasets.map((d, i) => {
let barWidth = AXIS_LEGEND_BAR_SIZE;
// let rightEndPoint = this.baseWidth - this.measures.margins.left - this.measures.margins.right;
@ -431,32 +462,31 @@ export default class AxisChart extends BaseChart {
let rect = legendBar(
// rightEndPoint - multiplier * barWidth, // To right align
barWidth * i,
'0',
"0",
barWidth,
this.colors[i],
d.name,
this.config.truncateLegends);
this.config.truncateLegends
);
this.legendArea.appendChild(rect);
});
}
}
// Overlay
makeOverlay() {
if(this.init) {
if (this.init) {
this.init = 0;
return;
}
if(this.overlayGuides) {
this.overlayGuides.forEach(g => {
if (this.overlayGuides) {
this.overlayGuides.forEach((g) => {
let o = g.overlay;
o.parentNode.removeChild(o);
});
}
this.overlayGuides = this.dataUnitComponents.map(c => {
this.overlayGuides = this.dataUnitComponents.map((c) => {
return {
type: c.unitType,
overlay: undefined,
@ -464,12 +494,12 @@ export default class AxisChart extends BaseChart {
};
});
if(this.state.currentIndex === undefined) {
if (this.state.currentIndex === undefined) {
this.state.currentIndex = this.state.datasetLength - 1;
}
// Render overlays
this.overlayGuides.map(d => {
this.overlayGuides.map((d) => {
let currentUnit = d.units[this.state.currentIndex];
d.overlay = makeOverlay[d.type](currentUnit);
@ -478,8 +508,8 @@ export default class AxisChart extends BaseChart {
}
updateOverlayGuides() {
if(this.overlayGuides) {
this.overlayGuides.forEach(g => {
if (this.overlayGuides) {
this.overlayGuides.forEach((g) => {
let o = g.overlay;
o.parentNode.removeChild(o);
});
@ -487,30 +517,30 @@ export default class AxisChart extends BaseChart {
}
bindOverlay() {
this.parent.addEventListener('data-select', () => {
this.parent.addEventListener("data-select", () => {
this.updateOverlay();
});
}
bindUnits() {
this.dataUnitComponents.map(c => {
c.units.map(unit => {
unit.addEventListener('click', () => {
let index = unit.getAttribute('data-point-index');
this.dataUnitComponents.map((c) => {
c.units.map((unit) => {
unit.addEventListener("click", () => {
let index = unit.getAttribute("data-point-index");
this.setCurrentDataPoint(index);
});
});
});
// Note: Doesn't work as tooltip is absolutely positioned
this.tip.container.addEventListener('click', () => {
let index = this.tip.container.getAttribute('data-point-index');
this.tip.container.addEventListener("click", () => {
let index = this.tip.container.getAttribute("data-point-index");
this.setCurrentDataPoint(index);
});
}
updateOverlay() {
this.overlayGuides.map(d => {
this.overlayGuides.map((d) => {
let currentUnit = d.units[this.state.currentIndex];
updateOverlay[d.type](currentUnit, d.overlay);
});
@ -524,12 +554,12 @@ export default class AxisChart extends BaseChart {
this.setCurrentDataPoint(this.state.currentIndex + 1);
}
getDataPoint(index=this.state.currentIndex) {
getDataPoint(index = this.state.currentIndex) {
let s = this.state;
let data_point = {
index: index,
label: s.xAxis.labels[index],
values: s.datasets.map(d => d.values[index])
values: s.datasets.map((d) => d.values[index]),
};
return data_point;
}
@ -537,17 +567,15 @@ export default class AxisChart extends BaseChart {
setCurrentDataPoint(index) {
let s = this.state;
index = parseInt(index);
if(index < 0) index = 0;
if(index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
if(index === s.currentIndex) return;
if (index < 0) index = 0;
if (index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
if (index === s.currentIndex) return;
s.currentIndex = index;
fire(this.parent, "data-select", this.getDataPoint());
}
// API
addDataPoint(label, datasetValues, index=this.state.datasetLength) {
addDataPoint(label, datasetValues, index = this.state.datasetLength) {
super.addDataPoint(label, datasetValues, index);
this.data.labels.splice(index, 0, label);
this.data.datasets.map((d, i) => {
@ -556,19 +584,19 @@ export default class AxisChart extends BaseChart {
this.update(this.data);
}
removeDataPoint(index = this.state.datasetLength-1) {
removeDataPoint(index = this.state.datasetLength - 1) {
if (this.data.labels.length <= 1) {
return;
}
super.removeDataPoint(index);
this.data.labels.splice(index, 1);
this.data.datasets.map(d => {
this.data.datasets.map((d) => {
d.values.splice(index, 1);
});
this.update(this.data);
}
updateDataset(datasetValues, index=0) {
updateDataset(datasetValues, index = 0) {
this.data.datasets[index].values = datasetValues;
this.update(this.data);
}
@ -577,7 +605,7 @@ export default class AxisChart extends BaseChart {
updateDatasets(datasets) {
this.data.datasets.map((d, i) => {
if(datasets[i]) {
if (datasets[i]) {
d.values = datasets[i];
}
});

View File

@ -1,16 +1,16 @@
import AggregationChart from './AggregationChart';
import { getComponent } from '../objects/ChartComponents';
import { getOffset } from '../utils/dom';
import { getPositionByAngle } from '../utils/helpers';
import { makeArcStrokePathStr, makeStrokeCircleStr } from '../utils/draw';
import { lightenDarkenColor } from '../utils/colors';
import { transform } from '../utils/animation';
import { FULL_ANGLE } from '../utils/constants';
import AggregationChart from "./AggregationChart";
import { getComponent } from "../objects/ChartComponents";
import { getOffset } from "../utils/dom";
import { getPositionByAngle } from "../utils/helpers";
import { makeArcStrokePathStr, makeStrokeCircleStr } from "../utils/draw";
import { lightenDarkenColor } from "../utils/colors";
import { transform } from "../utils/animation";
import { FULL_ANGLE } from "../utils/constants";
export default class DonutChart extends AggregationChart {
constructor(parent, args) {
super(parent, args);
this.type = 'donut';
this.type = "donut";
this.initTimeout = 0;
this.init = 1;
@ -47,16 +47,16 @@ export default class DonutChart extends AggregationChart {
s.sliceTotals.map((total, i) => {
const startAngle = curAngle;
const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
const largeArc = originDiffAngle > 180 ? 1: 0;
const largeArc = originDiffAngle > 180 ? 1 : 0;
const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
const endAngle = curAngle = curAngle + diffAngle;
const endAngle = (curAngle = curAngle + diffAngle);
const startPosition = getPositionByAngle(startAngle, radius);
const endPosition = getPositionByAngle(endAngle, radius);
const prevProperty = this.init && prevSlicesProperties[i];
let curStart,curEnd;
if(this.init) {
let curStart, curEnd;
if (this.init) {
curStart = prevProperty ? prevProperty.startPosition : startPosition;
curEnd = prevProperty ? prevProperty.endPosition : startPosition;
} else {
@ -65,8 +65,22 @@ export default class DonutChart extends AggregationChart {
}
const curPath =
originDiffAngle === 360
? makeStrokeCircleStr(curStart, curEnd, this.center, this.radius, this.clockWise, largeArc)
: makeArcStrokePathStr(curStart, curEnd, this.center, this.radius, this.clockWise, largeArc);
? makeStrokeCircleStr(
curStart,
curEnd,
this.center,
this.radius,
this.clockWise,
largeArc
)
: makeArcStrokePathStr(
curStart,
curEnd,
this.center,
this.radius,
this.clockWise,
largeArc
);
s.sliceStrings.push(curPath);
s.slicesProperties.push({
@ -76,9 +90,8 @@ export default class DonutChart extends AggregationChart {
total: s.grandTotal,
startAngle,
endAngle,
angle: diffAngle
angle: diffAngle,
});
});
this.init = 0;
}
@ -88,65 +101,76 @@ export default class DonutChart extends AggregationChart {
let componentConfigs = [
[
'donutSlices',
{ },
function() {
"donutSlices",
{},
function () {
return {
sliceStrings: s.sliceStrings,
colors: this.colors,
strokeWidth: this.strokeWidth,
};
}.bind(this)
]
}.bind(this),
],
];
this.components = new Map(componentConfigs
.map(args => {
this.components = new Map(
componentConfigs.map((args) => {
let component = getComponent(...args);
return [args[0], component];
}));
})
);
}
calTranslateByAngle(property){
const{ radius, hoverRadio } = this;
const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
calTranslateByAngle(property) {
const { radius, hoverRadio } = this;
const position = getPositionByAngle(
property.startAngle + property.angle / 2,
radius
);
return `translate3d(${position.x * hoverRadio}px,${
position.y * hoverRadio
}px,0)`;
}
hoverSlice(path,i,flag,e){
if(!path) return;
hoverSlice(path, i, flag, e) {
if (!path) return;
const color = this.colors[i];
if(flag) {
if (flag) {
transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
path.style.stroke = lightenDarkenColor(color, 50);
let g_off = getOffset(this.svg);
let x = e.pageX - g_off.left + 10;
let y = e.pageY - g_off.top - 10;
let title = (this.formatted_labels && this.formatted_labels.length > 0
? this.formatted_labels[i] : this.state.labels[i]) + ': ';
let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
this.tip.setValues(x, y, {name: title, value: percent + "%"});
let title =
(this.formatted_labels && this.formatted_labels.length > 0
? this.formatted_labels[i]
: this.state.labels[i]) + ": ";
let percent = (
(this.state.sliceTotals[i] * 100) /
this.state.grandTotal
).toFixed(1);
this.tip.setValues(x, y, { name: title, value: percent + "%" });
this.tip.showTip();
} else {
transform(path,'translate3d(0,0,0)');
transform(path, "translate3d(0,0,0)");
this.tip.hideTip();
path.style.stroke = color;
}
}
bindTooltip() {
this.container.addEventListener('mousemove', this.mouseMove);
this.container.addEventListener('mouseleave', this.mouseLeave);
this.container.addEventListener("mousemove", this.mouseMove);
this.container.addEventListener("mouseleave", this.mouseLeave);
}
mouseMove(e){
mouseMove(e) {
const target = e.target;
let slices = this.components.get('donutSlices').store;
let slices = this.components.get("donutSlices").store;
let prevIndex = this.curActiveSliceIndex;
let prevAcitve = this.curActiveSlice;
if(slices.includes(target)) {
if (slices.includes(target)) {
let i = slices.indexOf(target);
this.hoverSlice(prevAcitve, prevIndex,false);
this.hoverSlice(prevAcitve, prevIndex, false);
this.curActiveSlice = target;
this.curActiveSliceIndex = i;
this.hoverSlice(target, i, true, e);
@ -155,7 +179,7 @@ export default class DonutChart extends AggregationChart {
}
}
mouseLeave(){
this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
mouseLeave() {
this.hoverSlice(this.curActiveSlice, this.curActiveSliceIndex, false);
}
}

View File

@ -1,11 +1,29 @@
import BaseChart from './BaseChart';
import { getComponent } from '../objects/ChartComponents';
import { makeText, heatSquare } from '../utils/draw';
import { DAY_NAMES_SHORT, toMidnightUTC, addDays, areInSameMonth, getLastDateInMonth, setDayToSunday, getYyyyMmDd, getWeeksBetween, getMonthName, clone,
NO_OF_MILLIS, NO_OF_YEAR_MONTHS, NO_OF_DAYS_IN_WEEK } from '../utils/date-utils';
import { calcDistribution, getMaxCheckpoint } from '../utils/intervals';
import { getExtraHeight, getExtraWidth, HEATMAP_DISTRIBUTION_SIZE, HEATMAP_SQUARE_SIZE,
HEATMAP_GUTTER_SIZE } from '../utils/constants';
import BaseChart from "./BaseChart";
import { getComponent } from "../objects/ChartComponents";
import { makeText, heatSquare } from "../utils/draw";
import {
DAY_NAMES_SHORT,
toMidnightUTC,
addDays,
areInSameMonth,
getLastDateInMonth,
setDayToSunday,
getYyyyMmDd,
getWeeksBetween,
getMonthName,
clone,
NO_OF_MILLIS,
NO_OF_YEAR_MONTHS,
NO_OF_DAYS_IN_WEEK,
} from "../utils/date-utils";
import { calcDistribution, getMaxCheckpoint } from "../utils/intervals";
import {
getExtraHeight,
getExtraWidth,
HEATMAP_DISTRIBUTION_SIZE,
HEATMAP_SQUARE_SIZE,
HEATMAP_GUTTER_SIZE,
} from "../utils/constants";
const COL_WIDTH = HEATMAP_SQUARE_SIZE + HEATMAP_GUTTER_SIZE;
const ROW_HEIGHT = COL_WIDTH;
@ -14,13 +32,14 @@ const ROW_HEIGHT = COL_WIDTH;
export default class Heatmap extends BaseChart {
constructor(parent, options) {
super(parent, options);
this.type = 'heatmap';
this.type = "heatmap";
this.countLabel = options.countLabel || '';
this.countLabel = options.countLabel || "";
let validStarts = ['Sunday', 'Monday'];
let validStarts = ["Sunday", "Monday"];
let startSubDomain = validStarts.includes(options.startSubDomain)
? options.startSubDomain : 'Sunday';
? options.startSubDomain
: "Sunday";
this.startSubDomainIndex = validStarts.indexOf(startSubDomain);
this.setup();
@ -33,43 +52,43 @@ export default class Heatmap extends BaseChart {
m.paddings.top = ROW_HEIGHT * 3;
m.paddings.bottom = 0;
m.legendHeight = ROW_HEIGHT * 2;
m.baseHeight = ROW_HEIGHT * NO_OF_DAYS_IN_WEEK
+ getExtraHeight(m);
m.baseHeight = ROW_HEIGHT * NO_OF_DAYS_IN_WEEK + getExtraHeight(m);
let d = this.data;
let spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
this.independentWidth = (getWeeksBetween(d.start, d.end)
+ spacing) * COL_WIDTH + getExtraWidth(m);
this.independentWidth =
(getWeeksBetween(d.start, d.end) + spacing) * COL_WIDTH +
getExtraWidth(m);
}
updateWidth() {
let spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
let noOfWeeks = this.state.noOfWeeks ? this.state.noOfWeeks : 52;
this.baseWidth = (noOfWeeks + spacing) * COL_WIDTH
+ getExtraWidth(this.measures);
this.baseWidth =
(noOfWeeks + spacing) * COL_WIDTH + getExtraWidth(this.measures);
}
prepareData(data=this.data) {
if(data.start && data.end && data.start > data.end) {
throw new Error('Start date cannot be greater than end date.');
prepareData(data = this.data) {
if (data.start && data.end && data.start > data.end) {
throw new Error("Start date cannot be greater than end date.");
}
if(!data.start) {
if (!data.start) {
data.start = new Date();
data.start.setFullYear( data.start.getFullYear() - 1 );
data.start.setFullYear(data.start.getFullYear() - 1);
}
data.start = toMidnightUTC(data.start);
if(!data.end) {
if (!data.end) {
data.end = new Date();
}
data.end = toMidnightUTC(data.end);
data.dataPoints = data.dataPoints || {};
if(parseInt(Object.keys(data.dataPoints)[0]) > 100000) {
if (parseInt(Object.keys(data.dataPoints)[0]) > 100000) {
let points = {};
Object.keys(data.dataPoints).forEach(timestampSec => {
Object.keys(data.dataPoints).forEach((timestampSec) => {
let date = new Date(timestampSec * NO_OF_MILLIS);
points[getYyyyMmDd(date)] = data.dataPoints[timestampSec];
});
@ -88,7 +107,9 @@ export default class Heatmap extends BaseChart {
s.firstWeekStart = clone(s.start);
s.noOfWeeks = getWeeksBetween(s.start, s.end);
s.distribution = calcDistribution(
Object.values(this.data.dataPoints), HEATMAP_DISTRIBUTION_SIZE);
Object.values(this.data.dataPoints),
HEATMAP_DISTRIBUTION_SIZE
);
s.domainConfigs = this.getDomains();
}
@ -98,42 +119,39 @@ export default class Heatmap extends BaseChart {
let lessCol = this.discreteDomains ? 0 : 1;
let componentConfigs = s.domainConfigs.map((config, i) => [
'heatDomain',
"heatDomain",
{
index: config.index,
colWidth: COL_WIDTH,
rowHeight: ROW_HEIGHT,
squareSize: HEATMAP_SQUARE_SIZE,
radius: this.rawChartArgs.radius || 0,
xTranslate: s.domainConfigs
xTranslate:
s.domainConfigs
.filter((config, j) => j < i)
.map(config => config.cols.length - lessCol)
.reduce((a, b) => a + b, 0)
* COL_WIDTH
.map((config) => config.cols.length - lessCol)
.reduce((a, b) => a + b, 0) * COL_WIDTH,
},
function() {
function () {
return s.domainConfigs[i];
}.bind(this)
}.bind(this),
]);
this.components = new Map(componentConfigs
.map((args, i) => {
this.components = new Map(
componentConfigs.map((args, i) => {
let component = getComponent(...args);
return [args[0] + '-' + i, component];
return [args[0] + "-" + i, component];
})
);
let y = 0;
DAY_NAMES_SHORT.forEach((dayName, i) => {
if([1, 3, 5].includes(i)) {
let dayText = makeText('subdomain-name', -COL_WIDTH/2, y, dayName,
{
if ([1, 3, 5].includes(i)) {
let dayText = makeText("subdomain-name", -COL_WIDTH / 2, y, dayName, {
fontSize: HEATMAP_SQUARE_SIZE,
dy: 8,
textAnchor: 'end'
}
);
textAnchor: "end",
});
this.drawArea.appendChild(dayText);
}
y += ROW_HEIGHT;
@ -141,8 +159,8 @@ export default class Heatmap extends BaseChart {
}
update(data) {
if(!data) {
console.error('No data to update.');
if (!data) {
console.error("No data to update.");
}
this.data = this.prepareData(data);
@ -151,26 +169,31 @@ export default class Heatmap extends BaseChart {
}
bindTooltip() {
this.container.addEventListener('mousemove', (e) => {
this.components.forEach(comp => {
this.container.addEventListener("mousemove", (e) => {
this.components.forEach((comp) => {
let daySquares = comp.store;
let daySquare = e.target;
if(daySquares.includes(daySquare)) {
if (daySquares.includes(daySquare)) {
let count = daySquare.getAttribute("data-value");
let dateParts = daySquare.getAttribute("data-date").split("-");
let count = daySquare.getAttribute('data-value');
let dateParts = daySquare.getAttribute('data-date').split('-');
let month = getMonthName(parseInt(dateParts[1]) - 1, true);
let month = getMonthName(parseInt(dateParts[1])-1, true);
let gOff = this.container.getBoundingClientRect(),
pOff = daySquare.getBoundingClientRect();
let gOff = this.container.getBoundingClientRect(), pOff = daySquare.getBoundingClientRect();
let width = parseInt(e.target.getAttribute('width'));
let x = pOff.left - gOff.left + width/2;
let width = parseInt(e.target.getAttribute("width"));
let x = pOff.left - gOff.left + width / 2;
let y = pOff.top - gOff.top;
let value = count + ' ' + this.countLabel;
let name = ' on ' + month + ' ' + dateParts[0] + ', ' + dateParts[2];
let value = count + " " + this.countLabel;
let name = " on " + month + " " + dateParts[0] + ", " + dateParts[2];
this.tip.setValues(x, y, {name: name, value: value, valueFirst: 1}, []);
this.tip.setValues(
x,
y,
{ name: name, value: value, valueFirst: 1 },
[]
);
this.tip.showTip();
}
});
@ -178,33 +201,36 @@ export default class Heatmap extends BaseChart {
}
renderLegend() {
this.legendArea.textContent = '';
this.legendArea.textContent = "";
let x = 0;
let y = ROW_HEIGHT;
let radius = this.rawChartArgs.radius || 0;
let lessText = makeText('subdomain-name', x, y, 'Less',
{
let lessText = makeText("subdomain-name", x, y, "Less", {
fontSize: HEATMAP_SQUARE_SIZE + 1,
dy: 9
}
);
x = (COL_WIDTH * 2) + COL_WIDTH/2;
dy: 9,
});
x = COL_WIDTH * 2 + COL_WIDTH / 2;
this.legendArea.appendChild(lessText);
this.colors.slice(0, HEATMAP_DISTRIBUTION_SIZE).map((color, i) => {
const square = heatSquare('heatmap-legend-unit', x + (COL_WIDTH + 3) * i,
y, HEATMAP_SQUARE_SIZE, radius, color);
const square = heatSquare(
"heatmap-legend-unit",
x + (COL_WIDTH + 3) * i,
y,
HEATMAP_SQUARE_SIZE,
radius,
color
);
this.legendArea.appendChild(square);
});
let moreTextX = x + HEATMAP_DISTRIBUTION_SIZE * (COL_WIDTH + 3) + COL_WIDTH/4;
let moreText = makeText('subdomain-name', moreTextX, y, 'More',
{
let moreTextX =
x + HEATMAP_DISTRIBUTION_SIZE * (COL_WIDTH + 3) + COL_WIDTH / 4;
let moreText = makeText("subdomain-name", moreTextX, y, "More", {
fontSize: HEATMAP_SQUARE_SIZE + 1,
dy: 9
}
);
dy: 9,
});
this.legendArea.appendChild(moreText);
}
@ -213,15 +239,18 @@ export default class Heatmap extends BaseChart {
const [startMonth, startYear] = [s.start.getMonth(), s.start.getFullYear()];
const [endMonth, endYear] = [s.end.getMonth(), s.end.getFullYear()];
const noOfMonths = (endMonth - startMonth + 1) + (endYear - startYear) * 12;
const noOfMonths = endMonth - startMonth + 1 + (endYear - startYear) * 12;
let domainConfigs = [];
let startOfMonth = clone(s.start);
for(var i = 0; i < noOfMonths; i++) {
for (var i = 0; i < noOfMonths; i++) {
let endDate = s.end;
if(!areInSameMonth(startOfMonth, s.end)) {
let [month, year] = [startOfMonth.getMonth(), startOfMonth.getFullYear()];
if (!areInSameMonth(startOfMonth, s.end)) {
let [month, year] = [
startOfMonth.getMonth(),
startOfMonth.getFullYear(),
];
endDate = getLastDateInMonth(month, year);
}
domainConfigs.push(this.getDomainConfig(startOfMonth, endDate));
@ -233,29 +262,34 @@ export default class Heatmap extends BaseChart {
return domainConfigs;
}
getDomainConfig(startDate, endDate='') {
getDomainConfig(startDate, endDate = "") {
let [month, year] = [startDate.getMonth(), startDate.getFullYear()];
let startOfWeek = setDayToSunday(startDate); // TODO: Monday as well
endDate = endDate ? clone(endDate) : toMidnightUTC(getLastDateInMonth(month, year));
endDate = endDate
? clone(endDate)
: toMidnightUTC(getLastDateInMonth(month, year));
let domainConfig = {
index: month,
cols: []
cols: [],
};
addDays(endDate, 1);
let noOfMonthWeeks = getWeeksBetween(startOfWeek, endDate);
let cols = [], col;
for(var i = 0; i < noOfMonthWeeks; i++) {
let cols = [],
col;
for (var i = 0; i < noOfMonthWeeks; i++) {
col = this.getCol(startOfWeek, month);
cols.push(col);
startOfWeek = toMidnightUTC(new Date(col[NO_OF_DAYS_IN_WEEK - 1].yyyyMmDd));
startOfWeek = toMidnightUTC(
new Date(col[NO_OF_DAYS_IN_WEEK - 1].yyyyMmDd)
);
addDays(startOfWeek, 1);
}
if(col[NO_OF_DAYS_IN_WEEK - 1].dataValue !== undefined) {
if (col[NO_OF_DAYS_IN_WEEK - 1].dataValue !== undefined) {
addDays(startOfWeek, 1);
cols.push(this.getCol(startOfWeek, month, true));
}
@ -272,13 +306,14 @@ export default class Heatmap extends BaseChart {
let currentDate = clone(startDate);
let col = [];
for(var i = 0; i < NO_OF_DAYS_IN_WEEK; i++, addDays(currentDate, 1)) {
for (var i = 0; i < NO_OF_DAYS_IN_WEEK; i++, addDays(currentDate, 1)) {
let config = {};
// Non-generic adjustment for entire heatmap, needs state
let currentDateWithinData = currentDate >= s.start && currentDate <= s.end;
let currentDateWithinData =
currentDate >= s.start && currentDate <= s.end;
if(empty || currentDate.getMonth() !== month || !currentDateWithinData) {
if (empty || currentDate.getMonth() !== month || !currentDateWithinData) {
config.yyyyMmDd = getYyyyMmDd(currentDate);
} else {
config = this.getSubDomainConfig(currentDate);
@ -295,7 +330,7 @@ export default class Heatmap extends BaseChart {
let config = {
yyyyMmDd: yyyyMmDd,
dataValue: dataValue || 0,
fill: this.colors[getMaxCheckpoint(dataValue, this.state.distribution)]
fill: this.colors[getMaxCheckpoint(dataValue, this.state.distribution)],
};
return config;
}

View File

@ -1,7 +1,7 @@
import AxisChart from './AxisChart';
import { Y_AXIS_MARGIN } from '../utils/constants';
import AxisChart from "./AxisChart";
import { Y_AXIS_MARGIN } from "../utils/constants";
// import { ChartComponent } from '../objects/ChartComponents';
import { floatTwo } from '../utils/helpers';
import { floatTwo } from "../utils/helpers";
export default class MultiAxisChart extends AxisChart {
constructor(args) {
@ -11,17 +11,21 @@ export default class MultiAxisChart extends AxisChart {
}
preSetup() {
this.type = 'multiaxis';
this.type = "multiaxis";
}
setMeasures() {
super.setMeasures();
let noOfLeftAxes = this.data.datasets.filter(d => d.axisPosition === 'left').length;
this.measures.margins.left = (noOfLeftAxes) * Y_AXIS_MARGIN || Y_AXIS_MARGIN;
this.measures.margins.right = (this.data.datasets.length - noOfLeftAxes) * Y_AXIS_MARGIN || Y_AXIS_MARGIN;
let noOfLeftAxes = this.data.datasets.filter(
(d) => d.axisPosition === "left"
).length;
this.measures.margins.left = noOfLeftAxes * Y_AXIS_MARGIN || Y_AXIS_MARGIN;
this.measures.margins.right =
(this.data.datasets.length - noOfLeftAxes) * Y_AXIS_MARGIN ||
Y_AXIS_MARGIN;
}
prepareYAxis() { }
prepareYAxis() {}
prepareData(data) {
super.prepareData(data);
@ -31,20 +35,21 @@ export default class MultiAxisChart extends AxisChart {
// let axesNone = sets.filter(d => !d.axisPosition ||
// !['left', 'right'].includes(d.axisPosition));
let leftCount = 0, rightCount = 0;
let leftCount = 0,
rightCount = 0;
sets.forEach((d, i) => {
d.yAxis = {
position: d.axisPosition,
index: d.axisPosition === 'left' ? leftCount++ : rightCount++
index: d.axisPosition === "left" ? leftCount++ : rightCount++,
};
});
}
configure(args) {
super.configure(args);
this.config.xAxisMode = args.xAxisMode || 'tick';
this.config.yAxisMode = args.yAxisMode || 'span';
this.config.xAxisMode = args.xAxisMode || "tick";
this.config.yAxisMode = args.yAxisMode || "span";
}
// setUnitWidthAndXOffset() {
@ -54,59 +59,62 @@ export default class MultiAxisChart extends AxisChart {
configUnits() {
this.unitArgs = {
type: 'bar',
type: "bar",
args: {
spaceWidth: this.state.unitWidth/2,
}
spaceWidth: this.state.unitWidth / 2,
},
};
}
setYAxis() {
this.state.datasets.map(d => {
this.calcYAxisParameters(d.yAxis, d.values, this.unitType === 'line');
this.state.datasets.map((d) => {
this.calcYAxisParameters(d.yAxis, d.values, this.unitType === "line");
});
}
calcYUnits() {
this.state.datasets.map(d => {
d.positions = d.values.map(val => floatTwo(d.yAxis.zeroLine - val * d.yAxis.scaleMultiplier));
this.state.datasets.map((d) => {
d.positions = d.values.map((val) =>
floatTwo(d.yAxis.zeroLine - val * d.yAxis.scaleMultiplier)
);
});
}
// TODO: function doesn't exist, handle with components
renderConstants() {
this.state.datasets.map(d => {
let guidePos = d.yAxis.position === 'left'
this.state.datasets.map((d) => {
let guidePos =
d.yAxis.position === "left"
? -1 * d.yAxis.index * Y_AXIS_MARGIN
: this.width + d.yAxis.index * Y_AXIS_MARGIN;
this.renderer.xLine(guidePos, '', {
pos:'top',
mode: 'span',
this.renderer.xLine(guidePos, "", {
pos: "top",
mode: "span",
stroke: this.colors[i],
className: 'y-axis-guide'
})
className: "y-axis-guide",
});
});
}
getYAxesComponents() {
return this.data.datasets.map((e, i) => {
return new ChartComponent({
layerClass: 'y axis y-axis-' + i,
layerClass: "y axis y-axis-" + i,
make: () => {
let yAxis = this.state.datasets[i].yAxis;
this.renderer.setZeroline(yAxis.zeroline);
let options = {
pos: yAxis.position,
mode: 'tick',
mode: "tick",
offset: yAxis.index * Y_AXIS_MARGIN,
stroke: this.colors[i]
stroke: this.colors[i],
};
return yAxis.positions.map((position, j) =>
this.renderer.yLine(position, yAxis.labels[j], options)
);
},
animate: () => {}
animate: () => {},
});
});
}
@ -115,7 +123,7 @@ export default class MultiAxisChart extends AxisChart {
getChartComponents() {
return this.data.datasets.map((d, index) => {
return new ChartComponent({
layerClass: 'dataset-units dataset-' + index,
layerClass: "dataset-units dataset-" + index,
make: () => {
let d = this.state.datasets[index];
let unitType = this.unitArgs;
@ -146,8 +154,8 @@ export default class MultiAxisChart extends AxisChart {
let lastUnit = svgUnits[svgUnits.length - 1];
let parentNode = lastUnit.parentNode;
if(this.oldState.xExtra > 0) {
for(var i = 0; i<this.oldState.xExtra; i++) {
if (this.oldState.xExtra > 0) {
for (var i = 0; i < this.oldState.xExtra; i++) {
let unit = lastUnit.cloneNode(true);
parentNode.appendChild(unit);
svgUnits.push(unit);
@ -157,16 +165,18 @@ export default class MultiAxisChart extends AxisChart {
this.renderer.setZeroline(d.yAxis.zeroLine);
svgUnits.map((unit, i) => {
if(newX[i] === undefined || newY[i] === undefined) return;
this.elementsToAnimate.push(this.renderer['animate' + unitType](
if (newX[i] === undefined || newY[i] === undefined) return;
this.elementsToAnimate.push(
this.renderer["animate" + unitType](
unit, // unit, with info to replace where it came from in the data
newX[i],
newY[i],
index,
this.state.noOfDatasets
));
)
);
});
}
},
});
});
}

View File

@ -1,12 +1,12 @@
import AggregationChart from './AggregationChart';
import { getOffset } from '../utils/dom';
import { getComponent } from '../objects/ChartComponents';
import { PERCENTAGE_BAR_DEFAULT_HEIGHT } from '../utils/constants';
import AggregationChart from "./AggregationChart";
import { getOffset } from "../utils/dom";
import { getComponent } from "../objects/ChartComponents";
import { PERCENTAGE_BAR_DEFAULT_HEIGHT } from "../utils/constants";
export default class PercentageChart extends AggregationChart {
constructor(parent, args) {
super(parent, args);
this.type = 'percentage';
this.type = "percentage";
this.setup();
}
@ -27,25 +27,26 @@ export default class PercentageChart extends AggregationChart {
let componentConfigs = [
[
'percentageBars',
"percentageBars",
{
barHeight: this.barOptions.height,
},
function() {
function () {
return {
xPositions: s.xPositions,
widths: s.widths,
colors: this.colors
colors: this.colors,
};
}.bind(this)
]
}.bind(this),
],
];
this.components = new Map(componentConfigs
.map(args => {
this.components = new Map(
componentConfigs.map((args) => {
let component = getComponent(...args);
return [args[0], component];
}));
})
);
}
calc() {
@ -57,32 +58,37 @@ export default class PercentageChart extends AggregationChart {
let xPos = 0;
s.sliceTotals.map((value) => {
let width = this.width * value / s.grandTotal;
let width = (this.width * value) / s.grandTotal;
s.widths.push(width);
s.xPositions.push(xPos);
xPos += width;
});
}
makeDataByIndex() { }
makeDataByIndex() {}
bindTooltip() {
let s = this.state;
this.container.addEventListener('mousemove', (e) => {
let bars = this.components.get('percentageBars').store;
this.container.addEventListener("mousemove", (e) => {
let bars = this.components.get("percentageBars").store;
let bar = e.target;
if(bars.includes(bar)) {
if (bars.includes(bar)) {
let i = bars.indexOf(bar);
let gOff = getOffset(this.container), pOff = getOffset(bar);
let gOff = getOffset(this.container),
pOff = getOffset(bar);
let x = pOff.left - gOff.left + parseInt(bar.getAttribute('width'))/2;
let x = pOff.left - gOff.left + parseInt(bar.getAttribute("width")) / 2;
let y = pOff.top - gOff.top;
let title = (this.formattedLabels && this.formattedLabels.length>0
? this.formattedLabels[i] : this.state.labels[i]) + ': ';
let fraction = s.sliceTotals[i]/s.grandTotal;
let title =
(this.formattedLabels && this.formattedLabels.length > 0
? this.formattedLabels[i]
: this.state.labels[i]) + ": ";
let fraction = s.sliceTotals[i] / s.grandTotal;
this.tip.setValues(x, y, {name: title, value: (fraction*100).toFixed(1) + "%"});
this.tip.setValues(x, y, {
name: title,
value: (fraction * 100).toFixed(1) + "%",
});
this.tip.showTip();
}
});

View File

@ -1,16 +1,16 @@
import AggregationChart from './AggregationChart';
import { getComponent } from '../objects/ChartComponents';
import { getOffset, fire } from '../utils/dom';
import { getPositionByAngle } from '../utils/helpers';
import { makeArcPathStr, makeCircleStr } from '../utils/draw';
import { lightenDarkenColor } from '../utils/colors';
import { transform } from '../utils/animation';
import { FULL_ANGLE } from '../utils/constants';
import AggregationChart from "./AggregationChart";
import { getComponent } from "../objects/ChartComponents";
import { getOffset, fire } from "../utils/dom";
import { getPositionByAngle } from "../utils/helpers";
import { makeArcPathStr, makeCircleStr } from "../utils/draw";
import { lightenDarkenColor } from "../utils/colors";
import { transform } from "../utils/animation";
import { FULL_ANGLE } from "../utils/constants";
export default class PieChart extends AggregationChart {
constructor(parent, args) {
super(parent, args);
this.type = 'pie';
this.type = "pie";
this.initTimeout = 0;
this.init = 1;
@ -31,7 +31,7 @@ export default class PieChart extends AggregationChart {
calc() {
super.calc();
let s = this.state;
this.radius = (this.height > this.width ? this.center.x : this.center.y);
this.radius = this.height > this.width ? this.center.x : this.center.y;
const { radius, clockWise } = this;
@ -41,12 +41,11 @@ export default class PieChart extends AggregationChart {
let curAngle = 180 - this.config.startAngle;
s.sliceTotals.map((total, i) => {
const startAngle = curAngle;
const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
const largeArc = originDiffAngle > 180 ? 1 : 0;
const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
const endAngle = curAngle = curAngle + diffAngle;
const endAngle = (curAngle = curAngle + diffAngle);
const startPosition = getPositionByAngle(startAngle, radius);
const endPosition = getPositionByAngle(endAngle, radius);
@ -62,8 +61,22 @@ export default class PieChart extends AggregationChart {
}
const curPath =
originDiffAngle === 360
? makeCircleStr(curStart, curEnd, this.center, this.radius, clockWise, largeArc)
: makeArcPathStr(curStart, curEnd, this.center, this.radius, clockWise, largeArc);
? makeCircleStr(
curStart,
curEnd,
this.center,
this.radius,
clockWise,
largeArc
)
: makeArcPathStr(
curStart,
curEnd,
this.center,
this.radius,
clockWise,
largeArc
);
s.sliceStrings.push(curPath);
s.slicesProperties.push({
@ -73,7 +86,7 @@ export default class PieChart extends AggregationChart {
total: s.grandTotal,
startAngle,
endAngle,
angle: diffAngle
angle: diffAngle,
});
});
this.init = 0;
@ -84,29 +97,34 @@ export default class PieChart extends AggregationChart {
let componentConfigs = [
[
'pieSlices',
"pieSlices",
{},
function () {
return {
sliceStrings: s.sliceStrings,
colors: this.colors
colors: this.colors,
};
}.bind(this)
]
}.bind(this),
],
];
this.components = new Map(componentConfigs
.map(args => {
this.components = new Map(
componentConfigs.map((args) => {
let component = getComponent(...args);
return [args[0], component];
}));
})
);
}
calTranslateByAngle(property) {
const { radius, hoverRadio } = this;
const position = getPositionByAngle(property.startAngle + (property.angle / 2), radius);
return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
const position = getPositionByAngle(
property.startAngle + property.angle / 2,
radius
);
return `translate3d(${position.x * hoverRadio}px,${
position.y * hoverRadio
}px,0)`;
}
hoverSlice(path, i, flag, e) {
@ -118,28 +136,33 @@ export default class PieChart extends AggregationChart {
let g_off = getOffset(this.svg);
let x = e.pageX - g_off.left + 10;
let y = e.pageY - g_off.top - 10;
let title = (this.formatted_labels && this.formatted_labels.length > 0
? this.formatted_labels[i] : this.state.labels[i]) + ': ';
let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
let title =
(this.formatted_labels && this.formatted_labels.length > 0
? this.formatted_labels[i]
: this.state.labels[i]) + ": ";
let percent = (
(this.state.sliceTotals[i] * 100) /
this.state.grandTotal
).toFixed(1);
this.tip.setValues(x, y, { name: title, value: percent + "%" });
this.tip.showTip();
} else {
transform(path, 'translate3d(0,0,0)');
transform(path, "translate3d(0,0,0)");
this.tip.hideTip();
path.style.fill = color;
}
}
bindTooltip() {
this.container.addEventListener('mousemove', this.mouseMove);
this.container.addEventListener('mouseleave', this.mouseLeave);
this.container.addEventListener("mousemove", this.mouseMove);
this.container.addEventListener("mouseleave", this.mouseLeave);
}
getDataPoint(index = this.state.currentIndex) {
let s = this.state;
let data_point = {
index: index,
label: s.labels[index],
values: s.sliceTotals[index]
values: s.sliceTotals[index],
};
return data_point;
}
@ -154,17 +177,17 @@ export default class PieChart extends AggregationChart {
}
bindUnits() {
const units = this.components.get('pieSlices').store;
const units = this.components.get("pieSlices").store;
if (!units) return;
units.forEach((unit, index) => {
unit.addEventListener('click', () => {
unit.addEventListener("click", () => {
this.setCurrentDataPoint(index);
});
});
}
mouseMove(e) {
const target = e.target;
let slices = this.components.get('pieSlices').store;
let slices = this.components.get("pieSlices").store;
let prevIndex = this.curActiveSliceIndex;
let prevAcitve = this.curActiveSlice;
if (slices.includes(target)) {

View File

@ -1,10 +1,10 @@
import * as Charts from './chart';
import * as Charts from "./chart";
let frappe = { };
let frappe = {};
frappe.NAME = 'Frappe Charts';
frappe.VERSION = '1.6.2';
frappe.NAME = "Frappe Charts";
frappe.VERSION = "1.6.2";
frappe = Object.assign({ }, frappe, Charts);
frappe = Object.assign({}, frappe, Charts);
export default frappe;

View File

@ -1,19 +1,38 @@
import { makeSVGGroup } from '../utils/draw';
import { makeText, makePath, xLine, yLine, yMarker, yRegion, datasetBar, datasetDot, percentageBar, getPaths, heatSquare } from '../utils/draw';
import { equilizeNoOfElements } from '../utils/draw-utils';
import { translateHoriLine, translateVertLine, animateRegion, animateBar,
animateDot, animatePath, animatePathStr } from '../utils/animate';
import { getMonthName } from '../utils/date-utils';
import { makeSVGGroup } from "../utils/draw";
import {
makeText,
makePath,
xLine,
yLine,
yMarker,
yRegion,
datasetBar,
datasetDot,
percentageBar,
getPaths,
heatSquare,
} from "../utils/draw";
import { equilizeNoOfElements } from "../utils/draw-utils";
import {
translateHoriLine,
translateVertLine,
animateRegion,
animateBar,
animateDot,
animatePath,
animatePathStr,
} from "../utils/animate";
import { getMonthName } from "../utils/date-utils";
class ChartComponent {
constructor({
layerClass = '',
layerTransform = '',
layerClass = "",
layerTransform = "",
constants,
getData,
makeElements,
animateElements
animateElements,
}) {
this.layerTransform = layerTransform;
this.constants = constants;
@ -27,8 +46,10 @@ class ChartComponent {
this.labels = [];
this.layerClass = layerClass;
this.layerClass = typeof(this.layerClass) === 'function'
? this.layerClass() : this.layerClass;
this.layerClass =
typeof this.layerClass === "function"
? this.layerClass()
: this.layerClass;
this.refresh();
}
@ -49,11 +70,11 @@ class ChartComponent {
render(data) {
this.store = this.makeElements(data);
this.layer.textContent = '';
this.store.forEach(element => {
this.layer.textContent = "";
this.store.forEach((element) => {
this.layer.appendChild(element);
});
this.labels.forEach(element => {
this.labels.forEach((element) => {
this.layer.appendChild(element);
});
}
@ -61,7 +82,7 @@ class ChartComponent {
update(animate = true) {
this.refresh();
let animateElements = [];
if(animate) {
if (animate) {
animateElements = this.animateElements(this.data) || [];
}
return animateElements;
@ -70,25 +91,17 @@ class ChartComponent {
let componentConfigs = {
donutSlices: {
layerClass: 'donut-slices',
layerClass: "donut-slices",
makeElements(data) {
return data.sliceStrings.map((s, i) => {
let slice = makePath(s, 'donut-path', data.colors[i], 'none', data.strokeWidth);
slice.style.transition = 'transform .3s;';
return slice;
});
},
animateElements(newData) {
return this.store.map((slice, i) => animatePathStr(slice, newData.sliceStrings[i]));
},
},
pieSlices: {
layerClass: 'pie-slices',
makeElements(data) {
return data.sliceStrings.map((s, i) =>{
let slice = makePath(s, 'pie-path', 'none', data.colors[i]);
slice.style.transition = 'transform .3s;';
let slice = makePath(
s,
"donut-path",
data.colors[i],
"none",
data.strokeWidth
);
slice.style.transition = "transform .3s;";
return slice;
});
},
@ -97,33 +110,60 @@ let componentConfigs = {
return this.store.map((slice, i) =>
animatePathStr(slice, newData.sliceStrings[i])
);
}
},
},
pieSlices: {
layerClass: "pie-slices",
makeElements(data) {
return data.sliceStrings.map((s, i) => {
let slice = makePath(s, "pie-path", "none", data.colors[i]);
slice.style.transition = "transform .3s;";
return slice;
});
},
animateElements(newData) {
return this.store.map((slice, i) =>
animatePathStr(slice, newData.sliceStrings[i])
);
},
},
percentageBars: {
layerClass: 'percentage-bars',
layerClass: "percentage-bars",
makeElements(data) {
const numberOfPoints = data.xPositions.length;
return data.xPositions.map((x, i) =>{
return data.xPositions.map((x, i) => {
let y = 0;
let isLast = i == numberOfPoints - 1;
let isFirst = i == 0;
let bar = percentageBar(x, y, data.widths[i], this.constants.barHeight, isFirst, isLast, data.colors[i]);
let bar = percentageBar(
x,
y,
data.widths[i],
this.constants.barHeight,
isFirst,
isLast,
data.colors[i]
);
return bar;
});
},
animateElements(newData) {
if(newData) return [];
}
if (newData) return [];
},
},
yAxis: {
layerClass: 'y axis',
layerClass: "y axis",
makeElements(data) {
return data.positions.map((position, i) =>
yLine(position, data.labels[i], this.constants.width,
{mode: this.constants.mode, pos: this.constants.pos, shortenNumbers: this.constants.shortenNumbers})
yLine(position, data.labels[i], this.constants.width, {
mode: this.constants.mode,
pos: this.constants.pos,
shortenNumbers: this.constants.shortenNumbers,
})
);
},
@ -138,23 +178,23 @@ let componentConfigs = {
this.render({
positions: oldPos,
labels: newLabels
labels: newLabels,
});
return this.store.map((line, i) => {
return translateHoriLine(
line, newPos[i], oldPos[i]
);
return translateHoriLine(line, newPos[i], oldPos[i]);
});
}
},
},
xAxis: {
layerClass: 'x axis',
layerClass: "x axis",
makeElements(data) {
return data.positions.map((position, i) =>
xLine(position, data.calcLabels[i], this.constants.height,
{mode: this.constants.mode, pos: this.constants.pos})
xLine(position, data.calcLabels[i], this.constants.height, {
mode: this.constants.mode,
pos: this.constants.pos,
})
);
},
@ -169,117 +209,137 @@ let componentConfigs = {
this.render({
positions: oldPos,
calcLabels: newLabels
calcLabels: newLabels,
});
return this.store.map((line, i) => {
return translateVertLine(
line, newPos[i], oldPos[i]
);
return translateVertLine(line, newPos[i], oldPos[i]);
});
}
},
},
yMarkers: {
layerClass: 'y-markers',
layerClass: "y-markers",
makeElements(data) {
return data.map(m =>
yMarker(m.position, m.label, this.constants.width,
{labelPos: m.options.labelPos, mode: 'span', lineType: 'dashed'})
return data.map((m) =>
yMarker(m.position, m.label, this.constants.width, {
labelPos: m.options.labelPos,
mode: "span",
lineType: "dashed",
})
);
},
animateElements(newData) {
[this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
let newPos = newData.map(d => d.position);
let newLabels = newData.map(d => d.label);
let newOptions = newData.map(d => d.options);
let newPos = newData.map((d) => d.position);
let newLabels = newData.map((d) => d.label);
let newOptions = newData.map((d) => d.options);
let oldPos = this.oldData.map(d => d.position);
let oldPos = this.oldData.map((d) => d.position);
this.render(oldPos.map((pos, i) => {
this.render(
oldPos.map((pos, i) => {
return {
position: oldPos[i],
label: newLabels[i],
options: newOptions[i]
options: newOptions[i],
};
}));
})
);
return this.store.map((line, i) => {
return translateHoriLine(
line, newPos[i], oldPos[i]
);
return translateHoriLine(line, newPos[i], oldPos[i]);
});
}
},
},
yRegions: {
layerClass: 'y-regions',
layerClass: "y-regions",
makeElements(data) {
return data.map(r =>
yRegion(r.startPos, r.endPos, this.constants.width,
r.label, {labelPos: r.options.labelPos})
return data.map((r) =>
yRegion(r.startPos, r.endPos, this.constants.width, r.label, {
labelPos: r.options.labelPos,
})
);
},
animateElements(newData) {
[this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
let newPos = newData.map(d => d.endPos);
let newLabels = newData.map(d => d.label);
let newStarts = newData.map(d => d.startPos);
let newOptions = newData.map(d => d.options);
let newPos = newData.map((d) => d.endPos);
let newLabels = newData.map((d) => d.label);
let newStarts = newData.map((d) => d.startPos);
let newOptions = newData.map((d) => d.options);
let oldPos = this.oldData.map(d => d.endPos);
let oldStarts = this.oldData.map(d => d.startPos);
let oldPos = this.oldData.map((d) => d.endPos);
let oldStarts = this.oldData.map((d) => d.startPos);
this.render(oldPos.map((pos, i) => {
this.render(
oldPos.map((pos, i) => {
return {
startPos: oldStarts[i],
endPos: oldPos[i],
label: newLabels[i],
options: newOptions[i]
options: newOptions[i],
};
}));
})
);
let animateElements = [];
this.store.map((rectGroup, i) => {
animateElements = animateElements.concat(animateRegion(
rectGroup, newStarts[i], newPos[i], oldPos[i]
));
animateElements = animateElements.concat(
animateRegion(rectGroup, newStarts[i], newPos[i], oldPos[i])
);
});
return animateElements;
}
},
},
heatDomain: {
layerClass: function() { return 'heat-domain domain-' + this.constants.index; },
layerClass: function () {
return "heat-domain domain-" + this.constants.index;
},
makeElements(data) {
let {index, colWidth, rowHeight, squareSize, radius, xTranslate} = this.constants;
let { index, colWidth, rowHeight, squareSize, radius, xTranslate } =
this.constants;
let monthNameHeight = -12;
let x = xTranslate, y = 0;
let x = xTranslate,
y = 0;
this.serializedSubDomains = [];
data.cols.map((week, weekNo) => {
if(weekNo === 1) {
if (weekNo === 1) {
this.labels.push(
makeText('domain-name', x, monthNameHeight, getMonthName(index, true).toUpperCase(),
makeText(
"domain-name",
x,
monthNameHeight,
getMonthName(index, true).toUpperCase(),
{
fontSize: 9
fontSize: 9,
}
)
);
}
week.map((day, i) => {
if(day.fill) {
if (day.fill) {
let data = {
'data-date': day.yyyyMmDd,
'data-value': day.dataValue,
'data-day': i
"data-date": day.yyyyMmDd,
"data-value": day.dataValue,
"data-day": i,
};
let square = heatSquare('day', x, y, squareSize, radius, day.fill, data);
let square = heatSquare(
"day",
x,
y,
squareSize,
radius,
day.fill,
data
);
this.serializedSubDomains.push(square);
}
y += rowHeight;
@ -292,15 +352,17 @@ let componentConfigs = {
},
animateElements(newData) {
if(newData) return [];
}
if (newData) return [];
},
},
barGraph: {
layerClass: function() { return 'dataset-units dataset-bars dataset-' + this.constants.index; },
layerClass: function () {
return "dataset-units dataset-bars dataset-" + this.constants.index;
},
makeElements(data) {
let c = this.constants;
this.unitType = 'bar';
this.unitType = "bar";
this.units = data.yPositions.map((y, j) => {
return datasetBar(
data.xPositions[j],
@ -313,7 +375,7 @@ let componentConfigs = {
{
zeroLine: data.zeroLine,
barsWidth: data.barsWidth,
minHeight: c.minHeight
minHeight: c.minHeight,
}
);
});
@ -349,23 +411,31 @@ let componentConfigs = {
let animateElements = [];
this.store.map((bar, i) => {
animateElements = animateElements.concat(animateBar(
bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i],
{zeroLine: newData.zeroLine}
));
animateElements = animateElements.concat(
animateBar(
bar,
newXPos[i],
newYPos[i],
newData.barWidth,
newOffsets[i],
{ zeroLine: newData.zeroLine }
)
);
});
return animateElements;
}
},
},
lineGraph: {
layerClass: function() { return 'dataset-units dataset-line dataset-' + this.constants.index; },
layerClass: function () {
return "dataset-units dataset-line dataset-" + this.constants.index;
},
makeElements(data) {
let c = this.constants;
this.unitType = 'dot';
this.unitType = "dot";
this.paths = {};
if(!c.hideLine) {
if (!c.hideLine) {
this.paths = getPaths(
data.xPositions,
data.yPositions,
@ -373,24 +443,24 @@ let componentConfigs = {
{
heatline: c.heatline,
regionFill: c.regionFill,
spline: c.spline
spline: c.spline,
},
{
svgDefs: c.svgDefs,
zeroLine: data.zeroLine
zeroLine: data.zeroLine,
}
);
}
this.units = [];
if(!c.hideDots) {
if (!c.hideDots) {
this.units = data.yPositions.map((y, j) => {
return datasetDot(
data.xPositions[j],
y,
data.radius,
c.color,
(c.valuesOverPoints ? data.values[j] : ''),
c.valuesOverPoints ? data.values[j] : "",
j
);
});
@ -422,29 +492,37 @@ let componentConfigs = {
let animateElements = [];
if(Object.keys(this.paths).length) {
animateElements = animateElements.concat(animatePath(
this.paths, newXPos, newYPos, newData.zeroLine, this.constants.spline));
if (Object.keys(this.paths).length) {
animateElements = animateElements.concat(
animatePath(
this.paths,
newXPos,
newYPos,
newData.zeroLine,
this.constants.spline
)
);
}
if(this.units.length) {
if (this.units.length) {
this.units.map((dot, i) => {
animateElements = animateElements.concat(animateDot(
dot, newXPos[i], newYPos[i]));
animateElements = animateElements.concat(
animateDot(dot, newXPos[i], newYPos[i])
);
});
}
return animateElements;
}
}
},
},
};
export function getComponent(name, constants, getData) {
let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
let keys = Object.keys(componentConfigs).filter((k) => name.includes(k));
let config = componentConfigs[keys[0]];
Object.assign(config, {
constants: constants,
getData: getData
getData: getData,
});
return new ChartComponent(config);
}

View File

@ -1,15 +1,12 @@
import { $ } from '../utils/dom';
import { TOOLTIP_POINTER_TRIANGLE_HEIGHT } from '../utils/constants';
import { $ } from "../utils/dom";
import { TOOLTIP_POINTER_TRIANGLE_HEIGHT } from "../utils/constants";
export default class SvgTip {
constructor({
parent = null,
colors = []
}) {
constructor({ parent = null, colors = [] }) {
this.parent = parent;
this.colors = colors;
this.titleName = '';
this.titleValue = '';
this.titleName = "";
this.titleValue = "";
this.listValues = [];
this.titleValueFirst = 0;
@ -32,53 +29,54 @@ export default class SvgTip {
}
makeTooltip() {
this.container = $.create('div', {
this.container = $.create("div", {
inside: this.parent,
className: 'graph-svg-tip comparison',
className: "graph-svg-tip comparison",
innerHTML: `<span class="title"></span>
<ul class="data-point-list"></ul>
<div class="svg-pointer"></div>`
<div class="svg-pointer"></div>`,
});
this.hideTip();
this.title = this.container.querySelector('.title');
this.list = this.container.querySelector('.data-point-list');
this.dataPointList = this.container.querySelector('.data-point-list');
this.title = this.container.querySelector(".title");
this.list = this.container.querySelector(".data-point-list");
this.dataPointList = this.container.querySelector(".data-point-list");
this.parent.addEventListener('mouseleave', () => {
this.parent.addEventListener("mouseleave", () => {
this.hideTip();
});
}
fill() {
let title;
if(this.index) {
this.container.setAttribute('data-point-index', this.index);
if (this.index) {
this.container.setAttribute("data-point-index", this.index);
}
if(this.titleValueFirst) {
if (this.titleValueFirst) {
title = `<strong>${this.titleValue}</strong>${this.titleName}`;
} else {
title = `${this.titleName}<strong>${this.titleValue}</strong>`;
}
if (this.listValues.length > 4) {
this.list.classList.add('tooltip-grid');
this.list.classList.add("tooltip-grid");
} else {
this.list.classList.remove('tooltip-grid');
this.list.classList.remove("tooltip-grid");
}
this.title.innerHTML = title;
this.dataPointList.innerHTML = '';
this.dataPointList.innerHTML = "";
this.listValues.map((set, i) => {
const color = this.colors[i] || 'black';
let value = set.formatted === 0 || set.formatted ? set.formatted : set.value;
let li = $.create('li', {
const color = this.colors[i] || "black";
let value =
set.formatted === 0 || set.formatted ? set.formatted : set.value;
let li = $.create("li", {
innerHTML: `<div class="tooltip-legend" style="background: ${color};"></div>
<div>
<div class="tooltip-value">${ value === 0 || value ? value : '' }</div>
<div class="tooltip-label">${set.title ? set.title : '' }</div>
</div>`
<div class="tooltip-value">${value === 0 || value ? value : ""}</div>
<div class="tooltip-label">${set.title ? set.title : ""}</div>
</div>`,
});
this.dataPointList.appendChild(li);
@ -88,17 +86,17 @@ export default class SvgTip {
calcPosition() {
let width = this.container.offsetWidth;
this.top = this.y - this.container.offsetHeight
- TOOLTIP_POINTER_TRIANGLE_HEIGHT;
this.left = this.x - width/2;
this.top =
this.y - this.container.offsetHeight - TOOLTIP_POINTER_TRIANGLE_HEIGHT;
this.left = this.x - width / 2;
let maxLeft = this.parent.offsetWidth - width;
let pointer = this.container.querySelector('.svg-pointer');
let pointer = this.container.querySelector(".svg-pointer");
if(this.left < 0) {
if (this.left < 0) {
pointer.style.left = `calc(50% - ${-1 * this.left}px)`;
this.left = 0;
} else if(this.left > maxLeft) {
} else if (this.left > maxLeft) {
let delta = this.left - maxLeft;
let pointerOffset = `calc(50% + ${delta}px)`;
pointer.style.left = pointerOffset;
@ -121,14 +119,14 @@ export default class SvgTip {
}
hideTip() {
this.container.style.top = '0px';
this.container.style.left = '0px';
this.container.style.opacity = '0';
this.container.style.top = "0px";
this.container.style.left = "0px";
this.container.style.opacity = "0";
}
showTip() {
this.container.style.top = this.top + 'px';
this.container.style.left = this.left + 'px';
this.container.style.opacity = '1';
this.container.style.top = this.top + "px";
this.container.style.left = this.left + "px";
this.container.style.opacity = "1";
}
}

View File

@ -1,21 +1,21 @@
import { getBarHeightAndYAttr, getSplineCurvePointsStr } from './draw-utils';
import { getBarHeightAndYAttr, getSplineCurvePointsStr } from "./draw-utils";
export const UNIT_ANIM_DUR = 350;
export const PATH_ANIM_DUR = 350;
export const MARKER_LINE_ANIM_DUR = UNIT_ANIM_DUR;
export const REPLACE_ALL_NEW_DUR = 250;
export const STD_EASING = 'easein';
export const STD_EASING = "easein";
export function translate(unit, oldCoord, newCoord, duration) {
let old = typeof oldCoord === 'string' ? oldCoord : oldCoord.join(', ');
let old = typeof oldCoord === "string" ? oldCoord : oldCoord.join(", ");
return [
unit,
{transform: newCoord.join(', ')},
{ transform: newCoord.join(", ") },
duration,
STD_EASING,
"translate",
{transform: old}
{ transform: old },
];
}
@ -33,66 +33,82 @@ export function animateRegion(rectGroup, newY1, newY2, oldY2) {
let width = rect.getAttribute("width");
let rectAnim = [
rect,
{ height: newHeight, 'stroke-dasharray': `${width}, ${newHeight}` },
{ height: newHeight, "stroke-dasharray": `${width}, ${newHeight}` },
MARKER_LINE_ANIM_DUR,
STD_EASING
STD_EASING,
];
let groupAnim = translate(rectGroup, [0, oldY2], [0, newY2], MARKER_LINE_ANIM_DUR);
let groupAnim = translate(
rectGroup,
[0, oldY2],
[0, newY2],
MARKER_LINE_ANIM_DUR
);
return [rectAnim, groupAnim];
}
export function animateBar(bar, x, yTop, width, offset=0, meta={}) {
export function animateBar(bar, x, yTop, width, offset = 0, meta = {}) {
let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
y -= offset;
if(bar.nodeName !== 'rect') {
if (bar.nodeName !== "rect") {
let rect = bar.childNodes[0];
let rectAnim = [
rect,
{width: width, height: height},
{ width: width, height: height },
UNIT_ANIM_DUR,
STD_EASING
STD_EASING,
];
let oldCoordStr = bar.getAttribute("transform").split("(")[1].slice(0, -1);
let groupAnim = translate(bar, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
return [rectAnim, groupAnim];
} else {
return [[bar, {width: width, height: height, x: x, y: y}, UNIT_ANIM_DUR, STD_EASING]];
return [
[
bar,
{ width: width, height: height, x: x, y: y },
UNIT_ANIM_DUR,
STD_EASING,
],
];
}
// bar.animate({height: args.newHeight, y: yTop}, UNIT_ANIM_DUR, mina.easein);
}
export function animateDot(dot, x, y) {
if(dot.nodeName !== 'circle') {
if (dot.nodeName !== "circle") {
let oldCoordStr = dot.getAttribute("transform").split("(")[1].slice(0, -1);
let groupAnim = translate(dot, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
return [groupAnim];
} else {
return [[dot, {cx: x, cy: y}, UNIT_ANIM_DUR, STD_EASING]];
return [[dot, { cx: x, cy: y }, UNIT_ANIM_DUR, STD_EASING]];
}
// dot.animate({cy: yTop}, UNIT_ANIM_DUR, mina.easein);
}
export function animatePath(paths, newXList, newYList, zeroLine, spline) {
let pathComponents = [];
let pointsStr = newYList.map((y, i) => (newXList[i] + ',' + y)).join("L");
let pointsStr = newYList.map((y, i) => newXList[i] + "," + y).join("L");
if (spline)
pointsStr = getSplineCurvePointsStr(newXList, newYList);
if (spline) pointsStr = getSplineCurvePointsStr(newXList, newYList);
const animPath = [paths.path, {d:"M" + pointsStr}, PATH_ANIM_DUR, STD_EASING];
const animPath = [
paths.path,
{ d: "M" + pointsStr },
PATH_ANIM_DUR,
STD_EASING,
];
pathComponents.push(animPath);
if(paths.region) {
if (paths.region) {
let regStartPt = `${newXList[0]},${zeroLine}L`;
let regEndPt = `L${newXList.slice(-1)[0]}, ${zeroLine}`;
const animRegion = [
paths.region,
{d:"M" + regStartPt + pointsStr + regEndPt},
{ d: "M" + regStartPt + pointsStr + regEndPt },
PATH_ANIM_DUR,
STD_EASING
STD_EASING,
];
pathComponents.push(animRegion);
}
@ -101,5 +117,5 @@ export function animatePath(paths, newXList, newYList, zeroLine, spline) {
}
export function animatePathStr(oldPath, pathStr) {
return [oldPath, {d: pathStr}, UNIT_ANIM_DUR, STD_EASING];
return [oldPath, { d: pathStr }, UNIT_ANIM_DUR, STD_EASING];
}

View File

@ -1,6 +1,6 @@
// Leveraging SMIL Animations
import { REPLACE_ALL_NEW_DUR } from './animate';
import { REPLACE_ALL_NEW_DUR } from "./animate";
const EASING = {
ease: "0.25 0.1 0.25 1",
@ -8,22 +8,35 @@ const EASING = {
// easein: "0.42 0 1 1",
easein: "0.1 0.8 0.2 1",
easeout: "0 0 0.58 1",
easeinout: "0.42 0 0.58 1"
easeinout: "0.42 0 0.58 1",
};
function animateSVGElement(element, props, dur, easingType="linear", type=undefined, oldValues={}) {
function animateSVGElement(
element,
props,
dur,
easingType = "linear",
type = undefined,
oldValues = {}
) {
let animElement = element.cloneNode(true);
let newElement = element.cloneNode(true);
for(var attributeName in props) {
for (var attributeName in props) {
let animateElement;
if(attributeName === 'transform') {
animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
if (attributeName === "transform") {
animateElement = document.createElementNS(
"http://www.w3.org/2000/svg",
"animateTransform"
);
} else {
animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
animateElement = document.createElementNS(
"http://www.w3.org/2000/svg",
"animate"
);
}
let currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
let currentValue =
oldValues[attributeName] || element.getAttribute(attributeName);
let value = props[attributeName];
let animAttr = {
@ -31,15 +44,15 @@ function animateSVGElement(element, props, dur, easingType="linear", type=undefi
from: currentValue,
to: value,
begin: "0s",
dur: dur/1000 + "s",
dur: dur / 1000 + "s",
values: currentValue + ";" + value,
keySplines: EASING[easingType],
keyTimes: "0;1",
calcMode: "spline",
fill: 'freeze'
fill: "freeze",
};
if(type) {
if (type) {
animAttr["type"] = type;
}
@ -49,7 +62,7 @@ function animateSVGElement(element, props, dur, easingType="linear", type=undefi
animElement.appendChild(animateElement);
if(type) {
if (type) {
newElement.setAttribute(attributeName, `translate(${value})`);
} else {
newElement.setAttribute(attributeName, value);
@ -59,7 +72,8 @@ function animateSVGElement(element, props, dur, easingType="linear", type=undefi
return [animElement, newElement];
}
export function transform(element, style) { // eslint-disable-line no-unused-vars
export function transform(element, style) {
// eslint-disable-line no-unused-vars
element.style.transform = style;
element.style.webkitTransform = style;
element.style.msTransform = style;
@ -71,7 +85,7 @@ function animateSVG(svgContainer, elements) {
let newElements = [];
let animElements = [];
elements.map(element => {
elements.map((element) => {
let unit = element[0];
let parent = unit.parentNode;
@ -101,18 +115,17 @@ function animateSVG(svgContainer, elements) {
}
export function runSMILAnimation(parent, svgElement, elementsToAnimate) {
if(elementsToAnimate.length === 0) return;
if (elementsToAnimate.length === 0) return;
let animSvgElement = animateSVG(svgElement, elementsToAnimate);
if(svgElement.parentNode == parent) {
if (svgElement.parentNode == parent) {
parent.removeChild(svgElement);
parent.appendChild(animSvgElement);
}
// Replace the new svgElement (data has already been replaced)
setTimeout(() => {
if(animSvgElement.parentNode == parent) {
if (animSvgElement.parentNode == parent) {
parent.removeChild(animSvgElement);
parent.appendChild(svgElement);
}

View File

@ -1,6 +1,10 @@
import { fillArray } from '../utils/helpers';
import { DEFAULT_AXIS_CHART_TYPE, AXIS_DATASET_CHART_TYPES, DEFAULT_CHAR_WIDTH,
SERIES_LABEL_SPACE_RATIO } from '../utils/constants';
import { fillArray } from "../utils/helpers";
import {
DEFAULT_AXIS_CHART_TYPE,
AXIS_DATASET_CHART_TYPES,
DEFAULT_CHAR_WIDTH,
SERIES_LABEL_SPACE_RATIO,
} from "../utils/constants";
export function dataPrep(data, type) {
data.labels = data.labels || [];
@ -10,24 +14,26 @@ export function dataPrep(data, type) {
// Datasets
let datasets = data.datasets;
let zeroArray = new Array(datasetLength).fill(0);
if(!datasets) {
if (!datasets) {
// default
datasets = [{
values: zeroArray
}];
datasets = [
{
values: zeroArray,
},
];
}
datasets.map(d=> {
datasets.map((d) => {
// Set values
if(!d.values) {
if (!d.values) {
d.values = zeroArray;
} else {
// Check for non values
let vals = d.values;
vals = vals.map(val => (!isNaN(val) ? val : 0));
vals = vals.map((val) => (!isNaN(val) ? val : 0));
// Trim or extend
if(vals.length > datasetLength) {
if (vals.length > datasetLength) {
vals = vals.slice(0, datasetLength);
} else {
vals = fillArray(vals, datasetLength - vals.length, 0);
@ -36,20 +42,20 @@ export function dataPrep(data, type) {
}
// Set type
if(!d.chartType ) {
if(!AXIS_DATASET_CHART_TYPES.includes(type)) type = DEFAULT_AXIS_CHART_TYPE;
if (!d.chartType) {
if (!AXIS_DATASET_CHART_TYPES.includes(type))
type = DEFAULT_AXIS_CHART_TYPE;
d.chartType = type;
}
});
// Markers
// Regions
// data.yRegions = data.yRegions || [];
if(data.yRegions) {
data.yRegions.map(d => {
if(d.end < d.start) {
if (data.yRegions) {
data.yRegions.map((d) => {
if (d.end < d.start) {
[d.start, d.end] = [d.end, d.start];
}
});
@ -64,61 +70,60 @@ export function zeroDataPrep(realData) {
let zeroData = {
labels: realData.labels.slice(0, -1),
datasets: realData.datasets.map(d => {
datasets: realData.datasets.map((d) => {
return {
name: '',
name: "",
values: zeroArray.slice(0, -1),
chartType: d.chartType
chartType: d.chartType,
};
}),
};
if(realData.yMarkers) {
if (realData.yMarkers) {
zeroData.yMarkers = [
{
value: 0,
label: ''
}
label: "",
},
];
}
if(realData.yRegions) {
if (realData.yRegions) {
zeroData.yRegions = [
{
start: 0,
end: 0,
label: ''
}
label: "",
},
];
}
return zeroData;
}
export function getShortenedLabels(chartWidth, labels=[], isSeries=true) {
export function getShortenedLabels(chartWidth, labels = [], isSeries = true) {
let allowedSpace = (chartWidth / labels.length) * SERIES_LABEL_SPACE_RATIO;
if(allowedSpace <= 0) allowedSpace = 1;
if (allowedSpace <= 0) allowedSpace = 1;
let allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH;
let seriesMultiple;
if(isSeries) {
if (isSeries) {
// Find the maximum label length for spacing calculations
let maxLabelLength = Math.max(...labels.map(label => label.length));
seriesMultiple = Math.ceil(maxLabelLength/allowedLetters);
let maxLabelLength = Math.max(...labels.map((label) => label.length));
seriesMultiple = Math.ceil(maxLabelLength / allowedLetters);
}
let calcLabels = labels.map((label, i) => {
label += "";
if(label.length > allowedLetters) {
if(!isSeries) {
if(allowedLetters-3 > 0) {
label = label.slice(0, allowedLetters-3) + " ...";
if (label.length > allowedLetters) {
if (!isSeries) {
if (allowedLetters - 3 > 0) {
label = label.slice(0, allowedLetters - 3) + " ...";
} else {
label = label.slice(0, allowedLetters) + '..';
label = label.slice(0, allowedLetters) + "..";
}
} else {
if(i % seriesMultiple !== 0 && i !== (labels.length - 1)) {
if (i % seriesMultiple !== 0 && i !== labels.length - 1) {
label = "";
}
}

View File

@ -1,27 +1,27 @@
const PRESET_COLOR_MAP = {
'pink': '#F683AE',
'blue': '#318AD8',
'green': '#48BB74',
'grey': '#A6B1B9',
'red': '#F56B6B',
'yellow': '#FACF7A',
'purple': '#44427B',
'teal': '#5FD8C4',
'cyan': '#15CCEF',
'orange': '#F8814F',
'light-pink': '#FED7E5',
'light-blue': '#BFDDF7',
'light-green': '#48BB74',
'light-grey': '#F4F5F6',
'light-red': '#F6DFDF',
'light-yellow': '#FEE9BF',
'light-purple': '#E8E8F7',
'light-teal': '#D3FDF6',
'light-cyan': '#DDF8FD',
'light-orange': '#FECDB8'
pink: "#F683AE",
blue: "#318AD8",
green: "#48BB74",
grey: "#A6B1B9",
red: "#F56B6B",
yellow: "#FACF7A",
purple: "#44427B",
teal: "#5FD8C4",
cyan: "#15CCEF",
orange: "#F8814F",
"light-pink": "#FED7E5",
"light-blue": "#BFDDF7",
"light-green": "#48BB74",
"light-grey": "#F4F5F6",
"light-red": "#F6DFDF",
"light-yellow": "#FEE9BF",
"light-purple": "#E8E8F7",
"light-teal": "#D3FDF6",
"light-cyan": "#DDF8FD",
"light-orange": "#FECDB8",
};
function limitColor(r){
function limitColor(r) {
if (r > 255) return 255;
else if (r < 0) return 0;
return r;
@ -34,25 +34,27 @@ export function lightenDarkenColor(color, amt) {
col = col.slice(1);
usePound = true;
}
let num = parseInt(col,16);
let num = parseInt(col, 16);
let r = limitColor((num >> 16) + amt);
let b = limitColor(((num >> 8) & 0x00FF) + amt);
let g = limitColor((num & 0x0000FF) + amt);
return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
let b = limitColor(((num >> 8) & 0x00ff) + amt);
let g = limitColor((num & 0x0000ff) + amt);
return (usePound ? "#" : "") + (g | (b << 8) | (r << 16)).toString(16);
}
export function isValidColor(string) {
// https://stackoverflow.com/a/32685393
let HEX_RE = /(^\s*)(#)((?:[A-Fa-f0-9]{3}){1,2})$/i;
let RGB_RE = /(^\s*)(rgb|hsl)(a?)[(]\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*(?:,\s*([\d.]+)\s*)?[)]$/i;
let RGB_RE =
/(^\s*)(rgb|hsl)(a?)[(]\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*(?:,\s*([\d.]+)\s*)?[)]$/i;
return HEX_RE.test(string) || RGB_RE.test(string);
}
export const getColor = (color) => {
// When RGB color, convert to hexadecimal (alpha value is omitted)
if((/rgb[a]{0,1}\([\d, ]+\)/gim).test(color)) {
return (/\D+(\d*)\D+(\d*)\D+(\d*)/gim).exec(color)
.map((x, i) => (i !== 0 ? Number(x).toString(16) : '#'))
if (/rgb[a]{0,1}\([\d, ]+\)/gim.test(color)) {
return /\D+(\d*)\D+(\d*)\D+(\d*)/gim
.exec(color)
.map((x, i) => (i !== 0 ? Number(x).toString(16) : "#"))
.reduce((c, ch) => `${c}${ch}`);
}
return PRESET_COLOR_MAP[color] || color;

View File

@ -1,19 +1,26 @@
export const ALL_CHART_TYPES = ['line', 'scatter', 'bar', 'percentage', 'heatmap', 'pie'];
export const ALL_CHART_TYPES = [
"line",
"scatter",
"bar",
"percentage",
"heatmap",
"pie",
];
export const COMPATIBLE_CHARTS = {
bar: ['line', 'scatter', 'percentage', 'pie'],
line: ['scatter', 'bar', 'percentage', 'pie'],
pie: ['line', 'scatter', 'percentage', 'bar'],
percentage: ['bar', 'line', 'scatter', 'pie'],
heatmap: []
bar: ["line", "scatter", "percentage", "pie"],
line: ["scatter", "bar", "percentage", "pie"],
pie: ["line", "scatter", "percentage", "bar"],
percentage: ["bar", "line", "scatter", "pie"],
heatmap: [],
};
export const DATA_COLOR_DIVISIONS = {
bar: 'datasets',
line: 'datasets',
pie: 'labels',
percentage: 'labels',
heatmap: HEATMAP_DISTRIBUTION_SIZE
bar: "datasets",
line: "datasets",
pie: "labels",
percentage: "labels",
heatmap: HEATMAP_DISTRIBUTION_SIZE,
};
export const BASE_MEASURES = {
@ -21,13 +28,13 @@ export const BASE_MEASURES = {
top: 10,
bottom: 10,
left: 20,
right: 20
right: 20,
},
paddings: {
top: 20,
bottom: 40,
left: 30,
right: 10
right: 10,
},
baseHeight: 240,
@ -46,15 +53,19 @@ export function getLeftOffset(m) {
}
export function getExtraHeight(m) {
let totalExtraHeight = m.margins.top + m.margins.bottom
+ m.paddings.top + m.paddings.bottom
+ m.titleHeight + m.legendHeight;
let totalExtraHeight =
m.margins.top +
m.margins.bottom +
m.paddings.top +
m.paddings.bottom +
m.titleHeight +
m.legendHeight;
return totalExtraHeight;
}
export function getExtraWidth(m) {
let totalExtraWidth = m.margins.left + m.margins.right
+ m.paddings.left + m.paddings.right;
let totalExtraWidth =
m.margins.left + m.margins.right + m.paddings.left + m.paddings.right;
return totalExtraWidth;
}
@ -62,14 +73,14 @@ export function getExtraWidth(m) {
export const INIT_CHART_UPDATE_TIMEOUT = 700;
export const CHART_POST_ANIMATE_TIMEOUT = 400;
export const DEFAULT_AXIS_CHART_TYPE = 'line';
export const AXIS_DATASET_CHART_TYPES = ['line', 'bar'];
export const DEFAULT_AXIS_CHART_TYPE = "line";
export const AXIS_DATASET_CHART_TYPES = ["line", "bar"];
export const AXIS_LEGEND_BAR_SIZE = 100;
export const SERIES_LABEL_SPACE_RATIO = 0.6;
export const BAR_CHART_SPACE_RATIO = 0.5;
export const MIN_BAR_PERCENT_HEIGHT = 0.00;
export const MIN_BAR_PERCENT_HEIGHT = 0.0;
export const LINE_CHART_DOT_SIZE = 4;
export const DOT_OVERLAY_SIZE_INCR = 4;
@ -86,10 +97,39 @@ export const HEATMAP_GUTTER_SIZE = 2;
export const DEFAULT_CHAR_WIDTH = 7;
export const TOOLTIP_POINTER_TRIANGLE_HEIGHT = 7.48;
const DEFAULT_CHART_COLORS = ['pink', 'blue', 'green', 'grey', 'red', 'yellow', 'purple', 'teal', 'cyan', 'orange'];
const HEATMAP_COLORS_GREEN = ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
export const HEATMAP_COLORS_BLUE = ['#ebedf0', '#c0ddf9', '#73b3f3', '#3886e1', '#17459e'];
export const HEATMAP_COLORS_YELLOW = ['#ebedf0', '#fdf436', '#ffc700', '#ff9100', '#06001c'];
const DEFAULT_CHART_COLORS = [
"pink",
"blue",
"green",
"grey",
"red",
"yellow",
"purple",
"teal",
"cyan",
"orange",
];
const HEATMAP_COLORS_GREEN = [
"#ebedf0",
"#c6e48b",
"#7bc96f",
"#239a3b",
"#196127",
];
export const HEATMAP_COLORS_BLUE = [
"#ebedf0",
"#c0ddf9",
"#73b3f3",
"#3886e1",
"#17459e",
];
export const HEATMAP_COLORS_YELLOW = [
"#ebedf0",
"#fdf436",
"#ffc700",
"#ff9100",
"#06001c",
];
export const DEFAULT_COLORS = {
bar: DEFAULT_CHART_COLORS,
@ -97,7 +137,7 @@ export const DEFAULT_COLORS = {
pie: DEFAULT_CHART_COLORS,
percentage: DEFAULT_CHART_COLORS,
heatmap: HEATMAP_COLORS_GREEN,
donut: DEFAULT_CHART_COLORS
donut: DEFAULT_CHART_COLORS,
};
// Universal constants

View File

@ -6,14 +6,53 @@ export const DAYS_IN_YEAR = 375;
export const NO_OF_MILLIS = 1000;
export const SEC_IN_DAY = 86400;
export const MONTH_NAMES = ["January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December"];
export const MONTH_NAMES_SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
export const MONTH_NAMES = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
export const MONTH_NAMES_SHORT = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
export const DAY_NAMES_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
export const DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"];
export const DAY_NAMES_SHORT = [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
];
export const DAY_NAMES = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
// https://stackoverflow.com/a/11252167/6495043
function treatAsUtc(date) {
@ -33,9 +72,9 @@ export function getYyyyMmDd(date) {
let mm = date.getMonth() + 1; // getMonth() is zero-based
return [
date.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('-');
(mm > 9 ? "" : "0") + mm,
(dd > 9 ? "" : "0") + dd,
].join("-");
}
export function clone(date) {
@ -43,12 +82,12 @@ export function clone(date) {
}
export function timestampSec(date) {
return date.getTime()/NO_OF_MILLIS;
return date.getTime() / NO_OF_MILLIS;
}
export function timestampToMidnight(timestamp, roundAhead = false) {
let midnightTs = Math.floor(timestamp - (timestamp % SEC_IN_DAY));
if(roundAhead) {
if (roundAhead) {
return midnightTs + SEC_IN_DAY;
}
return midnightTs;
@ -67,16 +106,18 @@ export function getDaysBetween(startDate, endDate) {
}
export function areInSameMonth(startDate, endDate) {
return startDate.getMonth() === endDate.getMonth()
&& startDate.getFullYear() === endDate.getFullYear();
return (
startDate.getMonth() === endDate.getMonth() &&
startDate.getFullYear() === endDate.getFullYear()
);
}
export function getMonthName(i, short=false) {
export function getMonthName(i, short = false) {
let monthName = MONTH_NAMES[i];
return short ? monthName.slice(0, 3) : monthName;
}
export function getLastDateInMonth (month, year) {
export function getLastDateInMonth(month, year) {
return new Date(year, month + 1, 0); // 0: last day in previous month
}
@ -84,8 +125,8 @@ export function getLastDateInMonth (month, year) {
export function setDayToSunday(date) {
let newDate = clone(date);
const day = newDate.getDay();
if(day !== 0) {
addDays(newDate, (-1) * day);
if (day !== 0) {
addDays(newDate, -1 * day);
}
return newDate;
}

View File

@ -1,9 +1,10 @@
export function $(expr, con) {
return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
return typeof expr === "string"
? (con || document).querySelector(expr)
: expr || null;
}
export function findNodeIndex(node)
{
export function findNodeIndex(node) {
var i = 0;
while (node.previousSibling) {
node = node.previousSibling;
@ -20,22 +21,19 @@ $.create = (tag, o) => {
if (i === "inside") {
$(val).appendChild(element);
}
else if (i === "around") {
} else if (i === "around") {
var ref = $(val);
ref.parentNode.insertBefore(element, ref);
element.appendChild(ref);
} else if (i === "styles") {
if(typeof val === "object") {
Object.keys(val).map(prop => {
if (typeof val === "object") {
Object.keys(val).map((prop) => {
element.style[prop] = val[prop];
});
}
} else if (i in element ) {
} else if (i in element) {
element[i] = val;
}
else {
} else {
element.setAttribute(i, val);
}
}
@ -49,8 +47,12 @@ export function getOffset(element) {
// https://stackoverflow.com/a/7436602/6495043
// rect.top varies with scroll, so we add whatever has been
// scrolled to it to get absolute distance from actual page top
top: rect.top + (document.documentElement.scrollTop || document.body.scrollTop),
left: rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft)
top:
rect.top +
(document.documentElement.scrollTop || document.body.scrollTop),
left:
rect.left +
(document.documentElement.scrollLeft || document.body.scrollLeft),
};
}
@ -58,7 +60,7 @@ export function getOffset(element) {
// an element's offsetParent property will return null whenever it, or any of its parents,
// is hidden via the display style property.
export function isHidden(el) {
return (el.offsetParent === null);
return el.offsetParent === null;
}
export function isElementInViewport(el) {
@ -68,20 +70,24 @@ export function isElementInViewport(el) {
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
rect.bottom <=
(window.innerHeight ||
document.documentElement.clientHeight) /*or $(window).height() */ &&
rect.right <=
(window.innerWidth ||
document.documentElement.clientWidth) /*or $(window).width() */
);
}
export function getElementContentWidth(element) {
var styles = window.getComputedStyle(element);
var padding = parseFloat(styles.paddingLeft) +
parseFloat(styles.paddingRight);
var padding =
parseFloat(styles.paddingLeft) + parseFloat(styles.paddingRight);
return element.clientWidth - padding;
}
export function bind(element, o){
export function bind(element, o) {
if (element) {
for (var event in o) {
var callback = o[event];
@ -93,12 +99,12 @@ export function bind(element, o){
}
}
export function unbind(element, o){
export function unbind(element, o) {
if (element) {
for (var event in o) {
var callback = o[event];
event.split(/\s+/).forEach(function(event) {
event.split(/\s+/).forEach(function (event) {
element.removeEventListener(event, callback);
});
}
@ -108,7 +114,7 @@ export function unbind(element, o){
export function fire(target, type, properties) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent(type, true, true );
evt.initEvent(type, true, true);
for (var j in properties) {
evt[j] = properties[j];
@ -119,17 +125,23 @@ export function fire(target, type, properties) {
// https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
export function forEachNode(nodeList, callback, scope) {
if(!nodeList) return;
if (!nodeList) return;
for (var i = 0; i < nodeList.length; i++) {
callback.call(scope, nodeList[i], i);
}
}
export function activate($parent, $child, commonClass, activeClass='active', index = -1) {
export function activate(
$parent,
$child,
commonClass,
activeClass = "active",
index = -1
) {
let $children = $parent.querySelectorAll(`.${commonClass}.${activeClass}`);
forEachNode($children, (node, i) => {
if(index >= 0 && i <= index) return;
if (index >= 0 && i <= index) return;
node.classList.remove(activeClass);
});

View File

@ -1,4 +1,4 @@
import { fillArray } from './helpers';
import { fillArray } from "./helpers";
export function getBarHeightAndYAttr(yTop, zeroLine) {
let height, y;
@ -13,11 +13,13 @@ export function getBarHeightAndYAttr(yTop, zeroLine) {
return [height, y];
}
export function equilizeNoOfElements(array1, array2,
extraCount = array2.length - array1.length) {
export function equilizeNoOfElements(
array1,
array2,
extraCount = array2.length - array1.length
) {
// Doesn't work if either has zero elements.
if(extraCount > 0) {
if (extraCount > 0) {
array1 = fillArray(array1, extraCount);
} else {
array2 = fillArray(array2, extraCount);
@ -30,7 +32,7 @@ export function truncateString(txt, len) {
return;
}
if (txt.length > len) {
return txt.slice(0, len-3) + '...';
return txt.slice(0, len - 3) + "...";
} else {
return txt;
}
@ -38,8 +40,8 @@ export function truncateString(txt, len) {
export function shortenLargeNumber(label) {
let number;
if (typeof label === 'number') number = label;
else if (typeof label === 'string') {
if (typeof label === "number") number = label;
else if (typeof label === "string") {
number = Number(label);
if (Number.isNaN(number)) return label;
}
@ -48,17 +50,17 @@ export function shortenLargeNumber(label) {
let p = Math.floor(Math.log10(Math.abs(number)));
if (p <= 2) return number; // Return as is for a 3 digit number of less
let l = Math.floor(p / 3);
let shortened = (Math.pow(10, p - l * 3) * +(number / Math.pow(10, p)).toFixed(1));
let shortened =
Math.pow(10, p - l * 3) * +(number / Math.pow(10, p)).toFixed(1);
// Correct for floating point error upto 2 decimal places
return Math.round(shortened*100)/100 + ' ' + ['', 'K', 'M', 'B', 'T'][l];
return Math.round(shortened * 100) / 100 + " " + ["", "K", "M", "B", "T"][l];
}
// cubic bezier curve calculation (from example by François Romain)
export function getSplineCurvePointsStr(xList, yList) {
let points=[];
for(let i=0;i<xList.length;i++){
let points = [];
for (let i = 0; i < xList.length; i++) {
points.push([xList[i], yList[i]]);
}
@ -68,7 +70,7 @@ export function getSplineCurvePointsStr(xList, yList) {
let lengthY = pointB[1] - pointA[1];
return {
length: Math.sqrt(Math.pow(lengthX, 2) + Math.pow(lengthY, 2)),
angle: Math.atan2(lengthY, lengthX)
angle: Math.atan2(lengthY, lengthX),
};
};
@ -90,9 +92,11 @@ export function getSplineCurvePointsStr(xList, yList) {
};
let pointStr = (points, command) => {
return points.reduce((acc, point, i, a) => i === 0
? `${point[0]},${point[1]}`
: `${acc} ${command(point, i, a)}`, '');
return points.reduce(
(acc, point, i, a) =>
i === 0 ? `${point[0]},${point[1]}` : `${acc} ${command(point, i, a)}`,
""
);
};
return pointStr(points, bezierCommand);

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,16 @@
import { $ } from '../utils/dom';
import { CSSTEXT } from '../../css/chartsCss';
import { $ } from "../utils/dom";
import { CSSTEXT } from "../../css/chartsCss";
export function downloadFile(filename, data) {
var a = document.createElement('a');
var a = document.createElement("a");
a.style = "display: none";
var blob = new Blob(data, {type: "image/svg+xml; charset=utf-8"});
var blob = new Blob(data, { type: "image/svg+xml; charset=utf-8" });
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function(){
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 300);
@ -18,15 +18,15 @@ export function downloadFile(filename, data) {
export function prepareForExport(svg) {
let clone = svg.cloneNode(true);
clone.classList.add('chart-container');
clone.setAttribute('xmlns', "http://www.w3.org/2000/svg");
clone.setAttribute('xmlns:xlink', "http://www.w3.org/1999/xlink");
let styleEl = $.create('style', {
'innerHTML': CSSTEXT
clone.classList.add("chart-container");
clone.setAttribute("xmlns", "http://www.w3.org/2000/svg");
clone.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
let styleEl = $.create("style", {
innerHTML: CSSTEXT,
});
clone.insertBefore(styleEl, clone.firstChild);
let container = $.create('div');
let container = $.create("div");
container.appendChild(clone);
return container.innerHTML;

View File

@ -1,4 +1,4 @@
import { ANGLE_RATIO } from './constants';
import { ANGLE_RATIO } from "./constants";
/**
* Returns the value of a number upto 2 decimal places.
@ -73,7 +73,7 @@ export function bindChange(obj, getFn, setFn) {
get: function (target, prop) {
getFn();
return Reflect.get(target, prop);
}
},
});
}
@ -113,7 +113,7 @@ export function isValidNumber(candidate, nonNegative = false) {
export function round(d) {
// https://floating-point-gui.de/
// https://www.jacklmoore.com/notes/rounding-in-javascript/
return Number(Math.round(d + 'e4') + 'e-4');
return Number(Math.round(d + "e4") + "e-4");
}
/**

View File

@ -1,29 +1,29 @@
import { floatTwo } from './helpers';
import { floatTwo } from "./helpers";
function normalize(x) {
// Calculates mantissa and exponent of a number
// Returns normalized number and exponent
// https://stackoverflow.com/q/9383593/6495043
if(x===0) {
if (x === 0) {
return [0, 0];
}
if(isNaN(x)) {
return {mantissa: -6755399441055744, exponent: 972};
if (isNaN(x)) {
return { mantissa: -6755399441055744, exponent: 972 };
}
var sig = x > 0 ? 1 : -1;
if(!isFinite(x)) {
return {mantissa: sig * 4503599627370496, exponent: 972};
if (!isFinite(x)) {
return { mantissa: sig * 4503599627370496, exponent: 972 };
}
x = Math.abs(x);
var exp = Math.floor(Math.log10(x));
var man = x/Math.pow(10, exp);
var man = x / Math.pow(10, exp);
return [sig * man, exp];
}
function getChartRangeIntervals(max, min=0) {
function getChartRangeIntervals(max, min = 0) {
let upperBound = Math.ceil(max);
let lowerBound = Math.floor(min);
let range = upperBound - lowerBound;
@ -32,44 +32,44 @@ function getChartRangeIntervals(max, min=0) {
let partSize = 1;
// To avoid too many partitions
if(range > 5) {
if(range % 2 !== 0) {
if (range > 5) {
if (range % 2 !== 0) {
upperBound++;
// Recalc range
range = upperBound - lowerBound;
}
noOfParts = range/2;
noOfParts = range / 2;
partSize = 2;
}
// Special case: 1 and 2
if(range <= 2) {
if (range <= 2) {
noOfParts = 4;
partSize = range/noOfParts;
partSize = range / noOfParts;
}
// Special case: 0
if(range === 0) {
if (range === 0) {
noOfParts = 5;
partSize = 1;
}
let intervals = [];
for(var i = 0; i <= noOfParts; i++){
for (var i = 0; i <= noOfParts; i++) {
intervals.push(lowerBound + partSize * i);
}
return intervals;
}
function getChartIntervals(maxValue, minValue=0) {
function getChartIntervals(maxValue, minValue = 0) {
let [normalMaxValue, exponent] = normalize(maxValue);
let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
let normalMinValue = minValue ? minValue / Math.pow(10, exponent) : 0;
// Allow only 7 significant digits
normalMaxValue = normalMaxValue.toFixed(6);
let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
intervals = intervals.map(value => {
intervals = intervals.map((value) => {
// For negative exponents we want to divide by 10^-exponent to avoid
// floating point arithmetic bugs. For instance, in javascript
// 6 * 10^-1 == 0.6000000000000001, we instead want 6 / 10^1 == 0.6
@ -81,7 +81,7 @@ function getChartIntervals(maxValue, minValue=0) {
return intervals;
}
export function calcChartIntervals(values, withMinimum=false) {
export function calcChartIntervals(values, withMinimum = false) {
//*** Where the magic happens ***
// Calculates best-fit y intervals from given values
@ -91,7 +91,8 @@ export function calcChartIntervals(values, withMinimum=false) {
let minValue = Math.min(...values);
// Exponent to be used for pretty print
let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
let exponent = 0,
intervals = []; // eslint-disable-line no-unused-vars
function getPositiveFirstIntervals(maxValue, absMinValue) {
let intervals = getChartIntervals(maxValue);
@ -100,18 +101,18 @@ export function calcChartIntervals(values, withMinimum=false) {
// Then unshift the negative values
let value = 0;
for(var i = 1; value < absMinValue; i++) {
for (var i = 1; value < absMinValue; i++) {
value += intervalSize;
intervals.unshift((-1) * value);
intervals.unshift(-1 * value);
}
return intervals;
}
// CASE I: Both non-negative
if(maxValue >= 0 && minValue >= 0) {
if (maxValue >= 0 && minValue >= 0) {
exponent = normalize(maxValue)[1];
if(!withMinimum) {
if (!withMinimum) {
intervals = getChartIntervals(maxValue);
} else {
intervals = getChartIntervals(maxValue, minValue);
@ -119,8 +120,7 @@ export function calcChartIntervals(values, withMinimum=false) {
}
// CASE II: Only minValue negative
else if(maxValue > 0 && minValue < 0) {
else if (maxValue > 0 && minValue < 0) {
// `withMinimum` irrelevant in this case,
// We'll be handling both sides of zero separately
// (both starting from zero)
@ -129,21 +129,19 @@ export function calcChartIntervals(values, withMinimum=false) {
let absMinValue = Math.abs(minValue);
if(maxValue >= absMinValue) {
if (maxValue >= absMinValue) {
exponent = normalize(maxValue)[1];
intervals = getPositiveFirstIntervals(maxValue, absMinValue);
} else {
// Mirror: maxValue => absMinValue, then change sign
exponent = normalize(absMinValue)[1];
let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
intervals = posIntervals.reverse().map(d => d * (-1));
intervals = posIntervals.reverse().map((d) => d * -1);
}
}
// CASE III: Both non-positive
else if(maxValue <= 0 && minValue <= 0) {
else if (maxValue <= 0 && minValue <= 0) {
// Mirrored Case I:
// Work with positives, then reverse the sign and array
@ -151,45 +149,45 @@ export function calcChartIntervals(values, withMinimum=false) {
let pseudoMinValue = Math.abs(maxValue);
exponent = normalize(pseudoMaxValue)[1];
if(!withMinimum) {
if (!withMinimum) {
intervals = getChartIntervals(pseudoMaxValue);
} else {
intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
}
intervals = intervals.reverse().map(d => d * (-1));
intervals = intervals.reverse().map((d) => d * -1);
}
return intervals.sort((a, b) => (a - b));
return intervals.sort((a, b) => a - b);
}
export function getZeroIndex(yPts) {
let zeroIndex;
let interval = getIntervalSize(yPts);
if(yPts.indexOf(0) >= 0) {
if (yPts.indexOf(0) >= 0) {
// the range has a given zero
// zero-line on the chart
zeroIndex = yPts.indexOf(0);
} else if(yPts[0] > 0) {
} else if (yPts[0] > 0) {
// Minimum value is positive
// zero-line is off the chart: below
let min = yPts[0];
zeroIndex = (-1) * min / interval;
zeroIndex = (-1 * min) / interval;
} else {
// Maximum value is negative
// zero-line is off the chart: above
let max = yPts[yPts.length - 1];
zeroIndex = (-1) * max / interval + (yPts.length - 1);
zeroIndex = (-1 * max) / interval + (yPts.length - 1);
}
return zeroIndex;
}
export function getRealIntervals(max, noOfIntervals, min = 0, asc = 1) {
let range = max - min;
let part = range * 1.0 / noOfIntervals;
let part = (range * 1.0) / noOfIntervals;
let intervals = [];
for(var i = 0; i <= noOfIntervals; i++) {
for (var i = 0; i <= noOfIntervals; i++) {
intervals.push(min + part * i);
}
@ -201,7 +199,7 @@ export function getIntervalSize(orderedArray) {
}
export function getValueRange(orderedArray) {
return orderedArray[orderedArray.length-1] - orderedArray[0];
return orderedArray[orderedArray.length - 1] - orderedArray[0];
}
export function scale(val, yAxis) {
@ -213,13 +211,15 @@ export function isInRange(val, min, max) {
}
export function isInRange2D(coord, minCoord, maxCoord) {
return isInRange(coord[0], minCoord[0], maxCoord[0])
&& isInRange(coord[1], minCoord[1], maxCoord[1]);
return (
isInRange(coord[0], minCoord[0], maxCoord[0]) &&
isInRange(coord[1], minCoord[1], maxCoord[1])
);
}
export function getClosestInArray(goal, arr, index = false) {
let closest = arr.reduce(function(prev, curr) {
return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
let closest = arr.reduce(function (prev, curr) {
return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
}, []);
return index ? arr.indexOf(closest) : closest;
@ -234,7 +234,7 @@ export function calcDistribution(values, distributionSize) {
let distributionStep = 1 / (distributionSize - 1);
let distribution = [];
for(var i = 0; i < distributionSize; i++) {
for (var i = 0; i < distributionSize; i++) {
let checkpoint = dataMaxValue * (distributionStep * i);
distribution.push(checkpoint);
}
@ -243,5 +243,5 @@ export function calcDistribution(values, distributionSize) {
}
export function getMaxCheckpoint(value, distribution) {
return distribution.filter(d => d < value).length;
return distribution.filter((d) => d < value).length;
}

View File

@ -1,14 +1,14 @@
const assert = require('assert');
const colors = require('../colors');
const assert = require("assert");
const colors = require("../colors");
describe('utils.colors', () => {
it('should return #aaabac for RGB()', () => {
assert.equal(colors.getColor('rgb(170, 171, 172)'), '#aaabac');
describe("utils.colors", () => {
it("should return #aaabac for RGB()", () => {
assert.equal(colors.getColor("rgb(170, 171, 172)"), "#aaabac");
});
it('should return #ff5858 for the named color red', () => {
assert.equal(colors.getColor('red'), '#ff5858d');
it("should return #ff5858 for the named color red", () => {
assert.equal(colors.getColor("red"), "#ff5858d");
});
it('should return #1a5c29 for the hex color #1a5c29', () => {
assert.equal(colors.getColor('#1a5c29'), '#1a5c29');
it("should return #1a5c29 for the hex color #1a5c29", () => {
assert.equal(colors.getColor("#1a5c29"), "#1a5c29");
});
});

View File

@ -1,10 +1,10 @@
const assert = require('assert');
const helpers = require('../helpers');
const assert = require("assert");
const helpers = require("../helpers");
describe('utils.helpers', () => {
it('should return a value fixed upto 2 decimals', () => {
describe("utils.helpers", () => {
it("should return a value fixed upto 2 decimals", () => {
assert.equal(helpers.floatTwo(1.234), 1.23);
assert.equal(helpers.floatTwo(1.456), 1.46);
assert.equal(helpers.floatTwo(1), 1.00);
assert.equal(helpers.floatTwo(1), 1.0);
});
});