Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

frappe-charts.esm.js 98 KiB

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