25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

2624 satır
61 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. class SvgTip {
  57. constructor({
  58. parent = null,
  59. colors = []
  60. }) {
  61. this.parent = parent;
  62. this.colors = colors;
  63. this.title_name = '';
  64. this.title_value = '';
  65. this.list_values = [];
  66. this.title_value_first = 0;
  67. this.x = 0;
  68. this.y = 0;
  69. this.top = 0;
  70. this.left = 0;
  71. this.setup();
  72. }
  73. setup() {
  74. this.make_tooltip();
  75. }
  76. refresh() {
  77. this.fill();
  78. this.calc_position();
  79. // this.show_tip();
  80. }
  81. make_tooltip() {
  82. this.container = $.create('div', {
  83. inside: this.parent,
  84. className: 'graph-svg-tip comparison',
  85. innerHTML: `<span class="title"></span>
  86. <ul class="data-point-list"></ul>
  87. <div class="svg-pointer"></div>`
  88. });
  89. this.hide_tip();
  90. this.title = this.container.querySelector('.title');
  91. this.data_point_list = this.container.querySelector('.data-point-list');
  92. this.parent.addEventListener('mouseleave', () => {
  93. this.hide_tip();
  94. });
  95. }
  96. fill() {
  97. let title;
  98. if(this.title_value_first) {
  99. title = `<strong>${this.title_value}</strong>${this.title_name}`;
  100. } else {
  101. title = `${this.title_name}<strong>${this.title_value}</strong>`;
  102. }
  103. this.title.innerHTML = title;
  104. this.data_point_list.innerHTML = '';
  105. this.list_values.map((set, i) => {
  106. const color = this.colors[i] || 'black';
  107. let li = $.create('li', {
  108. styles: {
  109. 'border-top': `3px solid ${color}`
  110. },
  111. innerHTML: `<strong style="display: block;">${ set.value === 0 || set.value ? set.value : '' }</strong>
  112. ${set.title ? set.title : '' }`
  113. });
  114. this.data_point_list.appendChild(li);
  115. });
  116. }
  117. calc_position() {
  118. let width = this.container.offsetWidth;
  119. this.top = this.y - this.container.offsetHeight;
  120. this.left = this.x - width/2;
  121. let max_left = this.parent.offsetWidth - width;
  122. let pointer = this.container.querySelector('.svg-pointer');
  123. if(this.left < 0) {
  124. pointer.style.left = `calc(50% - ${-1 * this.left}px)`;
  125. this.left = 0;
  126. } else if(this.left > max_left) {
  127. let delta = this.left - max_left;
  128. let pointer_offset = `calc(50% + ${delta}px)`;
  129. pointer.style.left = pointer_offset;
  130. this.left = max_left;
  131. } else {
  132. pointer.style.left = `50%`;
  133. }
  134. }
  135. set_values(x, y, title_name = '', title_value = '', list_values = [], title_value_first = 0) {
  136. this.title_name = title_name;
  137. this.title_value = title_value;
  138. this.list_values = list_values;
  139. this.x = x;
  140. this.y = y;
  141. this.title_value_first = title_value_first;
  142. this.refresh();
  143. }
  144. hide_tip() {
  145. this.container.style.top = '0px';
  146. this.container.style.left = '0px';
  147. this.container.style.opacity = '0';
  148. }
  149. show_tip() {
  150. this.container.style.top = this.top + 'px';
  151. this.container.style.left = this.left + 'px';
  152. this.container.style.opacity = '1';
  153. }
  154. }
  155. /**
  156. * Returns the value of a number upto 2 decimal places.
  157. * @param {Number} d Any number
  158. */
  159. function floatTwo(d) {
  160. return parseFloat(d.toFixed(2));
  161. }
  162. /**
  163. * Returns whether or not two given arrays are equal.
  164. * @param {Array} arr1 First array
  165. * @param {Array} arr2 Second array
  166. */
  167. /**
  168. * Shuffles array in place. ES6 version
  169. * @param {Array} array An array containing the items.
  170. */
  171. /**
  172. * Fill an array with extra points
  173. * @param {Array} array Array
  174. * @param {Number} count number of filler elements
  175. * @param {Object} element element to fill with
  176. * @param {Boolean} start fill at start?
  177. */
  178. function fillArray(array, count, element, start=false) {
  179. if(!element) {
  180. element = start ? array[0] : array[array.length - 1];
  181. }
  182. let fillerArray = new Array(Math.abs(count)).fill(element);
  183. array = start ? fillerArray.concat(array) : array.concat(fillerArray);
  184. return array;
  185. }
  186. /**
  187. * Returns pixel width of string.
  188. * @param {String} string
  189. * @param {Number} charWidth Width of single char in pixels
  190. */
  191. const MIN_BAR_PERCENT_HEIGHT = 0.01;
  192. function getBarHeightAndYAttr(yTop, zeroLine, totalHeight) {
  193. let height, y;
  194. if (yTop <= zeroLine) {
  195. height = zeroLine - yTop;
  196. y = yTop;
  197. // In case of invisible bars
  198. if(height === 0) {
  199. height = totalHeight * MIN_BAR_PERCENT_HEIGHT;
  200. y -= height;
  201. }
  202. } else {
  203. height = yTop - zeroLine;
  204. y = zeroLine;
  205. // In case of invisible bars
  206. if(height === 0) {
  207. height = totalHeight * MIN_BAR_PERCENT_HEIGHT;
  208. }
  209. }
  210. return [height, y];
  211. }
  212. // let char_width = 8;
  213. // let allowed_space = avgUnitWidth * 1.5;
  214. // let allowed_letters = allowed_space / 8;
  215. // return values.map((value, i) => {
  216. // let space_taken = getStringWidth(value, char_width) + 2;
  217. // if(space_taken > allowed_space) {
  218. // if(is_series) {
  219. // // Skip some axis lines if X axis is a series
  220. // let skips = 1;
  221. // while((space_taken/skips)*2 > allowed_space) {
  222. // skips++;
  223. // }
  224. // if(i % skips !== 0) {
  225. // return;
  226. // }
  227. // } else {
  228. // value = value.slice(0, allowed_letters-3) + " ...";
  229. // }
  230. // }
  231. const AXIS_TICK_LENGTH = 6;
  232. const LABEL_MARGIN = 4;
  233. const FONT_SIZE = 10;
  234. const BASE_LINE_COLOR = '#dadada';
  235. function $$1(expr, con) {
  236. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  237. }
  238. function createSVG(tag, o) {
  239. var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  240. for (var i in o) {
  241. var val = o[i];
  242. if (i === "inside") {
  243. $$1(val).appendChild(element);
  244. }
  245. else if (i === "around") {
  246. var ref = $$1(val);
  247. ref.parentNode.insertBefore(element, ref);
  248. element.appendChild(ref);
  249. } else if (i === "styles") {
  250. if(typeof val === "object") {
  251. Object.keys(val).map(prop => {
  252. element.style[prop] = val[prop];
  253. });
  254. }
  255. } else {
  256. if(i === "className") { i = "class"; }
  257. if(i === "innerHTML") {
  258. element['textContent'] = val;
  259. } else {
  260. element.setAttribute(i, val);
  261. }
  262. }
  263. }
  264. return element;
  265. }
  266. function renderVerticalGradient(svgDefElem, gradientId) {
  267. return createSVG('linearGradient', {
  268. inside: svgDefElem,
  269. id: gradientId,
  270. x1: 0,
  271. x2: 0,
  272. y1: 0,
  273. y2: 1
  274. });
  275. }
  276. function setGradientStop(gradElem, offset, color, opacity) {
  277. return createSVG('stop', {
  278. 'inside': gradElem,
  279. 'style': `stop-color: ${color}`,
  280. 'offset': offset,
  281. 'stop-opacity': opacity
  282. });
  283. }
  284. function makeSVGContainer(parent, className, width, height) {
  285. return createSVG('svg', {
  286. className: className,
  287. inside: parent,
  288. width: width,
  289. height: height
  290. });
  291. }
  292. function makeSVGDefs(svgContainer) {
  293. return createSVG('defs', {
  294. inside: svgContainer,
  295. });
  296. }
  297. function makeSVGGroup(parent, className, transform='') {
  298. return createSVG('g', {
  299. className: className,
  300. inside: parent,
  301. transform: transform
  302. });
  303. }
  304. function makePath(pathStr, className='', stroke='none', fill='none') {
  305. return createSVG('path', {
  306. className: className,
  307. d: pathStr,
  308. styles: {
  309. stroke: stroke,
  310. fill: fill
  311. }
  312. });
  313. }
  314. function makeGradient(svgDefElem, color, lighter = false) {
  315. let gradientId ='path-fill-gradient' + '-' + color;
  316. let gradientDef = renderVerticalGradient(svgDefElem, gradientId);
  317. let opacities = [1, 0.6, 0.2];
  318. if(lighter) {
  319. opacities = [0.4, 0.2, 0];
  320. }
  321. setGradientStop(gradientDef, "0%", color, opacities[0]);
  322. setGradientStop(gradientDef, "50%", color, opacities[1]);
  323. setGradientStop(gradientDef, "100%", color, opacities[2]);
  324. return gradientId;
  325. }
  326. function makeHeatSquare(className, x, y, size, fill='none', data={}) {
  327. let args = {
  328. className: className,
  329. x: x,
  330. y: y,
  331. width: size,
  332. height: size,
  333. fill: fill
  334. };
  335. Object.keys(data).map(key => {
  336. args[key] = data[key];
  337. });
  338. return createSVG("rect", args);
  339. }
  340. function makeText(className, x, y, content) {
  341. return createSVG('text', {
  342. className: className,
  343. x: x,
  344. y: y,
  345. dy: (FONT_SIZE / 2) + 'px',
  346. 'font-size': FONT_SIZE + 'px',
  347. innerHTML: content
  348. });
  349. }
  350. function makeVertLine(x, label, y1, y2, options={}) {
  351. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  352. let l = createSVG('line', {
  353. className: 'line-vertical ' + options.className,
  354. x1: 0,
  355. x2: 0,
  356. y1: y1,
  357. y2: y2,
  358. styles: {
  359. stroke: options.stroke
  360. }
  361. });
  362. let text = createSVG('text', {
  363. x: 0,
  364. y: y1 > y2 ? y1 + LABEL_MARGIN : y1 - LABEL_MARGIN - FONT_SIZE,
  365. dy: FONT_SIZE + 'px',
  366. 'font-size': FONT_SIZE + 'px',
  367. 'text-anchor': 'middle',
  368. innerHTML: label
  369. });
  370. let line = createSVG('g', {
  371. transform: `translate(${ x }, 0)`
  372. });
  373. line.appendChild(l);
  374. line.appendChild(text);
  375. return line;
  376. }
  377. function makeHoriLine(y, label, x1, x2, options={}) {
  378. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  379. if(!options.lineType) options.lineType = '';
  380. let className = 'line-horizontal ' + options.className +
  381. (options.lineType === "dashed" ? "dashed": "");
  382. let l = createSVG('line', {
  383. className: className,
  384. x1: x1,
  385. x2: x2,
  386. y1: 0,
  387. y2: 0,
  388. styles: {
  389. stroke: options.stroke
  390. }
  391. });
  392. let text = createSVG('text', {
  393. x: x1 < x2 ? x1 - LABEL_MARGIN : x1 + LABEL_MARGIN,
  394. y: 0,
  395. dy: (FONT_SIZE / 2 - 2) + 'px',
  396. 'font-size': FONT_SIZE + 'px',
  397. 'text-anchor': x1 < x2 ? 'end' : 'start',
  398. innerHTML: label+""
  399. });
  400. let line = createSVG('g', {
  401. transform: `translate(0, ${ y })`,
  402. 'stroke-opacity': 1
  403. });
  404. if(text === 0 || text === '0') {
  405. line.style.stroke = "rgba(27, 31, 35, 0.6)";
  406. }
  407. line.appendChild(l);
  408. line.appendChild(text);
  409. return line;
  410. }
  411. class AxisChartRenderer {
  412. constructor(state) {
  413. this.refreshState(state);
  414. }
  415. refreshState(state) {
  416. this.totalHeight = state.totalHeight;
  417. this.totalWidth = state.totalWidth;
  418. this.zeroLine = state.zeroLine;
  419. this.unitWidth = state.unitWidth;
  420. this.xAxisMode = state.xAxisMode;
  421. this.yAxisMode = state.yAxisMode;
  422. }
  423. setZeroline(zeroLine) {
  424. this.zeroLine = zeroLine;
  425. }
  426. bar(x, yTop, args, color, index, datasetIndex, noOfDatasets, prevX, prevY) {
  427. let totalWidth = this.unitWidth - args.spaceWidth;
  428. let startX = x - totalWidth/2;
  429. // temp commented
  430. // let width = totalWidth / noOfDatasets;
  431. // let currentX = startX + width * datasetIndex;
  432. // temp
  433. let width = totalWidth;
  434. let currentX = startX;
  435. let [height, y] = getBarHeightAndYAttr(yTop, this.zeroLine, this.totalHeight);
  436. return createSVG('rect', {
  437. className: `bar mini`,
  438. style: `fill: ${color}`,
  439. 'data-point-index': index,
  440. x: currentX,
  441. y: y,
  442. width: width,
  443. height: height
  444. });
  445. }
  446. dot(x, y, args, color, index) {
  447. return createSVG('circle', {
  448. style: `fill: ${color}`,
  449. 'data-point-index': index,
  450. cx: x,
  451. cy: y,
  452. r: args.radius
  453. });
  454. }
  455. xLine(x, label, options={}) {
  456. if(!options.pos) options.pos = 'bottom';
  457. if(!options.offset) options.offset = 0;
  458. if(!options.mode) options.mode = this.xAxisMode;
  459. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  460. if(!options.className) options.className = '';
  461. // Draw X axis line in span/tick mode with optional label
  462. // y2(span)
  463. // |
  464. // |
  465. // x line |
  466. // |
  467. // |
  468. // ---------------------+-- y2(tick)
  469. // |
  470. // y1
  471. let y1 = this.totalHeight + AXIS_TICK_LENGTH;
  472. let y2 = options.mode === 'span' ? -1 * AXIS_TICK_LENGTH : this.totalHeight;
  473. if(options.mode === 'tick' && options.pos === 'top') {
  474. // top axis ticks
  475. y1 = -1 * AXIS_TICK_LENGTH;
  476. y2 = 0;
  477. }
  478. return makeVertLine(x, label, y1, y2, {
  479. stroke: options.stroke,
  480. className: options.className
  481. });
  482. }
  483. yLine(y, label, options={}) {
  484. if(!options.pos) options.pos = 'left';
  485. if(!options.offset) options.offset = 0;
  486. if(!options.mode) options.mode = this.yAxisMode;
  487. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  488. if(!options.className) options.className = '';
  489. let x1 = -1 * AXIS_TICK_LENGTH;
  490. let x2 = options.mode === 'span' ? this.totalWidth + AXIS_TICK_LENGTH : 0;
  491. if(options.mode === 'tick' && options.pos === 'right') {
  492. x1 = this.totalWidth + AXIS_TICK_LENGTH;
  493. x2 = this.totalWidth;
  494. }
  495. x1 += options.offset;
  496. x2 += options.offset;
  497. return makeHoriLine(y, label, x1, x2, {
  498. stroke: options.stroke,
  499. className: options.className
  500. });
  501. }
  502. xMarker() {}
  503. yMarker() {}
  504. xRegion() {}
  505. yRegion() {}
  506. }
  507. const PRESET_COLOR_MAP = {
  508. 'light-blue': '#7cd6fd',
  509. 'blue': '#5e64ff',
  510. 'violet': '#743ee2',
  511. 'red': '#ff5858',
  512. 'orange': '#ffa00a',
  513. 'yellow': '#feef72',
  514. 'green': '#28a745',
  515. 'light-green': '#98d85b',
  516. 'purple': '#b554ff',
  517. 'magenta': '#ffa3ef',
  518. 'black': '#36114C',
  519. 'grey': '#bdd3e6',
  520. 'light-grey': '#f0f4f7',
  521. 'dark-grey': '#b8c2cc'
  522. };
  523. const DEFAULT_COLORS = ['light-blue', 'blue', 'violet', 'red', 'orange',
  524. 'yellow', 'green', 'light-green', 'purple', 'magenta'];
  525. function limitColor(r){
  526. if (r > 255) return 255;
  527. else if (r < 0) return 0;
  528. return r;
  529. }
  530. function lightenDarkenColor(color, amt) {
  531. let col = getColor(color);
  532. let usePound = false;
  533. if (col[0] == "#") {
  534. col = col.slice(1);
  535. usePound = true;
  536. }
  537. let num = parseInt(col,16);
  538. let r = limitColor((num >> 16) + amt);
  539. let b = limitColor(((num >> 8) & 0x00FF) + amt);
  540. let g = limitColor((num & 0x0000FF) + amt);
  541. return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
  542. }
  543. function isValidColor(string) {
  544. // https://stackoverflow.com/a/8027444/6495043
  545. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(string);
  546. }
  547. const getColor = (color) => {
  548. return PRESET_COLOR_MAP[color] || color;
  549. };
  550. const ALL_CHART_TYPES = ['line', 'scatter', 'bar', 'percentage', 'heatmap', 'pie'];
  551. const COMPATIBLE_CHARTS = {
  552. bar: ['line', 'scatter', 'percentage', 'pie'],
  553. line: ['scatter', 'bar', 'percentage', 'pie'],
  554. pie: ['line', 'scatter', 'percentage', 'bar'],
  555. scatter: ['line', 'bar', 'percentage', 'pie'],
  556. percentage: ['bar', 'line', 'scatter', 'pie'],
  557. heatmap: []
  558. };
  559. // Needs structure as per only labels/datasets
  560. const COLOR_COMPATIBLE_CHARTS = {
  561. bar: ['line', 'scatter'],
  562. line: ['scatter', 'bar'],
  563. pie: ['percentage'],
  564. scatter: ['line', 'bar'],
  565. percentage: ['pie'],
  566. heatmap: []
  567. };
  568. function getDifferentChart(type, current_type, args) {
  569. if(type === current_type) return;
  570. if(!ALL_CHART_TYPES.includes(type)) {
  571. console.error(`'${type}' is not a valid chart type.`);
  572. }
  573. if(!COMPATIBLE_CHARTS[current_type].includes(type)) {
  574. console.error(`'${current_type}' chart cannot be converted to a '${type}' chart.`);
  575. }
  576. // whether the new chart can use the existing colors
  577. const useColor = COLOR_COMPATIBLE_CHARTS[current_type].includes(type);
  578. // Okay, this is anticlimactic
  579. // this function will need to actually be 'changeChartType(type)'
  580. // that will update only the required elements, but for now ...
  581. return new Chart({
  582. parent: args.parent,
  583. title: args.title,
  584. data: args.data,
  585. type: type,
  586. height: args.height,
  587. colors: useColor ? args.colors : undefined
  588. });
  589. }
  590. class BaseChart {
  591. constructor({
  592. height = 240,
  593. title = '',
  594. subtitle = '',
  595. colors = [],
  596. isNavigable = 0,
  597. showLegend = 1,
  598. type = '',
  599. parent,
  600. data
  601. }) {
  602. this.rawChartArgs = arguments[0];
  603. this.parent = typeof parent === 'string' ? document.querySelector(parent) : parent;
  604. this.title = title;
  605. this.subtitle = subtitle;
  606. this.argHeight = height;
  607. this.isNavigable = isNavigable;
  608. if(this.isNavigable) {
  609. this.currentIndex = 0;
  610. }
  611. this.configure(arguments[0]);
  612. }
  613. configure(args) {
  614. // Make a this.config, that has stuff like showTooltip,
  615. // showLegend, which then all functions will check
  616. this.setColors();
  617. // constants
  618. this.config = {
  619. showTooltip: 1, // calculate
  620. showLegend: 1,
  621. isNavigable: 0,
  622. // animate: 1
  623. animate: 0
  624. };
  625. this.state = {
  626. colors: this.colors
  627. };
  628. }
  629. setColors() {
  630. let args = this.rawChartArgs;
  631. // Needs structure as per only labels/datasets, from config
  632. const list = args.type === 'percentage' || args.type === 'pie'
  633. ? args.data.labels
  634. : args.data.datasets;
  635. if(!args.colors || (list && args.colors.length < list.length)) {
  636. this.colors = DEFAULT_COLORS;
  637. } else {
  638. this.colors = args.colors;
  639. }
  640. this.colors = this.colors.map(color => getColor(color));
  641. }
  642. setMargins() {
  643. // TODO: think for all
  644. let height = this.argHeight;
  645. this.baseHeight = height;
  646. this.height = height - 40; // change
  647. this.translateY = 20;
  648. this.setHorizontalMargin();
  649. }
  650. setHorizontalMargin() {
  651. this.translateXLeft = 60;
  652. this.translateXRight = 40;
  653. }
  654. validate(){
  655. if(!this.parent) {
  656. console.error("No parent element to render on was provided.");
  657. return false;
  658. }
  659. if(!this.parseData()) {
  660. return false;
  661. }
  662. return true;
  663. }
  664. parseData() {
  665. let data = this.rawChartArgs.data;
  666. let valid = this.checkData(data);
  667. if(!valid) return false;
  668. if(!this.config.animate) {
  669. this.data = data;
  670. } else {
  671. [this.data, this.firstUpdateData] =
  672. this.getFirstUpdateData(data);
  673. }
  674. return true;
  675. }
  676. checkData() {}
  677. getFirstUpdateData() {}
  678. setup() {
  679. if(this.validate()) {
  680. this._setup();
  681. }
  682. }
  683. _setup() {
  684. this.bindWindowEvents();
  685. this.setupConstants();
  686. this.prepareData();
  687. this.setupComponents();
  688. this.setMargins();
  689. this.makeContainer();
  690. this.makeTooltip(); // without binding
  691. this.draw(true);
  692. }
  693. bindWindowEvents() {
  694. window.addEventListener('resize orientationchange', () => this.draw());
  695. }
  696. setupConstants() {}
  697. setupComponents() {
  698. // Components config
  699. this.components = [];
  700. }
  701. makeContainer() {
  702. this.container = $.create('div', {
  703. className: 'chart-container',
  704. innerHTML: `<h6 class="title">${this.title}</h6>
  705. <h6 class="sub-title uppercase">${this.subtitle}</h6>
  706. <div class="frappe-chart graphics"></div>
  707. <div class="graph-stats-container"></div>`
  708. });
  709. // Chart needs a dedicated parent element
  710. this.parent.innerHTML = '';
  711. this.parent.appendChild(this.container);
  712. this.chartWrapper = this.container.querySelector('.frappe-chart');
  713. this.statsWrapper = this.container.querySelector('.graph-stats-container');
  714. }
  715. makeTooltip() {
  716. this.tip = new SvgTip({
  717. parent: this.chartWrapper,
  718. colors: this.colors
  719. });
  720. this.bindTooltip();
  721. }
  722. bindTooltip() {}
  723. draw(init=false) {
  724. // difference from update(): draw the whole object due to groudbreaking event (init, resize, etc.)
  725. // (draw everything, layers, groups, units)
  726. this.calcWidth();
  727. // refresh conponent with chart
  728. this.refresh();
  729. this.makeChartArea();
  730. this.setComponentParent();
  731. this.makeComponentLayers();
  732. this.renderLegend();
  733. this.setupNavigation(init);
  734. // first time plain render, so no rerender
  735. this.renderComponents();
  736. if(this.config.animate) this.update(this.firstUpdateData);
  737. }
  738. update() {
  739. // difference from draw(): yes you do rerender everything here as well,
  740. // but not things like the chart itself or layers, mosty only at component level
  741. // HERE IS WHERE THE ACTUAL STATE CHANGES, and old one matters, not in draw
  742. this.refresh();
  743. this.reRender();
  744. }
  745. calcWidth() {
  746. let outerAnnotationsWidth = 0;
  747. // let charWidth = 8;
  748. // this.specificValues.map(val => {
  749. // let strWidth = getStringWidth((val.title + ""), charWidth);
  750. // if(strWidth > outerAnnotationsWidth) {
  751. // outerAnnotationsWidth = strWidth - 40;
  752. // }
  753. // });
  754. this.baseWidth = getElementContentWidth(this.parent) - outerAnnotationsWidth;
  755. this.width = this.baseWidth - (this.translateXLeft + this.translateXRight);
  756. }
  757. refresh() { //?? refresh?
  758. this.oldState = this.state ? Object.assign({}, this.state) : {};
  759. this.intermedState = {};
  760. this.prepareData();
  761. this.reCalc();
  762. this.refreshRenderer();
  763. }
  764. makeChartArea() {
  765. this.svg = makeSVGContainer(
  766. this.chartWrapper,
  767. 'chart',
  768. this.baseWidth,
  769. this.baseHeight
  770. );
  771. this.svg_defs = makeSVGDefs(this.svg);
  772. this.drawArea = makeSVGGroup(
  773. this.svg,
  774. this.type + '-chart',
  775. `translate(${this.translateXLeft}, ${this.translateY})`
  776. );
  777. }
  778. prepareData() {}
  779. reCalc() {}
  780. // Will update values(state)
  781. // Will recalc specific parts depending on the update
  782. refreshRenderer() {}
  783. reRender(animate=true) {
  784. if(!animate) {
  785. this.renderComponents();
  786. return;
  787. }
  788. this.intermedState = this.calcIntermedState();
  789. this.animateComponents();
  790. setTimeout(() => {
  791. this.renderComponents();
  792. }, 400);
  793. // TODO: should be max anim duration required
  794. // (opt, should not redraw if still in animate?)
  795. }
  796. calcIntermedState() {
  797. this.intermedState = {};
  798. }
  799. // convenient component array abstractions
  800. setComponentParent() { this.components.forEach(c => c.setupParent(this.drawArea)); };
  801. makeComponentLayers() { this.components.forEach(c => c.makeLayer()); }
  802. renderComponents() { this.components.forEach(c => c.render()); }
  803. animateComponents() { this.components.forEach(c => c.animate()); }
  804. renderLegend() {}
  805. setupNavigation(init=false) {
  806. if(this.isNavigable) return;
  807. this.makeOverlay();
  808. if(init) {
  809. this.bindOverlay();
  810. document.addEventListener('keydown', (e) => {
  811. if(isElementInViewport(this.chartWrapper)) {
  812. e = e || window.event;
  813. if (e.keyCode == '37') {
  814. this.onLeftArrow();
  815. } else if (e.keyCode == '39') {
  816. this.onRightArrow();
  817. } else if (e.keyCode == '38') {
  818. this.onUpArrow();
  819. } else if (e.keyCode == '40') {
  820. this.onDownArrow();
  821. } else if (e.keyCode == '13') {
  822. this.onEnterKey();
  823. }
  824. }
  825. });
  826. }
  827. }
  828. makeOverlay() {}
  829. bindOverlay() {}
  830. bind_units() {}
  831. onLeftArrow() {}
  832. onRightArrow() {}
  833. onUpArrow() {}
  834. onDownArrow() {}
  835. onEnterKey() {}
  836. getDataPoint() {}
  837. updateCurrentDataPoint() {}
  838. getDifferentChart(type) {
  839. return getDifferentChart(type, this.type, this.rawChartArgs);
  840. }
  841. }
  842. const Y_AXIS_MARGIN = 60;
  843. class ChartComponent {
  844. constructor({
  845. layerClass = '',
  846. layerTransform = '',
  847. make,
  848. animate
  849. }) {
  850. this.layerClass = layerClass;
  851. this.layerTransform = layerTransform;
  852. this.make = make;
  853. this.animate = animate;
  854. this.layer = undefined;
  855. this.store = [];
  856. }
  857. refresh(args) {}
  858. render() {
  859. this.store = this.make();
  860. this.layer.textContent = '';
  861. this.store.forEach(element => {
  862. this.layer.appendChild(element);
  863. });
  864. }
  865. setupParent(parent) {
  866. this.parent = parent;
  867. }
  868. makeLayer() {
  869. this.layer = makeSVGGroup(this.parent, this.layerClass, this.layerTransform);
  870. }
  871. }
  872. const REPLACE_ALL_NEW_DUR = 250;
  873. // export function animateXLines(animator, lines, oldX, newX) {
  874. // // this.xAxisLines.map((xLine, i) => {
  875. // return lines.map((xLine, i) => {
  876. // return animator.verticalLine(xLine, newX[i], oldX[i]);
  877. // });
  878. // }
  879. // export function animateYLines(animator, lines, oldY, newY) {
  880. // // this.yAxisLines.map((yLine, i) => {
  881. // lines.map((yLine, i) => {
  882. // return animator.horizontalLine(yLine, newY[i], oldY[i]);
  883. // });
  884. // }
  885. // Leveraging SMIL Animations
  886. const EASING = {
  887. ease: "0.25 0.1 0.25 1",
  888. linear: "0 0 1 1",
  889. // easein: "0.42 0 1 1",
  890. easein: "0.1 0.8 0.2 1",
  891. easeout: "0 0 0.58 1",
  892. easeinout: "0.42 0 0.58 1"
  893. };
  894. function animateSVGElement(element, props, dur, easingType="linear", type=undefined, oldValues={}) {
  895. let animElement = element.cloneNode(true);
  896. let newElement = element.cloneNode(true);
  897. for(var attributeName in props) {
  898. let animateElement;
  899. if(attributeName === 'transform') {
  900. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
  901. } else {
  902. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
  903. }
  904. let currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
  905. let value = props[attributeName];
  906. let animAttr = {
  907. attributeName: attributeName,
  908. from: currentValue,
  909. to: value,
  910. begin: "0s",
  911. dur: dur/1000 + "s",
  912. values: currentValue + ";" + value,
  913. keySplines: EASING[easingType],
  914. keyTimes: "0;1",
  915. calcMode: "spline",
  916. fill: 'freeze'
  917. };
  918. if(type) {
  919. animAttr["type"] = type;
  920. }
  921. for (var i in animAttr) {
  922. animateElement.setAttribute(i, animAttr[i]);
  923. }
  924. animElement.appendChild(animateElement);
  925. if(type) {
  926. newElement.setAttribute(attributeName, `translate(${value})`);
  927. } else {
  928. newElement.setAttribute(attributeName, value);
  929. }
  930. }
  931. return [animElement, newElement];
  932. }
  933. function transform(element, style) { // eslint-disable-line no-unused-vars
  934. element.style.transform = style;
  935. element.style.webkitTransform = style;
  936. element.style.msTransform = style;
  937. element.style.mozTransform = style;
  938. element.style.oTransform = style;
  939. }
  940. function animateSVG(svgContainer, elements) {
  941. let newElements = [];
  942. let animElements = [];
  943. elements.map(element => {
  944. let obj = element[0];
  945. let parent = obj.unit.parentNode;
  946. let animElement, newElement;
  947. element[0] = obj.unit;
  948. [animElement, newElement] = animateSVGElement(...element);
  949. newElements.push(newElement);
  950. animElements.push([animElement, parent]);
  951. parent.replaceChild(animElement, obj.unit);
  952. if(obj.array) {
  953. obj.array[obj.index] = newElement;
  954. } else {
  955. obj.object[obj.key] = newElement;
  956. }
  957. });
  958. let animSvg = svgContainer.cloneNode(true);
  959. animElements.map((animElement, i) => {
  960. animElement[1].replaceChild(newElements[i], animElement[0]);
  961. elements[i][0] = newElements[i];
  962. });
  963. return animSvg;
  964. }
  965. function runSMILAnimation(parent, svgElement, elementsToAnimate) {
  966. if(elementsToAnimate.length === 0) return;
  967. let animSvgElement = animateSVG(svgElement, elementsToAnimate);
  968. if(svgElement.parentNode == parent) {
  969. parent.removeChild(svgElement);
  970. parent.appendChild(animSvgElement);
  971. }
  972. // Replace the new svgElement (data has already been replaced)
  973. setTimeout(() => {
  974. if(animSvgElement.parentNode == parent) {
  975. parent.removeChild(animSvgElement);
  976. parent.appendChild(svgElement);
  977. }
  978. }, REPLACE_ALL_NEW_DUR);
  979. }
  980. function normalize(x) {
  981. // Calculates mantissa and exponent of a number
  982. // Returns normalized number and exponent
  983. // https://stackoverflow.com/q/9383593/6495043
  984. if(x===0) {
  985. return [0, 0];
  986. }
  987. if(isNaN(x)) {
  988. return {mantissa: -6755399441055744, exponent: 972};
  989. }
  990. var sig = x > 0 ? 1 : -1;
  991. if(!isFinite(x)) {
  992. return {mantissa: sig * 4503599627370496, exponent: 972};
  993. }
  994. x = Math.abs(x);
  995. var exp = Math.floor(Math.log10(x));
  996. var man = x/Math.pow(10, exp);
  997. return [sig * man, exp];
  998. }
  999. function getRangeIntervals(max, min=0) {
  1000. let upperBound = Math.ceil(max);
  1001. let lowerBound = Math.floor(min);
  1002. let range = upperBound - lowerBound;
  1003. let noOfParts = range;
  1004. let partSize = 1;
  1005. // To avoid too many partitions
  1006. if(range > 5) {
  1007. if(range % 2 !== 0) {
  1008. upperBound++;
  1009. // Recalc range
  1010. range = upperBound - lowerBound;
  1011. }
  1012. noOfParts = range/2;
  1013. partSize = 2;
  1014. }
  1015. // Special case: 1 and 2
  1016. if(range <= 2) {
  1017. noOfParts = 4;
  1018. partSize = range/noOfParts;
  1019. }
  1020. // Special case: 0
  1021. if(range === 0) {
  1022. noOfParts = 5;
  1023. partSize = 1;
  1024. }
  1025. let intervals = [];
  1026. for(var i = 0; i <= noOfParts; i++){
  1027. intervals.push(lowerBound + partSize * i);
  1028. }
  1029. return intervals;
  1030. }
  1031. function getIntervals(maxValue, minValue=0) {
  1032. let [normalMaxValue, exponent] = normalize(maxValue);
  1033. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  1034. // Allow only 7 significant digits
  1035. normalMaxValue = normalMaxValue.toFixed(6);
  1036. let intervals = getRangeIntervals(normalMaxValue, normalMinValue);
  1037. intervals = intervals.map(value => value * Math.pow(10, exponent));
  1038. return intervals;
  1039. }
  1040. function calcIntervals(values, withMinimum=false) {
  1041. //*** Where the magic happens ***
  1042. // Calculates best-fit y intervals from given values
  1043. // and returns the interval array
  1044. let maxValue = Math.max(...values);
  1045. let minValue = Math.min(...values);
  1046. // Exponent to be used for pretty print
  1047. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  1048. function getPositiveFirstIntervals(maxValue, absMinValue) {
  1049. let intervals = getIntervals(maxValue);
  1050. let intervalSize = intervals[1] - intervals[0];
  1051. // Then unshift the negative values
  1052. let value = 0;
  1053. for(var i = 1; value < absMinValue; i++) {
  1054. value += intervalSize;
  1055. intervals.unshift((-1) * value);
  1056. }
  1057. return intervals;
  1058. }
  1059. // CASE I: Both non-negative
  1060. if(maxValue >= 0 && minValue >= 0) {
  1061. exponent = normalize(maxValue)[1];
  1062. if(!withMinimum) {
  1063. intervals = getIntervals(maxValue);
  1064. } else {
  1065. intervals = getIntervals(maxValue, minValue);
  1066. }
  1067. }
  1068. // CASE II: Only minValue negative
  1069. else if(maxValue > 0 && minValue < 0) {
  1070. // `withMinimum` irrelevant in this case,
  1071. // We'll be handling both sides of zero separately
  1072. // (both starting from zero)
  1073. // Because ceil() and floor() behave differently
  1074. // in those two regions
  1075. let absMinValue = Math.abs(minValue);
  1076. if(maxValue >= absMinValue) {
  1077. exponent = normalize(maxValue)[1];
  1078. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  1079. } else {
  1080. // Mirror: maxValue => absMinValue, then change sign
  1081. exponent = normalize(absMinValue)[1];
  1082. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  1083. intervals = posIntervals.map(d => d * (-1));
  1084. }
  1085. }
  1086. // CASE III: Both non-positive
  1087. else if(maxValue <= 0 && minValue <= 0) {
  1088. // Mirrored Case I:
  1089. // Work with positives, then reverse the sign and array
  1090. let pseudoMaxValue = Math.abs(minValue);
  1091. let pseudoMinValue = Math.abs(maxValue);
  1092. exponent = normalize(pseudoMaxValue)[1];
  1093. if(!withMinimum) {
  1094. intervals = getIntervals(pseudoMaxValue);
  1095. } else {
  1096. intervals = getIntervals(pseudoMaxValue, pseudoMinValue);
  1097. }
  1098. intervals = intervals.reverse().map(d => d * (-1));
  1099. }
  1100. return intervals;
  1101. }
  1102. function getZeroIndex(yPts) {
  1103. let zeroIndex;
  1104. let interval = getIntervalSize(yPts);
  1105. if(yPts.indexOf(0) >= 0) {
  1106. // the range has a given zero
  1107. // zero-line on the chart
  1108. zeroIndex = yPts.indexOf(0);
  1109. } else if(yPts[0] > 0) {
  1110. // Minimum value is positive
  1111. // zero-line is off the chart: below
  1112. let min = yPts[0];
  1113. zeroIndex = (-1) * min / interval;
  1114. } else {
  1115. // Maximum value is negative
  1116. // zero-line is off the chart: above
  1117. let max = yPts[yPts.length - 1];
  1118. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  1119. }
  1120. return zeroIndex;
  1121. }
  1122. function getIntervalSize(orderedArray) {
  1123. return orderedArray[1] - orderedArray[0];
  1124. }
  1125. function getValueRange(orderedArray) {
  1126. return orderedArray[orderedArray.length-1] - orderedArray[0];
  1127. }
  1128. function calcDistribution(values, distributionSize) {
  1129. // Assume non-negative values,
  1130. // implying distribution minimum at zero
  1131. let dataMaxValue = Math.max(...values);
  1132. let distributionStep = 1 / (distributionSize - 1);
  1133. let distribution = [];
  1134. for(var i = 0; i < distributionSize; i++) {
  1135. let checkpoint = dataMaxValue * (distributionStep * i);
  1136. distribution.push(checkpoint);
  1137. }
  1138. return distribution;
  1139. }
  1140. function getMaxCheckpoint(value, distribution) {
  1141. return distribution.filter(d => d < value).length;
  1142. }
  1143. class AxisChart extends BaseChart {
  1144. constructor(args) {
  1145. super(args);
  1146. this.is_series = args.is_series;
  1147. this.format_tooltip_y = args.format_tooltip_y;
  1148. this.format_tooltip_x = args.format_tooltip_x;
  1149. this.zeroLine = this.height;
  1150. }
  1151. setHorizontalMargin() {
  1152. this.translateXLeft = Y_AXIS_MARGIN;
  1153. this.translateXRight = Y_AXIS_MARGIN;
  1154. }
  1155. checkData(data) {
  1156. return true;
  1157. }
  1158. getFirstUpdateData(data) {
  1159. //
  1160. }
  1161. prepareData() {
  1162. let s = this.state;
  1163. s.xAxisLabels = this.data.labels || [];
  1164. s.xAxisPositions = [];
  1165. s.datasetLength = s.xAxisLabels.length;
  1166. let zeroArray = new Array(s.datasetLength).fill(0);
  1167. s.datasets = this.data.datasets; // whole dataset info too
  1168. if(!this.data.datasets) {
  1169. // default
  1170. s.datasets = [{
  1171. values: zeroArray // Proof that state version will be seen instead of this.data
  1172. }];
  1173. }
  1174. s.datasets.map((d, i)=> {
  1175. let vals = d.values;
  1176. if(!vals) {
  1177. vals = zeroArray;
  1178. } else {
  1179. // Check for non values
  1180. vals = vals.map(val => (!isNaN(val) ? val : 0));
  1181. // Trim or extend
  1182. if(vals.length > s.datasetLength) {
  1183. vals = vals.slice(0, s.datasetLength);
  1184. } else {
  1185. vals = fillArray(vals, s.datasetLength - vals.length, 0);
  1186. }
  1187. }
  1188. d.index = i;
  1189. });
  1190. s.noOfDatasets = s.datasets.length;
  1191. // s.yAxis = [];
  1192. this.prepareYAxis();
  1193. }
  1194. prepareYAxis() {
  1195. this.state.yAxis = {
  1196. labels: [],
  1197. positions: []
  1198. };
  1199. }
  1200. reCalc() {
  1201. let s = this.state;
  1202. // X
  1203. s.xAxisLabels = this.data.labels;
  1204. this.calcXPositions();
  1205. // Y
  1206. s.datasetsLabels = this.data.datasets.map(d => d.name);
  1207. this.setYAxis();
  1208. this.calcYUnits();
  1209. this.calcYMaximums();
  1210. // should be state
  1211. this.configUnits();
  1212. }
  1213. setYAxis() {
  1214. this.calcYAxisParameters(this.state.yAxis, this.getAllYValues(), this.type === 'line');
  1215. this.state.zeroLine = this.state.yAxis.zeroLine;
  1216. }
  1217. calcXPositions() {
  1218. let s = this.state;
  1219. this.setUnitWidthAndXOffset();
  1220. s.xAxisPositions = s.xAxisLabels.map((d, i) =>
  1221. floatTwo(s.xOffset + i * s.unitWidth));
  1222. s.xUnitPositions = new Array(s.noOfDatasets).fill(s.xAxisPositions);
  1223. }
  1224. calcYAxisParameters(yAxis, dataValues, withMinimum = 'false') {
  1225. yAxis.labels = calcIntervals(dataValues, withMinimum);
  1226. const yPts = yAxis.labels;
  1227. yAxis.scaleMultiplier = this.height / getValueRange(yPts);
  1228. const intervalHeight = getIntervalSize(yPts) * yAxis.scaleMultiplier;
  1229. yAxis.zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  1230. yAxis.positions = yPts.map(d => yAxis.zeroLine - d * yAxis.scaleMultiplier);
  1231. }
  1232. calcYUnits() {
  1233. let s = this.state;
  1234. s.datasets.map(d => {
  1235. d.positions = d.values.map(val => floatTwo(s.yAxis.zeroLine - val * s.yAxis.scaleMultiplier));
  1236. });
  1237. }
  1238. calcYMaximums() {
  1239. let s = this.state;
  1240. s.yUnitMinimums = new Array(s.datasetLength).fill(9999);
  1241. s.datasets.map((d, i) => {
  1242. d.positions.map((pos, j) => {
  1243. if(pos < s.yUnitMinimums[j]) {
  1244. s.yUnitMinimums[j] = pos;
  1245. }
  1246. });
  1247. });
  1248. // Tooltip refresh should not be needed?
  1249. // this.chartWrapper.removeChild(this.tip.container);
  1250. // this.make_tooltip();
  1251. }
  1252. configUnits() {}
  1253. setUnitWidthAndXOffset() {
  1254. this.state.unitWidth = this.width/(this.state.datasetLength);
  1255. this.state.xOffset = this.state.unitWidth/2;
  1256. }
  1257. getAllYValues() {
  1258. // TODO: yMarkers, regions, sums, every Y value ever
  1259. return [].concat(...this.state.datasets.map(d => d.values));
  1260. }
  1261. calcIntermedState() {
  1262. //
  1263. }
  1264. setupValues() {}
  1265. setupComponents() {
  1266. // TODO: rebind new units
  1267. // if(this.isNavigable) {
  1268. // this.bind_units(units_array);
  1269. // }
  1270. this.yMarkerLines = {};
  1271. this.xMarkerLines = {};
  1272. // Marker Regions
  1273. this.components = [
  1274. // temp
  1275. // this.yAxesAux,
  1276. ...this.getYAxesComponents(),
  1277. this.getXAxisComponents(),
  1278. // this.yMarkerLines,
  1279. // this.xMarkerLines,
  1280. ...this.getPathComponents(),
  1281. ...this.getDataUnitsComponents(this.config),
  1282. ];
  1283. }
  1284. getYAxesComponents() {
  1285. return [new ChartComponent({
  1286. layerClass: 'y axis',
  1287. make: () => {
  1288. let s = this.state;
  1289. return s.yAxis.positions.map((position, i) =>
  1290. this.renderer.yLine(position, s.yAxis.labels[i], {pos:'right'})
  1291. );
  1292. },
  1293. animate: () => {}
  1294. })];
  1295. }
  1296. getXAxisComponents() {
  1297. return new ChartComponent({
  1298. layerClass: 'x axis',
  1299. make: () => {
  1300. let s = this.state;
  1301. return s.xAxisPositions.map((position, i) =>
  1302. this.renderer.xLine(position, s.xAxisLabels[i], {pos:'top'})
  1303. );
  1304. },
  1305. // animate: (animator, lines, oldX, newX) => {
  1306. // lines.map((xLine, i) => {
  1307. // elements_to_animate.push(animator.verticalLine(
  1308. // xLine, newX[i], oldX[i]
  1309. // ));
  1310. // });
  1311. // }
  1312. });
  1313. }
  1314. getDataUnitsComponents() {
  1315. return this.state.datasets.map((d, index) => {
  1316. return new ChartComponent({
  1317. layerClass: 'dataset-units dataset-' + index,
  1318. make: () => {
  1319. let d = this.state.datasets[index];
  1320. let unitType = this.unitArgs;
  1321. return d.positions.map((y, j) => {
  1322. return this.renderer[unitType.type](
  1323. this.state.xAxisPositions[j],
  1324. y,
  1325. unitType.args,
  1326. this.colors[index],
  1327. j,
  1328. index,
  1329. this.state.datasetLength
  1330. );
  1331. });
  1332. },
  1333. animate: () => {}
  1334. });
  1335. });
  1336. }
  1337. getPathComponents() {
  1338. return [];
  1339. }
  1340. refreshRenderer() {
  1341. // These args are basically the current state of the chart,
  1342. // with constant and alive params mixed
  1343. let state = {
  1344. totalHeight: this.height,
  1345. totalWidth: this.width,
  1346. xAxisMode: this.config.xAxisMode,
  1347. yAxisMode: this.config.yAxisMode,
  1348. zeroLine: this.state.zeroLine,
  1349. unitWidth: this.state.unitWidth,
  1350. };
  1351. if(!this.renderer) {
  1352. this.renderer = new AxisChartRenderer(state);
  1353. } else {
  1354. this.renderer.refreshState(state);
  1355. }
  1356. }
  1357. }
  1358. class BarChart extends AxisChart {
  1359. constructor(args) {
  1360. super(args);
  1361. this.type = 'bar';
  1362. this.setup();
  1363. }
  1364. configure(args) {
  1365. super.configure(args);
  1366. this.config.xAxisMode = args.xAxisMode || 'tick';
  1367. this.config.yAxisMode = args.yAxisMode || 'span';
  1368. }
  1369. // setUnitWidthAndXOffset() {
  1370. // this.state.unitWidth = this.width/(this.state.datasetLength);
  1371. // this.state.xOffset = this.state.unitWidth/2;
  1372. // }
  1373. configUnits() {
  1374. this.unitArgs = {
  1375. type: 'bar',
  1376. args: {
  1377. spaceWidth: this.state.unitWidth/2,
  1378. }
  1379. };
  1380. }
  1381. // makeOverlay() {
  1382. // // Just make one out of the first element
  1383. // let index = this.xAxisLabels.length - 1;
  1384. // let unit = this.y[0].svg_units[index];
  1385. // this.updateCurrentDataPoint(index);
  1386. // if(this.overlay) {
  1387. // this.overlay.parentNode.removeChild(this.overlay);
  1388. // }
  1389. // this.overlay = unit.cloneNode();
  1390. // this.overlay.style.fill = '#000000';
  1391. // this.overlay.style.opacity = '0.4';
  1392. // this.drawArea.appendChild(this.overlay);
  1393. // }
  1394. // bindOverlay() {
  1395. // // on event, update overlay
  1396. // this.parent.addEventListener('data-select', (e) => {
  1397. // this.update_overlay(e.svg_unit);
  1398. // });
  1399. // }
  1400. // bind_units(units_array) {
  1401. // units_array.map(unit => {
  1402. // unit.addEventListener('click', () => {
  1403. // let index = unit.getAttribute('data-point-index');
  1404. // this.updateCurrentDataPoint(index);
  1405. // });
  1406. // });
  1407. // }
  1408. // update_overlay(unit) {
  1409. // let attributes = [];
  1410. // Object.keys(unit.attributes).map(index => {
  1411. // attributes.push(unit.attributes[index]);
  1412. // });
  1413. // attributes.filter(attr => attr.specified).map(attr => {
  1414. // this.overlay.setAttribute(attr.name, attr.nodeValue);
  1415. // });
  1416. // this.overlay.style.fill = '#000000';
  1417. // this.overlay.style.opacity = '0.4';
  1418. // }
  1419. // onLeftArrow() {
  1420. // this.updateCurrentDataPoint(this.currentIndex - 1);
  1421. // }
  1422. // onRightArrow() {
  1423. // this.updateCurrentDataPoint(this.currentIndex + 1);
  1424. // }
  1425. }
  1426. class LineChart extends AxisChart {
  1427. constructor(args) {
  1428. super(args);
  1429. this.type = 'line';
  1430. if(Object.getPrototypeOf(this) !== LineChart.prototype) {
  1431. return;
  1432. }
  1433. this.setup();
  1434. }
  1435. configure(args) {
  1436. super.configure(args);
  1437. this.config.xAxisMode = args.xAxisMode || 'span';
  1438. this.config.yAxisMode = args.yAxisMode || 'span';
  1439. this.config.dotRadius = args.dotRadius || 4;
  1440. this.config.heatline = args.heatline || 0;
  1441. this.config.regionFill = args.regionFill || 0;
  1442. this.config.showDots = args.showDots || 1;
  1443. }
  1444. configUnits() {
  1445. this.unitArgs = {
  1446. type: 'dot',
  1447. args: { radius: this.config.dotRadius }
  1448. };
  1449. }
  1450. // temp commented
  1451. setUnitWidthAndXOffset() {
  1452. this.state.unitWidth = this.width/(this.state.datasetLength - 1);
  1453. this.state.xOffset = 0;
  1454. }
  1455. getDataUnitsComponents(config) {
  1456. if(!config.showDots) {
  1457. return [];
  1458. } else {
  1459. return super.getDataUnitsComponents();
  1460. }
  1461. }
  1462. getPathComponents() {
  1463. return this.state.datasets.map((d, index) => {
  1464. return new ChartComponent({
  1465. layerClass: 'path dataset-path',
  1466. make: () => {
  1467. let d = this.state.datasets[index];
  1468. let color = this.colors[index];
  1469. let pointsList = d.positions.map((y, i) => (this.state.xAxisPositions[i] + ',' + y));
  1470. let pointsStr = pointsList.join("L");
  1471. let path = makePath("M"+pointsStr, 'line-graph-path', color);
  1472. // HeatLine
  1473. if(this.config.heatline) {
  1474. let gradient_id = makeGradient(this.svg_defs, color);
  1475. path.style.stroke = `url(#${gradient_id})`;
  1476. }
  1477. let components = [path];
  1478. // Region
  1479. if(this.config.regionFill) {
  1480. let gradient_id_region = makeGradient(this.svg_defs, color, true);
  1481. let zeroLine = this.state.yAxis.zeroLine;
  1482. let pathStr = "M" + `0,${zeroLine}L` + pointsStr + `L${this.width},${zeroLine}`;
  1483. components.push(makePath(pathStr, `region-fill`, 'none', `url(#${gradient_id_region})`));
  1484. }
  1485. return components;
  1486. },
  1487. animate: () => {}
  1488. });
  1489. });
  1490. }
  1491. }
  1492. class ScatterChart extends LineChart {
  1493. constructor(args) {
  1494. super(args);
  1495. this.type = 'scatter';
  1496. if(!args.dotRadius) {
  1497. this.dotRadius = 8;
  1498. } else {
  1499. this.dotRadius = args.dotRadius;
  1500. }
  1501. this.setup();
  1502. }
  1503. setup_values() {
  1504. super.setup_values();
  1505. this.unit_args = {
  1506. type: 'dot',
  1507. args: { radius: this.dotRadius }
  1508. };
  1509. }
  1510. make_paths() {}
  1511. make_path() {}
  1512. }
  1513. class MultiAxisChart extends AxisChart {
  1514. constructor(args) {
  1515. super(args);
  1516. this.type = 'multiaxis';
  1517. this.unitType = args.unitType || 'line';
  1518. this.setup();
  1519. }
  1520. setHorizontalMargin() {
  1521. let noOfLeftAxes = this.data.datasets.filter(d => d.axisPosition === 'left').length;
  1522. this.translateXLeft = (noOfLeftAxes) * Y_AXIS_MARGIN || Y_AXIS_MARGIN;
  1523. this.translateXRight = (this.data.datasets.length - noOfLeftAxes) * Y_AXIS_MARGIN || Y_AXIS_MARGIN;
  1524. }
  1525. prepareYAxis() {
  1526. let sets = this.state.datasets;
  1527. // let axesLeft = sets.filter(d => d.axisPosition === 'left');
  1528. // let axesRight = sets.filter(d => d.axisPosition === 'right');
  1529. // let axesNone = sets.filter(d => !d.axisPosition ||
  1530. // !['left', 'right'].includes(d.axisPosition));
  1531. let leftCount = 0, rightCount = 0;
  1532. sets.forEach((d, i) => {
  1533. d.yAxis = {
  1534. position: d.axisPosition,
  1535. index: d.axisPosition === 'left' ? leftCount++ : rightCount++
  1536. };
  1537. });
  1538. }
  1539. configure(args) {
  1540. super.configure(args);
  1541. this.config.xAxisMode = args.xAxisMode || 'tick';
  1542. this.config.yAxisMode = args.yAxisMode || 'span';
  1543. }
  1544. // setUnitWidthAndXOffset() {
  1545. // this.state.unitWidth = this.width/(this.state.datasetLength);
  1546. // this.state.xOffset = this.state.unitWidth/2;
  1547. // }
  1548. configUnits() {
  1549. this.unitArgs = {
  1550. type: 'bar',
  1551. args: {
  1552. spaceWidth: this.state.unitWidth/2,
  1553. }
  1554. };
  1555. }
  1556. setYAxis() {
  1557. this.state.datasets.map(d => {
  1558. this.calcYAxisParameters(d.yAxis, d.values, this.unitType === 'line');
  1559. });
  1560. }
  1561. calcYUnits() {
  1562. this.state.datasets.map(d => {
  1563. d.positions = d.values.map(val => floatTwo(d.yAxis.zeroLine - val * d.yAxis.scaleMultiplier));
  1564. });
  1565. }
  1566. getYAxesComponents() {
  1567. return this.state.datasets.map((e, i) => {
  1568. return new ChartComponent({
  1569. layerClass: 'y axis y-axis-' + i,
  1570. make: () => {
  1571. let yAxis = this.state.datasets[i].yAxis;
  1572. this.renderer.setZeroline(yAxis.zeroline);
  1573. let options = {
  1574. pos: yAxis.position,
  1575. mode: 'tick',
  1576. offset: yAxis.index * Y_AXIS_MARGIN,
  1577. stroke: this.colors[i]
  1578. };
  1579. let yAxisLines = yAxis.positions.map((position, j) =>
  1580. this.renderer.yLine(position, yAxis.labels[j], options)
  1581. );
  1582. let guidePos = yAxis.position === 'left'
  1583. ? -1 * yAxis.index * Y_AXIS_MARGIN
  1584. : this.width + yAxis.index * Y_AXIS_MARGIN;
  1585. yAxisLines.push(this.renderer.xLine(guidePos, '', {
  1586. pos:'top',
  1587. mode: 'span',
  1588. stroke: this.colors[i],
  1589. className: 'y-axis-guide'
  1590. }));
  1591. return yAxisLines;
  1592. },
  1593. animate: () => {}
  1594. });
  1595. });
  1596. }
  1597. getDataUnitsComponents() {
  1598. return this.state.datasets.map((d, index) => {
  1599. return new ChartComponent({
  1600. layerClass: 'dataset-units dataset-' + index,
  1601. make: () => {
  1602. let d = this.state.datasets[index];
  1603. let unitType = this.unitArgs;
  1604. // the only difference, should be tied to datasets or default
  1605. this.renderer.setZeroline(d.yAxis.zeroLine);
  1606. return d.positions.map((y, j) => {
  1607. return this.renderer[unitType.type](
  1608. this.state.xAxisPositions[j],
  1609. y,
  1610. unitType.args,
  1611. this.colors[index],
  1612. j,
  1613. index,
  1614. this.state.datasetLength
  1615. );
  1616. });
  1617. },
  1618. animate: () => {}
  1619. });
  1620. });
  1621. }
  1622. }
  1623. class PercentageChart extends BaseChart {
  1624. constructor(args) {
  1625. super(args);
  1626. this.type = 'percentage';
  1627. this.max_slices = 10;
  1628. this.max_legend_points = 6;
  1629. this.setup();
  1630. }
  1631. makeChartArea() {
  1632. this.chartWrapper.className += ' ' + 'graph-focus-margin';
  1633. this.chartWrapper.style.marginTop = '45px';
  1634. this.statsWrapper.className += ' ' + 'graph-focus-margin';
  1635. this.statsWrapper.style.marginBottom = '30px';
  1636. this.statsWrapper.style.paddingTop = '0px';
  1637. this.chartDiv = $.create('div', {
  1638. className: 'div',
  1639. inside: this.chartWrapper
  1640. });
  1641. this.chart = $.create('div', {
  1642. className: 'progress-chart',
  1643. inside: this.chartDiv
  1644. });
  1645. }
  1646. setupLayers() {
  1647. this.percentageBar = $.create('div', {
  1648. className: 'progress',
  1649. inside: this.chart
  1650. });
  1651. }
  1652. setup_values() {
  1653. this.slice_totals = [];
  1654. let all_totals = this.data.labels.map((d, i) => {
  1655. let total = 0;
  1656. this.data.datasets.map(e => {
  1657. total += e.values[i];
  1658. });
  1659. return [total, d];
  1660. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1661. let totals = all_totals;
  1662. if(all_totals.length > this.max_slices) {
  1663. all_totals.sort((a, b) => { return b[0] - a[0]; });
  1664. totals = all_totals.slice(0, this.max_slices-1);
  1665. let others = all_totals.slice(this.max_slices-1);
  1666. let sum_of_others = 0;
  1667. others.map(d => {sum_of_others += d[0];});
  1668. totals.push([sum_of_others, 'Rest']);
  1669. this.colors[this.max_slices-1] = 'grey';
  1670. }
  1671. this.labels = [];
  1672. totals.map(d => {
  1673. this.slice_totals.push(d[0]);
  1674. this.labels.push(d[1]);
  1675. });
  1676. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  1677. }
  1678. renderComponents() {
  1679. this.grand_total = this.slice_totals.reduce((a, b) => a + b, 0);
  1680. this.slices = [];
  1681. this.slice_totals.map((total, i) => {
  1682. let slice = $.create('div', {
  1683. className: `progress-bar`,
  1684. inside: this.percentageBar,
  1685. styles: {
  1686. background: this.colors[i],
  1687. width: total*100/this.grand_total + "%"
  1688. }
  1689. });
  1690. this.slices.push(slice);
  1691. });
  1692. }
  1693. bindTooltip() {
  1694. this.slices.map((slice, i) => {
  1695. slice.addEventListener('mouseenter', () => {
  1696. let g_off = getOffset(this.chartWrapper), p_off = getOffset(slice);
  1697. let x = p_off.left - g_off.left + slice.offsetWidth/2;
  1698. let y = p_off.top - g_off.top - 6;
  1699. let title = (this.formatted_labels && this.formatted_labels.length>0
  1700. ? this.formatted_labels[i] : this.labels[i]) + ': ';
  1701. let percent = (this.slice_totals[i]*100/this.grand_total).toFixed(1);
  1702. this.tip.set_values(x, y, title, percent + "%");
  1703. this.tip.show_tip();
  1704. });
  1705. });
  1706. }
  1707. renderLegend() {
  1708. let x_values = this.formatted_labels && this.formatted_labels.length > 0
  1709. ? this.formatted_labels : this.labels;
  1710. this.legend_totals.map((d, i) => {
  1711. if(d) {
  1712. let stats = $.create('div', {
  1713. className: 'stats',
  1714. inside: this.statsWrapper
  1715. });
  1716. stats.innerHTML = `<span class="indicator">
  1717. <i style="background: ${this.colors[i]}"></i>
  1718. <span class="text-muted">${x_values[i]}:</span>
  1719. ${d}
  1720. </span>`;
  1721. }
  1722. });
  1723. }
  1724. }
  1725. const ANGLE_RATIO = Math.PI / 180;
  1726. const FULL_ANGLE = 360;
  1727. class PieChart extends BaseChart {
  1728. constructor(args) {
  1729. super(args);
  1730. this.type = 'pie';
  1731. this.elements_to_animate = null;
  1732. this.hoverRadio = args.hoverRadio || 0.1;
  1733. this.max_slices = 10;
  1734. this.max_legend_points = 6;
  1735. this.isAnimate = false;
  1736. this.startAngle = args.startAngle || 0;
  1737. this.clockWise = args.clockWise || false;
  1738. this.mouseMove = this.mouseMove.bind(this);
  1739. this.mouseLeave = this.mouseLeave.bind(this);
  1740. this.setup();
  1741. }
  1742. setup_values() {
  1743. this.centerX = this.width / 2;
  1744. this.centerY = this.height / 2;
  1745. this.radius = (this.height > this.width ? this.centerX : this.centerY);
  1746. this.slice_totals = [];
  1747. let all_totals = this.data.labels.map((d, i) => {
  1748. let total = 0;
  1749. this.data.datasets.map(e => {
  1750. total += e.values[i];
  1751. });
  1752. return [total, d];
  1753. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1754. let totals = all_totals;
  1755. if(all_totals.length > this.max_slices) {
  1756. all_totals.sort((a, b) => { return b[0] - a[0]; });
  1757. totals = all_totals.slice(0, this.max_slices-1);
  1758. let others = all_totals.slice(this.max_slices-1);
  1759. let sum_of_others = 0;
  1760. others.map(d => {sum_of_others += d[0];});
  1761. totals.push([sum_of_others, 'Rest']);
  1762. this.colors[this.max_slices-1] = 'grey';
  1763. }
  1764. this.labels = [];
  1765. totals.map(d => {
  1766. this.slice_totals.push(d[0]);
  1767. this.labels.push(d[1]);
  1768. });
  1769. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  1770. }
  1771. static getPositionByAngle(angle,radius){
  1772. return {
  1773. x:Math.sin(angle * ANGLE_RATIO) * radius,
  1774. y:Math.cos(angle * ANGLE_RATIO) * radius,
  1775. };
  1776. }
  1777. makeArcPath(startPosition,endPosition){
  1778. const{centerX,centerY,radius,clockWise} = this;
  1779. 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`;
  1780. }
  1781. renderComponents(init){
  1782. const{radius,clockWise} = this;
  1783. this.grand_total = this.slice_totals.reduce((a, b) => a + b, 0);
  1784. const prevSlicesProperties = this.slicesProperties || [];
  1785. this.slices = [];
  1786. this.elements_to_animate = [];
  1787. this.slicesProperties = [];
  1788. let curAngle = 180 - this.startAngle;
  1789. this.slice_totals.map((total, i) => {
  1790. const startAngle = curAngle;
  1791. const originDiffAngle = (total / this.grand_total) * FULL_ANGLE;
  1792. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  1793. const endAngle = curAngle = curAngle + diffAngle;
  1794. const startPosition = PieChart.getPositionByAngle(startAngle,radius);
  1795. const endPosition = PieChart.getPositionByAngle(endAngle,radius);
  1796. const prevProperty = init && prevSlicesProperties[i];
  1797. let curStart,curEnd;
  1798. if(init){
  1799. curStart = prevProperty?prevProperty.startPosition : startPosition;
  1800. curEnd = prevProperty? prevProperty.endPosition : startPosition;
  1801. }else{
  1802. curStart = startPosition;
  1803. curEnd = endPosition;
  1804. }
  1805. const curPath = this.makeArcPath(curStart,curEnd);
  1806. let slice = makePath(curPath, 'pie-path', 'none', this.colors[i]);
  1807. slice.style.transition = 'transform .3s;';
  1808. this.drawArea.appendChild(slice);
  1809. this.slices.push(slice);
  1810. this.slicesProperties.push({
  1811. startPosition,
  1812. endPosition,
  1813. value: total,
  1814. total: this.grand_total,
  1815. startAngle,
  1816. endAngle,
  1817. angle:diffAngle
  1818. });
  1819. if(init){
  1820. this.elements_to_animate.push([{unit: slice, array: this.slices, index: this.slices.length - 1},
  1821. {d:this.makeArcPath(startPosition,endPosition)},
  1822. 650, "easein",null,{
  1823. d:curPath
  1824. }]);
  1825. }
  1826. });
  1827. if(init){
  1828. runSMILAnimation(this.chartWrapper, this.svg, this.elements_to_animate);
  1829. }
  1830. }
  1831. calTranslateByAngle(property){
  1832. const{radius,hoverRadio} = this;
  1833. const position = PieChart.getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  1834. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  1835. }
  1836. hoverSlice(path,i,flag,e){
  1837. if(!path) return;
  1838. const color = this.colors[i];
  1839. if(flag){
  1840. transform(path,this.calTranslateByAngle(this.slicesProperties[i]));
  1841. path.style.fill = lightenDarkenColor(color,50);
  1842. let g_off = getOffset(this.svg);
  1843. let x = e.pageX - g_off.left + 10;
  1844. let y = e.pageY - g_off.top - 10;
  1845. let title = (this.formatted_labels && this.formatted_labels.length>0
  1846. ? this.formatted_labels[i] : this.labels[i]) + ': ';
  1847. let percent = (this.slice_totals[i]*100/this.grand_total).toFixed(1);
  1848. this.tip.set_values(x, y, title, percent + "%");
  1849. this.tip.show_tip();
  1850. }else{
  1851. transform(path,'translate3d(0,0,0)');
  1852. this.tip.hide_tip();
  1853. path.style.fill = color;
  1854. }
  1855. }
  1856. mouseMove(e){
  1857. const target = e.target;
  1858. let prevIndex = this.curActiveSliceIndex;
  1859. let prevAcitve = this.curActiveSlice;
  1860. for(let i = 0; i < this.slices.length; i++){
  1861. if(target === this.slices[i]){
  1862. this.hoverSlice(prevAcitve,prevIndex,false);
  1863. this.curActiveSlice = target;
  1864. this.curActiveSliceIndex = i;
  1865. this.hoverSlice(target,i,true,e);
  1866. break;
  1867. }
  1868. }
  1869. }
  1870. mouseLeave(){
  1871. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  1872. }
  1873. bindTooltip() {
  1874. this.drawArea.addEventListener('mousemove',this.mouseMove);
  1875. this.drawArea.addEventListener('mouseleave',this.mouseLeave);
  1876. }
  1877. renderLegend() {
  1878. let x_values = this.formatted_labels && this.formatted_labels.length > 0
  1879. ? this.formatted_labels : this.labels;
  1880. this.legend_totals.map((d, i) => {
  1881. const color = this.colors[i];
  1882. if(d) {
  1883. let stats = $.create('div', {
  1884. className: 'stats',
  1885. inside: this.statsWrapper
  1886. });
  1887. stats.innerHTML = `<span class="indicator">
  1888. <i style="background-color:${color};"></i>
  1889. <span class="text-muted">${x_values[i]}:</span>
  1890. ${d}
  1891. </span>`;
  1892. }
  1893. });
  1894. }
  1895. }
  1896. // Playing around with dates
  1897. // https://stackoverflow.com/a/11252167/6495043
  1898. function treatAsUtc(dateStr) {
  1899. let result = new Date(dateStr);
  1900. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  1901. return result;
  1902. }
  1903. function getDdMmYyyy(date) {
  1904. let dd = date.getDate();
  1905. let mm = date.getMonth() + 1; // getMonth() is zero-based
  1906. return [
  1907. (dd>9 ? '' : '0') + dd,
  1908. (mm>9 ? '' : '0') + mm,
  1909. date.getFullYear()
  1910. ].join('-');
  1911. }
  1912. function getWeeksBetween(startDateStr, endDateStr) {
  1913. return Math.ceil(getDaysBetween(startDateStr, endDateStr) / 7);
  1914. }
  1915. function getDaysBetween(startDateStr, endDateStr) {
  1916. let millisecondsPerDay = 24 * 60 * 60 * 1000;
  1917. return (treatAsUtc(endDateStr) - treatAsUtc(startDateStr)) / millisecondsPerDay;
  1918. }
  1919. // mutates
  1920. function addDays(date, numberOfDays) {
  1921. date.setDate(date.getDate() + numberOfDays);
  1922. }
  1923. // export function getMonthName() {}
  1924. class Heatmap extends BaseChart {
  1925. constructor({
  1926. start = '',
  1927. domain = '',
  1928. subdomain = '',
  1929. data = {},
  1930. discrete_domains = 0,
  1931. count_label = '',
  1932. legend_colors = []
  1933. }) {
  1934. super(arguments[0]);
  1935. this.type = 'heatmap';
  1936. this.domain = domain;
  1937. this.subdomain = subdomain;
  1938. this.data = data;
  1939. this.discrete_domains = discrete_domains;
  1940. this.count_label = count_label;
  1941. let today = new Date();
  1942. this.start = start || addDays(today, 365);
  1943. legend_colors = legend_colors.slice(0, 5);
  1944. this.legend_colors = this.validate_colors(legend_colors)
  1945. ? legend_colors
  1946. : ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  1947. // Fixed 5-color theme,
  1948. // More colors are difficult to parse visually
  1949. this.distribution_size = 5;
  1950. this.translateX = 0;
  1951. // this.setup();
  1952. }
  1953. validate_colors(colors) {
  1954. if(colors.length < 5) return 0;
  1955. let valid = 1;
  1956. colors.forEach(function(string) {
  1957. if(!isValidColor(string)) {
  1958. valid = 0;
  1959. console.warn('"' + string + '" is not a valid color.');
  1960. }
  1961. }, this);
  1962. return valid;
  1963. }
  1964. setupConstants() {
  1965. this.today = new Date();
  1966. if(!this.start) {
  1967. this.start = new Date();
  1968. this.start.setFullYear( this.start.getFullYear() - 1 );
  1969. }
  1970. this.first_week_start = new Date(this.start.toDateString());
  1971. this.last_week_start = new Date(this.today.toDateString());
  1972. if(this.first_week_start.getDay() !== 7) {
  1973. addDays(this.first_week_start, (-1) * this.first_week_start.getDay());
  1974. }
  1975. if(this.last_week_start.getDay() !== 7) {
  1976. addDays(this.last_week_start, (-1) * this.last_week_start.getDay());
  1977. }
  1978. this.no_of_cols = getWeeksBetween(this.first_week_start + '', this.last_week_start + '') + 1;
  1979. }
  1980. calcWidth() {
  1981. this.baseWidth = (this.no_of_cols + 3) * 12 ;
  1982. if(this.discrete_domains) {
  1983. this.baseWidth += (12 * 12);
  1984. }
  1985. }
  1986. setupLayers() {
  1987. this.domain_label_group = this.makeLayer(
  1988. 'domain-label-group chart-label');
  1989. this.data_groups = this.makeLayer(
  1990. 'data-groups',
  1991. `translate(0, 20)`
  1992. );
  1993. }
  1994. setup_values() {
  1995. this.domain_label_group.textContent = '';
  1996. this.data_groups.textContent = '';
  1997. let data_values = Object.keys(this.data).map(key => this.data[key]);
  1998. this.distribution = calcDistribution(data_values, this.distribution_size);
  1999. this.month_names = ["January", "February", "March", "April", "May", "June",
  2000. "July", "August", "September", "October", "November", "December"
  2001. ];
  2002. this.render_all_weeks_and_store_x_values(this.no_of_cols);
  2003. }
  2004. render_all_weeks_and_store_x_values(no_of_weeks) {
  2005. let current_week_sunday = new Date(this.first_week_start);
  2006. this.week_col = 0;
  2007. this.current_month = current_week_sunday.getMonth();
  2008. this.months = [this.current_month + ''];
  2009. this.month_weeks = {}, this.month_start_points = [];
  2010. this.month_weeks[this.current_month] = 0;
  2011. this.month_start_points.push(13);
  2012. for(var i = 0; i < no_of_weeks; i++) {
  2013. let data_group, month_change = 0;
  2014. let day = new Date(current_week_sunday);
  2015. [data_group, month_change] = this.get_week_squares_group(day, this.week_col);
  2016. this.data_groups.appendChild(data_group);
  2017. this.week_col += 1 + parseInt(this.discrete_domains && month_change);
  2018. this.month_weeks[this.current_month]++;
  2019. if(month_change) {
  2020. this.current_month = (this.current_month + 1) % 12;
  2021. this.months.push(this.current_month + '');
  2022. this.month_weeks[this.current_month] = 1;
  2023. }
  2024. addDays(current_week_sunday, 7);
  2025. }
  2026. this.render_month_labels();
  2027. }
  2028. get_week_squares_group(current_date, index) {
  2029. const no_of_weekdays = 7;
  2030. const square_side = 10;
  2031. const cell_padding = 2;
  2032. const step = 1;
  2033. const today_time = this.today.getTime();
  2034. let month_change = 0;
  2035. let week_col_change = 0;
  2036. let data_group = makeSVGGroup(this.data_groups, 'data-group');
  2037. for(var y = 0, i = 0; i < no_of_weekdays; i += step, y += (square_side + cell_padding)) {
  2038. let data_value = 0;
  2039. let color_index = 0;
  2040. let current_timestamp = current_date.getTime()/1000;
  2041. let timestamp = Math.floor(current_timestamp - (current_timestamp % 86400)).toFixed(1);
  2042. if(this.data[timestamp]) {
  2043. data_value = this.data[timestamp];
  2044. }
  2045. if(this.data[Math.round(timestamp)]) {
  2046. data_value = this.data[Math.round(timestamp)];
  2047. }
  2048. if(data_value) {
  2049. color_index = getMaxCheckpoint(data_value, this.distribution);
  2050. }
  2051. let x = 13 + (index + week_col_change) * 12;
  2052. let dataAttr = {
  2053. 'data-date': getDdMmYyyy(current_date),
  2054. 'data-value': data_value,
  2055. 'data-day': current_date.getDay()
  2056. };
  2057. let heatSquare = makeHeatSquare('day', x, y, square_side,
  2058. this.legend_colors[color_index], dataAttr);
  2059. data_group.appendChild(heatSquare);
  2060. let next_date = new Date(current_date);
  2061. addDays(next_date, 1);
  2062. if(next_date.getTime() > today_time) break;
  2063. if(next_date.getMonth() - current_date.getMonth()) {
  2064. month_change = 1;
  2065. if(this.discrete_domains) {
  2066. week_col_change = 1;
  2067. }
  2068. this.month_start_points.push(13 + (index + week_col_change) * 12);
  2069. }
  2070. current_date = next_date;
  2071. }
  2072. return [data_group, month_change];
  2073. }
  2074. render_month_labels() {
  2075. // this.first_month_label = 1;
  2076. // if (this.first_week_start.getDate() > 8) {
  2077. // this.first_month_label = 0;
  2078. // }
  2079. // this.last_month_label = 1;
  2080. // let first_month = this.months.shift();
  2081. // let first_month_start = this.month_start_points.shift();
  2082. // render first month if
  2083. // let last_month = this.months.pop();
  2084. // let last_month_start = this.month_start_points.pop();
  2085. // render last month if
  2086. this.months.shift();
  2087. this.month_start_points.shift();
  2088. this.months.pop();
  2089. this.month_start_points.pop();
  2090. this.month_start_points.map((start, i) => {
  2091. let month_name = this.month_names[this.months[i]].substring(0, 3);
  2092. let text = makeText('y-value-text', start+12, 10, month_name);
  2093. this.domain_label_group.appendChild(text);
  2094. });
  2095. }
  2096. renderComponents() {
  2097. Array.prototype.slice.call(
  2098. this.container.querySelectorAll('.graph-stats-container, .sub-title, .title')
  2099. ).map(d => {
  2100. d.style.display = 'None';
  2101. });
  2102. this.chartWrapper.style.marginTop = '0px';
  2103. this.chartWrapper.style.paddingTop = '0px';
  2104. }
  2105. bindTooltip() {
  2106. Array.prototype.slice.call(
  2107. document.querySelectorAll(".data-group .day")
  2108. ).map(el => {
  2109. el.addEventListener('mouseenter', (e) => {
  2110. let count = e.target.getAttribute('data-value');
  2111. let date_parts = e.target.getAttribute('data-date').split('-');
  2112. let month = this.month_names[parseInt(date_parts[1])-1].substring(0, 3);
  2113. let g_off = this.chartWrapper.getBoundingClientRect(), p_off = e.target.getBoundingClientRect();
  2114. let width = parseInt(e.target.getAttribute('width'));
  2115. let x = p_off.left - g_off.left + (width+2)/2;
  2116. let y = p_off.top - g_off.top - (width+2)/2;
  2117. let value = count + ' ' + this.count_label;
  2118. let name = ' on ' + month + ' ' + date_parts[0] + ', ' + date_parts[2];
  2119. this.tip.set_values(x, y, name, value, [], 1);
  2120. this.tip.show_tip();
  2121. });
  2122. });
  2123. }
  2124. update(data) {
  2125. this.data = data;
  2126. this.setup_values();
  2127. this.bindTooltip();
  2128. }
  2129. }
  2130. const chartTypes = {
  2131. line: LineChart,
  2132. bar: BarChart,
  2133. multiaxis: MultiAxisChart,
  2134. scatter: ScatterChart,
  2135. percentage: PercentageChart,
  2136. heatmap: Heatmap,
  2137. pie: PieChart
  2138. };
  2139. function getChartByType(chartType = 'line', options) {
  2140. if (!chartTypes[chartType]) {
  2141. return new LineChart(options);
  2142. }
  2143. return new chartTypes[chartType](options);
  2144. }
  2145. class Chart {
  2146. constructor(args) {
  2147. return getChartByType(args.type, arguments[0]);
  2148. }
  2149. }
  2150. export default Chart;