Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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