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 98 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066
  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. // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
  41. // an element's offsetParent property will return null whenever it, or any of its parents,
  42. // is hidden via the display style property.
  43. function isHidden(el) {
  44. return (el.offsetParent === null);
  45. }
  46. function isElementInViewport(el) {
  47. // Although straightforward: https://stackoverflow.com/a/7557433/6495043
  48. var rect = el.getBoundingClientRect();
  49. return (
  50. rect.top >= 0 &&
  51. rect.left >= 0 &&
  52. rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
  53. rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
  54. );
  55. }
  56. function getElementContentWidth(element) {
  57. var styles = window.getComputedStyle(element);
  58. var padding = parseFloat(styles.paddingLeft) +
  59. parseFloat(styles.paddingRight);
  60. return element.clientWidth - padding;
  61. }
  62. function fire(target, type, properties) {
  63. var evt = document.createEvent("HTMLEvents");
  64. evt.initEvent(type, true, true );
  65. for (var j in properties) {
  66. evt[j] = properties[j];
  67. }
  68. return target.dispatchEvent(evt);
  69. }
  70. // https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
  71. const BASE_MEASURES = {
  72. margins: {
  73. top: 10,
  74. bottom: 10,
  75. left: 20,
  76. right: 20
  77. },
  78. paddings: {
  79. top: 20,
  80. bottom: 40,
  81. left: 30,
  82. right: 10
  83. },
  84. baseHeight: 240,
  85. titleHeight: 20,
  86. legendHeight: 30,
  87. titleFontSize: 12,
  88. };
  89. function getTopOffset(m) {
  90. return m.titleHeight + m.margins.top + m.paddings.top;
  91. }
  92. function getLeftOffset(m) {
  93. return m.margins.left + m.paddings.left;
  94. }
  95. function getExtraHeight(m) {
  96. let totalExtraHeight = m.margins.top + m.margins.bottom
  97. + m.paddings.top + m.paddings.bottom
  98. + m.titleHeight + m.legendHeight;
  99. return totalExtraHeight;
  100. }
  101. function getExtraWidth(m) {
  102. let totalExtraWidth = m.margins.left + m.margins.right
  103. + m.paddings.left + m.paddings.right;
  104. return totalExtraWidth;
  105. }
  106. const INIT_CHART_UPDATE_TIMEOUT = 700;
  107. const CHART_POST_ANIMATE_TIMEOUT = 400;
  108. const DEFAULT_AXIS_CHART_TYPE = 'line';
  109. const AXIS_DATASET_CHART_TYPES = ['line', 'bar'];
  110. const AXIS_LEGEND_BAR_SIZE = 100;
  111. const BAR_CHART_SPACE_RATIO = 0.5;
  112. const MIN_BAR_PERCENT_HEIGHT = 0.00;
  113. const LINE_CHART_DOT_SIZE = 4;
  114. const DOT_OVERLAY_SIZE_INCR = 4;
  115. const PERCENTAGE_BAR_DEFAULT_HEIGHT = 20;
  116. const PERCENTAGE_BAR_DEFAULT_DEPTH = 2;
  117. // Fixed 5-color theme,
  118. // More colors are difficult to parse visually
  119. const HEATMAP_DISTRIBUTION_SIZE = 5;
  120. const HEATMAP_SQUARE_SIZE = 10;
  121. const HEATMAP_GUTTER_SIZE = 2;
  122. const DEFAULT_CHAR_WIDTH = 7;
  123. const TOOLTIP_POINTER_TRIANGLE_HEIGHT = 5;
  124. const DEFAULT_CHART_COLORS = ['light-blue', 'blue', 'violet', 'red', 'orange',
  125. 'yellow', 'green', 'light-green', 'purple', 'magenta', 'light-grey', 'dark-grey'];
  126. const HEATMAP_COLORS_GREEN = ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  127. const DEFAULT_COLORS = {
  128. bar: DEFAULT_CHART_COLORS,
  129. line: DEFAULT_CHART_COLORS,
  130. pie: DEFAULT_CHART_COLORS,
  131. percentage: DEFAULT_CHART_COLORS,
  132. heatmap: HEATMAP_COLORS_GREEN,
  133. donut: DEFAULT_CHART_COLORS
  134. };
  135. // Universal constants
  136. const ANGLE_RATIO = Math.PI / 180;
  137. const FULL_ANGLE = 360;
  138. class SvgTip {
  139. constructor({
  140. parent = null,
  141. colors = []
  142. }) {
  143. this.parent = parent;
  144. this.colors = colors;
  145. this.titleName = '';
  146. this.titleValue = '';
  147. this.listValues = [];
  148. this.titleValueFirst = 0;
  149. this.x = 0;
  150. this.y = 0;
  151. this.top = 0;
  152. this.left = 0;
  153. this.setup();
  154. }
  155. setup() {
  156. this.makeTooltip();
  157. }
  158. refresh() {
  159. this.fill();
  160. this.calcPosition();
  161. }
  162. makeTooltip() {
  163. this.container = $.create('div', {
  164. inside: this.parent,
  165. className: 'graph-svg-tip comparison',
  166. innerHTML: `<span class="title"></span>
  167. <ul class="data-point-list"></ul>
  168. <div class="svg-pointer"></div>`
  169. });
  170. this.hideTip();
  171. this.title = this.container.querySelector('.title');
  172. this.dataPointList = this.container.querySelector('.data-point-list');
  173. this.parent.addEventListener('mouseleave', () => {
  174. this.hideTip();
  175. });
  176. }
  177. fill() {
  178. let title;
  179. if(this.index) {
  180. this.container.setAttribute('data-point-index', this.index);
  181. }
  182. if(this.titleValueFirst) {
  183. title = `<strong>${this.titleValue}</strong>${this.titleName}`;
  184. } else {
  185. title = `${this.titleName}<strong>${this.titleValue}</strong>`;
  186. }
  187. this.title.innerHTML = title;
  188. this.dataPointList.innerHTML = '';
  189. this.listValues.map((set, i) => {
  190. const color = this.colors[i] || 'black';
  191. let value = set.formatted === 0 || set.formatted ? set.formatted : set.value;
  192. let li = $.create('li', {
  193. styles: {
  194. 'border-top': `3px solid ${color}`
  195. },
  196. innerHTML: `<strong style="display: block;">${ value === 0 || value ? value : '' }</strong>
  197. ${set.title ? set.title : '' }`
  198. });
  199. this.dataPointList.appendChild(li);
  200. });
  201. }
  202. calcPosition() {
  203. let width = this.container.offsetWidth;
  204. this.top = this.y - this.container.offsetHeight
  205. - TOOLTIP_POINTER_TRIANGLE_HEIGHT;
  206. this.left = this.x - width/2;
  207. let maxLeft = this.parent.offsetWidth - width;
  208. let pointer = this.container.querySelector('.svg-pointer');
  209. if(this.left < 0) {
  210. pointer.style.left = `calc(50% - ${-1 * this.left}px)`;
  211. this.left = 0;
  212. } else if(this.left > maxLeft) {
  213. let delta = this.left - maxLeft;
  214. let pointerOffset = `calc(50% + ${delta}px)`;
  215. pointer.style.left = pointerOffset;
  216. this.left = maxLeft;
  217. } else {
  218. pointer.style.left = `50%`;
  219. }
  220. }
  221. setValues(x, y, title = {}, listValues = [], index = -1) {
  222. this.titleName = title.name;
  223. this.titleValue = title.value;
  224. this.listValues = listValues;
  225. this.x = x;
  226. this.y = y;
  227. this.titleValueFirst = title.valueFirst || 0;
  228. this.index = index;
  229. this.refresh();
  230. }
  231. hideTip() {
  232. this.container.style.top = '0px';
  233. this.container.style.left = '0px';
  234. this.container.style.opacity = '0';
  235. }
  236. showTip() {
  237. this.container.style.top = this.top + 'px';
  238. this.container.style.left = this.left + 'px';
  239. this.container.style.opacity = '1';
  240. }
  241. }
  242. /**
  243. * Returns the value of a number upto 2 decimal places.
  244. * @param {Number} d Any number
  245. */
  246. function floatTwo(d) {
  247. return parseFloat(d.toFixed(2));
  248. }
  249. /**
  250. * Returns whether or not two given arrays are equal.
  251. * @param {Array} arr1 First array
  252. * @param {Array} arr2 Second array
  253. */
  254. /**
  255. * Shuffles array in place. ES6 version
  256. * @param {Array} array An array containing the items.
  257. */
  258. /**
  259. * Fill an array with extra points
  260. * @param {Array} array Array
  261. * @param {Number} count number of filler elements
  262. * @param {Object} element element to fill with
  263. * @param {Boolean} start fill at start?
  264. */
  265. function fillArray(array, count, element, start=false) {
  266. if(!element) {
  267. element = start ? array[0] : array[array.length - 1];
  268. }
  269. let fillerArray = new Array(Math.abs(count)).fill(element);
  270. array = start ? fillerArray.concat(array) : array.concat(fillerArray);
  271. return array;
  272. }
  273. /**
  274. * Returns pixel width of string.
  275. * @param {String} string
  276. * @param {Number} charWidth Width of single char in pixels
  277. */
  278. function getStringWidth(string, charWidth) {
  279. return (string+"").length * charWidth;
  280. }
  281. // https://stackoverflow.com/a/29325222
  282. function getPositionByAngle(angle, radius) {
  283. return {
  284. x: Math.sin(angle * ANGLE_RATIO) * radius,
  285. y: Math.cos(angle * ANGLE_RATIO) * radius,
  286. };
  287. }
  288. /**
  289. * Check if a number is valid for svg attributes
  290. * @param {object} candidate Candidate to test
  291. * @param {Boolean} nonNegative flag to treat negative number as invalid
  292. */
  293. function isValidNumber(candidate, nonNegative=false) {
  294. if (Number.isNaN(candidate)) return false;
  295. else if (candidate === undefined) return false;
  296. else if (!Number.isFinite(candidate)) return false;
  297. else if (nonNegative && candidate < 0) return false;
  298. else return true;
  299. }
  300. /**
  301. * Round a number to the closes precision, max max precision 4
  302. * @param {Number} d Any Number
  303. */
  304. function round(d) {
  305. // https://floating-point-gui.de/
  306. // https://www.jacklmoore.com/notes/rounding-in-javascript/
  307. return Number(Math.round(d + 'e4') + 'e-4');
  308. }
  309. function getBarHeightAndYAttr(yTop, zeroLine) {
  310. let height, y;
  311. if (yTop <= zeroLine) {
  312. height = zeroLine - yTop;
  313. y = yTop;
  314. } else {
  315. height = yTop - zeroLine;
  316. y = zeroLine;
  317. }
  318. return [height, y];
  319. }
  320. function equilizeNoOfElements(array1, array2,
  321. extraCount = array2.length - array1.length) {
  322. // Doesn't work if either has zero elements.
  323. if(extraCount > 0) {
  324. array1 = fillArray(array1, extraCount);
  325. } else {
  326. array2 = fillArray(array2, extraCount);
  327. }
  328. return [array1, array2];
  329. }
  330. function truncateString(txt, len) {
  331. if (!txt) {
  332. return;
  333. }
  334. if (txt.length > len) {
  335. return txt.slice(0, len-3) + '...';
  336. } else {
  337. return txt;
  338. }
  339. }
  340. function shortenLargeNumber(label) {
  341. let number;
  342. if (typeof label === 'number') number = label;
  343. else if (typeof label === 'string') {
  344. number = Number(label);
  345. if (Number.isNaN(number)) return label;
  346. }
  347. // Using absolute since log wont work for negative numbers
  348. let p = Math.floor(Math.log10(Math.abs(number)));
  349. if (p <= 2) return number; // Return as is for a 3 digit number of less
  350. let l = Math.floor(p / 3);
  351. let shortened = (Math.pow(10, p - l * 3) * +(number / Math.pow(10, p)).toFixed(1));
  352. // Correct for floating point error upto 2 decimal places
  353. return Math.round(shortened*100)/100 + ' ' + ['', 'K', 'M', 'B', 'T'][l];
  354. }
  355. // cubic bezier curve calculation (from example by François Romain)
  356. function getSplineCurvePointsStr(xList, yList) {
  357. let points=[];
  358. for(let i=0;i<xList.length;i++){
  359. points.push([xList[i], yList[i]]);
  360. }
  361. let smoothing = 0.2;
  362. let line = (pointA, pointB) => {
  363. let lengthX = pointB[0] - pointA[0];
  364. let lengthY = pointB[1] - pointA[1];
  365. return {
  366. length: Math.sqrt(Math.pow(lengthX, 2) + Math.pow(lengthY, 2)),
  367. angle: Math.atan2(lengthY, lengthX)
  368. };
  369. };
  370. let controlPoint = (current, previous, next, reverse) => {
  371. let p = previous || current;
  372. let n = next || current;
  373. let o = line(p, n);
  374. let angle = o.angle + (reverse ? Math.PI : 0);
  375. let length = o.length * smoothing;
  376. let x = current[0] + Math.cos(angle) * length;
  377. let y = current[1] + Math.sin(angle) * length;
  378. return [x, y];
  379. };
  380. let bezierCommand = (point, i, a) => {
  381. let cps = controlPoint(a[i - 1], a[i - 2], point);
  382. let cpe = controlPoint(point, a[i - 1], a[i + 1], true);
  383. return `C ${cps[0]},${cps[1]} ${cpe[0]},${cpe[1]} ${point[0]},${point[1]}`;
  384. };
  385. let pointStr = (points, command) => {
  386. return points.reduce((acc, point, i, a) => i === 0
  387. ? `${point[0]},${point[1]}`
  388. : `${acc} ${command(point, i, a)}`, '');
  389. };
  390. return pointStr(points, bezierCommand);
  391. }
  392. const PRESET_COLOR_MAP = {
  393. 'light-blue': '#7cd6fd',
  394. 'blue': '#5e64ff',
  395. 'violet': '#743ee2',
  396. 'red': '#ff5858',
  397. 'orange': '#ffa00a',
  398. 'yellow': '#feef72',
  399. 'green': '#28a745',
  400. 'light-green': '#98d85b',
  401. 'purple': '#b554ff',
  402. 'magenta': '#ffa3ef',
  403. 'black': '#36114C',
  404. 'grey': '#bdd3e6',
  405. 'light-grey': '#f0f4f7',
  406. 'dark-grey': '#b8c2cc'
  407. };
  408. function limitColor(r){
  409. if (r > 255) return 255;
  410. else if (r < 0) return 0;
  411. return r;
  412. }
  413. function lightenDarkenColor(color, amt) {
  414. let col = getColor(color);
  415. let usePound = false;
  416. if (col[0] == "#") {
  417. col = col.slice(1);
  418. usePound = true;
  419. }
  420. let num = parseInt(col,16);
  421. let r = limitColor((num >> 16) + amt);
  422. let b = limitColor(((num >> 8) & 0x00FF) + amt);
  423. let g = limitColor((num & 0x0000FF) + amt);
  424. return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
  425. }
  426. function isValidColor(string) {
  427. // https://stackoverflow.com/a/32685393
  428. let HEX_RE = /(^\s*)(#)((?:[A-Fa-f0-9]{3}){1,2})$/i;
  429. let RGB_RE = /(^\s*)(rgb|hsl)(a?)[(]\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*(?:,\s*([\d.]+)\s*)?[)]$/i;
  430. return HEX_RE.test(string) || RGB_RE.test(string);
  431. }
  432. const getColor = (color) => {
  433. return PRESET_COLOR_MAP[color] || color;
  434. };
  435. const AXIS_TICK_LENGTH = 6;
  436. const LABEL_MARGIN = 4;
  437. const LABEL_MAX_CHARS = 15;
  438. const FONT_SIZE = 10;
  439. const BASE_LINE_COLOR = '#dadada';
  440. const FONT_FILL = '#555b51';
  441. function $$1(expr, con) {
  442. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  443. }
  444. function createSVG(tag, o) {
  445. var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  446. for (var i in o) {
  447. var val = o[i];
  448. if (i === "inside") {
  449. $$1(val).appendChild(element);
  450. }
  451. else if (i === "around") {
  452. var ref = $$1(val);
  453. ref.parentNode.insertBefore(element, ref);
  454. element.appendChild(ref);
  455. } else if (i === "styles") {
  456. if(typeof val === "object") {
  457. Object.keys(val).map(prop => {
  458. element.style[prop] = val[prop];
  459. });
  460. }
  461. } else {
  462. if(i === "className") { i = "class"; }
  463. if(i === "innerHTML") {
  464. element['textContent'] = val;
  465. } else {
  466. element.setAttribute(i, val);
  467. }
  468. }
  469. }
  470. return element;
  471. }
  472. function renderVerticalGradient(svgDefElem, gradientId) {
  473. return createSVG('linearGradient', {
  474. inside: svgDefElem,
  475. id: gradientId,
  476. x1: 0,
  477. x2: 0,
  478. y1: 0,
  479. y2: 1
  480. });
  481. }
  482. function setGradientStop(gradElem, offset, color, opacity) {
  483. return createSVG('stop', {
  484. 'inside': gradElem,
  485. 'style': `stop-color: ${color}`,
  486. 'offset': offset,
  487. 'stop-opacity': opacity
  488. });
  489. }
  490. function makeSVGContainer(parent, className, width, height) {
  491. return createSVG('svg', {
  492. className: className,
  493. inside: parent,
  494. width: width,
  495. height: height
  496. });
  497. }
  498. function makeSVGDefs(svgContainer) {
  499. return createSVG('defs', {
  500. inside: svgContainer,
  501. });
  502. }
  503. function makeSVGGroup(className, transform='', parent=undefined) {
  504. let args = {
  505. className: className,
  506. transform: transform
  507. };
  508. if(parent) args.inside = parent;
  509. return createSVG('g', args);
  510. }
  511. function makePath(pathStr, className='', stroke='none', fill='none', strokeWidth=2) {
  512. return createSVG('path', {
  513. className: className,
  514. d: pathStr,
  515. styles: {
  516. stroke: stroke,
  517. fill: fill,
  518. 'stroke-width': strokeWidth
  519. }
  520. });
  521. }
  522. function makeArcPathStr(startPosition, endPosition, center, radius, clockWise=1, largeArc=0){
  523. let [arcStartX, arcStartY] = [center.x + startPosition.x, center.y + startPosition.y];
  524. let [arcEndX, arcEndY] = [center.x + endPosition.x, center.y + endPosition.y];
  525. return `M${center.x} ${center.y}
  526. L${arcStartX} ${arcStartY}
  527. A ${radius} ${radius} 0 ${largeArc} ${clockWise ? 1 : 0}
  528. ${arcEndX} ${arcEndY} z`;
  529. }
  530. function makeCircleStr(startPosition, endPosition, center, radius, clockWise=1, largeArc=0){
  531. let [arcStartX, arcStartY] = [center.x + startPosition.x, center.y + startPosition.y];
  532. let [arcEndX, midArc, arcEndY] = [center.x + endPosition.x, center.y * 2, center.y + endPosition.y];
  533. return `M${center.x} ${center.y}
  534. L${arcStartX} ${arcStartY}
  535. A ${radius} ${radius} 0 ${largeArc} ${clockWise ? 1 : 0}
  536. ${arcEndX} ${midArc} z
  537. L${arcStartX} ${midArc}
  538. A ${radius} ${radius} 0 ${largeArc} ${clockWise ? 1 : 0}
  539. ${arcEndX} ${arcEndY} z`;
  540. }
  541. function makeArcStrokePathStr(startPosition, endPosition, center, radius, clockWise=1, largeArc=0){
  542. let [arcStartX, arcStartY] = [center.x + startPosition.x, center.y + startPosition.y];
  543. let [arcEndX, arcEndY] = [center.x + endPosition.x, center.y + endPosition.y];
  544. return `M${arcStartX} ${arcStartY}
  545. A ${radius} ${radius} 0 ${largeArc} ${clockWise ? 1 : 0}
  546. ${arcEndX} ${arcEndY}`;
  547. }
  548. function makeStrokeCircleStr(startPosition, endPosition, center, radius, clockWise=1, largeArc=0){
  549. let [arcStartX, arcStartY] = [center.x + startPosition.x, center.y + startPosition.y];
  550. let [arcEndX, midArc, arcEndY] = [center.x + endPosition.x, radius * 2 + arcStartY, center.y + startPosition.y];
  551. return `M${arcStartX} ${arcStartY}
  552. A ${radius} ${radius} 0 ${largeArc} ${clockWise ? 1 : 0}
  553. ${arcEndX} ${midArc}
  554. M${arcStartX} ${midArc}
  555. A ${radius} ${radius} 0 ${largeArc} ${clockWise ? 1 : 0}
  556. ${arcEndX} ${arcEndY}`;
  557. }
  558. function makeGradient(svgDefElem, color, lighter = false) {
  559. let gradientId ='path-fill-gradient' + '-' + color + '-' +(lighter ? 'lighter' : 'default');
  560. let gradientDef = renderVerticalGradient(svgDefElem, gradientId);
  561. let opacities = [1, 0.6, 0.2];
  562. if(lighter) {
  563. opacities = [0.4, 0.2, 0];
  564. }
  565. setGradientStop(gradientDef, "0%", color, opacities[0]);
  566. setGradientStop(gradientDef, "50%", color, opacities[1]);
  567. setGradientStop(gradientDef, "100%", color, opacities[2]);
  568. return gradientId;
  569. }
  570. function percentageBar(x, y, width, height,
  571. depth=PERCENTAGE_BAR_DEFAULT_DEPTH, fill='none') {
  572. let args = {
  573. className: 'percentage-bar',
  574. x: x,
  575. y: y,
  576. width: width,
  577. height: height,
  578. fill: fill,
  579. styles: {
  580. 'stroke': lightenDarkenColor(fill, -25),
  581. // Diabolically good: https://stackoverflow.com/a/9000859
  582. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray
  583. 'stroke-dasharray': `0, ${height + width}, ${width}, ${height}`,
  584. 'stroke-width': depth
  585. },
  586. };
  587. return createSVG("rect", args);
  588. }
  589. function heatSquare(className, x, y, size, radius, fill='none', data={}) {
  590. let args = {
  591. className: className,
  592. x: x,
  593. y: y,
  594. width: size,
  595. height: size,
  596. rx: radius,
  597. fill: fill
  598. };
  599. Object.keys(data).map(key => {
  600. args[key] = data[key];
  601. });
  602. return createSVG("rect", args);
  603. }
  604. function legendBar(x, y, size, fill='none', label, truncate=false) {
  605. label = truncate ? truncateString(label, LABEL_MAX_CHARS) : label;
  606. let args = {
  607. className: 'legend-bar',
  608. x: 0,
  609. y: 0,
  610. width: size,
  611. height: '2px',
  612. fill: fill
  613. };
  614. let text = createSVG('text', {
  615. className: 'legend-dataset-text',
  616. x: 0,
  617. y: 0,
  618. dy: (FONT_SIZE * 2) + 'px',
  619. 'font-size': (FONT_SIZE * 1.2) + 'px',
  620. 'text-anchor': 'start',
  621. fill: FONT_FILL,
  622. innerHTML: label
  623. });
  624. let group = createSVG('g', {
  625. transform: `translate(${x}, ${y})`
  626. });
  627. group.appendChild(createSVG("rect", args));
  628. group.appendChild(text);
  629. return group;
  630. }
  631. function legendDot(x, y, size, fill='none', label, truncate=false) {
  632. label = truncate ? truncateString(label, LABEL_MAX_CHARS) : label;
  633. let args = {
  634. className: 'legend-dot',
  635. cx: 0,
  636. cy: 0,
  637. r: size,
  638. fill: fill
  639. };
  640. let text = createSVG('text', {
  641. className: 'legend-dataset-text',
  642. x: 0,
  643. y: 0,
  644. dx: (FONT_SIZE) + 'px',
  645. dy: (FONT_SIZE/3) + 'px',
  646. 'font-size': (FONT_SIZE * 1.2) + 'px',
  647. 'text-anchor': 'start',
  648. fill: FONT_FILL,
  649. innerHTML: label
  650. });
  651. let group = createSVG('g', {
  652. transform: `translate(${x}, ${y})`
  653. });
  654. group.appendChild(createSVG("circle", args));
  655. group.appendChild(text);
  656. return group;
  657. }
  658. function makeText(className, x, y, content, options = {}) {
  659. let fontSize = options.fontSize || FONT_SIZE;
  660. let dy = options.dy !== undefined ? options.dy : (fontSize / 2);
  661. let fill = options.fill || FONT_FILL;
  662. let textAnchor = options.textAnchor || 'start';
  663. return createSVG('text', {
  664. className: className,
  665. x: x,
  666. y: y,
  667. dy: dy + 'px',
  668. 'font-size': fontSize + 'px',
  669. fill: fill,
  670. 'text-anchor': textAnchor,
  671. innerHTML: content
  672. });
  673. }
  674. function makeVertLine(x, label, y1, y2, options={}) {
  675. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  676. let l = createSVG('line', {
  677. className: 'line-vertical ' + options.className,
  678. x1: 0,
  679. x2: 0,
  680. y1: y1,
  681. y2: y2,
  682. styles: {
  683. stroke: options.stroke
  684. }
  685. });
  686. let text = createSVG('text', {
  687. x: 0,
  688. y: y1 > y2 ? y1 + LABEL_MARGIN : y1 - LABEL_MARGIN - FONT_SIZE,
  689. dy: FONT_SIZE + 'px',
  690. 'font-size': FONT_SIZE + 'px',
  691. 'text-anchor': 'middle',
  692. innerHTML: label + ""
  693. });
  694. let line = createSVG('g', {
  695. transform: `translate(${ x }, 0)`
  696. });
  697. line.appendChild(l);
  698. line.appendChild(text);
  699. return line;
  700. }
  701. function makeHoriLine(y, label, x1, x2, options={}) {
  702. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  703. if(!options.lineType) options.lineType = '';
  704. if (options.shortenNumbers) label = shortenLargeNumber(label);
  705. let className = 'line-horizontal ' + options.className +
  706. (options.lineType === "dashed" ? "dashed": "");
  707. let l = createSVG('line', {
  708. className: className,
  709. x1: x1,
  710. x2: x2,
  711. y1: 0,
  712. y2: 0,
  713. styles: {
  714. stroke: options.stroke
  715. }
  716. });
  717. let text = createSVG('text', {
  718. x: x1 < x2 ? x1 - LABEL_MARGIN : x1 + LABEL_MARGIN,
  719. y: 0,
  720. dy: (FONT_SIZE / 2 - 2) + 'px',
  721. 'font-size': FONT_SIZE + 'px',
  722. 'text-anchor': x1 < x2 ? 'end' : 'start',
  723. innerHTML: label+""
  724. });
  725. let line = createSVG('g', {
  726. transform: `translate(0, ${y})`,
  727. 'stroke-opacity': 1
  728. });
  729. if(text === 0 || text === '0') {
  730. line.style.stroke = "rgba(27, 31, 35, 0.6)";
  731. }
  732. line.appendChild(l);
  733. line.appendChild(text);
  734. return line;
  735. }
  736. function yLine(y, label, width, options={}) {
  737. if (!isValidNumber(y)) y = 0;
  738. if(!options.pos) options.pos = 'left';
  739. if(!options.offset) options.offset = 0;
  740. if(!options.mode) options.mode = 'span';
  741. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  742. if(!options.className) options.className = '';
  743. let x1 = -1 * AXIS_TICK_LENGTH;
  744. let x2 = options.mode === 'span' ? width + AXIS_TICK_LENGTH : 0;
  745. if(options.mode === 'tick' && options.pos === 'right') {
  746. x1 = width + AXIS_TICK_LENGTH;
  747. x2 = width;
  748. }
  749. // let offset = options.pos === 'left' ? -1 * options.offset : options.offset;
  750. x1 += options.offset;
  751. x2 += options.offset;
  752. return makeHoriLine(y, label, x1, x2, {
  753. stroke: options.stroke,
  754. className: options.className,
  755. lineType: options.lineType,
  756. shortenNumbers: options.shortenNumbers
  757. });
  758. }
  759. function xLine(x, label, height, options={}) {
  760. if (!isValidNumber(x)) x = 0;
  761. if(!options.pos) options.pos = 'bottom';
  762. if(!options.offset) options.offset = 0;
  763. if(!options.mode) options.mode = 'span';
  764. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  765. if(!options.className) options.className = '';
  766. // Draw X axis line in span/tick mode with optional label
  767. // y2(span)
  768. // |
  769. // |
  770. // x line |
  771. // |
  772. // |
  773. // ---------------------+-- y2(tick)
  774. // |
  775. // y1
  776. let y1 = height + AXIS_TICK_LENGTH;
  777. let y2 = options.mode === 'span' ? -1 * AXIS_TICK_LENGTH : height;
  778. if(options.mode === 'tick' && options.pos === 'top') {
  779. // top axis ticks
  780. y1 = -1 * AXIS_TICK_LENGTH;
  781. y2 = 0;
  782. }
  783. return makeVertLine(x, label, y1, y2, {
  784. stroke: options.stroke,
  785. className: options.className,
  786. lineType: options.lineType
  787. });
  788. }
  789. function yMarker(y, label, width, options={}) {
  790. if(!options.labelPos) options.labelPos = 'right';
  791. let x = options.labelPos === 'left' ? LABEL_MARGIN
  792. : width - getStringWidth(label, 5) - LABEL_MARGIN;
  793. let labelSvg = createSVG('text', {
  794. className: 'chart-label',
  795. x: x,
  796. y: 0,
  797. dy: (FONT_SIZE / -2) + 'px',
  798. 'font-size': FONT_SIZE + 'px',
  799. 'text-anchor': 'start',
  800. innerHTML: label+""
  801. });
  802. let line = makeHoriLine(y, '', 0, width, {
  803. stroke: options.stroke || BASE_LINE_COLOR,
  804. className: options.className || '',
  805. lineType: options.lineType
  806. });
  807. line.appendChild(labelSvg);
  808. return line;
  809. }
  810. function yRegion(y1, y2, width, label, options={}) {
  811. // return a group
  812. let height = y1 - y2;
  813. let rect = createSVG('rect', {
  814. className: `bar mini`, // remove class
  815. styles: {
  816. fill: `rgba(228, 234, 239, 0.49)`,
  817. stroke: BASE_LINE_COLOR,
  818. 'stroke-dasharray': `${width}, ${height}`
  819. },
  820. // 'data-point-index': index,
  821. x: 0,
  822. y: 0,
  823. width: width,
  824. height: height
  825. });
  826. if(!options.labelPos) options.labelPos = 'right';
  827. let x = options.labelPos === 'left' ? LABEL_MARGIN
  828. : width - getStringWidth(label+"", 4.5) - LABEL_MARGIN;
  829. let labelSvg = createSVG('text', {
  830. className: 'chart-label',
  831. x: x,
  832. y: 0,
  833. dy: (FONT_SIZE / -2) + 'px',
  834. 'font-size': FONT_SIZE + 'px',
  835. 'text-anchor': 'start',
  836. innerHTML: label+""
  837. });
  838. let region = createSVG('g', {
  839. transform: `translate(0, ${y2})`
  840. });
  841. region.appendChild(rect);
  842. region.appendChild(labelSvg);
  843. return region;
  844. }
  845. function datasetBar(x, yTop, width, color, label='', index=0, offset=0, meta={}) {
  846. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  847. y -= offset;
  848. if(height === 0) {
  849. height = meta.minHeight;
  850. y -= meta.minHeight;
  851. }
  852. // Preprocess numbers to avoid svg building errors
  853. if (!isValidNumber(x)) x = 0;
  854. if (!isValidNumber(y)) y = 0;
  855. if (!isValidNumber(height, true)) height = 0;
  856. if (!isValidNumber(width, true)) width = 0;
  857. let rect = createSVG('rect', {
  858. className: `bar mini`,
  859. style: `fill: ${color}`,
  860. 'data-point-index': index,
  861. x: x,
  862. y: y,
  863. width: width,
  864. height: height
  865. });
  866. label += "";
  867. if(!label && !label.length) {
  868. return rect;
  869. } else {
  870. rect.setAttribute('y', 0);
  871. rect.setAttribute('x', 0);
  872. let text = createSVG('text', {
  873. className: 'data-point-value',
  874. x: width/2,
  875. y: 0,
  876. dy: (FONT_SIZE / 2 * -1) + 'px',
  877. 'font-size': FONT_SIZE + 'px',
  878. 'text-anchor': 'middle',
  879. innerHTML: label
  880. });
  881. let group = createSVG('g', {
  882. 'data-point-index': index,
  883. transform: `translate(${x}, ${y})`
  884. });
  885. group.appendChild(rect);
  886. group.appendChild(text);
  887. return group;
  888. }
  889. }
  890. function datasetDot(x, y, radius, color, label='', index=0) {
  891. let dot = createSVG('circle', {
  892. style: `fill: ${color}`,
  893. 'data-point-index': index,
  894. cx: x,
  895. cy: y,
  896. r: radius
  897. });
  898. label += "";
  899. if(!label && !label.length) {
  900. return dot;
  901. } else {
  902. dot.setAttribute('cy', 0);
  903. dot.setAttribute('cx', 0);
  904. let text = createSVG('text', {
  905. className: 'data-point-value',
  906. x: 0,
  907. y: 0,
  908. dy: (FONT_SIZE / 2 * -1 - radius) + 'px',
  909. 'font-size': FONT_SIZE + 'px',
  910. 'text-anchor': 'middle',
  911. innerHTML: label
  912. });
  913. let group = createSVG('g', {
  914. 'data-point-index': index,
  915. transform: `translate(${x}, ${y})`
  916. });
  917. group.appendChild(dot);
  918. group.appendChild(text);
  919. return group;
  920. }
  921. }
  922. function getPaths(xList, yList, color, options={}, meta={}) {
  923. let pointsList = yList.map((y, i) => (xList[i] + ',' + y));
  924. let pointsStr = pointsList.join("L");
  925. // Spline
  926. if (options.spline)
  927. pointsStr = getSplineCurvePointsStr(xList, yList);
  928. let path = makePath("M"+pointsStr, 'line-graph-path', color);
  929. // HeatLine
  930. if(options.heatline) {
  931. let gradient_id = makeGradient(meta.svgDefs, color);
  932. path.style.stroke = `url(#${gradient_id})`;
  933. }
  934. let paths = {
  935. path: path
  936. };
  937. // Region
  938. if(options.regionFill) {
  939. let gradient_id_region = makeGradient(meta.svgDefs, color, true);
  940. let pathStr = "M" + `${xList[0]},${meta.zeroLine}L` + pointsStr + `L${xList.slice(-1)[0]},${meta.zeroLine}`;
  941. paths.region = makePath(pathStr, `region-fill`, 'none', `url(#${gradient_id_region})`);
  942. }
  943. return paths;
  944. }
  945. let makeOverlay = {
  946. 'bar': (unit) => {
  947. let transformValue;
  948. if(unit.nodeName !== 'rect') {
  949. transformValue = unit.getAttribute('transform');
  950. unit = unit.childNodes[0];
  951. }
  952. let overlay = unit.cloneNode();
  953. overlay.style.fill = '#000000';
  954. overlay.style.opacity = '0.4';
  955. if(transformValue) {
  956. overlay.setAttribute('transform', transformValue);
  957. }
  958. return overlay;
  959. },
  960. 'dot': (unit) => {
  961. let transformValue;
  962. if(unit.nodeName !== 'circle') {
  963. transformValue = unit.getAttribute('transform');
  964. unit = unit.childNodes[0];
  965. }
  966. let overlay = unit.cloneNode();
  967. let radius = unit.getAttribute('r');
  968. let fill = unit.getAttribute('fill');
  969. overlay.setAttribute('r', parseInt(radius) + DOT_OVERLAY_SIZE_INCR);
  970. overlay.setAttribute('fill', fill);
  971. overlay.style.opacity = '0.6';
  972. if(transformValue) {
  973. overlay.setAttribute('transform', transformValue);
  974. }
  975. return overlay;
  976. },
  977. 'heat_square': (unit) => {
  978. let transformValue;
  979. if(unit.nodeName !== 'circle') {
  980. transformValue = unit.getAttribute('transform');
  981. unit = unit.childNodes[0];
  982. }
  983. let overlay = unit.cloneNode();
  984. let radius = unit.getAttribute('r');
  985. let fill = unit.getAttribute('fill');
  986. overlay.setAttribute('r', parseInt(radius) + DOT_OVERLAY_SIZE_INCR);
  987. overlay.setAttribute('fill', fill);
  988. overlay.style.opacity = '0.6';
  989. if(transformValue) {
  990. overlay.setAttribute('transform', transformValue);
  991. }
  992. return overlay;
  993. }
  994. };
  995. let updateOverlay = {
  996. 'bar': (unit, overlay) => {
  997. let transformValue;
  998. if(unit.nodeName !== 'rect') {
  999. transformValue = unit.getAttribute('transform');
  1000. unit = unit.childNodes[0];
  1001. }
  1002. let attributes = ['x', 'y', 'width', 'height'];
  1003. Object.values(unit.attributes)
  1004. .filter(attr => attributes.includes(attr.name) && attr.specified)
  1005. .map(attr => {
  1006. overlay.setAttribute(attr.name, attr.nodeValue);
  1007. });
  1008. if(transformValue) {
  1009. overlay.setAttribute('transform', transformValue);
  1010. }
  1011. },
  1012. 'dot': (unit, overlay) => {
  1013. let transformValue;
  1014. if(unit.nodeName !== 'circle') {
  1015. transformValue = unit.getAttribute('transform');
  1016. unit = unit.childNodes[0];
  1017. }
  1018. let attributes = ['cx', 'cy'];
  1019. Object.values(unit.attributes)
  1020. .filter(attr => attributes.includes(attr.name) && attr.specified)
  1021. .map(attr => {
  1022. overlay.setAttribute(attr.name, attr.nodeValue);
  1023. });
  1024. if(transformValue) {
  1025. overlay.setAttribute('transform', transformValue);
  1026. }
  1027. },
  1028. 'heat_square': (unit, overlay) => {
  1029. let transformValue;
  1030. if(unit.nodeName !== 'circle') {
  1031. transformValue = unit.getAttribute('transform');
  1032. unit = unit.childNodes[0];
  1033. }
  1034. let attributes = ['cx', 'cy'];
  1035. Object.values(unit.attributes)
  1036. .filter(attr => attributes.includes(attr.name) && attr.specified)
  1037. .map(attr => {
  1038. overlay.setAttribute(attr.name, attr.nodeValue);
  1039. });
  1040. if(transformValue) {
  1041. overlay.setAttribute('transform', transformValue);
  1042. }
  1043. },
  1044. };
  1045. const UNIT_ANIM_DUR = 350;
  1046. const PATH_ANIM_DUR = 350;
  1047. const MARKER_LINE_ANIM_DUR = UNIT_ANIM_DUR;
  1048. const REPLACE_ALL_NEW_DUR = 250;
  1049. const STD_EASING = 'easein';
  1050. function translate(unit, oldCoord, newCoord, duration) {
  1051. let old = typeof oldCoord === 'string' ? oldCoord : oldCoord.join(', ');
  1052. return [
  1053. unit,
  1054. {transform: newCoord.join(', ')},
  1055. duration,
  1056. STD_EASING,
  1057. "translate",
  1058. {transform: old}
  1059. ];
  1060. }
  1061. function translateVertLine(xLine, newX, oldX) {
  1062. return translate(xLine, [oldX, 0], [newX, 0], MARKER_LINE_ANIM_DUR);
  1063. }
  1064. function translateHoriLine(yLine, newY, oldY) {
  1065. return translate(yLine, [0, oldY], [0, newY], MARKER_LINE_ANIM_DUR);
  1066. }
  1067. function animateRegion(rectGroup, newY1, newY2, oldY2) {
  1068. let newHeight = newY1 - newY2;
  1069. let rect = rectGroup.childNodes[0];
  1070. let width = rect.getAttribute("width");
  1071. let rectAnim = [
  1072. rect,
  1073. { height: newHeight, 'stroke-dasharray': `${width}, ${newHeight}` },
  1074. MARKER_LINE_ANIM_DUR,
  1075. STD_EASING
  1076. ];
  1077. let groupAnim = translate(rectGroup, [0, oldY2], [0, newY2], MARKER_LINE_ANIM_DUR);
  1078. return [rectAnim, groupAnim];
  1079. }
  1080. function animateBar(bar, x, yTop, width, offset=0, meta={}) {
  1081. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  1082. y -= offset;
  1083. if(bar.nodeName !== 'rect') {
  1084. let rect = bar.childNodes[0];
  1085. let rectAnim = [
  1086. rect,
  1087. {width: width, height: height},
  1088. UNIT_ANIM_DUR,
  1089. STD_EASING
  1090. ];
  1091. let oldCoordStr = bar.getAttribute("transform").split("(")[1].slice(0, -1);
  1092. let groupAnim = translate(bar, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  1093. return [rectAnim, groupAnim];
  1094. } else {
  1095. return [[bar, {width: width, height: height, x: x, y: y}, UNIT_ANIM_DUR, STD_EASING]];
  1096. }
  1097. // bar.animate({height: args.newHeight, y: yTop}, UNIT_ANIM_DUR, mina.easein);
  1098. }
  1099. function animateDot(dot, x, y) {
  1100. if(dot.nodeName !== 'circle') {
  1101. let oldCoordStr = dot.getAttribute("transform").split("(")[1].slice(0, -1);
  1102. let groupAnim = translate(dot, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
  1103. return [groupAnim];
  1104. } else {
  1105. return [[dot, {cx: x, cy: y}, UNIT_ANIM_DUR, STD_EASING]];
  1106. }
  1107. // dot.animate({cy: yTop}, UNIT_ANIM_DUR, mina.easein);
  1108. }
  1109. function animatePath(paths, newXList, newYList, zeroLine, spline) {
  1110. let pathComponents = [];
  1111. let pointsStr = newYList.map((y, i) => (newXList[i] + ',' + y)).join("L");
  1112. if (spline)
  1113. pointsStr = getSplineCurvePointsStr(newXList, newYList);
  1114. const animPath = [paths.path, {d:"M" + pointsStr}, PATH_ANIM_DUR, STD_EASING];
  1115. pathComponents.push(animPath);
  1116. if(paths.region) {
  1117. let regStartPt = `${newXList[0]},${zeroLine}L`;
  1118. let regEndPt = `L${newXList.slice(-1)[0]}, ${zeroLine}`;
  1119. const animRegion = [
  1120. paths.region,
  1121. {d:"M" + regStartPt + pointsStr + regEndPt},
  1122. PATH_ANIM_DUR,
  1123. STD_EASING
  1124. ];
  1125. pathComponents.push(animRegion);
  1126. }
  1127. return pathComponents;
  1128. }
  1129. function animatePathStr(oldPath, pathStr) {
  1130. return [oldPath, {d: pathStr}, UNIT_ANIM_DUR, STD_EASING];
  1131. }
  1132. // Leveraging SMIL Animations
  1133. const EASING = {
  1134. ease: "0.25 0.1 0.25 1",
  1135. linear: "0 0 1 1",
  1136. // easein: "0.42 0 1 1",
  1137. easein: "0.1 0.8 0.2 1",
  1138. easeout: "0 0 0.58 1",
  1139. easeinout: "0.42 0 0.58 1"
  1140. };
  1141. function animateSVGElement(element, props, dur, easingType="linear", type=undefined, oldValues={}) {
  1142. let animElement = element.cloneNode(true);
  1143. let newElement = element.cloneNode(true);
  1144. for(var attributeName in props) {
  1145. let animateElement;
  1146. if(attributeName === 'transform') {
  1147. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
  1148. } else {
  1149. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
  1150. }
  1151. let currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
  1152. let value = props[attributeName];
  1153. let animAttr = {
  1154. attributeName: attributeName,
  1155. from: currentValue,
  1156. to: value,
  1157. begin: "0s",
  1158. dur: dur/1000 + "s",
  1159. values: currentValue + ";" + value,
  1160. keySplines: EASING[easingType],
  1161. keyTimes: "0;1",
  1162. calcMode: "spline",
  1163. fill: 'freeze'
  1164. };
  1165. if(type) {
  1166. animAttr["type"] = type;
  1167. }
  1168. for (var i in animAttr) {
  1169. animateElement.setAttribute(i, animAttr[i]);
  1170. }
  1171. animElement.appendChild(animateElement);
  1172. if(type) {
  1173. newElement.setAttribute(attributeName, `translate(${value})`);
  1174. } else {
  1175. newElement.setAttribute(attributeName, value);
  1176. }
  1177. }
  1178. return [animElement, newElement];
  1179. }
  1180. function transform(element, style) { // eslint-disable-line no-unused-vars
  1181. element.style.transform = style;
  1182. element.style.webkitTransform = style;
  1183. element.style.msTransform = style;
  1184. element.style.mozTransform = style;
  1185. element.style.oTransform = style;
  1186. }
  1187. function animateSVG(svgContainer, elements) {
  1188. let newElements = [];
  1189. let animElements = [];
  1190. elements.map(element => {
  1191. let unit = element[0];
  1192. let parent = unit.parentNode;
  1193. let animElement, newElement;
  1194. element[0] = unit;
  1195. [animElement, newElement] = animateSVGElement(...element);
  1196. newElements.push(newElement);
  1197. animElements.push([animElement, parent]);
  1198. parent.replaceChild(animElement, unit);
  1199. });
  1200. let animSvg = svgContainer.cloneNode(true);
  1201. animElements.map((animElement, i) => {
  1202. animElement[1].replaceChild(newElements[i], animElement[0]);
  1203. elements[i][0] = newElements[i];
  1204. });
  1205. return animSvg;
  1206. }
  1207. function runSMILAnimation(parent, svgElement, elementsToAnimate) {
  1208. if(elementsToAnimate.length === 0) return;
  1209. let animSvgElement = animateSVG(svgElement, elementsToAnimate);
  1210. if(svgElement.parentNode == parent) {
  1211. parent.removeChild(svgElement);
  1212. parent.appendChild(animSvgElement);
  1213. }
  1214. // Replace the new svgElement (data has already been replaced)
  1215. setTimeout(() => {
  1216. if(animSvgElement.parentNode == parent) {
  1217. parent.removeChild(animSvgElement);
  1218. parent.appendChild(svgElement);
  1219. }
  1220. }, REPLACE_ALL_NEW_DUR);
  1221. }
  1222. const CSSTEXT = ".chart-container{position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif}.chart-container .axis,.chart-container .chart-label{fill:#555b51}.chart-container .axis line,.chart-container .chart-label line{stroke:#dadada}.chart-container .dataset-units circle{stroke:#fff;stroke-width:2}.chart-container .dataset-units path{fill:none;stroke-opacity:1;stroke-width:2px}.chart-container .dataset-path{stroke-width:2px}.chart-container .path-group path{fill:none;stroke-opacity:1;stroke-width:2px}.chart-container line.dashed{stroke-dasharray:5,3}.chart-container .axis-line .specific-value{text-anchor:start}.chart-container .axis-line .y-line{text-anchor:end}.chart-container .axis-line .x-line{text-anchor:middle}.chart-container .legend-dataset-text{fill:#6c7680;font-weight:600}.graph-svg-tip{position:absolute;z-index:99999;padding:10px;font-size:12px;color:#959da5;text-align:center;background:rgba(0,0,0,.8);border-radius:3px}.graph-svg-tip ul{padding-left:0;display:flex}.graph-svg-tip ol{padding-left:0;display:flex}.graph-svg-tip ul.data-point-list li{min-width:90px;flex:1;font-weight:600}.graph-svg-tip strong{color:#dfe2e5;font-weight:600}.graph-svg-tip .svg-pointer{position:absolute;height:5px;margin:0 0 0 -5px;content:' ';border:5px solid transparent;border-top-color:rgba(0,0,0,.8)}.graph-svg-tip.comparison{padding:0;text-align:left;pointer-events:none}.graph-svg-tip.comparison .title{display:block;padding:10px;margin:0;font-weight:600;line-height:1;pointer-events:none}.graph-svg-tip.comparison ul{margin:0;white-space:nowrap;list-style:none}.graph-svg-tip.comparison li{display:inline-block;padding:5px 10px}";
  1223. function downloadFile(filename, data) {
  1224. var a = document.createElement('a');
  1225. a.style = "display: none";
  1226. var blob = new Blob(data, {type: "image/svg+xml; charset=utf-8"});
  1227. var url = window.URL.createObjectURL(blob);
  1228. a.href = url;
  1229. a.download = filename;
  1230. document.body.appendChild(a);
  1231. a.click();
  1232. setTimeout(function(){
  1233. document.body.removeChild(a);
  1234. window.URL.revokeObjectURL(url);
  1235. }, 300);
  1236. }
  1237. function prepareForExport(svg) {
  1238. let clone = svg.cloneNode(true);
  1239. clone.classList.add('chart-container');
  1240. clone.setAttribute('xmlns', "http://www.w3.org/2000/svg");
  1241. clone.setAttribute('xmlns:xlink', "http://www.w3.org/1999/xlink");
  1242. let styleEl = $.create('style', {
  1243. 'innerHTML': CSSTEXT
  1244. });
  1245. clone.insertBefore(styleEl, clone.firstChild);
  1246. let container = $.create('div');
  1247. container.appendChild(clone);
  1248. return container.innerHTML;
  1249. }
  1250. class BaseChart {
  1251. constructor(parent, options) {
  1252. this.parent = typeof parent === 'string'
  1253. ? document.querySelector(parent)
  1254. : parent;
  1255. if (!(this.parent instanceof HTMLElement)) {
  1256. throw new Error('No `parent` element to render on was provided.');
  1257. }
  1258. this.rawChartArgs = options;
  1259. this.title = options.title || '';
  1260. this.type = options.type || '';
  1261. this.realData = this.prepareData(options.data);
  1262. this.data = this.prepareFirstData(this.realData);
  1263. this.colors = this.validateColors(options.colors, this.type);
  1264. this.config = {
  1265. showTooltip: 1, // calculate
  1266. showLegend: 1, // calculate
  1267. isNavigable: options.isNavigable || 0,
  1268. animate: (typeof options.animate !== 'undefined') ? options.animate : 1,
  1269. truncateLegends: options.truncateLegends || 1
  1270. };
  1271. this.measures = JSON.parse(JSON.stringify(BASE_MEASURES));
  1272. let m = this.measures;
  1273. this.setMeasures(options);
  1274. if(!this.title.length) { m.titleHeight = 0; }
  1275. if(!this.config.showLegend) m.legendHeight = 0;
  1276. this.argHeight = options.height || m.baseHeight;
  1277. this.state = {};
  1278. this.options = {};
  1279. this.initTimeout = INIT_CHART_UPDATE_TIMEOUT;
  1280. if(this.config.isNavigable) {
  1281. this.overlays = [];
  1282. }
  1283. this.configure(options);
  1284. }
  1285. prepareData(data) {
  1286. return data;
  1287. }
  1288. prepareFirstData(data) {
  1289. return data;
  1290. }
  1291. validateColors(colors, type) {
  1292. const validColors = [];
  1293. colors = (colors || []).concat(DEFAULT_COLORS[type]);
  1294. colors.forEach((string) => {
  1295. const color = getColor(string);
  1296. if(!isValidColor(color)) {
  1297. console.warn('"' + string + '" is not a valid color.');
  1298. } else {
  1299. validColors.push(color);
  1300. }
  1301. });
  1302. return validColors;
  1303. }
  1304. setMeasures() {
  1305. // Override measures, including those for title and legend
  1306. // set config for legend and title
  1307. }
  1308. configure() {
  1309. let height = this.argHeight;
  1310. this.baseHeight = height;
  1311. this.height = height - getExtraHeight(this.measures);
  1312. // Bind window events
  1313. this.boundDrawFn = () => this.draw(true);
  1314. window.addEventListener('resize', this.boundDrawFn);
  1315. window.addEventListener('orientationchange', this.boundDrawFn);
  1316. }
  1317. destroy() {
  1318. window.removeEventListener('resize', this.boundDrawFn);
  1319. window.removeEventListener('orientationchange', this.boundDrawFn);
  1320. }
  1321. // Has to be called manually
  1322. setup() {
  1323. this.makeContainer();
  1324. this.updateWidth();
  1325. this.makeTooltip();
  1326. this.draw(false, true);
  1327. }
  1328. makeContainer() {
  1329. // Chart needs a dedicated parent element
  1330. this.parent.innerHTML = '';
  1331. let args = {
  1332. inside: this.parent,
  1333. className: 'chart-container'
  1334. };
  1335. if(this.independentWidth) {
  1336. args.styles = { width: this.independentWidth + 'px' };
  1337. }
  1338. this.container = $.create('div', args);
  1339. }
  1340. makeTooltip() {
  1341. this.tip = new SvgTip({
  1342. parent: this.container,
  1343. colors: this.colors
  1344. });
  1345. this.bindTooltip();
  1346. }
  1347. bindTooltip() {}
  1348. draw(onlyWidthChange=false, init=false) {
  1349. if (onlyWidthChange && isHidden(this.parent)) {
  1350. // Don't update anything if the chart is hidden
  1351. return;
  1352. }
  1353. this.updateWidth();
  1354. this.calc(onlyWidthChange);
  1355. this.makeChartArea();
  1356. this.setupComponents();
  1357. this.components.forEach(c => c.setup(this.drawArea));
  1358. // this.components.forEach(c => c.make());
  1359. this.render(this.components, false);
  1360. if(init) {
  1361. this.data = this.realData;
  1362. setTimeout(() => {this.update(this.data);}, this.initTimeout);
  1363. }
  1364. this.renderLegend();
  1365. this.setupNavigation(init);
  1366. }
  1367. calc() {} // builds state
  1368. updateWidth() {
  1369. this.baseWidth = getElementContentWidth(this.parent);
  1370. this.width = this.baseWidth - getExtraWidth(this.measures);
  1371. }
  1372. makeChartArea() {
  1373. if(this.svg) {
  1374. this.container.removeChild(this.svg);
  1375. }
  1376. let m = this.measures;
  1377. this.svg = makeSVGContainer(
  1378. this.container,
  1379. 'frappe-chart chart',
  1380. this.baseWidth,
  1381. this.baseHeight
  1382. );
  1383. this.svgDefs = makeSVGDefs(this.svg);
  1384. if(this.title.length) {
  1385. this.titleEL = makeText(
  1386. 'title',
  1387. m.margins.left,
  1388. m.margins.top,
  1389. this.title,
  1390. {
  1391. fontSize: m.titleFontSize,
  1392. fill: '#666666',
  1393. dy: m.titleFontSize
  1394. }
  1395. );
  1396. }
  1397. let top = getTopOffset(m);
  1398. this.drawArea = makeSVGGroup(
  1399. this.type + '-chart chart-draw-area',
  1400. `translate(${getLeftOffset(m)}, ${top})`
  1401. );
  1402. if(this.config.showLegend) {
  1403. top += this.height + m.paddings.bottom;
  1404. this.legendArea = makeSVGGroup(
  1405. 'chart-legend',
  1406. `translate(${getLeftOffset(m)}, ${top})`
  1407. );
  1408. }
  1409. if(this.title.length) { this.svg.appendChild(this.titleEL); }
  1410. this.svg.appendChild(this.drawArea);
  1411. if(this.config.showLegend) { this.svg.appendChild(this.legendArea); }
  1412. this.updateTipOffset(getLeftOffset(m), getTopOffset(m));
  1413. }
  1414. updateTipOffset(x, y) {
  1415. this.tip.offset = {
  1416. x: x,
  1417. y: y
  1418. };
  1419. }
  1420. setupComponents() { this.components = new Map(); }
  1421. update(data) {
  1422. if(!data) {
  1423. console.error('No data to update.');
  1424. }
  1425. this.data = this.prepareData(data);
  1426. this.calc(); // builds state
  1427. this.render(this.components, this.config.animate);
  1428. }
  1429. render(components=this.components, animate=true) {
  1430. if(this.config.isNavigable) {
  1431. // Remove all existing overlays
  1432. this.overlays.map(o => o.parentNode.removeChild(o));
  1433. // ref.parentNode.insertBefore(element, ref);
  1434. }
  1435. let elementsToAnimate = [];
  1436. // Can decouple to this.refreshComponents() first to save animation timeout
  1437. components.forEach(c => {
  1438. elementsToAnimate = elementsToAnimate.concat(c.update(animate));
  1439. });
  1440. if(elementsToAnimate.length > 0) {
  1441. runSMILAnimation(this.container, this.svg, elementsToAnimate);
  1442. setTimeout(() => {
  1443. components.forEach(c => c.make());
  1444. this.updateNav();
  1445. }, CHART_POST_ANIMATE_TIMEOUT);
  1446. } else {
  1447. components.forEach(c => c.make());
  1448. this.updateNav();
  1449. }
  1450. }
  1451. updateNav() {
  1452. if(this.config.isNavigable) {
  1453. this.makeOverlay();
  1454. this.bindUnits();
  1455. }
  1456. }
  1457. renderLegend() {}
  1458. setupNavigation(init=false) {
  1459. if(!this.config.isNavigable) return;
  1460. if(init) {
  1461. this.bindOverlay();
  1462. this.keyActions = {
  1463. '13': this.onEnterKey.bind(this),
  1464. '37': this.onLeftArrow.bind(this),
  1465. '38': this.onUpArrow.bind(this),
  1466. '39': this.onRightArrow.bind(this),
  1467. '40': this.onDownArrow.bind(this),
  1468. };
  1469. document.addEventListener('keydown', (e) => {
  1470. if(isElementInViewport(this.container)) {
  1471. e = e || window.event;
  1472. if(this.keyActions[e.keyCode]) {
  1473. this.keyActions[e.keyCode]();
  1474. }
  1475. }
  1476. });
  1477. }
  1478. }
  1479. makeOverlay() {}
  1480. updateOverlay() {}
  1481. bindOverlay() {}
  1482. bindUnits() {}
  1483. onLeftArrow() {}
  1484. onRightArrow() {}
  1485. onUpArrow() {}
  1486. onDownArrow() {}
  1487. onEnterKey() {}
  1488. addDataPoint() {}
  1489. removeDataPoint() {}
  1490. getDataPoint() {}
  1491. setCurrentDataPoint() {}
  1492. updateDataset() {}
  1493. export() {
  1494. let chartSvg = prepareForExport(this.svg);
  1495. downloadFile(this.title || 'Chart', [chartSvg]);
  1496. }
  1497. }
  1498. class AggregationChart extends BaseChart {
  1499. constructor(parent, args) {
  1500. super(parent, args);
  1501. }
  1502. configure(args) {
  1503. super.configure(args);
  1504. this.config.formatTooltipY = args.tooltipOptions.formatTooltipY;
  1505. this.config.maxSlices = args.maxSlices || 20;
  1506. this.config.maxLegendPoints = args.maxLegendPoints || 20;
  1507. }
  1508. calc() {
  1509. let s = this.state;
  1510. let maxSlices = this.config.maxSlices;
  1511. s.sliceTotals = [];
  1512. let allTotals = this.data.labels.map((label, i) => {
  1513. let total = 0;
  1514. this.data.datasets.map(e => {
  1515. total += e.values[i];
  1516. });
  1517. return [total, label];
  1518. }).filter(d => { return d[0] >= 0; }); // keep only positive results
  1519. let totals = allTotals;
  1520. if(allTotals.length > maxSlices) {
  1521. // Prune and keep a grey area for rest as per maxSlices
  1522. allTotals.sort((a, b) => { return b[0] - a[0]; });
  1523. totals = allTotals.slice(0, maxSlices-1);
  1524. let remaining = allTotals.slice(maxSlices-1);
  1525. let sumOfRemaining = 0;
  1526. remaining.map(d => {sumOfRemaining += d[0];});
  1527. totals.push([sumOfRemaining, 'Rest']);
  1528. this.colors[maxSlices-1] = 'grey';
  1529. }
  1530. s.labels = [];
  1531. totals.map(d => {
  1532. s.sliceTotals.push(round(d[0]));
  1533. s.labels.push(d[1]);
  1534. });
  1535. s.grandTotal = s.sliceTotals.reduce((a, b) => a + b, 0);
  1536. this.center = {
  1537. x: this.width / 2,
  1538. y: this.height / 2
  1539. };
  1540. }
  1541. renderLegend() {
  1542. let s = this.state;
  1543. this.legendArea.textContent = '';
  1544. this.legendTotals = s.sliceTotals.slice(0, this.config.maxLegendPoints);
  1545. let count = 0;
  1546. let y = 0;
  1547. this.legendTotals.map((d, i) => {
  1548. let barWidth = 150;
  1549. let divisor = Math.floor(
  1550. (this.width - getExtraWidth(this.measures))/barWidth
  1551. );
  1552. if (this.legendTotals.length < divisor) {
  1553. barWidth = this.width/this.legendTotals.length;
  1554. }
  1555. if(count > divisor) {
  1556. count = 0;
  1557. y += 20;
  1558. }
  1559. let x = barWidth * count + 5;
  1560. let label = this.config.truncateLegends ? truncateString(s.labels[i], barWidth/10) : s.labels[i];
  1561. let formatted = this.config.formatTooltipY ? this.config.formatTooltipY(d) : d;
  1562. let dot = legendDot(
  1563. x,
  1564. y,
  1565. 5,
  1566. this.colors[i],
  1567. `${label}: ${formatted}`,
  1568. false
  1569. );
  1570. this.legendArea.appendChild(dot);
  1571. count++;
  1572. });
  1573. }
  1574. }
  1575. // Playing around with dates
  1576. const NO_OF_YEAR_MONTHS = 12;
  1577. const NO_OF_DAYS_IN_WEEK = 7;
  1578. const NO_OF_MILLIS = 1000;
  1579. const SEC_IN_DAY = 86400;
  1580. const MONTH_NAMES = ["January", "February", "March", "April", "May",
  1581. "June", "July", "August", "September", "October", "November", "December"];
  1582. const DAY_NAMES_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  1583. // https://stackoverflow.com/a/11252167/6495043
  1584. function treatAsUtc(date) {
  1585. let result = new Date(date);
  1586. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  1587. return result;
  1588. }
  1589. function getYyyyMmDd(date) {
  1590. let dd = date.getDate();
  1591. let mm = date.getMonth() + 1; // getMonth() is zero-based
  1592. return [
  1593. date.getFullYear(),
  1594. (mm>9 ? '' : '0') + mm,
  1595. (dd>9 ? '' : '0') + dd
  1596. ].join('-');
  1597. }
  1598. function clone(date) {
  1599. return new Date(date.getTime());
  1600. }
  1601. // export function getMonthsBetween(startDate, endDate) {}
  1602. function getWeeksBetween(startDate, endDate) {
  1603. let weekStartDate = setDayToSunday(startDate);
  1604. return Math.ceil(getDaysBetween(weekStartDate, endDate) / NO_OF_DAYS_IN_WEEK);
  1605. }
  1606. function getDaysBetween(startDate, endDate) {
  1607. let millisecondsPerDay = SEC_IN_DAY * NO_OF_MILLIS;
  1608. return (treatAsUtc(endDate) - treatAsUtc(startDate)) / millisecondsPerDay;
  1609. }
  1610. function areInSameMonth(startDate, endDate) {
  1611. return startDate.getMonth() === endDate.getMonth()
  1612. && startDate.getFullYear() === endDate.getFullYear();
  1613. }
  1614. function getMonthName(i, short=false) {
  1615. let monthName = MONTH_NAMES[i];
  1616. return short ? monthName.slice(0, 3) : monthName;
  1617. }
  1618. function getLastDateInMonth (month, year) {
  1619. return new Date(year, month + 1, 0); // 0: last day in previous month
  1620. }
  1621. // mutates
  1622. function setDayToSunday(date) {
  1623. let newDate = clone(date);
  1624. const day = newDate.getDay();
  1625. if(day !== 0) {
  1626. addDays(newDate, (-1) * day);
  1627. }
  1628. return newDate;
  1629. }
  1630. // mutates
  1631. function addDays(date, numberOfDays) {
  1632. date.setDate(date.getDate() + numberOfDays);
  1633. }
  1634. class ChartComponent {
  1635. constructor({
  1636. layerClass = '',
  1637. layerTransform = '',
  1638. constants,
  1639. getData,
  1640. makeElements,
  1641. animateElements
  1642. }) {
  1643. this.layerTransform = layerTransform;
  1644. this.constants = constants;
  1645. this.makeElements = makeElements;
  1646. this.getData = getData;
  1647. this.animateElements = animateElements;
  1648. this.store = [];
  1649. this.labels = [];
  1650. this.layerClass = layerClass;
  1651. this.layerClass = typeof(this.layerClass) === 'function'
  1652. ? this.layerClass() : this.layerClass;
  1653. this.refresh();
  1654. }
  1655. refresh(data) {
  1656. this.data = data || this.getData();
  1657. }
  1658. setup(parent) {
  1659. this.layer = makeSVGGroup(this.layerClass, this.layerTransform, parent);
  1660. }
  1661. make() {
  1662. this.render(this.data);
  1663. this.oldData = this.data;
  1664. }
  1665. render(data) {
  1666. this.store = this.makeElements(data);
  1667. this.layer.textContent = '';
  1668. this.store.forEach(element => {
  1669. this.layer.appendChild(element);
  1670. });
  1671. this.labels.forEach(element => {
  1672. this.layer.appendChild(element);
  1673. });
  1674. }
  1675. update(animate = true) {
  1676. this.refresh();
  1677. let animateElements = [];
  1678. if(animate) {
  1679. animateElements = this.animateElements(this.data) || [];
  1680. }
  1681. return animateElements;
  1682. }
  1683. }
  1684. let componentConfigs = {
  1685. donutSlices: {
  1686. layerClass: 'donut-slices',
  1687. makeElements(data) {
  1688. return data.sliceStrings.map((s, i) => {
  1689. let slice = makePath(s, 'donut-path', data.colors[i], 'none', data.strokeWidth);
  1690. slice.style.transition = 'transform .3s;';
  1691. return slice;
  1692. });
  1693. },
  1694. animateElements(newData) {
  1695. return this.store.map((slice, i) => animatePathStr(slice, newData.sliceStrings[i]));
  1696. },
  1697. },
  1698. pieSlices: {
  1699. layerClass: 'pie-slices',
  1700. makeElements(data) {
  1701. return data.sliceStrings.map((s, i) =>{
  1702. let slice = makePath(s, 'pie-path', 'none', data.colors[i]);
  1703. slice.style.transition = 'transform .3s;';
  1704. return slice;
  1705. });
  1706. },
  1707. animateElements(newData) {
  1708. return this.store.map((slice, i) =>
  1709. animatePathStr(slice, newData.sliceStrings[i])
  1710. );
  1711. }
  1712. },
  1713. percentageBars: {
  1714. layerClass: 'percentage-bars',
  1715. makeElements(data) {
  1716. return data.xPositions.map((x, i) =>{
  1717. let y = 0;
  1718. let bar = percentageBar(x, y, data.widths[i],
  1719. this.constants.barHeight, this.constants.barDepth, data.colors[i]);
  1720. return bar;
  1721. });
  1722. },
  1723. animateElements(newData) {
  1724. if(newData) return [];
  1725. }
  1726. },
  1727. yAxis: {
  1728. layerClass: 'y axis',
  1729. makeElements(data) {
  1730. return data.positions.map((position, i) =>
  1731. yLine(position, data.labels[i], this.constants.width,
  1732. {mode: this.constants.mode, pos: this.constants.pos, shortenNumbers: this.constants.shortenNumbers})
  1733. );
  1734. },
  1735. animateElements(newData) {
  1736. let newPos = newData.positions;
  1737. let newLabels = newData.labels;
  1738. let oldPos = this.oldData.positions;
  1739. let oldLabels = this.oldData.labels;
  1740. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1741. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1742. this.render({
  1743. positions: oldPos,
  1744. labels: newLabels
  1745. });
  1746. return this.store.map((line, i) => {
  1747. return translateHoriLine(
  1748. line, newPos[i], oldPos[i]
  1749. );
  1750. });
  1751. }
  1752. },
  1753. xAxis: {
  1754. layerClass: 'x axis',
  1755. makeElements(data) {
  1756. return data.positions.map((position, i) =>
  1757. xLine(position, data.calcLabels[i], this.constants.height,
  1758. {mode: this.constants.mode, pos: this.constants.pos})
  1759. );
  1760. },
  1761. animateElements(newData) {
  1762. let newPos = newData.positions;
  1763. let newLabels = newData.calcLabels;
  1764. let oldPos = this.oldData.positions;
  1765. let oldLabels = this.oldData.calcLabels;
  1766. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1767. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1768. this.render({
  1769. positions: oldPos,
  1770. calcLabels: newLabels
  1771. });
  1772. return this.store.map((line, i) => {
  1773. return translateVertLine(
  1774. line, newPos[i], oldPos[i]
  1775. );
  1776. });
  1777. }
  1778. },
  1779. yMarkers: {
  1780. layerClass: 'y-markers',
  1781. makeElements(data) {
  1782. return data.map(m =>
  1783. yMarker(m.position, m.label, this.constants.width,
  1784. {labelPos: m.options.labelPos, mode: 'span', lineType: 'dashed'})
  1785. );
  1786. },
  1787. animateElements(newData) {
  1788. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1789. let newPos = newData.map(d => d.position);
  1790. let newLabels = newData.map(d => d.label);
  1791. let newOptions = newData.map(d => d.options);
  1792. let oldPos = this.oldData.map(d => d.position);
  1793. this.render(oldPos.map((pos, i) => {
  1794. return {
  1795. position: oldPos[i],
  1796. label: newLabels[i],
  1797. options: newOptions[i]
  1798. };
  1799. }));
  1800. return this.store.map((line, i) => {
  1801. return translateHoriLine(
  1802. line, newPos[i], oldPos[i]
  1803. );
  1804. });
  1805. }
  1806. },
  1807. yRegions: {
  1808. layerClass: 'y-regions',
  1809. makeElements(data) {
  1810. return data.map(r =>
  1811. yRegion(r.startPos, r.endPos, this.constants.width,
  1812. r.label, {labelPos: r.options.labelPos})
  1813. );
  1814. },
  1815. animateElements(newData) {
  1816. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1817. let newPos = newData.map(d => d.endPos);
  1818. let newLabels = newData.map(d => d.label);
  1819. let newStarts = newData.map(d => d.startPos);
  1820. let newOptions = newData.map(d => d.options);
  1821. let oldPos = this.oldData.map(d => d.endPos);
  1822. let oldStarts = this.oldData.map(d => d.startPos);
  1823. this.render(oldPos.map((pos, i) => {
  1824. return {
  1825. startPos: oldStarts[i],
  1826. endPos: oldPos[i],
  1827. label: newLabels[i],
  1828. options: newOptions[i]
  1829. };
  1830. }));
  1831. let animateElements = [];
  1832. this.store.map((rectGroup, i) => {
  1833. animateElements = animateElements.concat(animateRegion(
  1834. rectGroup, newStarts[i], newPos[i], oldPos[i]
  1835. ));
  1836. });
  1837. return animateElements;
  1838. }
  1839. },
  1840. heatDomain: {
  1841. layerClass: function() { return 'heat-domain domain-' + this.constants.index; },
  1842. makeElements(data) {
  1843. let {index, colWidth, rowHeight, squareSize, radius, xTranslate} = this.constants;
  1844. let monthNameHeight = -12;
  1845. let x = xTranslate, y = 0;
  1846. this.serializedSubDomains = [];
  1847. data.cols.map((week, weekNo) => {
  1848. if(weekNo === 1) {
  1849. this.labels.push(
  1850. makeText('domain-name', x, monthNameHeight, getMonthName(index, true).toUpperCase(),
  1851. {
  1852. fontSize: 9
  1853. }
  1854. )
  1855. );
  1856. }
  1857. week.map((day, i) => {
  1858. if(day.fill) {
  1859. let data = {
  1860. 'data-date': day.yyyyMmDd,
  1861. 'data-value': day.dataValue,
  1862. 'data-day': i
  1863. };
  1864. let square = heatSquare('day', x, y, squareSize, radius, day.fill, data);
  1865. this.serializedSubDomains.push(square);
  1866. }
  1867. y += rowHeight;
  1868. });
  1869. y = 0;
  1870. x += colWidth;
  1871. });
  1872. return this.serializedSubDomains;
  1873. },
  1874. animateElements(newData) {
  1875. if(newData) return [];
  1876. }
  1877. },
  1878. barGraph: {
  1879. layerClass: function() { return 'dataset-units dataset-bars dataset-' + this.constants.index; },
  1880. makeElements(data) {
  1881. let c = this.constants;
  1882. this.unitType = 'bar';
  1883. this.units = data.yPositions.map((y, j) => {
  1884. return datasetBar(
  1885. data.xPositions[j],
  1886. y,
  1887. data.barWidth,
  1888. c.color,
  1889. data.labels[j],
  1890. j,
  1891. data.offsets[j],
  1892. {
  1893. zeroLine: data.zeroLine,
  1894. barsWidth: data.barsWidth,
  1895. minHeight: c.minHeight
  1896. }
  1897. );
  1898. });
  1899. return this.units;
  1900. },
  1901. animateElements(newData) {
  1902. let newXPos = newData.xPositions;
  1903. let newYPos = newData.yPositions;
  1904. let newOffsets = newData.offsets;
  1905. let newLabels = newData.labels;
  1906. let oldXPos = this.oldData.xPositions;
  1907. let oldYPos = this.oldData.yPositions;
  1908. let oldOffsets = this.oldData.offsets;
  1909. let oldLabels = this.oldData.labels;
  1910. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1911. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1912. [oldOffsets, newOffsets] = equilizeNoOfElements(oldOffsets, newOffsets);
  1913. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1914. this.render({
  1915. xPositions: oldXPos,
  1916. yPositions: oldYPos,
  1917. offsets: oldOffsets,
  1918. labels: newLabels,
  1919. zeroLine: this.oldData.zeroLine,
  1920. barsWidth: this.oldData.barsWidth,
  1921. barWidth: this.oldData.barWidth,
  1922. });
  1923. let animateElements = [];
  1924. this.store.map((bar, i) => {
  1925. animateElements = animateElements.concat(animateBar(
  1926. bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i],
  1927. {zeroLine: newData.zeroLine}
  1928. ));
  1929. });
  1930. return animateElements;
  1931. }
  1932. },
  1933. lineGraph: {
  1934. layerClass: function() { return 'dataset-units dataset-line dataset-' + this.constants.index; },
  1935. makeElements(data) {
  1936. let c = this.constants;
  1937. this.unitType = 'dot';
  1938. this.paths = {};
  1939. if(!c.hideLine) {
  1940. this.paths = getPaths(
  1941. data.xPositions,
  1942. data.yPositions,
  1943. c.color,
  1944. {
  1945. heatline: c.heatline,
  1946. regionFill: c.regionFill,
  1947. spline: c.spline
  1948. },
  1949. {
  1950. svgDefs: c.svgDefs,
  1951. zeroLine: data.zeroLine
  1952. }
  1953. );
  1954. }
  1955. this.units = [];
  1956. if(!c.hideDots) {
  1957. this.units = data.yPositions.map((y, j) => {
  1958. return datasetDot(
  1959. data.xPositions[j],
  1960. y,
  1961. data.radius,
  1962. c.color,
  1963. (c.valuesOverPoints ? data.values[j] : ''),
  1964. j
  1965. );
  1966. });
  1967. }
  1968. return Object.values(this.paths).concat(this.units);
  1969. },
  1970. animateElements(newData) {
  1971. let newXPos = newData.xPositions;
  1972. let newYPos = newData.yPositions;
  1973. let newValues = newData.values;
  1974. let oldXPos = this.oldData.xPositions;
  1975. let oldYPos = this.oldData.yPositions;
  1976. let oldValues = this.oldData.values;
  1977. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1978. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1979. [oldValues, newValues] = equilizeNoOfElements(oldValues, newValues);
  1980. this.render({
  1981. xPositions: oldXPos,
  1982. yPositions: oldYPos,
  1983. values: newValues,
  1984. zeroLine: this.oldData.zeroLine,
  1985. radius: this.oldData.radius,
  1986. });
  1987. let animateElements = [];
  1988. if(Object.keys(this.paths).length) {
  1989. animateElements = animateElements.concat(animatePath(
  1990. this.paths, newXPos, newYPos, newData.zeroLine, this.constants.spline));
  1991. }
  1992. if(this.units.length) {
  1993. this.units.map((dot, i) => {
  1994. animateElements = animateElements.concat(animateDot(
  1995. dot, newXPos[i], newYPos[i]));
  1996. });
  1997. }
  1998. return animateElements;
  1999. }
  2000. }
  2001. };
  2002. function getComponent(name, constants, getData) {
  2003. let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
  2004. let config = componentConfigs[keys[0]];
  2005. Object.assign(config, {
  2006. constants: constants,
  2007. getData: getData
  2008. });
  2009. return new ChartComponent(config);
  2010. }
  2011. class PercentageChart extends AggregationChart {
  2012. constructor(parent, args) {
  2013. super(parent, args);
  2014. this.type = 'percentage';
  2015. this.setup();
  2016. }
  2017. setMeasures(options) {
  2018. let m = this.measures;
  2019. this.barOptions = options.barOptions || {};
  2020. let b = this.barOptions;
  2021. b.height = b.height || PERCENTAGE_BAR_DEFAULT_HEIGHT;
  2022. b.depth = b.depth || PERCENTAGE_BAR_DEFAULT_DEPTH;
  2023. m.paddings.right = 30;
  2024. m.legendHeight = 60;
  2025. m.baseHeight = (b.height + b.depth * 0.5) * 8;
  2026. }
  2027. setupComponents() {
  2028. let s = this.state;
  2029. let componentConfigs = [
  2030. [
  2031. 'percentageBars',
  2032. {
  2033. barHeight: this.barOptions.height,
  2034. barDepth: this.barOptions.depth,
  2035. },
  2036. function() {
  2037. return {
  2038. xPositions: s.xPositions,
  2039. widths: s.widths,
  2040. colors: this.colors
  2041. };
  2042. }.bind(this)
  2043. ]
  2044. ];
  2045. this.components = new Map(componentConfigs
  2046. .map(args => {
  2047. let component = getComponent(...args);
  2048. return [args[0], component];
  2049. }));
  2050. }
  2051. calc() {
  2052. super.calc();
  2053. let s = this.state;
  2054. s.xPositions = [];
  2055. s.widths = [];
  2056. let xPos = 0;
  2057. s.sliceTotals.map((value) => {
  2058. let width = this.width * value / s.grandTotal;
  2059. s.widths.push(width);
  2060. s.xPositions.push(xPos);
  2061. xPos += width;
  2062. });
  2063. }
  2064. makeDataByIndex() { }
  2065. bindTooltip() {
  2066. let s = this.state;
  2067. this.container.addEventListener('mousemove', (e) => {
  2068. let bars = this.components.get('percentageBars').store;
  2069. let bar = e.target;
  2070. if(bars.includes(bar)) {
  2071. let i = bars.indexOf(bar);
  2072. let gOff = getOffset(this.container), pOff = getOffset(bar);
  2073. let x = pOff.left - gOff.left + parseInt(bar.getAttribute('width'))/2;
  2074. let y = pOff.top - gOff.top;
  2075. let title = (this.formattedLabels && this.formattedLabels.length>0
  2076. ? this.formattedLabels[i] : this.state.labels[i]) + ': ';
  2077. let fraction = s.sliceTotals[i]/s.grandTotal;
  2078. this.tip.setValues(x, y, {name: title, value: (fraction*100).toFixed(1) + "%"});
  2079. this.tip.showTip();
  2080. }
  2081. });
  2082. }
  2083. }
  2084. class PieChart extends AggregationChart {
  2085. constructor(parent, args) {
  2086. super(parent, args);
  2087. this.type = 'pie';
  2088. this.initTimeout = 0;
  2089. this.init = 1;
  2090. this.setup();
  2091. }
  2092. configure(args) {
  2093. super.configure(args);
  2094. this.mouseMove = this.mouseMove.bind(this);
  2095. this.mouseLeave = this.mouseLeave.bind(this);
  2096. this.hoverRadio = args.hoverRadio || 0.1;
  2097. this.config.startAngle = args.startAngle || 0;
  2098. this.clockWise = args.clockWise || false;
  2099. }
  2100. calc() {
  2101. super.calc();
  2102. let s = this.state;
  2103. this.radius = (this.height > this.width ? this.center.x : this.center.y);
  2104. const { radius, clockWise } = this;
  2105. const prevSlicesProperties = s.slicesProperties || [];
  2106. s.sliceStrings = [];
  2107. s.slicesProperties = [];
  2108. let curAngle = 180 - this.config.startAngle;
  2109. s.sliceTotals.map((total, i) => {
  2110. const startAngle = curAngle;
  2111. const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
  2112. const largeArc = originDiffAngle > 180 ? 1: 0;
  2113. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  2114. const endAngle = curAngle = curAngle + diffAngle;
  2115. const startPosition = getPositionByAngle(startAngle, radius);
  2116. const endPosition = getPositionByAngle(endAngle, radius);
  2117. const prevProperty = this.init && prevSlicesProperties[i];
  2118. let curStart,curEnd;
  2119. if(this.init) {
  2120. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  2121. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  2122. } else {
  2123. curStart = startPosition;
  2124. curEnd = endPosition;
  2125. }
  2126. const curPath =
  2127. originDiffAngle === 360
  2128. ? makeCircleStr(curStart, curEnd, this.center, this.radius, clockWise, largeArc)
  2129. : makeArcPathStr(curStart, curEnd, this.center, this.radius, clockWise, largeArc);
  2130. s.sliceStrings.push(curPath);
  2131. s.slicesProperties.push({
  2132. startPosition,
  2133. endPosition,
  2134. value: total,
  2135. total: s.grandTotal,
  2136. startAngle,
  2137. endAngle,
  2138. angle: diffAngle
  2139. });
  2140. });
  2141. this.init = 0;
  2142. }
  2143. setupComponents() {
  2144. let s = this.state;
  2145. let componentConfigs = [
  2146. [
  2147. 'pieSlices',
  2148. { },
  2149. function() {
  2150. return {
  2151. sliceStrings: s.sliceStrings,
  2152. colors: this.colors
  2153. };
  2154. }.bind(this)
  2155. ]
  2156. ];
  2157. this.components = new Map(componentConfigs
  2158. .map(args => {
  2159. let component = getComponent(...args);
  2160. return [args[0], component];
  2161. }));
  2162. }
  2163. calTranslateByAngle(property){
  2164. const{radius,hoverRadio} = this;
  2165. const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  2166. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  2167. }
  2168. hoverSlice(path,i,flag,e){
  2169. if(!path) return;
  2170. const color = this.colors[i];
  2171. if(flag) {
  2172. transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
  2173. path.style.fill = lightenDarkenColor(color, 50);
  2174. let g_off = getOffset(this.svg);
  2175. let x = e.pageX - g_off.left + 10;
  2176. let y = e.pageY - g_off.top - 10;
  2177. let title = (this.formatted_labels && this.formatted_labels.length > 0
  2178. ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
  2179. let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
  2180. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  2181. this.tip.showTip();
  2182. } else {
  2183. transform(path,'translate3d(0,0,0)');
  2184. this.tip.hideTip();
  2185. path.style.fill = color;
  2186. }
  2187. }
  2188. bindTooltip() {
  2189. this.container.addEventListener('mousemove', this.mouseMove);
  2190. this.container.addEventListener('mouseleave', this.mouseLeave);
  2191. }
  2192. mouseMove(e){
  2193. const target = e.target;
  2194. let slices = this.components.get('pieSlices').store;
  2195. let prevIndex = this.curActiveSliceIndex;
  2196. let prevAcitve = this.curActiveSlice;
  2197. if(slices.includes(target)) {
  2198. let i = slices.indexOf(target);
  2199. this.hoverSlice(prevAcitve, prevIndex,false);
  2200. this.curActiveSlice = target;
  2201. this.curActiveSliceIndex = i;
  2202. this.hoverSlice(target, i, true, e);
  2203. } else {
  2204. this.mouseLeave();
  2205. }
  2206. }
  2207. mouseLeave(){
  2208. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  2209. }
  2210. }
  2211. function normalize(x) {
  2212. // Calculates mantissa and exponent of a number
  2213. // Returns normalized number and exponent
  2214. // https://stackoverflow.com/q/9383593/6495043
  2215. if(x===0) {
  2216. return [0, 0];
  2217. }
  2218. if(isNaN(x)) {
  2219. return {mantissa: -6755399441055744, exponent: 972};
  2220. }
  2221. var sig = x > 0 ? 1 : -1;
  2222. if(!isFinite(x)) {
  2223. return {mantissa: sig * 4503599627370496, exponent: 972};
  2224. }
  2225. x = Math.abs(x);
  2226. var exp = Math.floor(Math.log10(x));
  2227. var man = x/Math.pow(10, exp);
  2228. return [sig * man, exp];
  2229. }
  2230. function getChartRangeIntervals(max, min=0) {
  2231. let upperBound = Math.ceil(max);
  2232. let lowerBound = Math.floor(min);
  2233. let range = upperBound - lowerBound;
  2234. let noOfParts = range;
  2235. let partSize = 1;
  2236. // To avoid too many partitions
  2237. if(range > 5) {
  2238. if(range % 2 !== 0) {
  2239. upperBound++;
  2240. // Recalc range
  2241. range = upperBound - lowerBound;
  2242. }
  2243. noOfParts = range/2;
  2244. partSize = 2;
  2245. }
  2246. // Special case: 1 and 2
  2247. if(range <= 2) {
  2248. noOfParts = 4;
  2249. partSize = range/noOfParts;
  2250. }
  2251. // Special case: 0
  2252. if(range === 0) {
  2253. noOfParts = 5;
  2254. partSize = 1;
  2255. }
  2256. let intervals = [];
  2257. for(var i = 0; i <= noOfParts; i++){
  2258. intervals.push(lowerBound + partSize * i);
  2259. }
  2260. return intervals;
  2261. }
  2262. function getChartIntervals(maxValue, minValue=0) {
  2263. let [normalMaxValue, exponent] = normalize(maxValue);
  2264. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  2265. // Allow only 7 significant digits
  2266. normalMaxValue = normalMaxValue.toFixed(6);
  2267. let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  2268. intervals = intervals.map(value => value * Math.pow(10, exponent));
  2269. return intervals;
  2270. }
  2271. function calcChartIntervals(values, withMinimum=false) {
  2272. //*** Where the magic happens ***
  2273. // Calculates best-fit y intervals from given values
  2274. // and returns the interval array
  2275. let maxValue = Math.max(...values);
  2276. let minValue = Math.min(...values);
  2277. // Exponent to be used for pretty print
  2278. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  2279. function getPositiveFirstIntervals(maxValue, absMinValue) {
  2280. let intervals = getChartIntervals(maxValue);
  2281. let intervalSize = intervals[1] - intervals[0];
  2282. // Then unshift the negative values
  2283. let value = 0;
  2284. for(var i = 1; value < absMinValue; i++) {
  2285. value += intervalSize;
  2286. intervals.unshift((-1) * value);
  2287. }
  2288. return intervals;
  2289. }
  2290. // CASE I: Both non-negative
  2291. if(maxValue >= 0 && minValue >= 0) {
  2292. exponent = normalize(maxValue)[1];
  2293. if(!withMinimum) {
  2294. intervals = getChartIntervals(maxValue);
  2295. } else {
  2296. intervals = getChartIntervals(maxValue, minValue);
  2297. }
  2298. }
  2299. // CASE II: Only minValue negative
  2300. else if(maxValue > 0 && minValue < 0) {
  2301. // `withMinimum` irrelevant in this case,
  2302. // We'll be handling both sides of zero separately
  2303. // (both starting from zero)
  2304. // Because ceil() and floor() behave differently
  2305. // in those two regions
  2306. let absMinValue = Math.abs(minValue);
  2307. if(maxValue >= absMinValue) {
  2308. exponent = normalize(maxValue)[1];
  2309. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  2310. } else {
  2311. // Mirror: maxValue => absMinValue, then change sign
  2312. exponent = normalize(absMinValue)[1];
  2313. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  2314. intervals = posIntervals.reverse().map(d => d * (-1));
  2315. }
  2316. }
  2317. // CASE III: Both non-positive
  2318. else if(maxValue <= 0 && minValue <= 0) {
  2319. // Mirrored Case I:
  2320. // Work with positives, then reverse the sign and array
  2321. let pseudoMaxValue = Math.abs(minValue);
  2322. let pseudoMinValue = Math.abs(maxValue);
  2323. exponent = normalize(pseudoMaxValue)[1];
  2324. if(!withMinimum) {
  2325. intervals = getChartIntervals(pseudoMaxValue);
  2326. } else {
  2327. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  2328. }
  2329. intervals = intervals.reverse().map(d => d * (-1));
  2330. }
  2331. return intervals;
  2332. }
  2333. function getZeroIndex(yPts) {
  2334. let zeroIndex;
  2335. let interval = getIntervalSize(yPts);
  2336. if(yPts.indexOf(0) >= 0) {
  2337. // the range has a given zero
  2338. // zero-line on the chart
  2339. zeroIndex = yPts.indexOf(0);
  2340. } else if(yPts[0] > 0) {
  2341. // Minimum value is positive
  2342. // zero-line is off the chart: below
  2343. let min = yPts[0];
  2344. zeroIndex = (-1) * min / interval;
  2345. } else {
  2346. // Maximum value is negative
  2347. // zero-line is off the chart: above
  2348. let max = yPts[yPts.length - 1];
  2349. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  2350. }
  2351. return zeroIndex;
  2352. }
  2353. function getIntervalSize(orderedArray) {
  2354. return orderedArray[1] - orderedArray[0];
  2355. }
  2356. function getValueRange(orderedArray) {
  2357. return orderedArray[orderedArray.length-1] - orderedArray[0];
  2358. }
  2359. function scale(val, yAxis) {
  2360. return floatTwo(yAxis.zeroLine - val * yAxis.scaleMultiplier);
  2361. }
  2362. function getClosestInArray(goal, arr, index = false) {
  2363. let closest = arr.reduce(function(prev, curr) {
  2364. return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
  2365. }, []);
  2366. return index ? arr.indexOf(closest) : closest;
  2367. }
  2368. function calcDistribution(values, distributionSize) {
  2369. // Assume non-negative values,
  2370. // implying distribution minimum at zero
  2371. let dataMaxValue = Math.max(...values);
  2372. let distributionStep = 1 / (distributionSize - 1);
  2373. let distribution = [];
  2374. for(var i = 0; i < distributionSize; i++) {
  2375. let checkpoint = dataMaxValue * (distributionStep * i);
  2376. distribution.push(checkpoint);
  2377. }
  2378. return distribution;
  2379. }
  2380. function getMaxCheckpoint(value, distribution) {
  2381. return distribution.filter(d => d < value).length;
  2382. }
  2383. const COL_WIDTH = HEATMAP_SQUARE_SIZE + HEATMAP_GUTTER_SIZE;
  2384. const ROW_HEIGHT = COL_WIDTH;
  2385. // const DAY_INCR = 1;
  2386. class Heatmap extends BaseChart {
  2387. constructor(parent, options) {
  2388. super(parent, options);
  2389. this.type = 'heatmap';
  2390. this.countLabel = options.countLabel || '';
  2391. let validStarts = ['Sunday', 'Monday'];
  2392. let startSubDomain = validStarts.includes(options.startSubDomain)
  2393. ? options.startSubDomain : 'Sunday';
  2394. this.startSubDomainIndex = validStarts.indexOf(startSubDomain);
  2395. this.setup();
  2396. }
  2397. setMeasures(options) {
  2398. let m = this.measures;
  2399. this.discreteDomains = options.discreteDomains === 0 ? 0 : 1;
  2400. m.paddings.top = ROW_HEIGHT * 3;
  2401. m.paddings.bottom = 0;
  2402. m.legendHeight = ROW_HEIGHT * 2;
  2403. m.baseHeight = ROW_HEIGHT * NO_OF_DAYS_IN_WEEK
  2404. + getExtraHeight(m);
  2405. let d = this.data;
  2406. let spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
  2407. this.independentWidth = (getWeeksBetween(d.start, d.end)
  2408. + spacing) * COL_WIDTH + getExtraWidth(m);
  2409. }
  2410. updateWidth() {
  2411. let spacing = this.discreteDomains ? NO_OF_YEAR_MONTHS : 0;
  2412. let noOfWeeks = this.state.noOfWeeks ? this.state.noOfWeeks : 52;
  2413. this.baseWidth = (noOfWeeks + spacing) * COL_WIDTH
  2414. + getExtraWidth(this.measures);
  2415. }
  2416. prepareData(data=this.data) {
  2417. if(data.start && data.end && data.start > data.end) {
  2418. throw new Error('Start date cannot be greater than end date.');
  2419. }
  2420. if(!data.start) {
  2421. data.start = new Date();
  2422. data.start.setFullYear( data.start.getFullYear() - 1 );
  2423. }
  2424. if(!data.end) { data.end = new Date(); }
  2425. data.dataPoints = data.dataPoints || {};
  2426. if(parseInt(Object.keys(data.dataPoints)[0]) > 100000) {
  2427. let points = {};
  2428. Object.keys(data.dataPoints).forEach(timestampSec$$1 => {
  2429. let date = new Date(timestampSec$$1 * NO_OF_MILLIS);
  2430. points[getYyyyMmDd(date)] = data.dataPoints[timestampSec$$1];
  2431. });
  2432. data.dataPoints = points;
  2433. }
  2434. return data;
  2435. }
  2436. calc() {
  2437. let s = this.state;
  2438. s.start = clone(this.data.start);
  2439. s.end = clone(this.data.end);
  2440. s.firstWeekStart = clone(s.start);
  2441. s.noOfWeeks = getWeeksBetween(s.start, s.end);
  2442. s.distribution = calcDistribution(
  2443. Object.values(this.data.dataPoints), HEATMAP_DISTRIBUTION_SIZE);
  2444. s.domainConfigs = this.getDomains();
  2445. }
  2446. setupComponents() {
  2447. let s = this.state;
  2448. let lessCol = this.discreteDomains ? 0 : 1;
  2449. let componentConfigs = s.domainConfigs.map((config, i) => [
  2450. 'heatDomain',
  2451. {
  2452. index: config.index,
  2453. colWidth: COL_WIDTH,
  2454. rowHeight: ROW_HEIGHT,
  2455. squareSize: HEATMAP_SQUARE_SIZE,
  2456. radius: this.rawChartArgs.radius || 0,
  2457. xTranslate: s.domainConfigs
  2458. .filter((config, j) => j < i)
  2459. .map(config => config.cols.length - lessCol)
  2460. .reduce((a, b) => a + b, 0)
  2461. * COL_WIDTH
  2462. },
  2463. function() {
  2464. return s.domainConfigs[i];
  2465. }.bind(this)
  2466. ]);
  2467. this.components = new Map(componentConfigs
  2468. .map((args, i) => {
  2469. let component = getComponent(...args);
  2470. return [args[0] + '-' + i, component];
  2471. })
  2472. );
  2473. let y = 0;
  2474. DAY_NAMES_SHORT.forEach((dayName, i) => {
  2475. if([1, 3, 5].includes(i)) {
  2476. let dayText = makeText('subdomain-name', -COL_WIDTH/2, y, dayName,
  2477. {
  2478. fontSize: HEATMAP_SQUARE_SIZE,
  2479. dy: 8,
  2480. textAnchor: 'end'
  2481. }
  2482. );
  2483. this.drawArea.appendChild(dayText);
  2484. }
  2485. y += ROW_HEIGHT;
  2486. });
  2487. }
  2488. update(data) {
  2489. if(!data) {
  2490. console.error('No data to update.');
  2491. }
  2492. this.data = this.prepareData(data);
  2493. this.draw();
  2494. this.bindTooltip();
  2495. }
  2496. bindTooltip() {
  2497. this.container.addEventListener('mousemove', (e) => {
  2498. this.components.forEach(comp => {
  2499. let daySquares = comp.store;
  2500. let daySquare = e.target;
  2501. if(daySquares.includes(daySquare)) {
  2502. let count = daySquare.getAttribute('data-value');
  2503. let dateParts = daySquare.getAttribute('data-date').split('-');
  2504. let month = getMonthName(parseInt(dateParts[1])-1, true);
  2505. let gOff = this.container.getBoundingClientRect(), pOff = daySquare.getBoundingClientRect();
  2506. let width = parseInt(e.target.getAttribute('width'));
  2507. let x = pOff.left - gOff.left + width/2;
  2508. let y = pOff.top - gOff.top;
  2509. let value = count + ' ' + this.countLabel;
  2510. let name = ' on ' + month + ' ' + dateParts[0] + ', ' + dateParts[2];
  2511. this.tip.setValues(x, y, {name: name, value: value, valueFirst: 1}, []);
  2512. this.tip.showTip();
  2513. }
  2514. });
  2515. });
  2516. }
  2517. renderLegend() {
  2518. this.legendArea.textContent = '';
  2519. let x = 0;
  2520. let y = ROW_HEIGHT;
  2521. let radius = this.rawChartArgs.radius || 0;
  2522. let lessText = makeText('subdomain-name', x, y, 'Less',
  2523. {
  2524. fontSize: HEATMAP_SQUARE_SIZE + 1,
  2525. dy: 9
  2526. }
  2527. );
  2528. x = (COL_WIDTH * 2) + COL_WIDTH/2;
  2529. this.legendArea.appendChild(lessText);
  2530. this.colors.slice(0, HEATMAP_DISTRIBUTION_SIZE).map((color, i) => {
  2531. const square = heatSquare('heatmap-legend-unit', x + (COL_WIDTH + 3) * i,
  2532. y, HEATMAP_SQUARE_SIZE, radius, color);
  2533. this.legendArea.appendChild(square);
  2534. });
  2535. let moreTextX = x + HEATMAP_DISTRIBUTION_SIZE * (COL_WIDTH + 3) + COL_WIDTH/4;
  2536. let moreText = makeText('subdomain-name', moreTextX, y, 'More',
  2537. {
  2538. fontSize: HEATMAP_SQUARE_SIZE + 1,
  2539. dy: 9
  2540. }
  2541. );
  2542. this.legendArea.appendChild(moreText);
  2543. }
  2544. getDomains() {
  2545. let s = this.state;
  2546. const [startMonth, startYear] = [s.start.getMonth(), s.start.getFullYear()];
  2547. const [endMonth, endYear] = [s.end.getMonth(), s.end.getFullYear()];
  2548. const noOfMonths = (endMonth - startMonth + 1) + (endYear - startYear) * 12;
  2549. let domainConfigs = [];
  2550. let startOfMonth = clone(s.start);
  2551. for(var i = 0; i < noOfMonths; i++) {
  2552. let endDate = s.end;
  2553. if(!areInSameMonth(startOfMonth, s.end)) {
  2554. let [month, year] = [startOfMonth.getMonth(), startOfMonth.getFullYear()];
  2555. endDate = getLastDateInMonth(month, year);
  2556. }
  2557. domainConfigs.push(this.getDomainConfig(startOfMonth, endDate));
  2558. addDays(endDate, 1);
  2559. startOfMonth = endDate;
  2560. }
  2561. return domainConfigs;
  2562. }
  2563. getDomainConfig(startDate, endDate='') {
  2564. let [month, year] = [startDate.getMonth(), startDate.getFullYear()];
  2565. let startOfWeek = setDayToSunday(startDate); // TODO: Monday as well
  2566. endDate = clone(endDate) || getLastDateInMonth(month, year);
  2567. let domainConfig = {
  2568. index: month,
  2569. cols: []
  2570. };
  2571. addDays(endDate, 1);
  2572. let noOfMonthWeeks = getWeeksBetween(startOfWeek, endDate);
  2573. let cols = [], col;
  2574. for(var i = 0; i < noOfMonthWeeks; i++) {
  2575. col = this.getCol(startOfWeek, month);
  2576. cols.push(col);
  2577. startOfWeek = new Date(col[NO_OF_DAYS_IN_WEEK - 1].yyyyMmDd);
  2578. addDays(startOfWeek, 1);
  2579. }
  2580. if(col[NO_OF_DAYS_IN_WEEK - 1].dataValue !== undefined) {
  2581. addDays(startOfWeek, 1);
  2582. cols.push(this.getCol(startOfWeek, month, true));
  2583. }
  2584. domainConfig.cols = cols;
  2585. return domainConfig;
  2586. }
  2587. getCol(startDate, month, empty = false) {
  2588. let s = this.state;
  2589. // startDate is the start of week
  2590. let currentDate = clone(startDate);
  2591. let col = [];
  2592. for(var i = 0; i < NO_OF_DAYS_IN_WEEK; i++, addDays(currentDate, 1)) {
  2593. let config = {};
  2594. // Non-generic adjustment for entire heatmap, needs state
  2595. let currentDateWithinData = currentDate >= s.start && currentDate <= s.end;
  2596. if(empty || currentDate.getMonth() !== month || !currentDateWithinData) {
  2597. config.yyyyMmDd = getYyyyMmDd(currentDate);
  2598. } else {
  2599. config = this.getSubDomainConfig(currentDate);
  2600. }
  2601. col.push(config);
  2602. }
  2603. return col;
  2604. }
  2605. getSubDomainConfig(date) {
  2606. let yyyyMmDd = getYyyyMmDd(date);
  2607. let dataValue = this.data.dataPoints[yyyyMmDd];
  2608. let config = {
  2609. yyyyMmDd: yyyyMmDd,
  2610. dataValue: dataValue || 0,
  2611. fill: this.colors[getMaxCheckpoint(dataValue, this.state.distribution)]
  2612. };
  2613. return config;
  2614. }
  2615. }
  2616. function dataPrep(data, type) {
  2617. data.labels = data.labels || [];
  2618. let datasetLength = data.labels.length;
  2619. // Datasets
  2620. let datasets = data.datasets;
  2621. let zeroArray = new Array(datasetLength).fill(0);
  2622. if(!datasets) {
  2623. // default
  2624. datasets = [{
  2625. values: zeroArray
  2626. }];
  2627. }
  2628. datasets.map(d=> {
  2629. // Set values
  2630. if(!d.values) {
  2631. d.values = zeroArray;
  2632. } else {
  2633. // Check for non values
  2634. let vals = d.values;
  2635. vals = vals.map(val => (!isNaN(val) ? val : 0));
  2636. // Trim or extend
  2637. if(vals.length > datasetLength) {
  2638. vals = vals.slice(0, datasetLength);
  2639. } else {
  2640. vals = fillArray(vals, datasetLength - vals.length, 0);
  2641. }
  2642. }
  2643. // Set labels
  2644. //
  2645. // Set type
  2646. if(!d.chartType ) {
  2647. if(!AXIS_DATASET_CHART_TYPES.includes(type)) type === DEFAULT_AXIS_CHART_TYPE;
  2648. d.chartType = type;
  2649. }
  2650. });
  2651. // Markers
  2652. // Regions
  2653. // data.yRegions = data.yRegions || [];
  2654. if(data.yRegions) {
  2655. data.yRegions.map(d => {
  2656. if(d.end < d.start) {
  2657. [d.start, d.end] = [d.end, d.start];
  2658. }
  2659. });
  2660. }
  2661. return data;
  2662. }
  2663. function zeroDataPrep(realData) {
  2664. let datasetLength = realData.labels.length;
  2665. let zeroArray = new Array(datasetLength).fill(0);
  2666. let zeroData = {
  2667. labels: realData.labels.slice(0, -1),
  2668. datasets: realData.datasets.map(d => {
  2669. return {
  2670. name: '',
  2671. values: zeroArray.slice(0, -1),
  2672. chartType: d.chartType
  2673. };
  2674. }),
  2675. };
  2676. if(realData.yMarkers) {
  2677. zeroData.yMarkers = [
  2678. {
  2679. value: 0,
  2680. label: ''
  2681. }
  2682. ];
  2683. }
  2684. if(realData.yRegions) {
  2685. zeroData.yRegions = [
  2686. {
  2687. start: 0,
  2688. end: 0,
  2689. label: ''
  2690. }
  2691. ];
  2692. }
  2693. return zeroData;
  2694. }
  2695. function getShortenedLabels(chartWidth, labels=[], isSeries=true) {
  2696. let allowedSpace = chartWidth / labels.length;
  2697. if(allowedSpace <= 0) allowedSpace = 1;
  2698. let allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH;
  2699. let seriesMultiple;
  2700. if(isSeries) {
  2701. // Find the maximum label length for spacing calculations
  2702. let maxLabelLength = Math.max(...labels.map(label => label.length));
  2703. seriesMultiple = Math.ceil(maxLabelLength/allowedLetters);
  2704. }
  2705. let calcLabels = labels.map((label, i) => {
  2706. label += "";
  2707. if(label.length > allowedLetters) {
  2708. if(!isSeries) {
  2709. if(allowedLetters-3 > 0) {
  2710. label = label.slice(0, allowedLetters-3) + " ...";
  2711. } else {
  2712. label = label.slice(0, allowedLetters) + '..';
  2713. }
  2714. } else {
  2715. if(i % seriesMultiple !== 0) {
  2716. label = "";
  2717. }
  2718. }
  2719. }
  2720. return label;
  2721. });
  2722. return calcLabels;
  2723. }
  2724. class AxisChart extends BaseChart {
  2725. constructor(parent, args) {
  2726. super(parent, args);
  2727. this.barOptions = args.barOptions || {};
  2728. this.lineOptions = args.lineOptions || {};
  2729. this.type = args.type || 'line';
  2730. this.init = 1;
  2731. this.setup();
  2732. }
  2733. setMeasures() {
  2734. if(this.data.datasets.length <= 1) {
  2735. this.config.showLegend = 0;
  2736. this.measures.paddings.bottom = 30;
  2737. }
  2738. }
  2739. configure(options) {
  2740. super.configure(options);
  2741. options.axisOptions = options.axisOptions || {};
  2742. options.tooltipOptions = options.tooltipOptions || {};
  2743. this.config.xAxisMode = options.axisOptions.xAxisMode || 'span';
  2744. this.config.yAxisMode = options.axisOptions.yAxisMode || 'span';
  2745. this.config.xIsSeries = options.axisOptions.xIsSeries || 0;
  2746. this.config.shortenYAxisNumbers = options.axisOptions.shortenYAxisNumbers || 0;
  2747. this.config.formatTooltipX = options.tooltipOptions.formatTooltipX;
  2748. this.config.formatTooltipY = options.tooltipOptions.formatTooltipY;
  2749. this.config.valuesOverPoints = options.valuesOverPoints;
  2750. }
  2751. prepareData(data=this.data) {
  2752. return dataPrep(data, this.type);
  2753. }
  2754. prepareFirstData(data=this.data) {
  2755. return zeroDataPrep(data);
  2756. }
  2757. calc(onlyWidthChange = false) {
  2758. this.calcXPositions();
  2759. if(!onlyWidthChange) {
  2760. this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
  2761. }
  2762. this.makeDataByIndex();
  2763. }
  2764. calcXPositions() {
  2765. let s = this.state;
  2766. let labels = this.data.labels;
  2767. s.datasetLength = labels.length;
  2768. s.unitWidth = this.width/(s.datasetLength);
  2769. // Default, as per bar, and mixed. Only line will be a special case
  2770. s.xOffset = s.unitWidth/2;
  2771. // // For a pure Line Chart
  2772. // s.unitWidth = this.width/(s.datasetLength - 1);
  2773. // s.xOffset = 0;
  2774. s.xAxis = {
  2775. labels: labels,
  2776. positions: labels.map((d, i) =>
  2777. floatTwo(s.xOffset + i * s.unitWidth)
  2778. )
  2779. };
  2780. }
  2781. calcYAxisParameters(dataValues, withMinimum = 'false') {
  2782. const yPts = calcChartIntervals(dataValues, withMinimum);
  2783. const scaleMultiplier = this.height / getValueRange(yPts);
  2784. const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
  2785. const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  2786. this.state.yAxis = {
  2787. labels: yPts,
  2788. positions: yPts.map(d => zeroLine - d * scaleMultiplier),
  2789. scaleMultiplier: scaleMultiplier,
  2790. zeroLine: zeroLine,
  2791. };
  2792. // Dependent if above changes
  2793. this.calcDatasetPoints();
  2794. this.calcYExtremes();
  2795. this.calcYRegions();
  2796. }
  2797. calcDatasetPoints() {
  2798. let s = this.state;
  2799. let scaleAll = values => values.map(val => scale(val, s.yAxis));
  2800. s.datasets = this.data.datasets.map((d, i) => {
  2801. let values = d.values;
  2802. let cumulativeYs = d.cumulativeYs || [];
  2803. return {
  2804. name: d.name,
  2805. index: i,
  2806. chartType: d.chartType,
  2807. values: values,
  2808. yPositions: scaleAll(values),
  2809. cumulativeYs: cumulativeYs,
  2810. cumulativeYPos: scaleAll(cumulativeYs),
  2811. };
  2812. });
  2813. }
  2814. calcYExtremes() {
  2815. let s = this.state;
  2816. if(this.barOptions.stacked) {
  2817. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
  2818. return;
  2819. }
  2820. s.yExtremes = new Array(s.datasetLength).fill(9999);
  2821. s.datasets.map(d => {
  2822. d.yPositions.map((pos, j) => {
  2823. if(pos < s.yExtremes[j]) {
  2824. s.yExtremes[j] = pos;
  2825. }
  2826. });
  2827. });
  2828. }
  2829. calcYRegions() {
  2830. let s = this.state;
  2831. if(this.data.yMarkers) {
  2832. this.state.yMarkers = this.data.yMarkers.map(d => {
  2833. d.position = scale(d.value, s.yAxis);
  2834. if(!d.options) d.options = {};
  2835. // if(!d.label.includes(':')) {
  2836. // d.label += ': ' + d.value;
  2837. // }
  2838. return d;
  2839. });
  2840. }
  2841. if(this.data.yRegions) {
  2842. this.state.yRegions = this.data.yRegions.map(d => {
  2843. d.startPos = scale(d.start, s.yAxis);
  2844. d.endPos = scale(d.end, s.yAxis);
  2845. if(!d.options) d.options = {};
  2846. return d;
  2847. });
  2848. }
  2849. }
  2850. getAllYValues() {
  2851. let key = 'values';
  2852. if(this.barOptions.stacked) {
  2853. key = 'cumulativeYs';
  2854. let cumulative = new Array(this.state.datasetLength).fill(0);
  2855. this.data.datasets.map((d, i) => {
  2856. let values = this.data.datasets[i].values;
  2857. d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
  2858. });
  2859. }
  2860. let allValueLists = this.data.datasets.map(d => d[key]);
  2861. if(this.data.yMarkers) {
  2862. allValueLists.push(this.data.yMarkers.map(d => d.value));
  2863. }
  2864. if(this.data.yRegions) {
  2865. this.data.yRegions.map(d => {
  2866. allValueLists.push([d.end, d.start]);
  2867. });
  2868. }
  2869. return [].concat(...allValueLists);
  2870. }
  2871. setupComponents() {
  2872. let componentConfigs = [
  2873. [
  2874. 'yAxis',
  2875. {
  2876. mode: this.config.yAxisMode,
  2877. width: this.width,
  2878. shortenNumbers: this.config.shortenYAxisNumbers
  2879. // pos: 'right'
  2880. },
  2881. function() {
  2882. return this.state.yAxis;
  2883. }.bind(this)
  2884. ],
  2885. [
  2886. 'xAxis',
  2887. {
  2888. mode: this.config.xAxisMode,
  2889. height: this.height,
  2890. // pos: 'right'
  2891. },
  2892. function() {
  2893. let s = this.state;
  2894. s.xAxis.calcLabels = getShortenedLabels(this.width,
  2895. s.xAxis.labels, this.config.xIsSeries);
  2896. return s.xAxis;
  2897. }.bind(this)
  2898. ],
  2899. [
  2900. 'yRegions',
  2901. {
  2902. width: this.width,
  2903. pos: 'right'
  2904. },
  2905. function() {
  2906. return this.state.yRegions;
  2907. }.bind(this)
  2908. ],
  2909. ];
  2910. let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
  2911. let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
  2912. let barsConfigs = barDatasets.map(d => {
  2913. let index = d.index;
  2914. return [
  2915. 'barGraph' + '-' + d.index,
  2916. {
  2917. index: index,
  2918. color: this.colors[index],
  2919. stacked: this.barOptions.stacked,
  2920. // same for all datasets
  2921. valuesOverPoints: this.config.valuesOverPoints,
  2922. minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
  2923. },
  2924. function() {
  2925. let s = this.state;
  2926. let d = s.datasets[index];
  2927. let stacked = this.barOptions.stacked;
  2928. let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
  2929. let barsWidth = s.unitWidth * (1 - spaceRatio);
  2930. let barWidth = barsWidth/(stacked ? 1 : barDatasets.length);
  2931. let xPositions = s.xAxis.positions.map(x => x - barsWidth/2);
  2932. if(!stacked) {
  2933. xPositions = xPositions.map(p => p + barWidth * index);
  2934. }
  2935. let labels = new Array(s.datasetLength).fill('');
  2936. if(this.config.valuesOverPoints) {
  2937. if(stacked && d.index === s.datasets.length - 1) {
  2938. labels = d.cumulativeYs;
  2939. } else {
  2940. labels = d.values;
  2941. }
  2942. }
  2943. let offsets = new Array(s.datasetLength).fill(0);
  2944. if(stacked) {
  2945. offsets = d.yPositions.map((y, j) => y - d.cumulativeYPos[j]);
  2946. }
  2947. return {
  2948. xPositions: xPositions,
  2949. yPositions: d.yPositions,
  2950. offsets: offsets,
  2951. // values: d.values,
  2952. labels: labels,
  2953. zeroLine: s.yAxis.zeroLine,
  2954. barsWidth: barsWidth,
  2955. barWidth: barWidth,
  2956. };
  2957. }.bind(this)
  2958. ];
  2959. });
  2960. let lineConfigs = lineDatasets.map(d => {
  2961. let index = d.index;
  2962. return [
  2963. 'lineGraph' + '-' + d.index,
  2964. {
  2965. index: index,
  2966. color: this.colors[index],
  2967. svgDefs: this.svgDefs,
  2968. heatline: this.lineOptions.heatline,
  2969. regionFill: this.lineOptions.regionFill,
  2970. spline: this.lineOptions.spline,
  2971. hideDots: this.lineOptions.hideDots,
  2972. hideLine: this.lineOptions.hideLine,
  2973. // same for all datasets
  2974. valuesOverPoints: this.config.valuesOverPoints,
  2975. },
  2976. function() {
  2977. let s = this.state;
  2978. let d = s.datasets[index];
  2979. let minLine = s.yAxis.positions[0] < s.yAxis.zeroLine
  2980. ? s.yAxis.positions[0] : s.yAxis.zeroLine;
  2981. return {
  2982. xPositions: s.xAxis.positions,
  2983. yPositions: d.yPositions,
  2984. values: d.values,
  2985. zeroLine: minLine,
  2986. radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE,
  2987. };
  2988. }.bind(this)
  2989. ];
  2990. });
  2991. let markerConfigs = [
  2992. [
  2993. 'yMarkers',
  2994. {
  2995. width: this.width,
  2996. pos: 'right'
  2997. },
  2998. function() {
  2999. return this.state.yMarkers;
  3000. }.bind(this)
  3001. ]
  3002. ];
  3003. componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
  3004. let optionals = ['yMarkers', 'yRegions'];
  3005. this.dataUnitComponents = [];
  3006. this.components = new Map(componentConfigs
  3007. .filter(args => !optionals.includes(args[0]) || this.state[args[0]])
  3008. .map(args => {
  3009. let component = getComponent(...args);
  3010. if(args[0].includes('lineGraph') || args[0].includes('barGraph')) {
  3011. this.dataUnitComponents.push(component);
  3012. }
  3013. return [args[0], component];
  3014. }));
  3015. }
  3016. makeDataByIndex() {
  3017. this.dataByIndex = {};
  3018. let s = this.state;
  3019. let formatX = this.config.formatTooltipX;
  3020. let formatY = this.config.formatTooltipY;
  3021. let titles = s.xAxis.labels;
  3022. titles.map((label, index) => {
  3023. let values = this.state.datasets.map((set, i) => {
  3024. let value = set.values[index];
  3025. return {
  3026. title: set.name,
  3027. value: value,
  3028. yPos: set.yPositions[index],
  3029. color: this.colors[i],
  3030. formatted: formatY ? formatY(value) : value,
  3031. };
  3032. });
  3033. this.dataByIndex[index] = {
  3034. label: label,
  3035. formattedLabel: formatX ? formatX(label) : label,
  3036. xPos: s.xAxis.positions[index],
  3037. values: values,
  3038. yExtreme: s.yExtremes[index],
  3039. };
  3040. });
  3041. }
  3042. bindTooltip() {
  3043. // NOTE: could be in tooltip itself, as it is a given functionality for its parent
  3044. this.container.addEventListener('mousemove', (e) => {
  3045. let m = this.measures;
  3046. let o = getOffset(this.container);
  3047. let relX = e.pageX - o.left - getLeftOffset(m);
  3048. let relY = e.pageY - o.top;
  3049. if(relY < this.height + getTopOffset(m)
  3050. && relY > getTopOffset(m)) {
  3051. this.mapTooltipXPosition(relX);
  3052. } else {
  3053. this.tip.hideTip();
  3054. }
  3055. });
  3056. }
  3057. mapTooltipXPosition(relX) {
  3058. let s = this.state;
  3059. if(!s.yExtremes) return;
  3060. let index = getClosestInArray(relX, s.xAxis.positions, true);
  3061. if (index >= 0) {
  3062. let dbi = this.dataByIndex[index];
  3063. this.tip.setValues(
  3064. dbi.xPos + this.tip.offset.x,
  3065. dbi.yExtreme + this.tip.offset.y,
  3066. {name: dbi.formattedLabel, value: ''},
  3067. dbi.values,
  3068. index
  3069. );
  3070. this.tip.showTip();
  3071. }
  3072. }
  3073. renderLegend() {
  3074. let s = this.data;
  3075. if(s.datasets.length > 1) {
  3076. this.legendArea.textContent = '';
  3077. s.datasets.map((d, i) => {
  3078. let barWidth = AXIS_LEGEND_BAR_SIZE;
  3079. // let rightEndPoint = this.baseWidth - this.measures.margins.left - this.measures.margins.right;
  3080. // let multiplier = s.datasets.length - i;
  3081. let rect = legendBar(
  3082. // rightEndPoint - multiplier * barWidth, // To right align
  3083. barWidth * i,
  3084. '0',
  3085. barWidth,
  3086. this.colors[i],
  3087. d.name,
  3088. this.config.truncateLegends);
  3089. this.legendArea.appendChild(rect);
  3090. });
  3091. }
  3092. }
  3093. // Overlay
  3094. makeOverlay() {
  3095. if(this.init) {
  3096. this.init = 0;
  3097. return;
  3098. }
  3099. if(this.overlayGuides) {
  3100. this.overlayGuides.forEach(g => {
  3101. let o = g.overlay;
  3102. o.parentNode.removeChild(o);
  3103. });
  3104. }
  3105. this.overlayGuides = this.dataUnitComponents.map(c => {
  3106. return {
  3107. type: c.unitType,
  3108. overlay: undefined,
  3109. units: c.units,
  3110. };
  3111. });
  3112. if(this.state.currentIndex === undefined) {
  3113. this.state.currentIndex = this.state.datasetLength - 1;
  3114. }
  3115. // Render overlays
  3116. this.overlayGuides.map(d => {
  3117. let currentUnit = d.units[this.state.currentIndex];
  3118. d.overlay = makeOverlay[d.type](currentUnit);
  3119. this.drawArea.appendChild(d.overlay);
  3120. });
  3121. }
  3122. updateOverlayGuides() {
  3123. if(this.overlayGuides) {
  3124. this.overlayGuides.forEach(g => {
  3125. let o = g.overlay;
  3126. o.parentNode.removeChild(o);
  3127. });
  3128. }
  3129. }
  3130. bindOverlay() {
  3131. this.parent.addEventListener('data-select', () => {
  3132. this.updateOverlay();
  3133. });
  3134. }
  3135. bindUnits() {
  3136. this.dataUnitComponents.map(c => {
  3137. c.units.map(unit => {
  3138. unit.addEventListener('click', () => {
  3139. let index = unit.getAttribute('data-point-index');
  3140. this.setCurrentDataPoint(index);
  3141. });
  3142. });
  3143. });
  3144. // Note: Doesn't work as tooltip is absolutely positioned
  3145. this.tip.container.addEventListener('click', () => {
  3146. let index = this.tip.container.getAttribute('data-point-index');
  3147. this.setCurrentDataPoint(index);
  3148. });
  3149. }
  3150. updateOverlay() {
  3151. this.overlayGuides.map(d => {
  3152. let currentUnit = d.units[this.state.currentIndex];
  3153. updateOverlay[d.type](currentUnit, d.overlay);
  3154. });
  3155. }
  3156. onLeftArrow() {
  3157. this.setCurrentDataPoint(this.state.currentIndex - 1);
  3158. }
  3159. onRightArrow() {
  3160. this.setCurrentDataPoint(this.state.currentIndex + 1);
  3161. }
  3162. getDataPoint(index=this.state.currentIndex) {
  3163. let s = this.state;
  3164. let data_point = {
  3165. index: index,
  3166. label: s.xAxis.labels[index],
  3167. values: s.datasets.map(d => d.values[index])
  3168. };
  3169. return data_point;
  3170. }
  3171. setCurrentDataPoint(index) {
  3172. let s = this.state;
  3173. index = parseInt(index);
  3174. if(index < 0) index = 0;
  3175. if(index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
  3176. if(index === s.currentIndex) return;
  3177. s.currentIndex = index;
  3178. fire(this.parent, "data-select", this.getDataPoint());
  3179. }
  3180. // API
  3181. addDataPoint(label, datasetValues, index=this.state.datasetLength) {
  3182. super.addDataPoint(label, datasetValues, index);
  3183. this.data.labels.splice(index, 0, label);
  3184. this.data.datasets.map((d, i) => {
  3185. d.values.splice(index, 0, datasetValues[i]);
  3186. });
  3187. this.update(this.data);
  3188. }
  3189. removeDataPoint(index = this.state.datasetLength-1) {
  3190. if (this.data.labels.length <= 1) {
  3191. return;
  3192. }
  3193. super.removeDataPoint(index);
  3194. this.data.labels.splice(index, 1);
  3195. this.data.datasets.map(d => {
  3196. d.values.splice(index, 1);
  3197. });
  3198. this.update(this.data);
  3199. }
  3200. updateDataset(datasetValues, index=0) {
  3201. this.data.datasets[index].values = datasetValues;
  3202. this.update(this.data);
  3203. }
  3204. // addDataset(dataset, index) {}
  3205. // removeDataset(index = 0) {}
  3206. updateDatasets(datasets) {
  3207. this.data.datasets.map((d, i) => {
  3208. if(datasets[i]) {
  3209. d.values = datasets[i];
  3210. }
  3211. });
  3212. this.update(this.data);
  3213. }
  3214. // updateDataPoint(dataPoint, index = 0) {}
  3215. // addDataPoint(dataPoint, index = 0) {}
  3216. // removeDataPoint(index = 0) {}
  3217. }
  3218. class DonutChart extends AggregationChart {
  3219. constructor(parent, args) {
  3220. super(parent, args);
  3221. this.type = 'donut';
  3222. this.initTimeout = 0;
  3223. this.init = 1;
  3224. this.setup();
  3225. }
  3226. configure(args) {
  3227. super.configure(args);
  3228. this.mouseMove = this.mouseMove.bind(this);
  3229. this.mouseLeave = this.mouseLeave.bind(this);
  3230. this.hoverRadio = args.hoverRadio || 0.1;
  3231. this.config.startAngle = args.startAngle || 0;
  3232. this.clockWise = args.clockWise || false;
  3233. this.strokeWidth = args.strokeWidth || 30;
  3234. }
  3235. calc() {
  3236. super.calc();
  3237. let s = this.state;
  3238. this.radius =
  3239. this.height > this.width
  3240. ? this.center.x - this.strokeWidth / 2
  3241. : this.center.y - this.strokeWidth / 2;
  3242. const { radius, clockWise } = this;
  3243. const prevSlicesProperties = s.slicesProperties || [];
  3244. s.sliceStrings = [];
  3245. s.slicesProperties = [];
  3246. let curAngle = 180 - this.config.startAngle;
  3247. s.sliceTotals.map((total, i) => {
  3248. const startAngle = curAngle;
  3249. const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
  3250. const largeArc = originDiffAngle > 180 ? 1: 0;
  3251. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  3252. const endAngle = curAngle = curAngle + diffAngle;
  3253. const startPosition = getPositionByAngle(startAngle, radius);
  3254. const endPosition = getPositionByAngle(endAngle, radius);
  3255. const prevProperty = this.init && prevSlicesProperties[i];
  3256. let curStart,curEnd;
  3257. if(this.init) {
  3258. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  3259. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  3260. } else {
  3261. curStart = startPosition;
  3262. curEnd = endPosition;
  3263. }
  3264. const curPath =
  3265. originDiffAngle === 360
  3266. ? makeStrokeCircleStr(curStart, curEnd, this.center, this.radius, this.clockWise, largeArc)
  3267. : makeArcStrokePathStr(curStart, curEnd, this.center, this.radius, this.clockWise, largeArc);
  3268. s.sliceStrings.push(curPath);
  3269. s.slicesProperties.push({
  3270. startPosition,
  3271. endPosition,
  3272. value: total,
  3273. total: s.grandTotal,
  3274. startAngle,
  3275. endAngle,
  3276. angle: diffAngle
  3277. });
  3278. });
  3279. this.init = 0;
  3280. }
  3281. setupComponents() {
  3282. let s = this.state;
  3283. let componentConfigs = [
  3284. [
  3285. 'donutSlices',
  3286. { },
  3287. function() {
  3288. return {
  3289. sliceStrings: s.sliceStrings,
  3290. colors: this.colors,
  3291. strokeWidth: this.strokeWidth,
  3292. };
  3293. }.bind(this)
  3294. ]
  3295. ];
  3296. this.components = new Map(componentConfigs
  3297. .map(args => {
  3298. let component = getComponent(...args);
  3299. return [args[0], component];
  3300. }));
  3301. }
  3302. calTranslateByAngle(property){
  3303. const{ radius, hoverRadio } = this;
  3304. const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  3305. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  3306. }
  3307. hoverSlice(path,i,flag,e){
  3308. if(!path) return;
  3309. const color = this.colors[i];
  3310. if(flag) {
  3311. transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
  3312. path.style.stroke = lightenDarkenColor(color, 50);
  3313. let g_off = getOffset(this.svg);
  3314. let x = e.pageX - g_off.left + 10;
  3315. let y = e.pageY - g_off.top - 10;
  3316. let title = (this.formatted_labels && this.formatted_labels.length > 0
  3317. ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
  3318. let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
  3319. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  3320. this.tip.showTip();
  3321. } else {
  3322. transform(path,'translate3d(0,0,0)');
  3323. this.tip.hideTip();
  3324. path.style.stroke = color;
  3325. }
  3326. }
  3327. bindTooltip() {
  3328. this.container.addEventListener('mousemove', this.mouseMove);
  3329. this.container.addEventListener('mouseleave', this.mouseLeave);
  3330. }
  3331. mouseMove(e){
  3332. const target = e.target;
  3333. let slices = this.components.get('donutSlices').store;
  3334. let prevIndex = this.curActiveSliceIndex;
  3335. let prevAcitve = this.curActiveSlice;
  3336. if(slices.includes(target)) {
  3337. let i = slices.indexOf(target);
  3338. this.hoverSlice(prevAcitve, prevIndex,false);
  3339. this.curActiveSlice = target;
  3340. this.curActiveSliceIndex = i;
  3341. this.hoverSlice(target, i, true, e);
  3342. } else {
  3343. this.mouseLeave();
  3344. }
  3345. }
  3346. mouseLeave(){
  3347. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  3348. }
  3349. }
  3350. // import MultiAxisChart from './charts/MultiAxisChart';
  3351. const chartTypes = {
  3352. bar: AxisChart,
  3353. line: AxisChart,
  3354. // multiaxis: MultiAxisChart,
  3355. percentage: PercentageChart,
  3356. heatmap: Heatmap,
  3357. pie: PieChart,
  3358. donut: DonutChart,
  3359. };
  3360. function getChartByType(chartType = 'line', parent, options) {
  3361. if (chartType === 'axis-mixed') {
  3362. options.type = 'line';
  3363. return new AxisChart(parent, options);
  3364. }
  3365. if (!chartTypes[chartType]) {
  3366. console.error("Undefined chart type: " + chartType);
  3367. return;
  3368. }
  3369. return new chartTypes[chartType](parent, options);
  3370. }
  3371. class Chart {
  3372. constructor(parent, options) {
  3373. return getChartByType(options.type, parent, options);
  3374. }
  3375. }
  3376. export { Chart, PercentageChart, PieChart, Heatmap, AxisChart };