All files / platform/ui/src/components/LineChart/d3LineChart lineChart.ts

9.09% Statements 8/88
0% Branches 0/29
0% Functions 0/24
9.75% Lines 8/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273                        34x                                                                         34x 34x                 34x           34x                 34x                           34x                                                                           34x                                                                                                                                                                                                                                                                                                    
import * as d3Array from 'd3-array';
import * as d3Axis from 'd3-axis';
import * as d3Scale from 'd3-scale';
import * as d3ScaleChromatic from 'd3-scale-chromatic';
import * as d3Selection from 'd3-selection';
import * as d3Shape from 'd3-shape';
 
import chart from './chart';
import events from './events';
 
const {
  external: { resetZoom },
} = events;
 
/**
 * @typedef TimecoursePoint It defines a tuple of timecourse value (time X intensity)
 * @type {array}
 * @property {number} 0 indicates x|y value on the pair (x,y)
 * @property {number} 1 indicates x|y value on the pair (x,y)
 */
 
/**
 * @typedef TimecoursePointDef It defines the shape of a given TimecoursePoint Axis
 * @type {object}
 * @property {string} label label for given TimecoursePoint Axis
 * @property {string} [unit] unit for given TimecoursePoint Axis
 * @property {string} type defines the type of given TimecoursePoint Axis
 * @property {number} indexRef refers the index into given TimecoursePoint for the current Axis Definition
 */
 
/**
 * It gets max value of an array, considering value of param index
 *
 * @param {TimecoursePoint[]} array array of items to be evaluated
 * @param {number} index index of each array`s item to be evaluated
 * @return {any} max value
 */
function _getMaxValue(array, index) {
  return d3Array.max(array, arrayItem => {
    return arrayItem[index];
  });
}
 
function _getMinValue(array, index) {
  return d3Array.min(array, arrayItem => {
    return arrayItem[index];
  });
}
 
const LEGEND = { width: 100, margin: 10 };
const MARGIN = { top: 20, right: 20, bottom: 50, left: 50 };
 
function _createAxisScale(domainBottom, domainUpper, rangeBottom, rangeUpper) {
  return d3Scale
    .scaleLinear()
    .domain([domainBottom, domainUpper * 1.05])
    .range([rangeBottom, rangeUpper]);
}
 
const _getSeriesColor = series => {
  const seriesLabels = series.reduce((labels, series) => [...labels, series.label], []);
 
  return d3Scale.scaleOrdinal().domain(seriesLabels).range(d3ScaleChromatic.schemeSet2);
};
 
const _updateSeriesColors = series => {
  const seriesColor = _getSeriesColor(series);
 
  return series.map(series => ({
    ...series,
    color: series.color ?? seriesColor(series.label),
  }));
};
 
const _textEllipses = (width, padding = 0) => {
  return function (...args) {
    const self = d3Selection.select(this);
    let textLength = self.node().getComputedTextLength();
    let text = self.text();
 
    while (textLength > width - 2 * padding && text.length > 0) {
      text = text.slice(0, -1);
      self.text(text + '...');
      textLength = self.node().getComputedTextLength();
    }
  };
};
 
const _addLegend = (root, series, chartWidth, chartHeight, legendWidth) => {
  const legendItemHeight = 25;
  const legendHeight = legendItemHeight * series.length;
 
  const legendContainer = chart.legend.addNode(
    root,
    legendWidth,
    legendHeight,
    chartWidth + LEGEND.margin,
    chartHeight / 2 - legendHeight / 2
  );
 
  const seriesLabels = series.reduce((labels, series) => [...labels, series.label], []);
 
  const seriesColors = series.reduce((colors, series) => [...colors, series.color], []);
 
  chart.legend.setLabels(
    legendContainer,
    seriesLabels,
    seriesColors,
    legendItemHeight,
    legendWidth,
    _textEllipses
  );
};
 
/**
 * It creates a svg chart containing lines, dots, axis, labels
 *
 * @param {object} d3SVGRef svg content reference to append chart
 * @param {Object<string, TimecoursePointDef>} axis definition of axis
 * @param {object} points list of points to be created
 * @param {number} width width for whole content including lines, dots, axis, labels
 * @param {number} height height for whole content including lines, dots, axis, labels
 * @param {boolean} showAxisLabels flag to display labels or not
 *
 * @modifies {d3SVGRef}
 */
