您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

3208 行
76 KiB

  1. function $(expr, con) {
  2. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  3. }
  4. $.create = (tag, o) => {
  5. var element = document.createElement(tag);
  6. for (var i in o) {
  7. var val = o[i];
  8. if (i === "inside") {
  9. $(val).appendChild(element);
  10. }
  11. else if (i === "around") {
  12. var ref = $(val);
  13. ref.parentNode.insertBefore(element, ref);
  14. element.appendChild(ref);
  15. } else if (i === "styles") {
  16. if(typeof val === "object") {
  17. Object.keys(val).map(prop => {
  18. element.style[prop] = val[prop];
  19. });
  20. }
  21. } else if (i in element ) {
  22. element[i] = val;
  23. }
  24. else {
  25. element.setAttribute(i, val);
  26. }
  27. }
  28. return element;
  29. };
  30. function getOffset(element) {
  31. let rect = element.getBoundingClientRect();
  32. return {
  33. // https://stackoverflow.com/a/7436602/6495043
  34. // rect.top varies with scroll, so we add whatever has been
  35. // scrolled to it to get absolute distance from actual page top
  36. top: rect.top + (document.documentElement.scrollTop || document.body.scrollTop),
  37. left: rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft)
  38. };
  39. }
  40. function isElementInViewport(el) {
  41. // Although straightforward: https://stackoverflow.com/a/7557433/6495043
  42. var rect = el.getBoundingClientRect();
  43. return (
  44. rect.top >= 0 &&
  45. rect.left >= 0 &&
  46. rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
  47. rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
  48. );
  49. }
  50. function getElementContentWidth(element) {
  51. var styles = window.getComputedStyle(element);
  52. var padding = parseFloat(styles.paddingLeft) +
  53. parseFloat(styles.paddingRight);
  54. return element.clientWidth - padding;
  55. }
  56. function fire(target, type, properties) {
  57. var evt = document.createEvent("HTMLEvents");
  58. evt.initEvent(type, true, true );
  59. for (var j in properties) {
  60. evt[j] = properties[j];
  61. }
  62. return target.dispatchEvent(evt);
  63. }
  64. class SvgTip {
  65. constructor({
  66. parent = null,
  67. colors = []
  68. }) {
  69. this.parent = parent;
  70. this.colors = colors;
  71. this.title_name = '';
  72. this.title_value = '';
  73. this.list_values = [];
  74. this.title_value_first = 0;
  75. this.x = 0;
  76. this.y = 0;
  77. this.top = 0;
  78. this.left = 0;
  79. this.setup();
  80. }
  81. setup() {
  82. this.make_tooltip();
  83. }
  84. refresh() {
  85. this.fill();
  86. this.calc_position();
  87. // this.show_tip();
  88. }
  89. make_tooltip() {
  90. this.container = $.create('div', {
  91. inside: this.parent,
  92. className: 'graph-svg-tip comparison',
  93. innerHTML: `<span class="title"></span>
  94. <ul class="data-point-list"></ul>
  95. <div class="svg-pointer"></div>`
  96. });
  97. this.hide_tip();
  98. this.title = this.container.querySelector('.title');
  99. this.data_point_list = this.container.querySelector('.data-point-list');
  100. this.parent.addEventListener('mouseleave', () => {
  101. this.hide_tip();
  102. });
  103. }
  104. fill() {
  105. let title;
  106. if(this.title_value_first) {
  107. title = `<strong>${this.title_value}</strong>${this.title_name}`;
  108. } else {
  109. title = `${this.title_name}<strong>${this.title_value}</strong>`;
  110. }
  111. this.title.innerHTML = title;
  112. this.data_point_list.innerHTML = '';
  113. this.list_values.map((set, i) => {
  114. const color = this.colors[i] || 'black';
  115. let li = $.create('li', {
  116. styles: {
  117. 'border-top': `3px solid ${color}`
  118. },
  119. innerHTML: `<strong style="display: block;">${ set.value === 0 || set.value ? set.value : '' }</strong>
  120. ${set.title ? set.title : '' }`
  121. });
  122. this.data_point_list.appendChild(li);
  123. });
  124. }
  125. calc_position() {
  126. let width = this.container.offsetWidth;
  127. this.top = this.y - this.container.offsetHeight;
  128. this.left = this.x - width/2;
  129. let max_left = this.parent.offsetWidth - width;
  130. let pointer = this.container.querySelector('.svg-pointer');
  131. if(this.left < 0) {
  132. pointer.style.left = `calc(50% - ${-1 * this.left}px)`;
  133. this.left = 0;
  134. } else if(this.left > max_left) {
  135. let delta = this.left - max_left;
  136. let pointer_offset = `calc(50% + ${delta}px)`;
  137. pointer.style.left = pointer_offset;
  138. this.left = max_left;
  139. } else {
  140. pointer.style.left = `50%`;
  141. }
  142. }
  143. set_values(x, y, title_name = '', title_value = '', list_values = [], title_value_first = 0) {
  144. this.title_name = title_name;
  145. this.title_value = title_value;
  146. this.list_values = list_values;
  147. this.x = x;
  148. this.y = y;
  149. this.title_value_first = title_value_first;
  150. this.refresh();
  151. }
  152. hide_tip() {
  153. this.container.style.top = '0px';
  154. this.container.style.left = '0px';
  155. this.container.style.opacity = '0';
  156. }
  157. show_tip() {
  158. this.container.style.top = this.top + 'px';
  159. this.container.style.left = this.left + 'px';
  160. this.container.style.opacity = '1';
  161. }
  162. }
  163. /**
  164. * Returns the value of a number upto 2 decimal places.
  165. * @param {Number} d Any number
  166. */
  167. function floatTwo(d) {
  168. return parseFloat(d.toFixed(2));
  169. }
  170. /**
  171. * Returns whether or not two given arrays are equal.
  172. * @param {Array} arr1 First array
  173. * @param {Array} arr2 Second array
  174. */
  175. /**
  176. * Shuffles array in place. ES6 version
  177. * @param {Array} array An array containing the items.
  178. */
  179. /**
  180. * Fill an array with extra points
  181. * @param {Array} array Array
  182. * @param {Number} count number of filler elements
  183. * @param {Object} element element to fill with
  184. * @param {Boolean} start fill at start?
  185. */
  186. function fillArray(array, count, element, start=false) {
  187. if(!element) {
  188. element = start ? array[0] : array[array.length - 1];
  189. }
  190. let fillerArray = new Array(Math.abs(count)).fill(element);
  191. array = start ? fillerArray.concat(array) : array.concat(fillerArray);
  192. return array;
  193. }
  194. /**
  195. * Returns pixel width of string.
  196. * @param {String} string
  197. * @param {Number} charWidth Width of single char in pixels
  198. */
  199. function getStringWidth(string, charWidth) {
  200. return (string+"").length * charWidth;
  201. }
  202. function getBarHeightAndYAttr(yTop, zeroLine) {
  203. let height, y;
  204. if (yTop <= zeroLine) {
  205. height = zeroLine - yTop;
  206. y = yTop;
  207. } else {
  208. height = yTop - zeroLine;
  209. y = zeroLine;
  210. }
  211. return [height, y];
  212. }
  213. function equilizeNoOfElements(array1, array2,
  214. extra_count=array2.length - array1.length) {
  215. // Doesn't work if either has zero elements.
  216. if(extra_count > 0) {
  217. array1 = fillArray(array1, extra_count);
  218. } else {
  219. array2 = fillArray(array2, extra_count);
  220. }
  221. return [array1, array2];
  222. }
  223. const UNIT_ANIM_DUR = 350;
  224. const PATH_ANIM_DUR = 350;
  225. const MARKER_LINE_ANIM_DUR = UNIT_ANIM_DUR;
  226. const REPLACE_ALL_NEW_DUR = 250;
  227. const STD_EASING = 'easein';
  228. function translate(unit, oldCoord, newCoord, duration) {
  229. let old = typeof oldCoord === 'string' ? oldCoord : oldCoord.join(', ');
  230. return [
  231. unit,
  232. {transform: newCoord.join(', ')},
  233. duration,
  234. STD_EASING,
  235. "translate",
  236. {transform: old}
  237. ];
  238. }
  239. function translateVertLine(xLine, newX, oldX) {
  240. return translate(xLine, [oldX, 0], [newX, 0], MARKER_LINE_ANIM_DUR);
  241. }
  242. function translateHoriLine(yLine, newY, oldY) {
  243. return translate(yLine, [0, oldY], [0, newY], MARKER_LINE_ANIM_DUR);
  244. }
  245. function animateRegion(rectGroup, newY1, newY2, oldY2) {
  246. let newHeight = newY1 - newY2;
  247. let rect = rectGroup.childNodes[0];
  248. let width = rect.getAttribute("width");
  249. let rectAnim = [
  250. rect,
  251. { height: newHeight, 'stroke-dasharray': `${width}, ${newHeight}` },
  252. MARKER_LINE_ANIM_DUR,
  253. STD_EASING
  254. ];
  255. let groupAnim = translate(rectGroup, [0, oldY2], [0, newY2], MARKER_LINE_ANIM_DUR);
  256. return [rectAnim, groupAnim];
  257. }
  258. function animateBar(bar, x, yTop, width, offset=0, index=0, meta={}) {
  259. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  260. y -= offset;
  261. if(bar.nodeName !== 'rect') {
  262. let rect = bar.childNodes[0];
  263. let rectAnim = [
  264. rect,
  265. {width: width, height: height},
  266. UNIT_ANIM_DUR,
  267. STD_EASING
  268. ];
  269. let oldCoordStr = bar.getAttribute("transform").split("(")[1].slice(0, -1);
  270. let groupAnim = translate(bar, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  271. return [rectAnim, groupAnim];
  272. } else {
  273. return [[bar, {width: width, height: height, x: x, y: y}, UNIT_ANIM_DUR, STD_EASING]];
  274. }
  275. // bar.animate({height: args.newHeight, y: yTop}, UNIT_ANIM_DUR, mina.easein);
  276. }
  277. function animateDot(dot, x, y) {
  278. if(dot.nodeName !== 'circle') {
  279. let oldCoordStr = dot.getAttribute("transform").split("(")[1].slice(0, -1);
  280. let groupAnim = translate(dot, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  281. return [groupAnim];
  282. } else {
  283. return [[dot, {cx: x, cy: y}, UNIT_ANIM_DUR, STD_EASING]];
  284. }
  285. // dot.animate({cy: yTop}, UNIT_ANIM_DUR, mina.easein);
  286. }
  287. function animatePath(paths, newXList, newYList, zeroLine) {
  288. let pathComponents = [];
  289. let pointsStr = newYList.map((y, i) => (newXList[i] + ',' + y));
  290. let pathStr = pointsStr.join("L");
  291. const animPath = [paths.path, {d:"M"+pathStr}, PATH_ANIM_DUR, STD_EASING];
  292. pathComponents.push(animPath);
  293. if(paths.region) {
  294. let regStartPt = `${newXList[0]},${zeroLine}L`;
  295. let regEndPt = `L${newXList.slice(-1)[0]}, ${zeroLine}`;
  296. const animRegion = [
  297. paths.region,
  298. {d:"M" + regStartPt + pathStr + regEndPt},
  299. PATH_ANIM_DUR,
  300. STD_EASING
  301. ];
  302. pathComponents.push(animRegion);
  303. }
  304. return pathComponents;
  305. }
  306. const VERT_SPACE_OUTSIDE_BASE_CHART = 40;
  307. const TRANSLATE_Y_BASE_CHART = 20;
  308. const LEFT_MARGIN_BASE_CHART = 60;
  309. const RIGHT_MARGIN_BASE_CHART = 40;
  310. const Y_AXIS_MARGIN = 60;
  311. const INIT_CHART_UPDATE_TIMEOUT = 700;
  312. const CHART_POST_ANIMATE_TIMEOUT = 400;
  313. const DEFAULT_AXIS_CHART_TYPE = 'line';
  314. const AXIS_DATASET_CHART_TYPES = ['line', 'bar'];
  315. const BAR_CHART_SPACE_RATIO = 0.5;
  316. const MIN_BAR_PERCENT_HEIGHT = 0.01;
  317. const LINE_CHART_DOT_SIZE = 4;
  318. const DOT_OVERLAY_SIZE_INCR = 4;
  319. const DEFAULT_CHAR_WIDTH = 8;
  320. const AXIS_TICK_LENGTH = 6;
  321. const LABEL_MARGIN = 4;
  322. const FONT_SIZE = 10;
  323. const BASE_LINE_COLOR = '#dadada';
  324. function $$1(expr, con) {
  325. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  326. }
  327. function createSVG(tag, o) {
  328. var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  329. for (var i in o) {
  330. var val = o[i];
  331. if (i === "inside") {
  332. $$1(val).appendChild(element);
  333. }
  334. else if (i === "around") {
  335. var ref = $$1(val);
  336. ref.parentNode.insertBefore(element, ref);
  337. element.appendChild(ref);
  338. } else if (i === "styles") {
  339. if(typeof val === "object") {
  340. Object.keys(val).map(prop => {
  341. element.style[prop] = val[prop];
  342. });
  343. }
  344. } else {
  345. if(i === "className") { i = "class"; }
  346. if(i === "innerHTML") {
  347. element['textContent'] = val;
  348. } else {
  349. element.setAttribute(i, val);
  350. }
  351. }
  352. }
  353. return element;
  354. }
  355. function renderVerticalGradient(svgDefElem, gradientId) {
  356. return createSVG('linearGradient', {
  357. inside: svgDefElem,
  358. id: gradientId,
  359. x1: 0,
  360. x2: 0,
  361. y1: 0,
  362. y2: 1
  363. });
  364. }
  365. function setGradientStop(gradElem, offset, color, opacity) {
  366. return createSVG('stop', {
  367. 'inside': gradElem,
  368. 'style': `stop-color: ${color}`,
  369. 'offset': offset,
  370. 'stop-opacity': opacity
  371. });
  372. }
  373. function makeSVGContainer(parent, className, width, height) {
  374. return createSVG('svg', {
  375. className: className,
  376. inside: parent,
  377. width: width,
  378. height: height
  379. });
  380. }
  381. function makeSVGDefs(svgContainer) {
  382. return createSVG('defs', {
  383. inside: svgContainer,
  384. });
  385. }
  386. function makeSVGGroup(parent, className, transform='') {
  387. return createSVG('g', {
  388. className: className,
  389. inside: parent,
  390. transform: transform
  391. });
  392. }
  393. function makePath(pathStr, className='', stroke='none', fill='none') {
  394. return createSVG('path', {
  395. className: className,
  396. d: pathStr,
  397. styles: {
  398. stroke: stroke,
  399. fill: fill
  400. }
  401. });
  402. }
  403. function makeGradient(svgDefElem, color, lighter = false) {
  404. let gradientId ='path-fill-gradient' + '-' + color + '-' +(lighter ? 'lighter' : 'default');
  405. let gradientDef = renderVerticalGradient(svgDefElem, gradientId);
  406. let opacities = [1, 0.6, 0.2];
  407. if(lighter) {
  408. opacities = [0.4, 0.2, 0];
  409. }
  410. setGradientStop(gradientDef, "0%", color, opacities[0]);
  411. setGradientStop(gradientDef, "50%", color, opacities[1]);
  412. setGradientStop(gradientDef, "100%", color, opacities[2]);
  413. return gradientId;
  414. }
  415. function makeHeatSquare(className, x, y, size, fill='none', data={}) {
  416. let args = {
  417. className: className,
  418. x: x,
  419. y: y,
  420. width: size,
  421. height: size,
  422. fill: fill
  423. };
  424. Object.keys(data).map(key => {
  425. args[key] = data[key];
  426. });
  427. return createSVG("rect", args);
  428. }
  429. function makeText(className, x, y, content) {
  430. return createSVG('text', {
  431. className: className,
  432. x: x,
  433. y: y,
  434. dy: (FONT_SIZE / 2) + 'px',
  435. 'font-size': FONT_SIZE + 'px',
  436. innerHTML: content
  437. });
  438. }
  439. function makeVertLine(x, label, y1, y2, options={}) {
  440. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  441. let l = createSVG('line', {
  442. className: 'line-vertical ' + options.className,
  443. x1: 0,
  444. x2: 0,
  445. y1: y1,
  446. y2: y2,
  447. styles: {
  448. stroke: options.stroke
  449. }
  450. });
  451. let text = createSVG('text', {
  452. x: 0,
  453. y: y1 > y2 ? y1 + LABEL_MARGIN : y1 - LABEL_MARGIN - FONT_SIZE,
  454. dy: FONT_SIZE + 'px',
  455. 'font-size': FONT_SIZE + 'px',
  456. 'text-anchor': 'middle',
  457. innerHTML: label
  458. });
  459. let line = createSVG('g', {
  460. transform: `translate(${ x }, 0)`
  461. });
  462. line.appendChild(l);
  463. line.appendChild(text);
  464. return line;
  465. }
  466. function makeHoriLine(y, label, x1, x2, options={}) {
  467. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  468. if(!options.lineType) options.lineType = '';
  469. let className = 'line-horizontal ' + options.className +
  470. (options.lineType === "dashed" ? "dashed": "");
  471. let l = createSVG('line', {
  472. className: className,
  473. x1: x1,
  474. x2: x2,
  475. y1: 0,
  476. y2: 0,
  477. styles: {
  478. stroke: options.stroke
  479. }
  480. });
  481. let text = createSVG('text', {
  482. x: x1 < x2 ? x1 - LABEL_MARGIN : x1 + LABEL_MARGIN,
  483. y: 0,
  484. dy: (FONT_SIZE / 2 - 2) + 'px',
  485. 'font-size': FONT_SIZE + 'px',
  486. 'text-anchor': x1 < x2 ? 'end' : 'start',
  487. innerHTML: label+""
  488. });
  489. let line = createSVG('g', {
  490. transform: `translate(0, ${y})`,
  491. 'stroke-opacity': 1
  492. });
  493. if(text === 0 || text === '0') {
  494. line.style.stroke = "rgba(27, 31, 35, 0.6)";
  495. }
  496. line.appendChild(l);
  497. line.appendChild(text);
  498. return line;
  499. }
  500. function yLine(y, label, width, options={}) {
  501. if(!options.pos) options.pos = 'left';
  502. if(!options.offset) options.offset = 0;
  503. if(!options.mode) options.mode = 'span';
  504. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  505. if(!options.className) options.className = '';
  506. let x1 = -1 * AXIS_TICK_LENGTH;
  507. let x2 = options.mode === 'span' ? width + AXIS_TICK_LENGTH : 0;
  508. if(options.mode === 'tick' && options.pos === 'right') {
  509. x1 = width + AXIS_TICK_LENGTH;
  510. x2 = width;
  511. }
  512. x1 += options.offset;
  513. x2 += options.offset;
  514. return makeHoriLine(y, label, x1, x2, {
  515. stroke: options.stroke,
  516. className: options.className,
  517. lineType: options.lineType
  518. });
  519. }
  520. function xLine(x, label, height, options={}) {
  521. if(!options.pos) options.pos = 'bottom';
  522. if(!options.offset) options.offset = 0;
  523. if(!options.mode) options.mode = 'span';
  524. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  525. if(!options.className) options.className = '';
  526. // Draw X axis line in span/tick mode with optional label
  527. // y2(span)
  528. // |
  529. // |
  530. // x line |
  531. // |
  532. // |
  533. // ---------------------+-- y2(tick)
  534. // |
  535. // y1
  536. let y1 = height + AXIS_TICK_LENGTH;
  537. let y2 = options.mode === 'span' ? -1 * AXIS_TICK_LENGTH : height;
  538. if(options.mode === 'tick' && options.pos === 'top') {
  539. // top axis ticks
  540. y1 = -1 * AXIS_TICK_LENGTH;
  541. y2 = 0;
  542. }
  543. return makeVertLine(x, label, y1, y2, {
  544. stroke: options.stroke,
  545. className: options.className,
  546. lineType: options.lineType
  547. });
  548. }
  549. function yMarker(y, label, width, options={}) {
  550. let labelSvg = createSVG('text', {
  551. className: 'chart-label',
  552. x: width - getStringWidth(label, 5) - LABEL_MARGIN,
  553. y: 0,
  554. dy: (FONT_SIZE / -2) + 'px',
  555. 'font-size': FONT_SIZE + 'px',
  556. 'text-anchor': 'start',
  557. innerHTML: label+""
  558. });
  559. let line = makeHoriLine(y, '', 0, width, {
  560. stroke: options.stroke || BASE_LINE_COLOR,
  561. className: options.className || '',
  562. lineType: options.lineType
  563. });
  564. line.appendChild(labelSvg);
  565. return line;
  566. }
  567. function yRegion(y1, y2, width, label) {
  568. // return a group
  569. let height = y1 - y2;
  570. let rect = createSVG('rect', {
  571. className: `bar mini`, // remove class
  572. styles: {
  573. fill: `rgba(228, 234, 239, 0.49)`,
  574. stroke: BASE_LINE_COLOR,
  575. 'stroke-dasharray': `${width}, ${height}`
  576. },
  577. // 'data-point-index': index,
  578. x: 0,
  579. y: 0,
  580. width: width,
  581. height: height
  582. });
  583. let labelSvg = createSVG('text', {
  584. className: 'chart-label',
  585. x: width - getStringWidth(label, 4.5) - LABEL_MARGIN,
  586. y: 0,
  587. dy: (FONT_SIZE / -2) + 'px',
  588. 'font-size': FONT_SIZE + 'px',
  589. 'text-anchor': 'start',
  590. innerHTML: label+""
  591. });
  592. let region = createSVG('g', {
  593. transform: `translate(0, ${y2})`
  594. });
  595. region.appendChild(rect);
  596. region.appendChild(labelSvg);
  597. return region;
  598. }
  599. function datasetBar(x, yTop, width, color, label='', index=0, offset=0, meta={}) {
  600. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  601. y -= offset;
  602. let rect = createSVG('rect', {
  603. className: `bar mini`,
  604. style: `fill: ${color}`,
  605. 'data-point-index': index,
  606. x: x,
  607. y: y,
  608. width: width,
  609. height: height || meta.minHeight // TODO: correct y for positive min height
  610. });
  611. if(!label && !label.length) {
  612. return rect;
  613. } else {
  614. rect.setAttribute('y', 0);
  615. rect.setAttribute('x', 0);
  616. let text = createSVG('text', {
  617. className: 'data-point-value',
  618. x: width/2,
  619. y: 0,
  620. dy: (FONT_SIZE / 2 * -1) + 'px',
  621. 'font-size': FONT_SIZE + 'px',
  622. 'text-anchor': 'middle',
  623. innerHTML: label
  624. });
  625. let group = createSVG('g', {
  626. transform: `translate(${x}, ${y})`
  627. });
  628. group.appendChild(rect);
  629. group.appendChild(text);
  630. return group;
  631. }
  632. }
  633. function datasetDot(x, y, radius, color, label='', index=0, meta={}) {
  634. let dot = createSVG('circle', {
  635. style: `fill: ${color}`,
  636. 'data-point-index': index,
  637. cx: x,
  638. cy: y,
  639. r: radius
  640. });
  641. if(!label && !label.length) {
  642. return dot;
  643. } else {
  644. dot.setAttribute('cy', 0);
  645. dot.setAttribute('cx', 0);
  646. let text = createSVG('text', {
  647. className: 'data-point-value',
  648. x: 0,
  649. y: 0,
  650. dy: (FONT_SIZE / 2 * -1 - radius) + 'px',
  651. 'font-size': FONT_SIZE + 'px',
  652. 'text-anchor': 'middle',
  653. innerHTML: label
  654. });
  655. let group = createSVG('g', {
  656. transform: `translate(${x}, ${y})`
  657. });
  658. group.appendChild(dot);
  659. group.appendChild(text);
  660. return group;
  661. }
  662. }
  663. function getPaths(xList, yList, color, options={}, meta={}) {
  664. let pointsList = yList.map((y, i) => (xList[i] + ',' + y));
  665. let pointsStr = pointsList.join("L");
  666. let path = makePath("M"+pointsStr, 'line-graph-path', color);
  667. // HeatLine
  668. if(options.heatline) {
  669. let gradient_id = makeGradient(meta.svgDefs, color);
  670. path.style.stroke = `url(#${gradient_id})`;
  671. }
  672. let paths = {
  673. path: path
  674. };
  675. // Region
  676. if(options.regionFill) {
  677. let gradient_id_region = makeGradient(meta.svgDefs, color, true);
  678. // TODO: use zeroLine OR minimum
  679. let pathStr = "M" + `${xList[0]},${meta.zeroLine}L` + pointsStr + `L${xList.slice(-1)[0]},${meta.zeroLine}`;
  680. paths.region = makePath(pathStr, `region-fill`, 'none', `url(#${gradient_id_region})`);
  681. }
  682. return paths;
  683. }
  684. let makeOverlay = {
  685. 'bar': (unit) => {
  686. let transformValue;
  687. if(unit.nodeName !== 'rect') {
  688. transformValue = unit.getAttribute('transform');
  689. unit = unit.childNodes[0];
  690. }
  691. let overlay = unit.cloneNode();
  692. overlay.style.fill = '#000000';
  693. overlay.style.opacity = '0.4';
  694. if(transformValue) {
  695. overlay.setAttribute('transform', transformValue);
  696. }
  697. return overlay;
  698. },
  699. 'dot': (unit) => {
  700. let transformValue;
  701. if(unit.nodeName !== 'circle') {
  702. transformValue = unit.getAttribute('transform');
  703. unit = unit.childNodes[0];
  704. }
  705. let overlay = unit.cloneNode();
  706. let radius = unit.getAttribute('r');
  707. overlay.setAttribute('r', radius + DOT_OVERLAY_SIZE_INCR);
  708. overlay.style.fill = '#000000';
  709. overlay.style.opacity = '0.4';
  710. if(transformValue) {
  711. overlay.setAttribute('transform', transformValue);
  712. }
  713. return overlay;
  714. }
  715. };
  716. let updateOverlay = {
  717. 'bar': (unit, overlay) => {
  718. let transformValue;
  719. if(unit.nodeName !== 'rect') {
  720. transformValue = unit.getAttribute('transform');
  721. unit = unit.childNodes[0];
  722. }
  723. let attributes = ['x', 'y', 'width', 'height'];
  724. Object.values(unit.attributes)
  725. .filter(attr => attributes.includes(attr.name) && attr.specified)
  726. .map(attr => {
  727. overlay.setAttribute(attr.name, attr.nodeValue);
  728. });
  729. if(transformValue) {
  730. overlay.setAttribute('transform', transformValue);
  731. }
  732. },
  733. 'dot': (unit, overlay) => {
  734. let transformValue;
  735. if(unit.nodeName !== 'circle') {
  736. transformValue = unit.getAttribute('transform');
  737. unit = unit.childNodes[0];
  738. }
  739. let attributes = ['cx', 'cy'];
  740. Object.values(unit.attributes)
  741. .filter(attr => attributes.includes(attr.name) && attr.specified)
  742. .map(attr => {
  743. overlay.setAttribute(attr.name, attr.nodeValue);
  744. });
  745. if(transformValue) {
  746. overlay.setAttribute('transform', transformValue);
  747. }
  748. }
  749. };
  750. const PRESET_COLOR_MAP = {
  751. 'light-blue': '#7cd6fd',
  752. 'blue': '#5e64ff',
  753. 'violet': '#743ee2',
  754. 'red': '#ff5858',
  755. 'orange': '#ffa00a',
  756. 'yellow': '#feef72',
  757. 'green': '#28a745',
  758. 'light-green': '#98d85b',
  759. 'purple': '#b554ff',
  760. 'magenta': '#ffa3ef',
  761. 'black': '#36114C',
  762. 'grey': '#bdd3e6',
  763. 'light-grey': '#f0f4f7',
  764. 'dark-grey': '#b8c2cc'
  765. };
  766. const DEFAULT_COLORS = ['light-blue', 'blue', 'violet', 'red', 'orange',
  767. 'yellow', 'green', 'light-green', 'purple', 'magenta'];
  768. function limitColor(r){
  769. if (r > 255) return 255;
  770. else if (r < 0) return 0;
  771. return r;
  772. }
  773. function lightenDarkenColor(color, amt) {
  774. let col = getColor(color);
  775. let usePound = false;
  776. if (col[0] == "#") {
  777. col = col.slice(1);
  778. usePound = true;
  779. }
  780. let num = parseInt(col,16);
  781. let r = limitColor((num >> 16) + amt);
  782. let b = limitColor(((num >> 8) & 0x00FF) + amt);
  783. let g = limitColor((num & 0x0000FF) + amt);
  784. return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
  785. }
  786. function isValidColor(string) {
  787. // https://stackoverflow.com/a/8027444/6495043
  788. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(string);
  789. }
  790. const getColor = (color) => {
  791. return PRESET_COLOR_MAP[color] || color;
  792. };
  793. const ALL_CHART_TYPES = ['line', 'scatter', 'bar', 'percentage', 'heatmap', 'pie'];
  794. const COMPATIBLE_CHARTS = {
  795. bar: ['line', 'scatter', 'percentage', 'pie'],
  796. line: ['scatter', 'bar', 'percentage', 'pie'],
  797. pie: ['line', 'scatter', 'percentage', 'bar'],
  798. scatter: ['line', 'bar', 'percentage', 'pie'],
  799. percentage: ['bar', 'line', 'scatter', 'pie'],
  800. heatmap: []
  801. };
  802. // Needs structure as per only labels/datasets
  803. const COLOR_COMPATIBLE_CHARTS = {
  804. bar: ['line', 'scatter'],
  805. line: ['scatter', 'bar'],
  806. pie: ['percentage'],
  807. scatter: ['line', 'bar'],
  808. percentage: ['pie'],
  809. heatmap: []
  810. };
  811. function getDifferentChart(type, current_type, parent, args) {
  812. if(type === current_type) return;
  813. if(!ALL_CHART_TYPES.includes(type)) {
  814. console.error(`'${type}' is not a valid chart type.`);
  815. }
  816. if(!COMPATIBLE_CHARTS[current_type].includes(type)) {
  817. console.error(`'${current_type}' chart cannot be converted to a '${type}' chart.`);
  818. }
  819. // whether the new chart can use the existing colors
  820. const useColor = COLOR_COMPATIBLE_CHARTS[current_type].includes(type);
  821. // Okay, this is anticlimactic
  822. // this function will need to actually be 'changeChartType(type)'
  823. // that will update only the required elements, but for now ...
  824. return new Chart(parent, {
  825. title: args.title,
  826. data: args.data,
  827. type: type,
  828. height: args.height,
  829. colors: useColor ? args.colors : undefined
  830. });
  831. }
  832. // Leveraging SMIL Animations
  833. const EASING = {
  834. ease: "0.25 0.1 0.25 1",
  835. linear: "0 0 1 1",
  836. // easein: "0.42 0 1 1",
  837. easein: "0.1 0.8 0.2 1",
  838. easeout: "0 0 0.58 1",
  839. easeinout: "0.42 0 0.58 1"
  840. };
  841. function animateSVGElement(element, props, dur, easingType="linear", type=undefined, oldValues={}) {
  842. let animElement = element.cloneNode(true);
  843. let newElement = element.cloneNode(true);
  844. for(var attributeName in props) {
  845. let animateElement;
  846. if(attributeName === 'transform') {
  847. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
  848. } else {
  849. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
  850. }
  851. let currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
  852. let value = props[attributeName];
  853. let animAttr = {
  854. attributeName: attributeName,
  855. from: currentValue,
  856. to: value,
  857. begin: "0s",
  858. dur: dur/1000 + "s",
  859. values: currentValue + ";" + value,
  860. keySplines: EASING[easingType],
  861. keyTimes: "0;1",
  862. calcMode: "spline",
  863. fill: 'freeze'
  864. };
  865. if(type) {
  866. animAttr["type"] = type;
  867. }
  868. for (var i in animAttr) {
  869. animateElement.setAttribute(i, animAttr[i]);
  870. }
  871. animElement.appendChild(animateElement);
  872. if(type) {
  873. newElement.setAttribute(attributeName, `translate(${value})`);
  874. } else {
  875. newElement.setAttribute(attributeName, value);
  876. }
  877. }
  878. return [animElement, newElement];
  879. }
  880. function transform(element, style) { // eslint-disable-line no-unused-vars
  881. element.style.transform = style;
  882. element.style.webkitTransform = style;
  883. element.style.msTransform = style;
  884. element.style.mozTransform = style;
  885. element.style.oTransform = style;
  886. }
  887. function animateSVG(svgContainer, elements) {
  888. let newElements = [];
  889. let animElements = [];
  890. elements.map(element => {
  891. let unit = element[0];
  892. let parent = unit.parentNode;
  893. let animElement, newElement;
  894. element[0] = unit;
  895. [animElement, newElement] = animateSVGElement(...element);
  896. newElements.push(newElement);
  897. animElements.push([animElement, parent]);
  898. parent.replaceChild(animElement, unit);
  899. });
  900. let animSvg = svgContainer.cloneNode(true);
  901. animElements.map((animElement, i) => {
  902. animElement[1].replaceChild(newElements[i], animElement[0]);
  903. elements[i][0] = newElements[i];
  904. });
  905. return animSvg;
  906. }
  907. function runSMILAnimation(parent, svgElement, elementsToAnimate) {
  908. if(elementsToAnimate.length === 0) return;
  909. let animSvgElement = animateSVG(svgElement, elementsToAnimate);
  910. if(svgElement.parentNode == parent) {
  911. parent.removeChild(svgElement);
  912. parent.appendChild(animSvgElement);
  913. }
  914. // Replace the new svgElement (data has already been replaced)
  915. setTimeout(() => {
  916. if(animSvgElement.parentNode == parent) {
  917. parent.removeChild(animSvgElement);
  918. parent.appendChild(svgElement);
  919. }
  920. }, REPLACE_ALL_NEW_DUR);
  921. }
  922. class BaseChart {
  923. constructor(parent, options) {
  924. this.rawChartArgs = options;
  925. this.parent = typeof parent === 'string' ? document.querySelector(parent) : parent;
  926. if (!(this.parent instanceof HTMLElement)) {
  927. throw new Error('No `parent` element to render on was provided.');
  928. }
  929. this.title = options.title || '';
  930. this.subtitle = options.subtitle || '';
  931. this.argHeight = options.height || 240;
  932. this.type = options.type || '';
  933. this.realData = this.prepareData(options.data);
  934. this.data = this.prepareFirstData(this.realData);
  935. this.colors = [];
  936. this.config = {
  937. showTooltip: 1, // calculate
  938. showLegend: options.showLegend || 1,
  939. isNavigable: options.isNavigable || 0,
  940. animate: 1
  941. };
  942. this.state = {};
  943. this.options = {};
  944. if(this.config.isNavigable) {
  945. this.overlays = [];
  946. }
  947. this.configure(options);
  948. }
  949. configure(args) {
  950. this.setColors();
  951. this.setMargins();
  952. // Bind window events
  953. window.addEventListener('resize', () => this.draw(true));
  954. window.addEventListener('orientationchange', () => this.draw(true));
  955. }
  956. setColors() {
  957. let args = this.rawChartArgs;
  958. // Needs structure as per only labels/datasets, from config
  959. const list = args.type === 'percentage' || args.type === 'pie'
  960. ? args.data.labels
  961. : args.data.datasets;
  962. if(!args.colors || (list && args.colors.length < list.length)) {
  963. this.colors = DEFAULT_COLORS;
  964. } else {
  965. this.colors = args.colors;
  966. }
  967. this.colors = this.colors.map(color => getColor(color));
  968. }
  969. setMargins() {
  970. let height = this.argHeight;
  971. this.baseHeight = height;
  972. this.height = height - VERT_SPACE_OUTSIDE_BASE_CHART;
  973. this.translateY = TRANSLATE_Y_BASE_CHART;
  974. // Horizontal margins
  975. this.leftMargin = LEFT_MARGIN_BASE_CHART;
  976. this.rightMargin = RIGHT_MARGIN_BASE_CHART;
  977. }
  978. validate() {
  979. return true;
  980. }
  981. setup() {
  982. if(this.validate()) {
  983. this._setup();
  984. }
  985. }
  986. _setup() {
  987. this.makeContainer();
  988. this.makeTooltip();
  989. this.draw(false, true);
  990. }
  991. setupComponents() {
  992. this.components = new Map();
  993. }
  994. makeContainer() {
  995. this.container = $.create('div', {
  996. className: 'chart-container',
  997. innerHTML: `<h6 class="title">${this.title}</h6>
  998. <h6 class="sub-title uppercase">${this.subtitle}</h6>
  999. <div class="frappe-chart graphics"></div>
  1000. <div class="graph-stats-container"></div>`
  1001. });
  1002. // Chart needs a dedicated parent element
  1003. this.parent.innerHTML = '';
  1004. this.parent.appendChild(this.container);
  1005. this.chartWrapper = this.container.querySelector('.frappe-chart');
  1006. this.statsWrapper = this.container.querySelector('.graph-stats-container');
  1007. }
  1008. makeTooltip() {
  1009. this.tip = new SvgTip({
  1010. parent: this.chartWrapper,
  1011. colors: this.colors
  1012. });
  1013. this.bindTooltip();
  1014. }
  1015. bindTooltip() {}
  1016. draw(onlyWidthChange=false, init=false) {
  1017. this.calcWidth();
  1018. this.calc(onlyWidthChange);
  1019. this.makeChartArea();
  1020. this.setupComponents();
  1021. this.components.forEach(c => c.setup(this.drawArea));
  1022. // this.components.forEach(c => c.make());
  1023. this.render(this.components, false);
  1024. if(init) {
  1025. this.data = this.realData;
  1026. setTimeout(() => {this.update();}, INIT_CHART_UPDATE_TIMEOUT);
  1027. }
  1028. this.renderLegend();
  1029. this.setupNavigation(init);
  1030. }
  1031. calcWidth() {
  1032. this.baseWidth = getElementContentWidth(this.parent);
  1033. this.width = this.baseWidth - (this.leftMargin + this.rightMargin);
  1034. }
  1035. update(data=this.data) {
  1036. this.data = this.prepareData(data);
  1037. this.calc(); // builds state
  1038. this.render();
  1039. }
  1040. prepareData(data=this.data) {
  1041. return data;
  1042. }
  1043. prepareFirstData(data=this.data) {
  1044. return data;
  1045. }
  1046. calc() {} // builds state
  1047. render(components=this.components, animate=true) {
  1048. if(this.config.isNavigable) {
  1049. // Remove all existing overlays
  1050. this.overlays.map(o => o.parentNode.removeChild(o));
  1051. // ref.parentNode.insertBefore(element, ref);
  1052. }
  1053. let elementsToAnimate = [];
  1054. // Can decouple to this.refreshComponents() first to save animation timeout
  1055. components.forEach(c => {
  1056. elementsToAnimate = elementsToAnimate.concat(c.update(animate));
  1057. });
  1058. if(elementsToAnimate.length > 0) {
  1059. runSMILAnimation(this.chartWrapper, this.svg, elementsToAnimate);
  1060. setTimeout(() => {
  1061. components.forEach(c => c.make());
  1062. this.updateNav();
  1063. }, CHART_POST_ANIMATE_TIMEOUT);
  1064. } else {
  1065. components.forEach(c => c.make());
  1066. this.updateNav();
  1067. }
  1068. }
  1069. updateNav() {
  1070. if(this.config.isNavigable) {
  1071. // if(!this.overlayGuides){
  1072. this.makeOverlay();
  1073. this.bindUnits();
  1074. // } else {
  1075. // this.updateOverlay();
  1076. // }
  1077. }
  1078. }
  1079. makeChartArea() {
  1080. if(this.svg) {
  1081. this.chartWrapper.removeChild(this.svg);
  1082. }
  1083. this.svg = makeSVGContainer(
  1084. this.chartWrapper,
  1085. 'chart',
  1086. this.baseWidth,
  1087. this.baseHeight
  1088. );
  1089. this.svgDefs = makeSVGDefs(this.svg);
  1090. // I WISH !!!
  1091. // this.svg = makeSVGGroup(
  1092. // svgContainer,
  1093. // 'flipped-coord-system',
  1094. // `translate(0, ${this.baseHeight}) scale(1, -1)`
  1095. // );
  1096. this.drawArea = makeSVGGroup(
  1097. this.svg,
  1098. this.type + '-chart',
  1099. `translate(${this.leftMargin}, ${this.translateY})`
  1100. );
  1101. }
  1102. renderLegend() {}
  1103. setupNavigation(init=false) {
  1104. if(!this.config.isNavigable) return;
  1105. if(init) {
  1106. this.bindOverlay();
  1107. this.keyActions = {
  1108. '13': this.onEnterKey.bind(this),
  1109. '37': this.onLeftArrow.bind(this),
  1110. '38': this.onUpArrow.bind(this),
  1111. '39': this.onRightArrow.bind(this),
  1112. '40': this.onDownArrow.bind(this),
  1113. };
  1114. document.addEventListener('keydown', (e) => {
  1115. if(isElementInViewport(this.chartWrapper)) {
  1116. e = e || window.event;
  1117. if(this.keyActions[e.keyCode]) {
  1118. this.keyActions[e.keyCode]();
  1119. }
  1120. }
  1121. });
  1122. }
  1123. }
  1124. makeOverlay() {}
  1125. updateOverlay() {}
  1126. bindOverlay() {}
  1127. bindUnits() {}
  1128. onLeftArrow() {}
  1129. onRightArrow() {}
  1130. onUpArrow() {}
  1131. onDownArrow() {}
  1132. onEnterKey() {}
  1133. getDataPoint(index = 0) {}
  1134. setCurrentDataPoint(point) {}
  1135. updateDataset(dataset, index) {}
  1136. addDataset(dataset, index) {}
  1137. removeDataset(index = 0) {}
  1138. updateDatasets(datasets) {}
  1139. updateDataPoint(dataPoint, index = 0) {}
  1140. addDataPoint(dataPoint, index = 0) {}
  1141. removeDataPoint(index = 0) {}
  1142. getDifferentChart(type) {
  1143. return getDifferentChart(type, this.type, this.parent, this.rawChartArgs);
  1144. }
  1145. }
  1146. class PercentageChart extends BaseChart {
  1147. constructor(parent, args) {
  1148. super(parent, args);
  1149. this.type = 'percentage';
  1150. this.max_slices = 10;
  1151. this.max_legend_points = 6;
  1152. this.setup();
  1153. }
  1154. makeChartArea() {
  1155. this.chartWrapper.className += ' ' + 'graph-focus-margin';
  1156. this.chartWrapper.style.marginTop = '45px';
  1157. this.statsWrapper.className += ' ' + 'graph-focus-margin';
  1158. this.statsWrapper.style.marginBottom = '30px';
  1159. this.statsWrapper.style.paddingTop = '0px';
  1160. this.svg = $.create('div', {
  1161. className: 'div',
  1162. inside: this.chartWrapper
  1163. });
  1164. this.chart = $.create('div', {
  1165. className: 'progress-chart',
  1166. inside: this.svg
  1167. });
  1168. this.percentageBar = $.create('div', {
  1169. className: 'progress',
  1170. inside: this.chart
  1171. });
  1172. }
  1173. render() {
  1174. this.grand_total = this.sliceTotals.reduce((a, b) => a + b, 0);
  1175. this.slices = [];
  1176. this.sliceTotals.map((total, i) => {
  1177. let slice = $.create('div', {
  1178. className: `progress-bar`,
  1179. inside: this.percentageBar,
  1180. styles: {
  1181. background: this.colors[i],
  1182. width: total*100/this.grand_total + "%"
  1183. }
  1184. });
  1185. this.slices.push(slice);
  1186. });
  1187. }
  1188. calc() {
  1189. this.sliceTotals = [];
  1190. let all_totals = this.data.labels.map((d, i) => {
  1191. let total = 0;
  1192. this.data.datasets.map(e => {
  1193. total += e.values[i];
  1194. });
  1195. return [total, d];
  1196. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1197. let totals = all_totals;
  1198. if(all_totals.length > this.max_slices) {
  1199. all_totals.sort((a, b) => { return b[0] - a[0]; });
  1200. totals = all_totals.slice(0, this.max_slices-1);
  1201. let others = all_totals.slice(this.max_slices-1);
  1202. let sum_of_others = 0;
  1203. others.map(d => {sum_of_others += d[0];});
  1204. totals.push([sum_of_others, 'Rest']);
  1205. this.colors[this.max_slices-1] = 'grey';
  1206. }
  1207. this.labels = [];
  1208. totals.map(d => {
  1209. this.sliceTotals.push(d[0]);
  1210. this.labels.push(d[1]);
  1211. });
  1212. this.legend_totals = this.sliceTotals.slice(0, this.max_legend_points);
  1213. }
  1214. bindTooltip() {
  1215. // this.slices.map((slice, i) => {
  1216. // slice.addEventListener('mouseenter', () => {
  1217. // let g_off = getOffset(this.chartWrapper), p_off = getOffset(slice);
  1218. // let x = p_off.left - g_off.left + slice.offsetWidth/2;
  1219. // let y = p_off.top - g_off.top - 6;
  1220. // let title = (this.formatted_labels && this.formatted_labels.length>0
  1221. // ? this.formatted_labels[i] : this.labels[i]) + ': ';
  1222. // let percent = (this.sliceTotals[i]*100/this.grand_total).toFixed(1);
  1223. // this.tip.set_values(x, y, title, percent + "%");
  1224. // this.tip.show_tip();
  1225. // });
  1226. // });
  1227. }
  1228. renderLegend() {
  1229. // let x_values = this.formatted_labels && this.formatted_labels.length > 0
  1230. // ? this.formatted_labels : this.labels;
  1231. // this.legend_totals.map((d, i) => {
  1232. // if(d) {
  1233. // let stats = $.create('div', {
  1234. // className: 'stats',
  1235. // inside: this.statsWrapper
  1236. // });
  1237. // stats.innerHTML = `<span class="indicator">
  1238. // <i style="background: ${this.colors[i]}"></i>
  1239. // <span class="text-muted">${x_values[i]}:</span>
  1240. // ${d}
  1241. // </span>`;
  1242. // }
  1243. // });
  1244. }
  1245. }
  1246. const ANGLE_RATIO = Math.PI / 180;
  1247. const FULL_ANGLE = 360;
  1248. class PieChart extends BaseChart {
  1249. constructor(parent, args) {
  1250. super(parent, args);
  1251. this.type = 'pie';
  1252. this.elements_to_animate = null;
  1253. this.hoverRadio = args.hoverRadio || 0.1;
  1254. this.max_slices = 10;
  1255. this.max_legend_points = 6;
  1256. this.isAnimate = false;
  1257. this.startAngle = args.startAngle || 0;
  1258. this.clockWise = args.clockWise || false;
  1259. this.mouseMove = this.mouseMove.bind(this);
  1260. this.mouseLeave = this.mouseLeave.bind(this);
  1261. this.setup();
  1262. }
  1263. calc() {
  1264. this.centerX = this.width / 2;
  1265. this.centerY = this.height / 2;
  1266. this.radius = (this.height > this.width ? this.centerX : this.centerY);
  1267. this.slice_totals = [];
  1268. let all_totals = this.data.labels.map((d, i) => {
  1269. let total = 0;
  1270. this.data.datasets.map(e => {
  1271. total += e.values[i];
  1272. });
  1273. return [total, d];
  1274. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1275. let totals = all_totals;
  1276. if(all_totals.length > this.max_slices) {
  1277. all_totals.sort((a, b) => { return b[0] - a[0]; });
  1278. totals = all_totals.slice(0, this.max_slices-1);
  1279. let others = all_totals.slice(this.max_slices-1);
  1280. let sum_of_others = 0;
  1281. others.map(d => {sum_of_others += d[0];});
  1282. totals.push([sum_of_others, 'Rest']);
  1283. this.colors[this.max_slices-1] = 'grey';
  1284. }
  1285. this.labels = [];
  1286. totals.map(d => {
  1287. this.slice_totals.push(d[0]);
  1288. this.labels.push(d[1]);
  1289. });
  1290. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  1291. }
  1292. static getPositionByAngle(angle,radius) {
  1293. return {
  1294. x:Math.sin(angle * ANGLE_RATIO) * radius,
  1295. y:Math.cos(angle * ANGLE_RATIO) * radius,
  1296. };
  1297. }
  1298. makeArcPath(startPosition,endPosition){
  1299. const{centerX,centerY,radius,clockWise} = this;
  1300. return `M${centerX} ${centerY} L${centerX+startPosition.x} ${centerY+startPosition.y} A ${radius} ${radius} 0 0 ${clockWise ? 1 : 0} ${centerX+endPosition.x} ${centerY+endPosition.y} z`;
  1301. }
  1302. render(init) {
  1303. const{radius,clockWise} = this;
  1304. this.grand_total = this.slice_totals.reduce((a, b) => a + b, 0);
  1305. const prevSlicesProperties = this.slicesProperties || [];
  1306. this.slices = [];
  1307. this.elements_to_animate = [];
  1308. this.slicesProperties = [];
  1309. let curAngle = 180 - this.startAngle;
  1310. this.slice_totals.map((total, i) => {
  1311. const startAngle = curAngle;
  1312. const originDiffAngle = (total / this.grand_total) * FULL_ANGLE;
  1313. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  1314. const endAngle = curAngle = curAngle + diffAngle;
  1315. const startPosition = PieChart.getPositionByAngle(startAngle,radius);
  1316. const endPosition = PieChart.getPositionByAngle(endAngle,radius);
  1317. const prevProperty = init && prevSlicesProperties[i];
  1318. let curStart,curEnd;
  1319. if(init){
  1320. curStart = prevProperty?prevProperty.startPosition : startPosition;
  1321. curEnd = prevProperty? prevProperty.endPosition : startPosition;
  1322. }else{
  1323. curStart = startPosition;
  1324. curEnd = endPosition;
  1325. }
  1326. const curPath = this.makeArcPath(curStart,curEnd);
  1327. let slice = makePath(curPath, 'pie-path', 'none', this.colors[i]);
  1328. slice.style.transition = 'transform .3s;';
  1329. this.drawArea.appendChild(slice);
  1330. this.slices.push(slice);
  1331. this.slicesProperties.push({
  1332. startPosition,
  1333. endPosition,
  1334. value: total,
  1335. total: this.grand_total,
  1336. startAngle,
  1337. endAngle,
  1338. angle:diffAngle
  1339. });
  1340. if(init){
  1341. this.elements_to_animate.push([{unit: slice, array: this.slices, index: this.slices.length - 1},
  1342. {d:this.makeArcPath(startPosition,endPosition)},
  1343. 650, "easein",null,{
  1344. d:curPath
  1345. }]);
  1346. }
  1347. });
  1348. if(init){
  1349. runSMILAnimation(this.chartWrapper, this.svg, this.elements_to_animate);
  1350. }
  1351. }
  1352. calTranslateByAngle(property){
  1353. const{radius,hoverRadio} = this;
  1354. const position = PieChart.getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  1355. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  1356. }
  1357. hoverSlice(path,i,flag,e){
  1358. if(!path) return;
  1359. const color = this.colors[i];
  1360. if(flag){
  1361. transform(path,this.calTranslateByAngle(this.slicesProperties[i]));
  1362. path.style.fill = lightenDarkenColor(color,50);
  1363. let g_off = getOffset(this.svg);
  1364. let x = e.pageX - g_off.left + 10;
  1365. let y = e.pageY - g_off.top - 10;
  1366. let title = (this.formatted_labels && this.formatted_labels.length>0
  1367. ? this.formatted_labels[i] : this.labels[i]) + ': ';
  1368. let percent = (this.slice_totals[i]*100/this.grand_total).toFixed(1);
  1369. this.tip.set_values(x, y, title, percent + "%");
  1370. this.tip.show_tip();
  1371. }else{
  1372. transform(path,'translate3d(0,0,0)');
  1373. this.tip.hide_tip();
  1374. path.style.fill = color;
  1375. }
  1376. }
  1377. mouseMove(e){
  1378. const target = e.target;
  1379. let prevIndex = this.curActiveSliceIndex;
  1380. let prevAcitve = this.curActiveSlice;
  1381. for(let i = 0; i < this.slices.length; i++){
  1382. if(target === this.slices[i]){
  1383. this.hoverSlice(prevAcitve,prevIndex,false);
  1384. this.curActiveSlice = target;
  1385. this.curActiveSliceIndex = i;
  1386. this.hoverSlice(target,i,true,e);
  1387. break;
  1388. }
  1389. }
  1390. }
  1391. mouseLeave(){
  1392. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  1393. }
  1394. bindTooltip() {
  1395. // this.drawArea.addEventListener('mousemove',this.mouseMove);
  1396. // this.drawArea.addEventListener('mouseleave',this.mouseLeave);
  1397. }
  1398. renderLegend() {
  1399. let x_values = this.formatted_labels && this.formatted_labels.length > 0
  1400. ? this.formatted_labels : this.labels;
  1401. this.legend_totals.map((d, i) => {
  1402. const color = this.colors[i];
  1403. if(d) {
  1404. let stats = $.create('div', {
  1405. className: 'stats',
  1406. inside: this.statsWrapper
  1407. });
  1408. stats.innerHTML = `<span class="indicator">
  1409. <i style="background-color:${color};"></i>
  1410. <span class="text-muted">${x_values[i]}:</span>
  1411. ${d}
  1412. </span>`;
  1413. }
  1414. });
  1415. }
  1416. }
  1417. // Playing around with dates
  1418. // https://stackoverflow.com/a/11252167/6495043
  1419. function treatAsUtc(dateStr) {
  1420. let result = new Date(dateStr);
  1421. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  1422. return result;
  1423. }
  1424. function getDdMmYyyy(date) {
  1425. let dd = date.getDate();
  1426. let mm = date.getMonth() + 1; // getMonth() is zero-based
  1427. return [
  1428. (dd>9 ? '' : '0') + dd,
  1429. (mm>9 ? '' : '0') + mm,
  1430. date.getFullYear()
  1431. ].join('-');
  1432. }
  1433. function getWeeksBetween(startDateStr, endDateStr) {
  1434. return Math.ceil(getDaysBetween(startDateStr, endDateStr) / 7);
  1435. }
  1436. function getDaysBetween(startDateStr, endDateStr) {
  1437. let millisecondsPerDay = 24 * 60 * 60 * 1000;
  1438. return (treatAsUtc(endDateStr) - treatAsUtc(startDateStr)) / millisecondsPerDay;
  1439. }
  1440. // mutates
  1441. function addDays(date, numberOfDays) {
  1442. date.setDate(date.getDate() + numberOfDays);
  1443. }
  1444. // export function getMonthName() {}
  1445. function normalize(x) {
  1446. // Calculates mantissa and exponent of a number
  1447. // Returns normalized number and exponent
  1448. // https://stackoverflow.com/q/9383593/6495043
  1449. if(x===0) {
  1450. return [0, 0];
  1451. }
  1452. if(isNaN(x)) {
  1453. return {mantissa: -6755399441055744, exponent: 972};
  1454. }
  1455. var sig = x > 0 ? 1 : -1;
  1456. if(!isFinite(x)) {
  1457. return {mantissa: sig * 4503599627370496, exponent: 972};
  1458. }
  1459. x = Math.abs(x);
  1460. var exp = Math.floor(Math.log10(x));
  1461. var man = x/Math.pow(10, exp);
  1462. return [sig * man, exp];
  1463. }
  1464. function getChartRangeIntervals(max, min=0) {
  1465. let upperBound = Math.ceil(max);
  1466. let lowerBound = Math.floor(min);
  1467. let range = upperBound - lowerBound;
  1468. let noOfParts = range;
  1469. let partSize = 1;
  1470. // To avoid too many partitions
  1471. if(range > 5) {
  1472. if(range % 2 !== 0) {
  1473. upperBound++;
  1474. // Recalc range
  1475. range = upperBound - lowerBound;
  1476. }
  1477. noOfParts = range/2;
  1478. partSize = 2;
  1479. }
  1480. // Special case: 1 and 2
  1481. if(range <= 2) {
  1482. noOfParts = 4;
  1483. partSize = range/noOfParts;
  1484. }
  1485. // Special case: 0
  1486. if(range === 0) {
  1487. noOfParts = 5;
  1488. partSize = 1;
  1489. }
  1490. let intervals = [];
  1491. for(var i = 0; i <= noOfParts; i++){
  1492. intervals.push(lowerBound + partSize * i);
  1493. }
  1494. return intervals;
  1495. }
  1496. function getChartIntervals(maxValue, minValue=0) {
  1497. let [normalMaxValue, exponent] = normalize(maxValue);
  1498. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  1499. // Allow only 7 significant digits
  1500. normalMaxValue = normalMaxValue.toFixed(6);
  1501. let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  1502. intervals = intervals.map(value => value * Math.pow(10, exponent));
  1503. return intervals;
  1504. }
  1505. function calcChartIntervals(values, withMinimum=false) {
  1506. //*** Where the magic happens ***
  1507. // Calculates best-fit y intervals from given values
  1508. // and returns the interval array
  1509. let maxValue = Math.max(...values);
  1510. let minValue = Math.min(...values);
  1511. // Exponent to be used for pretty print
  1512. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  1513. function getPositiveFirstIntervals(maxValue, absMinValue) {
  1514. let intervals = getChartIntervals(maxValue);
  1515. let intervalSize = intervals[1] - intervals[0];
  1516. // Then unshift the negative values
  1517. let value = 0;
  1518. for(var i = 1; value < absMinValue; i++) {
  1519. value += intervalSize;
  1520. intervals.unshift((-1) * value);
  1521. }
  1522. return intervals;
  1523. }
  1524. // CASE I: Both non-negative
  1525. if(maxValue >= 0 && minValue >= 0) {
  1526. exponent = normalize(maxValue)[1];
  1527. if(!withMinimum) {
  1528. intervals = getChartIntervals(maxValue);
  1529. } else {
  1530. intervals = getChartIntervals(maxValue, minValue);
  1531. }
  1532. }
  1533. // CASE II: Only minValue negative
  1534. else if(maxValue > 0 && minValue < 0) {
  1535. // `withMinimum` irrelevant in this case,
  1536. // We'll be handling both sides of zero separately
  1537. // (both starting from zero)
  1538. // Because ceil() and floor() behave differently
  1539. // in those two regions
  1540. let absMinValue = Math.abs(minValue);
  1541. if(maxValue >= absMinValue) {
  1542. exponent = normalize(maxValue)[1];
  1543. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  1544. } else {
  1545. // Mirror: maxValue => absMinValue, then change sign
  1546. exponent = normalize(absMinValue)[1];
  1547. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  1548. intervals = posIntervals.map(d => d * (-1));
  1549. }
  1550. }
  1551. // CASE III: Both non-positive
  1552. else if(maxValue <= 0 && minValue <= 0) {
  1553. // Mirrored Case I:
  1554. // Work with positives, then reverse the sign and array
  1555. let pseudoMaxValue = Math.abs(minValue);
  1556. let pseudoMinValue = Math.abs(maxValue);
  1557. exponent = normalize(pseudoMaxValue)[1];
  1558. if(!withMinimum) {
  1559. intervals = getChartIntervals(pseudoMaxValue);
  1560. } else {
  1561. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  1562. }
  1563. intervals = intervals.reverse().map(d => d * (-1));
  1564. }
  1565. return intervals;
  1566. }
  1567. function getZeroIndex(yPts) {
  1568. let zeroIndex;
  1569. let interval = getIntervalSize(yPts);
  1570. if(yPts.indexOf(0) >= 0) {
  1571. // the range has a given zero
  1572. // zero-line on the chart
  1573. zeroIndex = yPts.indexOf(0);
  1574. } else if(yPts[0] > 0) {
  1575. // Minimum value is positive
  1576. // zero-line is off the chart: below
  1577. let min = yPts[0];
  1578. zeroIndex = (-1) * min / interval;
  1579. } else {
  1580. // Maximum value is negative
  1581. // zero-line is off the chart: above
  1582. let max = yPts[yPts.length - 1];
  1583. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  1584. }
  1585. return zeroIndex;
  1586. }
  1587. function getIntervalSize(orderedArray) {
  1588. return orderedArray[1] - orderedArray[0];
  1589. }
  1590. function getValueRange(orderedArray) {
  1591. return orderedArray[orderedArray.length-1] - orderedArray[0];
  1592. }
  1593. function scale(val, yAxis) {
  1594. return floatTwo(yAxis.zeroLine - val * yAxis.scaleMultiplier)
  1595. }
  1596. function calcDistribution(values, distributionSize) {
  1597. // Assume non-negative values,
  1598. // implying distribution minimum at zero
  1599. let dataMaxValue = Math.max(...values);
  1600. let distributionStep = 1 / (distributionSize - 1);
  1601. let distribution = [];
  1602. for(var i = 0; i < distributionSize; i++) {
  1603. let checkpoint = dataMaxValue * (distributionStep * i);
  1604. distribution.push(checkpoint);
  1605. }
  1606. return distribution;
  1607. }
  1608. function getMaxCheckpoint(value, distribution) {
  1609. return distribution.filter(d => d < value).length;
  1610. }
  1611. class Heatmap extends BaseChart {
  1612. constructor(parent, options) {
  1613. super(parent, options);
  1614. this.type = 'heatmap';
  1615. this.domain = options.domain || '';
  1616. this.subdomain = options.subdomain || '';
  1617. this.data = options.data || {};
  1618. this.discrete_domains = options.discrete_domains || 1;
  1619. this.count_label = options.count_label || '';
  1620. let today = new Date();
  1621. this.start = options.start || addDays(today, 365);
  1622. let legend_colors = (options.legend_colors || []).slice(0, 5);
  1623. this.legend_colors = this.validate_colors(legend_colors)
  1624. ? legend_colors
  1625. : ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  1626. // Fixed 5-color theme,
  1627. // More colors are difficult to parse visually
  1628. this.distribution_size = 5;
  1629. this.translateX = 0;
  1630. this.setup();
  1631. }
  1632. validate_colors(colors) {
  1633. if(colors.length < 5) return 0;
  1634. let valid = 1;
  1635. colors.forEach(function(string) {
  1636. if(!isValidColor(string)) {
  1637. valid = 0;
  1638. console.warn('"' + string + '" is not a valid color.');
  1639. }
  1640. }, this);
  1641. return valid;
  1642. }
  1643. configure() {
  1644. super.configure();
  1645. this.today = new Date();
  1646. if(!this.start) {
  1647. this.start = new Date();
  1648. this.start.setFullYear( this.start.getFullYear() - 1 );
  1649. }
  1650. this.first_week_start = new Date(this.start.toDateString());
  1651. this.last_week_start = new Date(this.today.toDateString());
  1652. if(this.first_week_start.getDay() !== 7) {
  1653. addDays(this.first_week_start, (-1) * this.first_week_start.getDay());
  1654. }
  1655. if(this.last_week_start.getDay() !== 7) {
  1656. addDays(this.last_week_start, (-1) * this.last_week_start.getDay());
  1657. }
  1658. this.no_of_cols = getWeeksBetween(this.first_week_start + '', this.last_week_start + '') + 1;
  1659. }
  1660. calcWidth() {
  1661. this.baseWidth = (this.no_of_cols + 3) * 12 ;
  1662. if(this.discrete_domains) {
  1663. this.baseWidth += (12 * 12);
  1664. }
  1665. }
  1666. makeChartArea() {
  1667. super.makeChartArea();
  1668. this.domainLabelGroup = makeSVGGroup(this.drawArea,
  1669. 'domain-label-group chart-label');
  1670. this.dataGroups = makeSVGGroup(this.drawArea,
  1671. 'data-groups',
  1672. `translate(0, 20)`
  1673. );
  1674. // Array.prototype.slice.call(
  1675. // this.container.querySelectorAll('.graph-stats-container, .sub-title, .title')
  1676. // ).map(d => {
  1677. // d.style.display = 'None';
  1678. // });
  1679. // this.chartWrapper.style.marginTop = '0px';
  1680. // this.chartWrapper.style.paddingTop = '0px';
  1681. }
  1682. calc() {
  1683. let data_values = Object.keys(this.data).map(key => this.data[key]);
  1684. this.distribution = calcDistribution(data_values, this.distribution_size);
  1685. this.month_names = ["January", "February", "March", "April", "May", "June",
  1686. "July", "August", "September", "October", "November", "December"
  1687. ];
  1688. }
  1689. render() {
  1690. this.renderAllWeeksAndStoreXValues(this.no_of_cols);
  1691. }
  1692. renderAllWeeksAndStoreXValues(no_of_weeks) {
  1693. // renderAllWeeksAndStoreXValues
  1694. this.domainLabelGroup.textContent = '';
  1695. this.dataGroups.textContent = '';
  1696. let current_week_sunday = new Date(this.first_week_start);
  1697. this.week_col = 0;
  1698. this.current_month = current_week_sunday.getMonth();
  1699. this.months = [this.current_month + ''];
  1700. this.month_weeks = {}, this.month_start_points = [];
  1701. this.month_weeks[this.current_month] = 0;
  1702. this.month_start_points.push(13);
  1703. for(var i = 0; i < no_of_weeks; i++) {
  1704. let data_group, month_change = 0;
  1705. let day = new Date(current_week_sunday);
  1706. [data_group, month_change] = this.get_week_squares_group(day, this.week_col);
  1707. this.dataGroups.appendChild(data_group);
  1708. this.week_col += 1 + parseInt(this.discrete_domains && month_change);
  1709. this.month_weeks[this.current_month]++;
  1710. if(month_change) {
  1711. this.current_month = (this.current_month + 1) % 12;
  1712. this.months.push(this.current_month + '');
  1713. this.month_weeks[this.current_month] = 1;
  1714. }
  1715. addDays(current_week_sunday, 7);
  1716. }
  1717. this.render_month_labels();
  1718. }
  1719. get_week_squares_group(current_date, index) {
  1720. const no_of_weekdays = 7;
  1721. const square_side = 10;
  1722. const cell_padding = 2;
  1723. const step = 1;
  1724. const today_time = this.today.getTime();
  1725. let month_change = 0;
  1726. let week_col_change = 0;
  1727. let data_group = makeSVGGroup(this.dataGroups, 'data-group');
  1728. for(var y = 0, i = 0; i < no_of_weekdays; i += step, y += (square_side + cell_padding)) {
  1729. let data_value = 0;
  1730. let colorIndex = 0;
  1731. let current_timestamp = current_date.getTime()/1000;
  1732. let timestamp = Math.floor(current_timestamp - (current_timestamp % 86400)).toFixed(1);
  1733. if(this.data[timestamp]) {
  1734. data_value = this.data[timestamp];
  1735. }
  1736. if(this.data[Math.round(timestamp)]) {
  1737. data_value = this.data[Math.round(timestamp)];
  1738. }
  1739. if(data_value) {
  1740. colorIndex = getMaxCheckpoint(data_value, this.distribution);
  1741. }
  1742. let x = 13 + (index + week_col_change) * 12;
  1743. let dataAttr = {
  1744. 'data-date': getDdMmYyyy(current_date),
  1745. 'data-value': data_value,
  1746. 'data-day': current_date.getDay()
  1747. };
  1748. let heatSquare = makeHeatSquare('day', x, y, square_side,
  1749. this.legend_colors[colorIndex], dataAttr);
  1750. data_group.appendChild(heatSquare);
  1751. let next_date = new Date(current_date);
  1752. addDays(next_date, 1);
  1753. if(next_date.getTime() > today_time) break;
  1754. if(next_date.getMonth() - current_date.getMonth()) {
  1755. month_change = 1;
  1756. if(this.discrete_domains) {
  1757. week_col_change = 1;
  1758. }
  1759. this.month_start_points.push(13 + (index + week_col_change) * 12);
  1760. }
  1761. current_date = next_date;
  1762. }
  1763. return [data_group, month_change];
  1764. }
  1765. render_month_labels() {
  1766. // this.first_month_label = 1;
  1767. // if (this.first_week_start.getDate() > 8) {
  1768. // this.first_month_label = 0;
  1769. // }
  1770. // this.last_month_label = 1;
  1771. // let first_month = this.months.shift();
  1772. // let first_month_start = this.month_start_points.shift();
  1773. // render first month if
  1774. // let last_month = this.months.pop();
  1775. // let last_month_start = this.month_start_points.pop();
  1776. // render last month if
  1777. this.months.shift();
  1778. this.month_start_points.shift();
  1779. this.months.pop();
  1780. this.month_start_points.pop();
  1781. this.month_start_points.map((start, i) => {
  1782. let month_name = this.month_names[this.months[i]].substring(0, 3);
  1783. let text = makeText('y-value-text', start+12, 10, month_name);
  1784. this.domainLabelGroup.appendChild(text);
  1785. });
  1786. }
  1787. bindTooltip() {
  1788. Array.prototype.slice.call(
  1789. document.querySelectorAll(".data-group .day")
  1790. ).map(el => {
  1791. el.addEventListener('mouseenter', (e) => {
  1792. let count = e.target.getAttribute('data-value');
  1793. let date_parts = e.target.getAttribute('data-date').split('-');
  1794. let month = this.month_names[parseInt(date_parts[1])-1].substring(0, 3);
  1795. let g_off = this.chartWrapper.getBoundingClientRect(), p_off = e.target.getBoundingClientRect();
  1796. let width = parseInt(e.target.getAttribute('width'));
  1797. let x = p_off.left - g_off.left + (width+2)/2;
  1798. let y = p_off.top - g_off.top - (width+2)/2;
  1799. let value = count + ' ' + this.count_label;
  1800. let name = ' on ' + month + ' ' + date_parts[0] + ', ' + date_parts[2];
  1801. this.tip.set_values(x, y, name, value, [], 1);
  1802. this.tip.show_tip();
  1803. });
  1804. });
  1805. }
  1806. update(data) {
  1807. super.update(data);
  1808. this.bindTooltip();
  1809. }
  1810. }
  1811. function dataPrep(data, type) {
  1812. data.labels = data.labels || [];
  1813. let datasetLength = data.labels.length;
  1814. // Datasets
  1815. let datasets = data.datasets;
  1816. let zeroArray = new Array(datasetLength).fill(0);
  1817. if(!datasets) {
  1818. // default
  1819. datasets = [{
  1820. values: zeroArray
  1821. }];
  1822. }
  1823. datasets.map((d, i)=> {
  1824. // Set values
  1825. if(!d.values) {
  1826. d.values = zeroArray;
  1827. } else {
  1828. // Check for non values
  1829. let vals = d.values;
  1830. vals = vals.map(val => (!isNaN(val) ? val : 0));
  1831. // Trim or extend
  1832. if(vals.length > datasetLength) {
  1833. vals = vals.slice(0, datasetLength);
  1834. } else {
  1835. vals = fillArray(vals, datasetLength - vals.length, 0);
  1836. }
  1837. }
  1838. // Set labels
  1839. //
  1840. // Set type
  1841. if(!d.chartType ) {
  1842. if(!AXIS_DATASET_CHART_TYPES.includes(type)) type === DEFAULT_AXIS_CHART_TYPE;
  1843. d.chartType = type;
  1844. }
  1845. });
  1846. // Markers
  1847. // Regions
  1848. // data.yRegions = data.yRegions || [];
  1849. if(data.yRegions) {
  1850. data.yRegions.map(d => {
  1851. if(d.end < d.start) {
  1852. [d.start, d.end] = [d.end, d.start];
  1853. }
  1854. });
  1855. }
  1856. return data;
  1857. }
  1858. function zeroDataPrep(realData) {
  1859. let datasetLength = realData.labels.length;
  1860. let zeroArray = new Array(datasetLength).fill(0);
  1861. let zeroData = {
  1862. labels: realData.labels.slice(0, -1),
  1863. datasets: realData.datasets.map(d => {
  1864. return {
  1865. name: '',
  1866. values: zeroArray.slice(0, -1),
  1867. chartType: d.chartType
  1868. }
  1869. }),
  1870. };
  1871. if(realData.yMarkers) {
  1872. zeroData.yMarkers = [
  1873. {
  1874. value: 0,
  1875. label: ''
  1876. }
  1877. ];
  1878. }
  1879. if(realData.yRegions) {
  1880. zeroData.yRegions = [
  1881. {
  1882. start: 0,
  1883. end: 0,
  1884. label: ''
  1885. }
  1886. ];
  1887. }
  1888. return zeroData;
  1889. }
  1890. function getShortenedLabels(chartWidth, labels=[], isSeries=true) {
  1891. let allowedSpace = chartWidth / labels.length;
  1892. let allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH;
  1893. let calcLabels = labels.map((label, i) => {
  1894. label += "";
  1895. if(label.length > allowedLetters) {
  1896. if(!isSeries) {
  1897. if(allowedLetters-3 > 0) {
  1898. label = label.slice(0, allowedLetters-3) + " ...";
  1899. } else {
  1900. label = label.slice(0, allowedLetters) + '..';
  1901. }
  1902. } else {
  1903. let multiple = Math.ceil(label.length/allowedLetters);
  1904. if(i % multiple !== 0) {
  1905. label = "";
  1906. }
  1907. }
  1908. }
  1909. return label;
  1910. });
  1911. return calcLabels;
  1912. }
  1913. class ChartComponent {
  1914. constructor({
  1915. layerClass = '',
  1916. layerTransform = '',
  1917. constants,
  1918. getData,
  1919. makeElements,
  1920. animateElements
  1921. }) {
  1922. this.layerTransform = layerTransform;
  1923. this.constants = constants;
  1924. this.makeElements = makeElements;
  1925. this.getData = getData;
  1926. this.animateElements = animateElements;
  1927. this.store = [];
  1928. this.layerClass = layerClass;
  1929. this.layerClass = typeof(this.layerClass) === 'function'
  1930. ? this.layerClass() : this.layerClass;
  1931. this.refresh();
  1932. }
  1933. refresh(data) {
  1934. this.data = data || this.getData();
  1935. }
  1936. setup(parent) {
  1937. this.layer = makeSVGGroup(parent, this.layerClass, this.layerTransform);
  1938. }
  1939. make() {
  1940. this.render(this.data);
  1941. this.oldData = this.data;
  1942. }
  1943. render(data) {
  1944. this.store = this.makeElements(data);
  1945. this.layer.textContent = '';
  1946. this.store.forEach(element => {
  1947. this.layer.appendChild(element);
  1948. });
  1949. }
  1950. update(animate = true) {
  1951. this.refresh();
  1952. let animateElements = [];
  1953. if(animate) {
  1954. animateElements = this.animateElements(this.data);
  1955. }
  1956. return animateElements;
  1957. }
  1958. }
  1959. let componentConfigs = {
  1960. yAxis: {
  1961. layerClass: 'y axis',
  1962. makeElements(data) {
  1963. return data.positions.map((position, i) =>
  1964. yLine(position, data.labels[i], this.constants.width,
  1965. {mode: this.constants.mode, pos: this.constants.pos})
  1966. );
  1967. },
  1968. animateElements(newData) {
  1969. let newPos = newData.positions;
  1970. let newLabels = newData.labels;
  1971. let oldPos = this.oldData.positions;
  1972. let oldLabels = this.oldData.labels;
  1973. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1974. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1975. this.render({
  1976. positions: oldPos,
  1977. labels: newLabels
  1978. });
  1979. return this.store.map((line, i) => {
  1980. return translateHoriLine(
  1981. line, newPos[i], oldPos[i]
  1982. );
  1983. });
  1984. }
  1985. },
  1986. xAxis: {
  1987. layerClass: 'x axis',
  1988. makeElements(data) {
  1989. return data.positions.map((position, i) =>
  1990. xLine(position, data.calcLabels[i], this.constants.height,
  1991. {mode: this.constants.mode, pos: this.constants.pos})
  1992. );
  1993. },
  1994. animateElements(newData) {
  1995. let newPos = newData.positions;
  1996. let newLabels = newData.calcLabels;
  1997. let oldPos = this.oldData.positions;
  1998. let oldLabels = this.oldData.calcLabels;
  1999. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  2000. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  2001. this.render({
  2002. positions: oldPos,
  2003. calcLabels: newLabels
  2004. });
  2005. return this.store.map((line, i) => {
  2006. return translateVertLine(
  2007. line, newPos[i], oldPos[i]
  2008. );
  2009. });
  2010. }
  2011. },
  2012. yMarkers: {
  2013. layerClass: 'y-markers',
  2014. makeElements(data) {
  2015. return data.map(marker =>
  2016. yMarker(marker.position, marker.label, this.constants.width,
  2017. {pos:'right', mode: 'span', lineType: 'dashed'})
  2018. );
  2019. },
  2020. animateElements(newData) {
  2021. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  2022. let newPos = newData.map(d => d.position);
  2023. let newLabels = newData.map(d => d.label);
  2024. let oldPos = this.oldData.map(d => d.position);
  2025. let oldLabels = this.oldData.map(d => d.label);
  2026. this.render(oldPos.map((pos, i) => {
  2027. return {
  2028. position: oldPos[i],
  2029. label: newLabels[i]
  2030. }
  2031. }));
  2032. return this.store.map((line, i) => {
  2033. return translateHoriLine(
  2034. line, newPos[i], oldPos[i]
  2035. );
  2036. });
  2037. }
  2038. },
  2039. yRegions: {
  2040. layerClass: 'y-regions',
  2041. makeElements(data) {
  2042. return data.map(region =>
  2043. yRegion(region.start, region.end, this.constants.width,
  2044. region.label)
  2045. );
  2046. },
  2047. animateElements(newData) {
  2048. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  2049. let newPos = newData.map(d => d.end);
  2050. let newLabels = newData.map(d => d.label);
  2051. let newStarts = newData.map(d => d.start);
  2052. let oldPos = this.oldData.map(d => d.end);
  2053. let oldLabels = this.oldData.map(d => d.label);
  2054. let oldStarts = this.oldData.map(d => d.start);
  2055. this.render(oldPos.map((pos, i) => {
  2056. return {
  2057. start: oldStarts[i],
  2058. end: oldPos[i],
  2059. label: newLabels[i]
  2060. }
  2061. }));
  2062. let animateElements = [];
  2063. this.store.map((rectGroup, i) => {
  2064. animateElements = animateElements.concat(animateRegion(
  2065. rectGroup, newStarts[i], newPos[i], oldPos[i]
  2066. ));
  2067. });
  2068. return animateElements;
  2069. }
  2070. },
  2071. barGraph: {
  2072. layerClass: function() { return 'dataset-units dataset-bars dataset-' + this.constants.index; },
  2073. makeElements(data) {
  2074. let c = this.constants;
  2075. this.unitType = 'bar';
  2076. this.units = data.yPositions.map((y, j) => {
  2077. return datasetBar(
  2078. data.xPositions[j],
  2079. y,
  2080. data.barWidth,
  2081. c.color,
  2082. data.labels[j],
  2083. j,
  2084. data.offsets[j],
  2085. {
  2086. zeroLine: data.zeroLine,
  2087. barsWidth: data.barsWidth,
  2088. minHeight: c.minHeight
  2089. }
  2090. )
  2091. });
  2092. return this.units;
  2093. },
  2094. animateElements(newData) {
  2095. let c = this.constants;
  2096. let newXPos = newData.xPositions;
  2097. let newYPos = newData.yPositions;
  2098. let newOffsets = newData.offsets;
  2099. let newLabels = newData.labels;
  2100. let oldXPos = this.oldData.xPositions;
  2101. let oldYPos = this.oldData.yPositions;
  2102. let oldOffsets = this.oldData.offsets;
  2103. let oldLabels = this.oldData.labels;
  2104. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  2105. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  2106. [oldOffsets, newOffsets] = equilizeNoOfElements(oldOffsets, newOffsets);
  2107. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  2108. this.render({
  2109. xPositions: oldXPos,
  2110. yPositions: oldYPos,
  2111. offsets: oldOffsets,
  2112. labels: newLabels,
  2113. zeroLine: this.oldData.zeroLine,
  2114. barsWidth: this.oldData.barsWidth,
  2115. barWidth: this.oldData.barWidth,
  2116. });
  2117. let animateElements = [];
  2118. this.store.map((bar, i) => {
  2119. animateElements = animateElements.concat(animateBar(
  2120. bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i], c.index,
  2121. {zeroLine: newData.zeroLine}
  2122. ));
  2123. });
  2124. return animateElements;
  2125. }
  2126. },
  2127. lineGraph: {
  2128. layerClass: function() { return 'dataset-units dataset-line dataset-' + this.constants.index; },
  2129. makeElements(data) {
  2130. let c = this.constants;
  2131. this.unitType = 'dot';
  2132. this.paths = {};
  2133. if(!c.hideLine) {
  2134. this.paths = getPaths(
  2135. data.xPositions,
  2136. data.yPositions,
  2137. c.color,
  2138. {
  2139. heatline: c.heatline,
  2140. regionFill: c.regionFill
  2141. },
  2142. {
  2143. svgDefs: c.svgDefs,
  2144. zeroLine: data.zeroLine
  2145. }
  2146. );
  2147. }
  2148. this.units = [];
  2149. if(!c.hideDots) {
  2150. this.units = data.yPositions.map((y, j) => {
  2151. return datasetDot(
  2152. data.xPositions[j],
  2153. y,
  2154. data.radius,
  2155. c.color,
  2156. (c.valuesOverPoints ? data.values[j] : ''),
  2157. j
  2158. )
  2159. });
  2160. }
  2161. return Object.values(this.paths).concat(this.units);
  2162. },
  2163. animateElements(newData) {
  2164. let newXPos = newData.xPositions;
  2165. let newYPos = newData.yPositions;
  2166. let newValues = newData.values;
  2167. let oldXPos = this.oldData.xPositions;
  2168. let oldYPos = this.oldData.yPositions;
  2169. let oldValues = this.oldData.values;
  2170. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  2171. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  2172. [oldValues, newValues] = equilizeNoOfElements(oldValues, newValues);
  2173. this.render({
  2174. xPositions: oldXPos,
  2175. yPositions: oldYPos,
  2176. values: newValues,
  2177. zeroLine: this.oldData.zeroLine,
  2178. radius: this.oldData.radius,
  2179. });
  2180. let animateElements = [];
  2181. if(Object.keys(this.paths).length) {
  2182. animateElements = animateElements.concat(animatePath(
  2183. this.paths, newXPos, newYPos, newData.zeroLine));
  2184. }
  2185. if(this.units.length) {
  2186. this.units.map((dot, i) => {
  2187. animateElements = animateElements.concat(animateDot(
  2188. dot, newXPos[i], newYPos[i]));
  2189. });
  2190. }
  2191. return animateElements;
  2192. }
  2193. }
  2194. };
  2195. function getComponent(name, constants, getData) {
  2196. let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
  2197. let config = componentConfigs[keys[0]];
  2198. Object.assign(config, {
  2199. constants: constants,
  2200. getData: getData
  2201. });
  2202. return new ChartComponent(config);
  2203. }
  2204. class AxisChart extends BaseChart {
  2205. constructor(parent, args) {
  2206. super(parent, args);
  2207. this.barOptions = args.barOptions || {};
  2208. this.lineOptions = args.lineOptions || {};
  2209. this.type = args.type || 'line';
  2210. this.setup();
  2211. }
  2212. configure(args) {
  2213. super.configure();
  2214. args.axisOptions = args.axisOptions || {};
  2215. args.tooltipOptions = args.tooltipOptions || {};
  2216. this.config.xAxisMode = args.axisOptions.xAxisMode || 'span';
  2217. this.config.yAxisMode = args.axisOptions.yAxisMode || 'span';
  2218. this.config.xIsSeries = args.axisOptions.xIsSeries || 1;
  2219. this.config.formatTooltipX = args.tooltipOptions.formatTooltipX;
  2220. this.config.formatTooltipY = args.tooltipOptions.formatTooltipY;
  2221. this.config.valuesOverPoints = args.valuesOverPoints;
  2222. }
  2223. setMargins() {
  2224. super.setMargins();
  2225. this.leftMargin = Y_AXIS_MARGIN;
  2226. this.rightMargin = Y_AXIS_MARGIN;
  2227. }
  2228. prepareData(data=this.data) {
  2229. return dataPrep(data, this.type);
  2230. }
  2231. prepareFirstData(data=this.data) {
  2232. return zeroDataPrep(data);
  2233. }
  2234. calc(onlyWidthChange = false) {
  2235. this.calcXPositions();
  2236. if(onlyWidthChange) return;
  2237. this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
  2238. }
  2239. calcXPositions(s=this.state) {
  2240. let labels = this.data.labels;
  2241. s.datasetLength = labels.length;
  2242. s.unitWidth = this.width/(s.datasetLength);
  2243. // Default, as per bar, and mixed. Only line will be a special case
  2244. s.xOffset = s.unitWidth/2;
  2245. // // For a pure Line Chart
  2246. // s.unitWidth = this.width/(s.datasetLength - 1);
  2247. // s.xOffset = 0;
  2248. s.xAxis = {
  2249. labels: labels,
  2250. positions: labels.map((d, i) =>
  2251. floatTwo(s.xOffset + i * s.unitWidth)
  2252. )
  2253. };
  2254. }
  2255. calcYAxisParameters(dataValues, withMinimum = 'false') {
  2256. const yPts = calcChartIntervals(dataValues, withMinimum);
  2257. const scaleMultiplier = this.height / getValueRange(yPts);
  2258. const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
  2259. const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  2260. this.state.yAxis = {
  2261. labels: yPts,
  2262. positions: yPts.map(d => zeroLine - d * scaleMultiplier),
  2263. scaleMultiplier: scaleMultiplier,
  2264. zeroLine: zeroLine,
  2265. };
  2266. // Dependent if above changes
  2267. this.calcDatasetPoints();
  2268. this.calcYExtremes();
  2269. this.calcYRegions();
  2270. }
  2271. calcDatasetPoints() {
  2272. let s = this.state;
  2273. let scaleAll = values => values.map(val => scale(val, s.yAxis));
  2274. s.datasets = this.data.datasets.map((d, i) => {
  2275. let values = d.values;
  2276. let cumulativeYs = d.cumulativeYs || [];
  2277. return {
  2278. name: d.name,
  2279. index: i,
  2280. chartType: d.chartType,
  2281. values: values,
  2282. yPositions: scaleAll(values),
  2283. cumulativeYs: cumulativeYs,
  2284. cumulativeYPos: scaleAll(cumulativeYs),
  2285. };
  2286. });
  2287. }
  2288. calcYExtremes() {
  2289. let s = this.state;
  2290. if(this.barOptions.stacked) {
  2291. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
  2292. return;
  2293. }
  2294. s.yExtremes = new Array(s.datasetLength).fill(9999);
  2295. s.datasets.map((d, i) => {
  2296. d.yPositions.map((pos, j) => {
  2297. if(pos < s.yExtremes[j]) {
  2298. s.yExtremes[j] = pos;
  2299. }
  2300. });
  2301. });
  2302. }
  2303. calcYRegions() {
  2304. let s = this.state;
  2305. if(this.data.yMarkers) {
  2306. this.state.yMarkers = this.data.yMarkers.map(d => {
  2307. d.position = scale(d.value, s.yAxis);
  2308. if(!d.label.includes(':')) {
  2309. d.label += ': ' + d.value;
  2310. }
  2311. return d;
  2312. });
  2313. }
  2314. if(this.data.yRegions) {
  2315. this.state.yRegions = this.data.yRegions.map(d => {
  2316. d.start = scale(d.start, s.yAxis);
  2317. d.end = scale(d.end, s.yAxis);
  2318. return d;
  2319. });
  2320. }
  2321. }
  2322. getAllYValues() {
  2323. // TODO: yMarkers, regions, sums, every Y value ever
  2324. let key = 'values';
  2325. if(this.barOptions.stacked) {
  2326. key = 'cumulativeYs';
  2327. let cumulative = new Array(this.state.datasetLength).fill(0);
  2328. this.data.datasets.map((d, i) => {
  2329. let values = this.data.datasets[i].values;
  2330. d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
  2331. });
  2332. }
  2333. return [].concat(...this.data.datasets.map(d => d[key]));
  2334. }
  2335. setupComponents() {
  2336. let componentConfigs = [
  2337. [
  2338. 'yAxis',
  2339. {
  2340. mode: this.config.yAxisMode,
  2341. width: this.width,
  2342. // pos: 'right'
  2343. },
  2344. function() {
  2345. return this.state.yAxis;
  2346. }.bind(this)
  2347. ],
  2348. [
  2349. 'xAxis',
  2350. {
  2351. mode: this.config.xAxisMode,
  2352. height: this.height,
  2353. // pos: 'right'
  2354. },
  2355. function() {
  2356. let s = this.state;
  2357. s.xAxis.calcLabels = getShortenedLabels(this.width,
  2358. s.xAxis.labels, this.config.xIsSeries);
  2359. return s.xAxis;
  2360. }.bind(this)
  2361. ],
  2362. [
  2363. 'yRegions',
  2364. {
  2365. width: this.width,
  2366. pos: 'right'
  2367. },
  2368. function() {
  2369. return this.state.yRegions;
  2370. }.bind(this)
  2371. ],
  2372. ];
  2373. let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
  2374. let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
  2375. // console.log('barDatasets', barDatasets, this.state.datasets);
  2376. let barsConfigs = barDatasets.map(d => {
  2377. let index = d.index;
  2378. return [
  2379. 'barGraph' + '-' + d.index,
  2380. {
  2381. index: index,
  2382. color: this.colors[index],
  2383. stacked: this.barOptions.stacked,
  2384. // same for all datasets
  2385. valuesOverPoints: this.config.valuesOverPoints,
  2386. minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
  2387. },
  2388. function() {
  2389. let s = this.state;
  2390. let d = s.datasets[index];
  2391. let stacked = this.barOptions.stacked;
  2392. let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
  2393. let barsWidth = s.unitWidth * (1 - spaceRatio);
  2394. let barWidth = barsWidth/(stacked ? 1 : barDatasets.length);
  2395. let xPositions = s.xAxis.positions.map(x => x - barsWidth/2);
  2396. if(!stacked) {
  2397. xPositions = xPositions.map(p => p + barWidth * index);
  2398. }
  2399. let labels = new Array(s.datasetLength).fill('');
  2400. if(this.valuesOverPoints) {
  2401. if(stacked && d.index === s.datasets.length - 1) {
  2402. labels = d.cumulativeYs;
  2403. } else {
  2404. labels = d.values;
  2405. }
  2406. }
  2407. let offsets = new Array(s.datasetLength).fill(0);
  2408. if(stacked) {
  2409. offsets = d.yPositions.map((y, j) => y - d.cumulativeYPos[j]);
  2410. }
  2411. return {
  2412. xPositions: xPositions,
  2413. yPositions: d.yPositions,
  2414. offsets: offsets,
  2415. // values: d.values,
  2416. labels: labels,
  2417. zeroLine: s.yAxis.zeroLine,
  2418. barsWidth: barsWidth,
  2419. barWidth: barWidth,
  2420. };
  2421. }.bind(this)
  2422. ];
  2423. });
  2424. let lineConfigs = lineDatasets.map(d => {
  2425. let index = d.index;
  2426. return [
  2427. 'lineGraph' + '-' + d.index,
  2428. {
  2429. index: index,
  2430. color: this.colors[index],
  2431. svgDefs: this.svgDefs,
  2432. heatline: this.lineOptions.heatline,
  2433. regionFill: this.lineOptions.regionFill,
  2434. hideDots: this.lineOptions.hideDots,
  2435. hideLine: this.lineOptions.hideLine,
  2436. // same for all datasets
  2437. valuesOverPoints: this.config.valuesOverPoints,
  2438. },
  2439. function() {
  2440. let s = this.state;
  2441. let d = s.datasets[index];
  2442. return {
  2443. xPositions: s.xAxis.positions,
  2444. yPositions: d.yPositions,
  2445. values: d.values,
  2446. zeroLine: s.yAxis.zeroLine,
  2447. radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE,
  2448. };
  2449. }.bind(this)
  2450. ];
  2451. });
  2452. let markerConfigs = [
  2453. [
  2454. 'yMarkers',
  2455. {
  2456. width: this.width,
  2457. pos: 'right'
  2458. },
  2459. function() {
  2460. return this.state.yMarkers;
  2461. }.bind(this)
  2462. ]
  2463. ];
  2464. componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
  2465. let optionals = ['yMarkers', 'yRegions'];
  2466. this.dataUnitComponents = [];
  2467. this.components = new Map(componentConfigs
  2468. .filter(args => !optionals.includes(args[0]) || this.state[args[0]])
  2469. .map(args => {
  2470. let component = getComponent(...args);
  2471. if(args[0].includes('lineGraph') || args[0].includes('barGraph')) {
  2472. this.dataUnitComponents.push(component);
  2473. }
  2474. return [args[0], component];
  2475. }));
  2476. }
  2477. bindTooltip() {
  2478. // NOTE: could be in tooltip itself, as it is a given functionality for its parent
  2479. this.chartWrapper.addEventListener('mousemove', (e) => {
  2480. let o = getOffset(this.chartWrapper);
  2481. let relX = e.pageX - o.left - this.leftMargin;
  2482. let relY = e.pageY - o.top - this.translateY;
  2483. if(relY < this.height + this.translateY * 2) {
  2484. this.mapTooltipXPosition(relX);
  2485. } else {
  2486. this.tip.hide_tip();
  2487. }
  2488. });
  2489. }
  2490. mapTooltipXPosition(relX) {
  2491. let s = this.state;
  2492. if(!s.yExtremes) return;
  2493. let titles = s.xAxis.labels;
  2494. if(this.formatTooltipX && this.formatTooltipX(titles[0])) {
  2495. titles = titles.map(d=>this.formatTooltipX(d));
  2496. }
  2497. let formatY = this.formatTooltipY && this.formatTooltipY(this.y[0].values[0]);
  2498. for(var i=s.datasetLength - 1; i >= 0 ; i--) {
  2499. let xVal = s.xAxis.positions[i];
  2500. // let delta = i === 0 ? s.unitWidth : xVal - s.xAxis.positions[i-1];
  2501. if(relX > xVal - s.unitWidth/2) {
  2502. let x = xVal + this.leftMargin;
  2503. let y = s.yExtremes[i] + this.translateY;
  2504. let values = this.data.datasets.map((set, j) => {
  2505. return {
  2506. title: set.title,
  2507. value: formatY ? this.formatTooltipY(set.values[i]) : set.values[i],
  2508. color: this.colors[j],
  2509. };
  2510. });
  2511. this.tip.set_values(x, y, titles[i], '', values);
  2512. this.tip.show_tip();
  2513. break;
  2514. }
  2515. }
  2516. }
  2517. makeOverlay() {
  2518. if(this.overlayGuides) {
  2519. this.overlayGuides.forEach(g => {
  2520. let o = g.overlay;
  2521. o.parentNode.removeChild(o);
  2522. });
  2523. }
  2524. this.overlayGuides = this.dataUnitComponents.map(c => {
  2525. return {
  2526. type: c.unitType,
  2527. overlay: undefined,
  2528. units: c.units,
  2529. }
  2530. });
  2531. if(this.state.currentIndex === undefined) {
  2532. this.state.currentIndex = this.state.datasetLength - 1;
  2533. }
  2534. // Render overlays
  2535. this.overlayGuides.map(d => {
  2536. let currentUnit = d.units[this.state.currentIndex];
  2537. d.overlay = makeOverlay[d.type](currentUnit);
  2538. this.drawArea.appendChild(d.overlay);
  2539. });
  2540. }
  2541. updateOverlayGuides() {
  2542. if(this.overlayGuides) {
  2543. this.overlayGuides.forEach(g => {
  2544. let o = g.overlay;
  2545. o.parentNode.removeChild(o);
  2546. });
  2547. }
  2548. }
  2549. bindOverlay() {
  2550. // on event, update overlay
  2551. this.parent.addEventListener('data-select', (e) => {
  2552. this.updateOverlay();
  2553. });
  2554. }
  2555. bindUnits(units_array) {
  2556. // units_array.map(unit => {
  2557. // unit.addEventListener('click', () => {
  2558. // let index = unit.getAttribute('data-point-index');
  2559. // this.setCurrentDataPoint(index);
  2560. // });
  2561. // });
  2562. }
  2563. updateOverlay() {
  2564. this.overlayGuides.map(d => {
  2565. let currentUnit = d.units[this.state.currentIndex];
  2566. updateOverlay[d.type](currentUnit, d.overlay);
  2567. });
  2568. }
  2569. onLeftArrow() {
  2570. this.setCurrentDataPoint(this.state.currentIndex - 1);
  2571. }
  2572. onRightArrow() {
  2573. this.setCurrentDataPoint(this.state.currentIndex + 1);
  2574. }
  2575. getDataPoint(index=this.state.currentIndex) {
  2576. // check for length
  2577. let data_point = {
  2578. index: index
  2579. };
  2580. // let y = this.y[0];
  2581. // ['svg_units', 'yUnitPositions', 'values'].map(key => {
  2582. // let data_key = key.slice(0, key.length-1);
  2583. // data_point[data_key] = y[key][index];
  2584. // });
  2585. // data_point.label = this.xAxis.labels[index];
  2586. return data_point;
  2587. }
  2588. setCurrentDataPoint(index) {
  2589. let s = this.state;
  2590. index = parseInt(index);
  2591. if(index < 0) index = 0;
  2592. if(index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
  2593. if(index === s.currentIndex) return;
  2594. s.currentIndex = index;
  2595. fire(this.parent, "data-select", this.getDataPoint());
  2596. }
  2597. // API
  2598. addDataPoint(label, datasetValues, index=this.state.datasetLength) {
  2599. super.addDataPoint(label, datasetValues, index);
  2600. // console.log(label, datasetValues, this.data.labels);
  2601. this.data.labels.splice(index, 0, label);
  2602. this.data.datasets.map((d, i) => {
  2603. d.values.splice(index, 0, datasetValues[i]);
  2604. });
  2605. // console.log(this.data);
  2606. this.update(this.data);
  2607. }
  2608. removeDataPoint(index = this.state.datasetLength-1) {
  2609. super.removeDataPoint(index);
  2610. this.data.labels.splice(index, 1);
  2611. this.data.datasets.map(d => {
  2612. d.values.splice(index, 1);
  2613. });
  2614. this.update(this.data);
  2615. }
  2616. // getDataPoint(index = 0) {}
  2617. // setCurrentDataPoint(point) {}
  2618. updateDataset(datasetValues, index=0) {
  2619. this.data.datasets[index].values = datasetValues;
  2620. this.update(this.data);
  2621. }
  2622. // addDataset(dataset, index) {}
  2623. // removeDataset(index = 0) {}
  2624. // updateDatasets(datasets) {}
  2625. // updateDataPoint(dataPoint, index = 0) {}
  2626. // addDataPoint(dataPoint, index = 0) {}
  2627. // removeDataPoint(index = 0) {}
  2628. }
  2629. // keep a binding at the end of chart
  2630. const chartTypes = {
  2631. // multiaxis: MultiAxisChart,
  2632. percentage: PercentageChart,
  2633. heatmap: Heatmap,
  2634. pie: PieChart
  2635. };
  2636. function getChartByType(chartType = 'line', parent, options) {
  2637. if(chartType === 'line') {
  2638. options.type = 'line';
  2639. return new AxisChart(parent, options);
  2640. } else if (chartType === 'bar') {
  2641. options.type = 'bar';
  2642. return new AxisChart(parent, options);
  2643. } else if (chartType === 'axis-mixed') {
  2644. options.type = 'line';
  2645. return new AxisChart(parent, options);
  2646. }
  2647. if (!chartTypes[chartType]) {
  2648. console.error("Undefined chart type: " + chartType);
  2649. return;
  2650. }
  2651. return new chartTypes[chartType](parent, options);
  2652. }
  2653. class Chart {
  2654. constructor(parent, options) {
  2655. return getChartByType(options.type, parent, options);
  2656. }
  2657. }
  2658. export default Chart;