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

frappe-charts.esm.js 87 KiB

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