const addLineChartNode = ({
  d3SVGRef,
  axis,
  series,
  width,
  height,
  legendWidth = LEGEND.width,
  showAxisLabels = true,
  showAxisGrid = false,
  showLegend = false,
  transparentChartBackground = false,
}) => {
  const marginRight = showLegend ? legendWidth + 2 * LEGEND.margin : MARGIN.right;
  const _width = width - MARGIN.left - marginRight;
  const _height = height - MARGIN.top - MARGIN.bottom;
  const { x: XAxis, y: YAxis } = axis;
 
  series = _updateSeriesColors(series);
 
  let maxX = -Infinity;
  let minX = Infinity;
  let maxY = -Infinity;
  let minY = Infinity;
 
  series.forEach(currentSeries => {
    minX = Math.min(minX, _getMinValue(currentSeries.points, XAxis.indexRef));
    maxX = Math.max(maxX, _getMaxValue(currentSeries.points, XAxis.indexRef));
    minY = Math.min(minY, _getMinValue(currentSeries.points, YAxis.indexRef));
    maxY = Math.max(maxY, _getMaxValue(currentSeries.points, YAxis.indexRef));
  });
 
  minX = axis?.x?.range?.min ?? minX;
  maxX = axis?.x?.range?.max ?? maxX;
  minY = axis?.y?.range?.min ?? minY;
  maxY = axis?.y?.range?.max ?? maxY;
 
  const xAxisScale = _createAxisScale(minX, maxX, 0, _width);
  const yAxisScale = _createAxisScale(minY, maxY, _height, 0);
 
  const parseXPoint = axisScale => point => {
    return (axisScale || xAxisScale)(point.x);
  };
 
  const parseYPoint = axisScale => point => {
    return (axisScale || yAxisScale)(point.y);
  };
 
  // Remove old D3 elements
  chart.removeContents(d3SVGRef);
 
  const chartWrapper = chart.container.addNode(d3SVGRef, width, height, MARGIN.left, MARGIN.top);
 
  // add background
  chart.background.addNode(chartWrapper, _width, _height, transparentChartBackground);
 
  // call the x axis in a group tag
  const xAxisGenerator = d3Axis.axisBottom(xAxisScale);
 
  Iif (showAxisGrid) {
    xAxisGenerator.tickSize(-_height).tickPadding(10);
  }
  const gXAxis = chart.axis.addNode(
    chartWrapper,
    XAxis,
    undefined,
    _height,
    undefined,
    () => xAxisGenerator,
    showAxisLabels,
    _width / 2,
    _height + MARGIN.bottom / 2 + 10,
    undefined,
    showAxisGrid
  );
  const yAxisGenerator = d3Axis.axisLeft(yAxisScale);
 
  Iif (showAxisGrid) {
    yAxisGenerator.tickSize(-_width).tickPadding(10);
  }
  // add y axis
  const gYAxis = chart.axis.addNode(
    chartWrapper,
    YAxis,
    undefined,
    undefined,
    undefined,
    () => yAxisGenerator,
    showAxisLabels,
    0 - _height / 2,
    0 - MARGIN.left,
    [
      { key: 'transform', value: 'rotate(-90)' },
      { key: 'dy', value: '1em' },
    ],
    showAxisGrid
  );
 
  const datasets = [];
 
  series.forEach((currentSeries, seriesIndex) => {
    const { points } = currentSeries;
    const line = d3Shape.line().x(parseXPoint(xAxisScale)).y(parseYPoint(yAxisScale));
 
    const dataset = points.map((point, pointIndex) => {
      return { x: point[0], y: point[1], seriesIndex, pointIndex };
    });
 
    const seriesContainer = chart.series.addNode(chartWrapper, seriesIndex, {
      color: currentSeries.color || '#00ff00',
    });
 
    chart.lines.addNode(seriesContainer, dataset, line);
 
    // add chart points
    chart.points.addNode(
      seriesContainer,
      dataset,
      parseXPoint(xAxisScale),
      parseYPoint(yAxisScale)
    );
 
    datasets.push(dataset);
  });
 
  Iif (showLegend) {
    _addLegend(chartWrapper, series, _width, _height, legendWidth);
  }
 
  // bind events
  events.bindMouseEvents(
    chartWrapper,
    gXAxis,
    gYAxis,
    xAxisScale,
    yAxisScale,
    xAxisGenerator,
    yAxisGenerator,
    parseXPoint,
    parseYPoint,
    datasets
  );
 
  return chartWrapper;
};
 
export { addLineChartNode, resetZoom };