You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

frappe-charts.esm.js 76 KiB

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