No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

frappe-charts.esm.js 67 KiB

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