chartist.js 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516
  1. (function (root, factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. // AMD. Register as an anonymous module unless amdModuleId is set
  4. define('Chartist', [], function () {
  5. return (root['Chartist'] = factory());
  6. });
  7. } else if (typeof module === 'object' && module.exports) {
  8. // Node. Does not work with strict CommonJS, but
  9. // only CommonJS-like environments that support module.exports,
  10. // like Node.
  11. module.exports = factory();
  12. } else {
  13. root['Chartist'] = factory();
  14. }
  15. }(this, function () {
  16. /* Chartist.js 0.11.4
  17. * Copyright © 2019 Gion Kunz
  18. * Free to use under either the WTFPL license or the MIT license.
  19. * https://raw.githubusercontent.com/gionkunz/chartist-js/master/LICENSE-WTFPL
  20. * https://raw.githubusercontent.com/gionkunz/chartist-js/master/LICENSE-MIT
  21. */
  22. /**
  23. * The core module of Chartist that is mainly providing static functions and higher level functions for chart modules.
  24. *
  25. * @module Chartist.Core
  26. */
  27. var Chartist = {
  28. version: '0.11.4'
  29. };
  30. (function (globalRoot, Chartist) {
  31. 'use strict';
  32. var window = globalRoot.window;
  33. var document = globalRoot.document;
  34. /**
  35. * This object contains all namespaces used within Chartist.
  36. *
  37. * @memberof Chartist.Core
  38. * @type {{svg: string, xmlns: string, xhtml: string, xlink: string, ct: string}}
  39. */
  40. Chartist.namespaces = {
  41. svg: 'http://www.w3.org/2000/svg',
  42. xmlns: 'http://www.w3.org/2000/xmlns/',
  43. xhtml: 'http://www.w3.org/1999/xhtml',
  44. xlink: 'http://www.w3.org/1999/xlink',
  45. ct: 'http://gionkunz.github.com/chartist-js/ct'
  46. };
  47. /**
  48. * Helps to simplify functional style code
  49. *
  50. * @memberof Chartist.Core
  51. * @param {*} n This exact value will be returned by the noop function
  52. * @return {*} The same value that was provided to the n parameter
  53. */
  54. Chartist.noop = function (n) {
  55. return n;
  56. };
  57. /**
  58. * Generates a-z from a number 0 to 26
  59. *
  60. * @memberof Chartist.Core
  61. * @param {Number} n A number from 0 to 26 that will result in a letter a-z
  62. * @return {String} A character from a-z based on the input number n
  63. */
  64. Chartist.alphaNumerate = function (n) {
  65. // Limit to a-z
  66. return String.fromCharCode(97 + n % 26);
  67. };
  68. /**
  69. * Simple recursive object extend
  70. *
  71. * @memberof Chartist.Core
  72. * @param {Object} target Target object where the source will be merged into
  73. * @param {Object...} sources This object (objects) will be merged into target and then target is returned
  74. * @return {Object} An object that has the same reference as target but is extended and merged with the properties of source
  75. */
  76. Chartist.extend = function (target) {
  77. var i, source, sourceProp;
  78. target = target || {};
  79. for (i = 1; i < arguments.length; i++) {
  80. source = arguments[i];
  81. for (var prop in source) {
  82. sourceProp = source[prop];
  83. if (typeof sourceProp === 'object' && sourceProp !== null && !(sourceProp instanceof Array)) {
  84. target[prop] = Chartist.extend(target[prop], sourceProp);
  85. } else {
  86. target[prop] = sourceProp;
  87. }
  88. }
  89. }
  90. return target;
  91. };
  92. /**
  93. * Replaces all occurrences of subStr in str with newSubStr and returns a new string.
  94. *
  95. * @memberof Chartist.Core
  96. * @param {String} str
  97. * @param {String} subStr
  98. * @param {String} newSubStr
  99. * @return {String}
  100. */
  101. Chartist.replaceAll = function(str, subStr, newSubStr) {
  102. return str.replace(new RegExp(subStr, 'g'), newSubStr);
  103. };
  104. /**
  105. * Converts a number to a string with a unit. If a string is passed then this will be returned unmodified.
  106. *
  107. * @memberof Chartist.Core
  108. * @param {Number} value
  109. * @param {String} unit
  110. * @return {String} Returns the passed number value with unit.
  111. */
  112. Chartist.ensureUnit = function(value, unit) {
  113. if(typeof value === 'number') {
  114. value = value + unit;
  115. }
  116. return value;
  117. };
  118. /**
  119. * Converts a number or string to a quantity object.
  120. *
  121. * @memberof Chartist.Core
  122. * @param {String|Number} input
  123. * @return {Object} Returns an object containing the value as number and the unit as string.
  124. */
  125. Chartist.quantity = function(input) {
  126. if (typeof input === 'string') {
  127. var match = (/^(\d+)\s*(.*)$/g).exec(input);
  128. return {
  129. value : +match[1],
  130. unit: match[2] || undefined
  131. };
  132. }
  133. return { value: input };
  134. };
  135. /**
  136. * This is a wrapper around document.querySelector that will return the query if it's already of type Node
  137. *
  138. * @memberof Chartist.Core
  139. * @param {String|Node} query The query to use for selecting a Node or a DOM node that will be returned directly
  140. * @return {Node}
  141. */
  142. Chartist.querySelector = function(query) {
  143. return query instanceof Node ? query : document.querySelector(query);
  144. };
  145. /**
  146. * Functional style helper to produce array with given length initialized with undefined values
  147. *
  148. * @memberof Chartist.Core
  149. * @param length
  150. * @return {Array}
  151. */
  152. Chartist.times = function(length) {
  153. return Array.apply(null, new Array(length));
  154. };
  155. /**
  156. * Sum helper to be used in reduce functions
  157. *
  158. * @memberof Chartist.Core
  159. * @param previous
  160. * @param current
  161. * @return {*}
  162. */
  163. Chartist.sum = function(previous, current) {
  164. return previous + (current ? current : 0);
  165. };
  166. /**
  167. * Multiply helper to be used in `Array.map` for multiplying each value of an array with a factor.
  168. *
  169. * @memberof Chartist.Core
  170. * @param {Number} factor
  171. * @returns {Function} Function that can be used in `Array.map` to multiply each value in an array
  172. */
  173. Chartist.mapMultiply = function(factor) {
  174. return function(num) {
  175. return num * factor;
  176. };
  177. };
  178. /**
  179. * Add helper to be used in `Array.map` for adding a addend to each value of an array.
  180. *
  181. * @memberof Chartist.Core
  182. * @param {Number} addend
  183. * @returns {Function} Function that can be used in `Array.map` to add a addend to each value in an array
  184. */
  185. Chartist.mapAdd = function(addend) {
  186. return function(num) {
  187. return num + addend;
  188. };
  189. };
  190. /**
  191. * Map for multi dimensional arrays where their nested arrays will be mapped in serial. The output array will have the length of the largest nested array. The callback function is called with variable arguments where each argument is the nested array value (or undefined if there are no more values).
  192. *
  193. * @memberof Chartist.Core
  194. * @param arr
  195. * @param cb
  196. * @return {Array}
  197. */
  198. Chartist.serialMap = function(arr, cb) {
  199. var result = [],
  200. length = Math.max.apply(null, arr.map(function(e) {
  201. return e.length;
  202. }));
  203. Chartist.times(length).forEach(function(e, index) {
  204. var args = arr.map(function(e) {
  205. return e[index];
  206. });
  207. result[index] = cb.apply(null, args);
  208. });
  209. return result;
  210. };
  211. /**
  212. * This helper function can be used to round values with certain precision level after decimal. This is used to prevent rounding errors near float point precision limit.
  213. *
  214. * @memberof Chartist.Core
  215. * @param {Number} value The value that should be rounded with precision
  216. * @param {Number} [digits] The number of digits after decimal used to do the rounding
  217. * @returns {number} Rounded value
  218. */
  219. Chartist.roundWithPrecision = function(value, digits) {
  220. var precision = Math.pow(10, digits || Chartist.precision);
  221. return Math.round(value * precision) / precision;
  222. };
  223. /**
  224. * Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number.
  225. *
  226. * @memberof Chartist.Core
  227. * @type {number}
  228. */
  229. Chartist.precision = 8;
  230. /**
  231. * A map with characters to escape for strings to be safely used as attribute values.
  232. *
  233. * @memberof Chartist.Core
  234. * @type {Object}
  235. */
  236. Chartist.escapingMap = {
  237. '&': '&amp;',
  238. '<': '&lt;',
  239. '>': '&gt;',
  240. '"': '&quot;',
  241. '\'': '&#039;'
  242. };
  243. /**
  244. * This function serializes arbitrary data to a string. In case of data that can't be easily converted to a string, this function will create a wrapper object and serialize the data using JSON.stringify. The outcoming string will always be escaped using Chartist.escapingMap.
  245. * If called with null or undefined the function will return immediately with null or undefined.
  246. *
  247. * @memberof Chartist.Core
  248. * @param {Number|String|Object} data
  249. * @return {String}
  250. */
  251. Chartist.serialize = function(data) {
  252. if(data === null || data === undefined) {
  253. return data;
  254. } else if(typeof data === 'number') {
  255. data = ''+data;
  256. } else if(typeof data === 'object') {
  257. data = JSON.stringify({data: data});
  258. }
  259. return Object.keys(Chartist.escapingMap).reduce(function(result, key) {
  260. return Chartist.replaceAll(result, key, Chartist.escapingMap[key]);
  261. }, data);
  262. };
  263. /**
  264. * This function de-serializes a string previously serialized with Chartist.serialize. The string will always be unescaped using Chartist.escapingMap before it's returned. Based on the input value the return type can be Number, String or Object. JSON.parse is used with try / catch to see if the unescaped string can be parsed into an Object and this Object will be returned on success.
  265. *
  266. * @memberof Chartist.Core
  267. * @param {String} data
  268. * @return {String|Number|Object}
  269. */
  270. Chartist.deserialize = function(data) {
  271. if(typeof data !== 'string') {
  272. return data;
  273. }
  274. data = Object.keys(Chartist.escapingMap).reduce(function(result, key) {
  275. return Chartist.replaceAll(result, Chartist.escapingMap[key], key);
  276. }, data);
  277. try {
  278. data = JSON.parse(data);
  279. data = data.data !== undefined ? data.data : data;
  280. } catch(e) {}
  281. return data;
  282. };
  283. /**
  284. * Create or reinitialize the SVG element for the chart
  285. *
  286. * @memberof Chartist.Core
  287. * @param {Node} container The containing DOM Node object that will be used to plant the SVG element
  288. * @param {String} width Set the width of the SVG element. Default is 100%
  289. * @param {String} height Set the height of the SVG element. Default is 100%
  290. * @param {String} className Specify a class to be added to the SVG element
  291. * @return {Object} The created/reinitialized SVG element
  292. */
  293. Chartist.createSvg = function (container, width, height, className) {
  294. var svg;
  295. width = width || '100%';
  296. height = height || '100%';
  297. // Check if there is a previous SVG element in the container that contains the Chartist XML namespace and remove it
  298. // Since the DOM API does not support namespaces we need to manually search the returned list http://www.w3.org/TR/selectors-api/
  299. Array.prototype.slice.call(container.querySelectorAll('svg')).filter(function filterChartistSvgObjects(svg) {
  300. return svg.getAttributeNS(Chartist.namespaces.xmlns, 'ct');
  301. }).forEach(function removePreviousElement(svg) {
  302. container.removeChild(svg);
  303. });
  304. // Create svg object with width and height or use 100% as default
  305. svg = new Chartist.Svg('svg').attr({
  306. width: width,
  307. height: height
  308. }).addClass(className);
  309. svg._node.style.width = width;
  310. svg._node.style.height = height;
  311. // Add the DOM node to our container
  312. container.appendChild(svg._node);
  313. return svg;
  314. };
  315. /**
  316. * Ensures that the data object passed as second argument to the charts is present and correctly initialized.
  317. *
  318. * @param {Object} data The data object that is passed as second argument to the charts
  319. * @return {Object} The normalized data object
  320. */
  321. Chartist.normalizeData = function(data, reverse, multi) {
  322. var labelCount;
  323. var output = {
  324. raw: data,
  325. normalized: {}
  326. };
  327. // Check if we should generate some labels based on existing series data
  328. output.normalized.series = Chartist.getDataArray({
  329. series: data.series || []
  330. }, reverse, multi);
  331. // If all elements of the normalized data array are arrays we're dealing with
  332. // multi series data and we need to find the largest series if they are un-even
  333. if (output.normalized.series.every(function(value) {
  334. return value instanceof Array;
  335. })) {
  336. // Getting the series with the the most elements
  337. labelCount = Math.max.apply(null, output.normalized.series.map(function(series) {
  338. return series.length;
  339. }));
  340. } else {
  341. // We're dealing with Pie data so we just take the normalized array length
  342. labelCount = output.normalized.series.length;
  343. }
  344. output.normalized.labels = (data.labels || []).slice();
  345. // Padding the labels to labelCount with empty strings
  346. Array.prototype.push.apply(
  347. output.normalized.labels,
  348. Chartist.times(Math.max(0, labelCount - output.normalized.labels.length)).map(function() {
  349. return '';
  350. })
  351. );
  352. if(reverse) {
  353. Chartist.reverseData(output.normalized);
  354. }
  355. return output;
  356. };
  357. /**
  358. * This function safely checks if an objects has an owned property.
  359. *
  360. * @param {Object} object The object where to check for a property
  361. * @param {string} property The property name
  362. * @returns {boolean} Returns true if the object owns the specified property
  363. */
  364. Chartist.safeHasProperty = function(object, property) {
  365. return object !== null &&
  366. typeof object === 'object' &&
  367. object.hasOwnProperty(property);
  368. };
  369. /**
  370. * Checks if a value is considered a hole in the data series.
  371. *
  372. * @param {*} value
  373. * @returns {boolean} True if the value is considered a data hole
  374. */
  375. Chartist.isDataHoleValue = function(value) {
  376. return value === null ||
  377. value === undefined ||
  378. (typeof value === 'number' && isNaN(value));
  379. };
  380. /**
  381. * Reverses the series, labels and series data arrays.
  382. *
  383. * @memberof Chartist.Core
  384. * @param data
  385. */
  386. Chartist.reverseData = function(data) {
  387. data.labels.reverse();
  388. data.series.reverse();
  389. for (var i = 0; i < data.series.length; i++) {
  390. if(typeof(data.series[i]) === 'object' && data.series[i].data !== undefined) {
  391. data.series[i].data.reverse();
  392. } else if(data.series[i] instanceof Array) {
  393. data.series[i].reverse();
  394. }
  395. }
  396. };
  397. /**
  398. * Convert data series into plain array
  399. *
  400. * @memberof Chartist.Core
  401. * @param {Object} data The series object that contains the data to be visualized in the chart
  402. * @param {Boolean} [reverse] If true the whole data is reversed by the getDataArray call. This will modify the data object passed as first parameter. The labels as well as the series order is reversed. The whole series data arrays are reversed too.
  403. * @param {Boolean} [multi] Create a multi dimensional array from a series data array where a value object with `x` and `y` values will be created.
  404. * @return {Array} A plain array that contains the data to be visualized in the chart
  405. */
  406. Chartist.getDataArray = function(data, reverse, multi) {
  407. // Recursively walks through nested arrays and convert string values to numbers and objects with value properties
  408. // to values. Check the tests in data core -> data normalization for a detailed specification of expected values
  409. function recursiveConvert(value) {
  410. if(Chartist.safeHasProperty(value, 'value')) {
  411. // We are dealing with value object notation so we need to recurse on value property
  412. return recursiveConvert(value.value);
  413. } else if(Chartist.safeHasProperty(value, 'data')) {
  414. // We are dealing with series object notation so we need to recurse on data property
  415. return recursiveConvert(value.data);
  416. } else if(value instanceof Array) {
  417. // Data is of type array so we need to recurse on the series
  418. return value.map(recursiveConvert);
  419. } else if(Chartist.isDataHoleValue(value)) {
  420. // We're dealing with a hole in the data and therefore need to return undefined
  421. // We're also returning undefined for multi value output
  422. return undefined;
  423. } else {
  424. // We need to prepare multi value output (x and y data)
  425. if(multi) {
  426. var multiValue = {};
  427. // Single series value arrays are assumed to specify the Y-Axis value
  428. // For example: [1, 2] => [{x: undefined, y: 1}, {x: undefined, y: 2}]
  429. // If multi is a string then it's assumed that it specified which dimension should be filled as default
  430. if(typeof multi === 'string') {
  431. multiValue[multi] = Chartist.getNumberOrUndefined(value);
  432. } else {
  433. multiValue.y = Chartist.getNumberOrUndefined(value);
  434. }
  435. multiValue.x = value.hasOwnProperty('x') ? Chartist.getNumberOrUndefined(value.x) : multiValue.x;
  436. multiValue.y = value.hasOwnProperty('y') ? Chartist.getNumberOrUndefined(value.y) : multiValue.y;
  437. return multiValue;
  438. } else {
  439. // We can return simple data
  440. return Chartist.getNumberOrUndefined(value);
  441. }
  442. }
  443. }
  444. return data.series.map(recursiveConvert);
  445. };
  446. /**
  447. * Converts a number into a padding object.
  448. *
  449. * @memberof Chartist.Core
  450. * @param {Object|Number} padding
  451. * @param {Number} [fallback] This value is used to fill missing values if a incomplete padding object was passed
  452. * @returns {Object} Returns a padding object containing top, right, bottom, left properties filled with the padding number passed in as argument. If the argument is something else than a number (presumably already a correct padding object) then this argument is directly returned.
  453. */
  454. Chartist.normalizePadding = function(padding, fallback) {
  455. fallback = fallback || 0;
  456. return typeof padding === 'number' ? {
  457. top: padding,
  458. right: padding,
  459. bottom: padding,
  460. left: padding
  461. } : {
  462. top: typeof padding.top === 'number' ? padding.top : fallback,
  463. right: typeof padding.right === 'number' ? padding.right : fallback,
  464. bottom: typeof padding.bottom === 'number' ? padding.bottom : fallback,
  465. left: typeof padding.left === 'number' ? padding.left : fallback
  466. };
  467. };
  468. Chartist.getMetaData = function(series, index) {
  469. var value = series.data ? series.data[index] : series[index];
  470. return value ? value.meta : undefined;
  471. };
  472. /**
  473. * Calculate the order of magnitude for the chart scale
  474. *
  475. * @memberof Chartist.Core
  476. * @param {Number} value The value Range of the chart
  477. * @return {Number} The order of magnitude
  478. */
  479. Chartist.orderOfMagnitude = function (value) {
  480. return Math.floor(Math.log(Math.abs(value)) / Math.LN10);
  481. };
  482. /**
  483. * Project a data length into screen coordinates (pixels)
  484. *
  485. * @memberof Chartist.Core
  486. * @param {Object} axisLength The svg element for the chart
  487. * @param {Number} length Single data value from a series array
  488. * @param {Object} bounds All the values to set the bounds of the chart
  489. * @return {Number} The projected data length in pixels
  490. */
  491. Chartist.projectLength = function (axisLength, length, bounds) {
  492. return length / bounds.range * axisLength;
  493. };
  494. /**
  495. * Get the height of the area in the chart for the data series
  496. *
  497. * @memberof Chartist.Core
  498. * @param {Object} svg The svg element for the chart
  499. * @param {Object} options The Object that contains all the optional values for the chart
  500. * @return {Number} The height of the area in the chart for the data series
  501. */
  502. Chartist.getAvailableHeight = function (svg, options) {
  503. return Math.max((Chartist.quantity(options.height).value || svg.height()) - (options.chartPadding.top + options.chartPadding.bottom) - options.axisX.offset, 0);
  504. };
  505. /**
  506. * Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.
  507. *
  508. * @memberof Chartist.Core
  509. * @param {Array} data The array that contains the data to be visualized in the chart
  510. * @param {Object} options The Object that contains the chart options
  511. * @param {String} dimension Axis dimension 'x' or 'y' used to access the correct value and high / low configuration
  512. * @return {Object} An object that contains the highest and lowest value that will be visualized on the chart.
  513. */
  514. Chartist.getHighLow = function (data, options, dimension) {
  515. // TODO: Remove workaround for deprecated global high / low config. Axis high / low configuration is preferred
  516. options = Chartist.extend({}, options, dimension ? options['axis' + dimension.toUpperCase()] : {});
  517. var highLow = {
  518. high: options.high === undefined ? -Number.MAX_VALUE : +options.high,
  519. low: options.low === undefined ? Number.MAX_VALUE : +options.low
  520. };
  521. var findHigh = options.high === undefined;
  522. var findLow = options.low === undefined;
  523. // Function to recursively walk through arrays and find highest and lowest number
  524. function recursiveHighLow(data) {
  525. if(data === undefined) {
  526. return undefined;
  527. } else if(data instanceof Array) {
  528. for (var i = 0; i < data.length; i++) {
  529. recursiveHighLow(data[i]);
  530. }
  531. } else {
  532. var value = dimension ? +data[dimension] : +data;
  533. if (findHigh && value > highLow.high) {
  534. highLow.high = value;
  535. }
  536. if (findLow && value < highLow.low) {
  537. highLow.low = value;
  538. }
  539. }
  540. }
  541. // Start to find highest and lowest number recursively
  542. if(findHigh || findLow) {
  543. recursiveHighLow(data);
  544. }
  545. // Overrides of high / low based on reference value, it will make sure that the invisible reference value is
  546. // used to generate the chart. This is useful when the chart always needs to contain the position of the
  547. // invisible reference value in the view i.e. for bipolar scales.
  548. if (options.referenceValue || options.referenceValue === 0) {
  549. highLow.high = Math.max(options.referenceValue, highLow.high);
  550. highLow.low = Math.min(options.referenceValue, highLow.low);
  551. }
  552. // If high and low are the same because of misconfiguration or flat data (only the same value) we need
  553. // to set the high or low to 0 depending on the polarity
  554. if (highLow.high <= highLow.low) {
  555. // If both values are 0 we set high to 1
  556. if (highLow.low === 0) {
  557. highLow.high = 1;
  558. } else if (highLow.low < 0) {
  559. // If we have the same negative value for the bounds we set bounds.high to 0
  560. highLow.high = 0;
  561. } else if (highLow.high > 0) {
  562. // If we have the same positive value for the bounds we set bounds.low to 0
  563. highLow.low = 0;
  564. } else {
  565. // If data array was empty, values are Number.MAX_VALUE and -Number.MAX_VALUE. Set bounds to prevent errors
  566. highLow.high = 1;
  567. highLow.low = 0;
  568. }
  569. }
  570. return highLow;
  571. };
  572. /**
  573. * Checks if a value can be safely coerced to a number. This includes all values except null which result in finite numbers when coerced. This excludes NaN, since it's not finite.
  574. *
  575. * @memberof Chartist.Core
  576. * @param value
  577. * @returns {Boolean}
  578. */
  579. Chartist.isNumeric = function(value) {
  580. return value === null ? false : isFinite(value);
  581. };
  582. /**
  583. * Returns true on all falsey values except the numeric value 0.
  584. *
  585. * @memberof Chartist.Core
  586. * @param value
  587. * @returns {boolean}
  588. */
  589. Chartist.isFalseyButZero = function(value) {
  590. return !value && value !== 0;
  591. };
  592. /**
  593. * Returns a number if the passed parameter is a valid number or the function will return undefined. On all other values than a valid number, this function will return undefined.
  594. *
  595. * @memberof Chartist.Core
  596. * @param value
  597. * @returns {*}
  598. */
  599. Chartist.getNumberOrUndefined = function(value) {
  600. return Chartist.isNumeric(value) ? +value : undefined;
  601. };
  602. /**
  603. * Checks if provided value object is multi value (contains x or y properties)
  604. *
  605. * @memberof Chartist.Core
  606. * @param value
  607. */
  608. Chartist.isMultiValue = function(value) {
  609. return typeof value === 'object' && ('x' in value || 'y' in value);
  610. };
  611. /**
  612. * Gets a value from a dimension `value.x` or `value.y` while returning value directly if it's a valid numeric value. If the value is not numeric and it's falsey this function will return `defaultValue`.
  613. *
  614. * @memberof Chartist.Core
  615. * @param value
  616. * @param dimension
  617. * @param defaultValue
  618. * @returns {*}
  619. */
  620. Chartist.getMultiValue = function(value, dimension) {
  621. if(Chartist.isMultiValue(value)) {
  622. return Chartist.getNumberOrUndefined(value[dimension || 'y']);
  623. } else {
  624. return Chartist.getNumberOrUndefined(value);
  625. }
  626. };
  627. /**
  628. * Pollard Rho Algorithm to find smallest factor of an integer value. There are more efficient algorithms for factorization, but this one is quite efficient and not so complex.
  629. *
  630. * @memberof Chartist.Core
  631. * @param {Number} num An integer number where the smallest factor should be searched for
  632. * @returns {Number} The smallest integer factor of the parameter num.
  633. */
  634. Chartist.rho = function(num) {
  635. if(num === 1) {
  636. return num;
  637. }
  638. function gcd(p, q) {
  639. if (p % q === 0) {
  640. return q;
  641. } else {
  642. return gcd(q, p % q);
  643. }
  644. }
  645. function f(x) {
  646. return x * x + 1;
  647. }
  648. var x1 = 2, x2 = 2, divisor;
  649. if (num % 2 === 0) {
  650. return 2;
  651. }
  652. do {
  653. x1 = f(x1) % num;
  654. x2 = f(f(x2)) % num;
  655. divisor = gcd(Math.abs(x1 - x2), num);
  656. } while (divisor === 1);
  657. return divisor;
  658. };
  659. /**
  660. * Calculate and retrieve all the bounds for the chart and return them in one array
  661. *
  662. * @memberof Chartist.Core
  663. * @param {Number} axisLength The length of the Axis used for
  664. * @param {Object} highLow An object containing a high and low property indicating the value range of the chart.
  665. * @param {Number} scaleMinSpace The minimum projected length a step should result in
  666. * @param {Boolean} onlyInteger
  667. * @return {Object} All the values to set the bounds of the chart
  668. */
  669. Chartist.getBounds = function (axisLength, highLow, scaleMinSpace, onlyInteger) {
  670. var i,
  671. optimizationCounter = 0,
  672. newMin,
  673. newMax,
  674. bounds = {
  675. high: highLow.high,
  676. low: highLow.low
  677. };
  678. bounds.valueRange = bounds.high - bounds.low;
  679. bounds.oom = Chartist.orderOfMagnitude(bounds.valueRange);
  680. bounds.step = Math.pow(10, bounds.oom);
  681. bounds.min = Math.floor(bounds.low / bounds.step) * bounds.step;
  682. bounds.max = Math.ceil(bounds.high / bounds.step) * bounds.step;
  683. bounds.range = bounds.max - bounds.min;
  684. bounds.numberOfSteps = Math.round(bounds.range / bounds.step);
  685. // Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace
  686. // If we are already below the scaleMinSpace value we will scale up
  687. var length = Chartist.projectLength(axisLength, bounds.step, bounds);
  688. var scaleUp = length < scaleMinSpace;
  689. var smallestFactor = onlyInteger ? Chartist.rho(bounds.range) : 0;
  690. // First check if we should only use integer steps and if step 1 is still larger than scaleMinSpace so we can use 1
  691. if(onlyInteger && Chartist.projectLength(axisLength, 1, bounds) >= scaleMinSpace) {
  692. bounds.step = 1;
  693. } else if(onlyInteger && smallestFactor < bounds.step && Chartist.projectLength(axisLength, smallestFactor, bounds) >= scaleMinSpace) {
  694. // If step 1 was too small, we can try the smallest factor of range
  695. // If the smallest factor is smaller than the current bounds.step and the projected length of smallest factor
  696. // is larger than the scaleMinSpace we should go for it.
  697. bounds.step = smallestFactor;
  698. } else {
  699. // Trying to divide or multiply by 2 and find the best step value
  700. while (true) {
  701. if (scaleUp && Chartist.projectLength(axisLength, bounds.step, bounds) <= scaleMinSpace) {
  702. bounds.step *= 2;
  703. } else if (!scaleUp && Chartist.projectLength(axisLength, bounds.step / 2, bounds) >= scaleMinSpace) {
  704. bounds.step /= 2;
  705. if(onlyInteger && bounds.step % 1 !== 0) {
  706. bounds.step *= 2;
  707. break;
  708. }
  709. } else {
  710. break;
  711. }
  712. if(optimizationCounter++ > 1000) {
  713. throw new Error('Exceeded maximum number of iterations while optimizing scale step!');
  714. }
  715. }
  716. }
  717. var EPSILON = 2.221E-16;
  718. bounds.step = Math.max(bounds.step, EPSILON);
  719. function safeIncrement(value, increment) {
  720. // If increment is too small use *= (1+EPSILON) as a simple nextafter
  721. if (value === (value += increment)) {
  722. value *= (1 + (increment > 0 ? EPSILON : -EPSILON));
  723. }
  724. return value;
  725. }
  726. // Narrow min and max based on new step
  727. newMin = bounds.min;
  728. newMax = bounds.max;
  729. while (newMin + bounds.step <= bounds.low) {
  730. newMin = safeIncrement(newMin, bounds.step);
  731. }
  732. while (newMax - bounds.step >= bounds.high) {
  733. newMax = safeIncrement(newMax, -bounds.step);
  734. }
  735. bounds.min = newMin;
  736. bounds.max = newMax;
  737. bounds.range = bounds.max - bounds.min;
  738. var values = [];
  739. for (i = bounds.min; i <= bounds.max; i = safeIncrement(i, bounds.step)) {
  740. var value = Chartist.roundWithPrecision(i);
  741. if (value !== values[values.length - 1]) {
  742. values.push(value);
  743. }
  744. }
  745. bounds.values = values;
  746. return bounds;
  747. };
  748. /**
  749. * Calculate cartesian coordinates of polar coordinates
  750. *
  751. * @memberof Chartist.Core
  752. * @param {Number} centerX X-axis coordinates of center point of circle segment
  753. * @param {Number} centerY X-axis coordinates of center point of circle segment
  754. * @param {Number} radius Radius of circle segment
  755. * @param {Number} angleInDegrees Angle of circle segment in degrees
  756. * @return {{x:Number, y:Number}} Coordinates of point on circumference
  757. */
  758. Chartist.polarToCartesian = function (centerX, centerY, radius, angleInDegrees) {
  759. var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
  760. return {
  761. x: centerX + (radius * Math.cos(angleInRadians)),
  762. y: centerY + (radius * Math.sin(angleInRadians))
  763. };
  764. };
  765. /**
  766. * Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right
  767. *
  768. * @memberof Chartist.Core
  769. * @param {Object} svg The svg element for the chart
  770. * @param {Object} options The Object that contains all the optional values for the chart
  771. * @param {Number} [fallbackPadding] The fallback padding if partial padding objects are used
  772. * @return {Object} The chart rectangles coordinates inside the svg element plus the rectangles measurements
  773. */
  774. Chartist.createChartRect = function (svg, options, fallbackPadding) {
  775. var hasAxis = !!(options.axisX || options.axisY);
  776. var yAxisOffset = hasAxis ? options.axisY.offset : 0;
  777. var xAxisOffset = hasAxis ? options.axisX.offset : 0;
  778. // If width or height results in invalid value (including 0) we fallback to the unitless settings or even 0
  779. var width = svg.width() || Chartist.quantity(options.width).value || 0;
  780. var height = svg.height() || Chartist.quantity(options.height).value || 0;
  781. var normalizedPadding = Chartist.normalizePadding(options.chartPadding, fallbackPadding);
  782. // If settings were to small to cope with offset (legacy) and padding, we'll adjust
  783. width = Math.max(width, yAxisOffset + normalizedPadding.left + normalizedPadding.right);
  784. height = Math.max(height, xAxisOffset + normalizedPadding.top + normalizedPadding.bottom);
  785. var chartRect = {
  786. padding: normalizedPadding,
  787. width: function () {
  788. return this.x2 - this.x1;
  789. },
  790. height: function () {
  791. return this.y1 - this.y2;
  792. }
  793. };
  794. if(hasAxis) {
  795. if (options.axisX.position === 'start') {
  796. chartRect.y2 = normalizedPadding.top + xAxisOffset;
  797. chartRect.y1 = Math.max(height - normalizedPadding.bottom, chartRect.y2 + 1);
  798. } else {
  799. chartRect.y2 = normalizedPadding.top;
  800. chartRect.y1 = Math.max(height - normalizedPadding.bottom - xAxisOffset, chartRect.y2 + 1);
  801. }
  802. if (options.axisY.position === 'start') {
  803. chartRect.x1 = normalizedPadding.left + yAxisOffset;
  804. chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1);
  805. } else {
  806. chartRect.x1 = normalizedPadding.left;
  807. chartRect.x2 = Math.max(width - normalizedPadding.right - yAxisOffset, chartRect.x1 + 1);
  808. }
  809. } else {
  810. chartRect.x1 = normalizedPadding.left;
  811. chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1);
  812. chartRect.y2 = normalizedPadding.top;
  813. chartRect.y1 = Math.max(height - normalizedPadding.bottom, chartRect.y2 + 1);
  814. }
  815. return chartRect;
  816. };
  817. /**
  818. * Creates a grid line based on a projected value.
  819. *
  820. * @memberof Chartist.Core
  821. * @param position
  822. * @param index
  823. * @param axis
  824. * @param offset
  825. * @param length
  826. * @param group
  827. * @param classes
  828. * @param eventEmitter
  829. */
  830. Chartist.createGrid = function(position, index, axis, offset, length, group, classes, eventEmitter) {
  831. var positionalData = {};
  832. positionalData[axis.units.pos + '1'] = position;
  833. positionalData[axis.units.pos + '2'] = position;
  834. positionalData[axis.counterUnits.pos + '1'] = offset;
  835. positionalData[axis.counterUnits.pos + '2'] = offset + length;
  836. var gridElement = group.elem('line', positionalData, classes.join(' '));
  837. // Event for grid draw
  838. eventEmitter.emit('draw',
  839. Chartist.extend({
  840. type: 'grid',
  841. axis: axis,
  842. index: index,
  843. group: group,
  844. element: gridElement
  845. }, positionalData)
  846. );
  847. };
  848. /**
  849. * Creates a grid background rect and emits the draw event.
  850. *
  851. * @memberof Chartist.Core
  852. * @param gridGroup
  853. * @param chartRect
  854. * @param className
  855. * @param eventEmitter
  856. */
  857. Chartist.createGridBackground = function (gridGroup, chartRect, className, eventEmitter) {
  858. var gridBackground = gridGroup.elem('rect', {
  859. x: chartRect.x1,
  860. y: chartRect.y2,
  861. width: chartRect.width(),
  862. height: chartRect.height(),
  863. }, className, true);
  864. // Event for grid background draw
  865. eventEmitter.emit('draw', {
  866. type: 'gridBackground',
  867. group: gridGroup,
  868. element: gridBackground
  869. });
  870. };
  871. /**
  872. * Creates a label based on a projected value and an axis.
  873. *
  874. * @memberof Chartist.Core
  875. * @param position
  876. * @param length
  877. * @param index
  878. * @param labels
  879. * @param axis
  880. * @param axisOffset
  881. * @param labelOffset
  882. * @param group
  883. * @param classes
  884. * @param useForeignObject
  885. * @param eventEmitter
  886. */
  887. Chartist.createLabel = function(position, length, index, labels, axis, axisOffset, labelOffset, group, classes, useForeignObject, eventEmitter) {
  888. var labelElement;
  889. var positionalData = {};
  890. positionalData[axis.units.pos] = position + labelOffset[axis.units.pos];
  891. positionalData[axis.counterUnits.pos] = labelOffset[axis.counterUnits.pos];
  892. positionalData[axis.units.len] = length;
  893. positionalData[axis.counterUnits.len] = Math.max(0, axisOffset - 10);
  894. if(useForeignObject) {
  895. // We need to set width and height explicitly to px as span will not expand with width and height being
  896. // 100% in all browsers
  897. var content = document.createElement('span');
  898. content.className = classes.join(' ');
  899. content.setAttribute('xmlns', Chartist.namespaces.xhtml);
  900. content.innerText = labels[index];
  901. content.style[axis.units.len] = Math.round(positionalData[axis.units.len]) + 'px';
  902. content.style[axis.counterUnits.len] = Math.round(positionalData[axis.counterUnits.len]) + 'px';
  903. labelElement = group.foreignObject(content, Chartist.extend({
  904. style: 'overflow: visible;'
  905. }, positionalData));
  906. } else {
  907. labelElement = group.elem('text', positionalData, classes.join(' ')).text(labels[index]);
  908. }
  909. eventEmitter.emit('draw', Chartist.extend({
  910. type: 'label',
  911. axis: axis,
  912. index: index,
  913. group: group,
  914. element: labelElement,
  915. text: labels[index]
  916. }, positionalData));
  917. };
  918. /**
  919. * Helper to read series specific options from options object. It automatically falls back to the global option if
  920. * there is no option in the series options.
  921. *
  922. * @param {Object} series Series object
  923. * @param {Object} options Chartist options object
  924. * @param {string} key The options key that should be used to obtain the options
  925. * @returns {*}
  926. */
  927. Chartist.getSeriesOption = function(series, options, key) {
  928. if(series.name && options.series && options.series[series.name]) {
  929. var seriesOptions = options.series[series.name];
  930. return seriesOptions.hasOwnProperty(key) ? seriesOptions[key] : options[key];
  931. } else {
  932. return options[key];
  933. }
  934. };
  935. /**
  936. * Provides options handling functionality with callback for options changes triggered by responsive options and media query matches
  937. *
  938. * @memberof Chartist.Core
  939. * @param {Object} options Options set by user
  940. * @param {Array} responsiveOptions Optional functions to add responsive behavior to chart
  941. * @param {Object} eventEmitter The event emitter that will be used to emit the options changed events
  942. * @return {Object} The consolidated options object from the defaults, base and matching responsive options
  943. */
  944. Chartist.optionsProvider = function (options, responsiveOptions, eventEmitter) {
  945. var baseOptions = Chartist.extend({}, options),
  946. currentOptions,
  947. mediaQueryListeners = [],
  948. i;
  949. function updateCurrentOptions(mediaEvent) {
  950. var previousOptions = currentOptions;
  951. currentOptions = Chartist.extend({}, baseOptions);
  952. if (responsiveOptions) {
  953. for (i = 0; i < responsiveOptions.length; i++) {
  954. var mql = window.matchMedia(responsiveOptions[i][0]);
  955. if (mql.matches) {
  956. currentOptions = Chartist.extend(currentOptions, responsiveOptions[i][1]);
  957. }
  958. }
  959. }
  960. if(eventEmitter && mediaEvent) {
  961. eventEmitter.emit('optionsChanged', {
  962. previousOptions: previousOptions,
  963. currentOptions: currentOptions
  964. });
  965. }
  966. }
  967. function removeMediaQueryListeners() {
  968. mediaQueryListeners.forEach(function(mql) {
  969. mql.removeListener(updateCurrentOptions);
  970. });
  971. }
  972. if (!window.matchMedia) {
  973. throw 'window.matchMedia not found! Make sure you\'re using a polyfill.';
  974. } else if (responsiveOptions) {
  975. for (i = 0; i < responsiveOptions.length; i++) {
  976. var mql = window.matchMedia(responsiveOptions[i][0]);
  977. mql.addListener(updateCurrentOptions);
  978. mediaQueryListeners.push(mql);
  979. }
  980. }
  981. // Execute initially without an event argument so we get the correct options
  982. updateCurrentOptions();
  983. return {
  984. removeMediaQueryListeners: removeMediaQueryListeners,
  985. getCurrentOptions: function getCurrentOptions() {
  986. return Chartist.extend({}, currentOptions);
  987. }
  988. };
  989. };
  990. /**
  991. * Splits a list of coordinates and associated values into segments. Each returned segment contains a pathCoordinates
  992. * valueData property describing the segment.
  993. *
  994. * With the default options, segments consist of contiguous sets of points that do not have an undefined value. Any
  995. * points with undefined values are discarded.
  996. *
  997. * **Options**
  998. * The following options are used to determine how segments are formed
  999. * ```javascript
  1000. * var options = {
  1001. * // If fillHoles is true, undefined values are simply discarded without creating a new segment. Assuming other options are default, this returns single segment.
  1002. * fillHoles: false,
  1003. * // If increasingX is true, the coordinates in all segments have strictly increasing x-values.
  1004. * increasingX: false
  1005. * };
  1006. * ```
  1007. *
  1008. * @memberof Chartist.Core
  1009. * @param {Array} pathCoordinates List of point coordinates to be split in the form [x1, y1, x2, y2 ... xn, yn]
  1010. * @param {Array} values List of associated point values in the form [v1, v2 .. vn]
  1011. * @param {Object} options Options set by user
  1012. * @return {Array} List of segments, each containing a pathCoordinates and valueData property.
  1013. */
  1014. Chartist.splitIntoSegments = function(pathCoordinates, valueData, options) {
  1015. var defaultOptions = {
  1016. increasingX: false,
  1017. fillHoles: false
  1018. };
  1019. options = Chartist.extend({}, defaultOptions, options);
  1020. var segments = [];
  1021. var hole = true;
  1022. for(var i = 0; i < pathCoordinates.length; i += 2) {
  1023. // If this value is a "hole" we set the hole flag
  1024. if(Chartist.getMultiValue(valueData[i / 2].value) === undefined) {
  1025. // if(valueData[i / 2].value === undefined) {
  1026. if(!options.fillHoles) {
  1027. hole = true;
  1028. }
  1029. } else {
  1030. if(options.increasingX && i >= 2 && pathCoordinates[i] <= pathCoordinates[i-2]) {
  1031. // X is not increasing, so we need to make sure we start a new segment
  1032. hole = true;
  1033. }
  1034. // If it's a valid value we need to check if we're coming out of a hole and create a new empty segment
  1035. if(hole) {
  1036. segments.push({
  1037. pathCoordinates: [],
  1038. valueData: []
  1039. });
  1040. // As we have a valid value now, we are not in a "hole" anymore
  1041. hole = false;
  1042. }
  1043. // Add to the segment pathCoordinates and valueData
  1044. segments[segments.length - 1].pathCoordinates.push(pathCoordinates[i], pathCoordinates[i + 1]);
  1045. segments[segments.length - 1].valueData.push(valueData[i / 2]);
  1046. }
  1047. }
  1048. return segments;
  1049. };
  1050. }(this || global, Chartist));
  1051. ;/**
  1052. * Chartist path interpolation functions.
  1053. *
  1054. * @module Chartist.Interpolation
  1055. */
  1056. /* global Chartist */
  1057. (function(globalRoot, Chartist) {
  1058. 'use strict';
  1059. Chartist.Interpolation = {};
  1060. /**
  1061. * This interpolation function does not smooth the path and the result is only containing lines and no curves.
  1062. *
  1063. * @example
  1064. * var chart = new Chartist.Line('.ct-chart', {
  1065. * labels: [1, 2, 3, 4, 5],
  1066. * series: [[1, 2, 8, 1, 7]]
  1067. * }, {
  1068. * lineSmooth: Chartist.Interpolation.none({
  1069. * fillHoles: false
  1070. * })
  1071. * });
  1072. *
  1073. *
  1074. * @memberof Chartist.Interpolation
  1075. * @return {Function}
  1076. */
  1077. Chartist.Interpolation.none = function(options) {
  1078. var defaultOptions = {
  1079. fillHoles: false
  1080. };
  1081. options = Chartist.extend({}, defaultOptions, options);
  1082. return function none(pathCoordinates, valueData) {
  1083. var path = new Chartist.Svg.Path();
  1084. var hole = true;
  1085. for(var i = 0; i < pathCoordinates.length; i += 2) {
  1086. var currX = pathCoordinates[i];
  1087. var currY = pathCoordinates[i + 1];
  1088. var currData = valueData[i / 2];
  1089. if(Chartist.getMultiValue(currData.value) !== undefined) {
  1090. if(hole) {
  1091. path.move(currX, currY, false, currData);
  1092. } else {
  1093. path.line(currX, currY, false, currData);
  1094. }
  1095. hole = false;
  1096. } else if(!options.fillHoles) {
  1097. hole = true;
  1098. }
  1099. }
  1100. return path;
  1101. };
  1102. };
  1103. /**
  1104. * Simple smoothing creates horizontal handles that are positioned with a fraction of the length between two data points. You can use the divisor option to specify the amount of smoothing.
  1105. *
  1106. * Simple smoothing can be used instead of `Chartist.Smoothing.cardinal` if you'd like to get rid of the artifacts it produces sometimes. Simple smoothing produces less flowing lines but is accurate by hitting the points and it also doesn't swing below or above the given data point.
  1107. *
  1108. * All smoothing functions within Chartist are factory functions that accept an options parameter. The simple interpolation function accepts one configuration parameter `divisor`, between 1 and ∞, which controls the smoothing characteristics.
  1109. *
  1110. * @example
  1111. * var chart = new Chartist.Line('.ct-chart', {
  1112. * labels: [1, 2, 3, 4, 5],
  1113. * series: [[1, 2, 8, 1, 7]]
  1114. * }, {
  1115. * lineSmooth: Chartist.Interpolation.simple({
  1116. * divisor: 2,
  1117. * fillHoles: false
  1118. * })
  1119. * });
  1120. *
  1121. *
  1122. * @memberof Chartist.Interpolation
  1123. * @param {Object} options The options of the simple interpolation factory function.
  1124. * @return {Function}
  1125. */
  1126. Chartist.Interpolation.simple = function(options) {
  1127. var defaultOptions = {
  1128. divisor: 2,
  1129. fillHoles: false
  1130. };
  1131. options = Chartist.extend({}, defaultOptions, options);
  1132. var d = 1 / Math.max(1, options.divisor);
  1133. return function simple(pathCoordinates, valueData) {
  1134. var path = new Chartist.Svg.Path();
  1135. var prevX, prevY, prevData;
  1136. for(var i = 0; i < pathCoordinates.length; i += 2) {
  1137. var currX = pathCoordinates[i];
  1138. var currY = pathCoordinates[i + 1];
  1139. var length = (currX - prevX) * d;
  1140. var currData = valueData[i / 2];
  1141. if(currData.value !== undefined) {
  1142. if(prevData === undefined) {
  1143. path.move(currX, currY, false, currData);
  1144. } else {
  1145. path.curve(
  1146. prevX + length,
  1147. prevY,
  1148. currX - length,
  1149. currY,
  1150. currX,
  1151. currY,
  1152. false,
  1153. currData
  1154. );
  1155. }
  1156. prevX = currX;
  1157. prevY = currY;
  1158. prevData = currData;
  1159. } else if(!options.fillHoles) {
  1160. prevX = currX = prevData = undefined;
  1161. }
  1162. }
  1163. return path;
  1164. };
  1165. };
  1166. /**
  1167. * Cardinal / Catmull-Rome spline interpolation is the default smoothing function in Chartist. It produces nice results where the splines will always meet the points. It produces some artifacts though when data values are increased or decreased rapidly. The line may not follow a very accurate path and if the line should be accurate this smoothing function does not produce the best results.
  1168. *
  1169. * Cardinal splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`.
  1170. *
  1171. * All smoothing functions within Chartist are factory functions that accept an options parameter. The cardinal interpolation function accepts one configuration parameter `tension`, between 0 and 1, which controls the smoothing intensity.
  1172. *
  1173. * @example
  1174. * var chart = new Chartist.Line('.ct-chart', {
  1175. * labels: [1, 2, 3, 4, 5],
  1176. * series: [[1, 2, 8, 1, 7]]
  1177. * }, {
  1178. * lineSmooth: Chartist.Interpolation.cardinal({
  1179. * tension: 1,
  1180. * fillHoles: false
  1181. * })
  1182. * });
  1183. *
  1184. * @memberof Chartist.Interpolation
  1185. * @param {Object} options The options of the cardinal factory function.
  1186. * @return {Function}
  1187. */
  1188. Chartist.Interpolation.cardinal = function(options) {
  1189. var defaultOptions = {
  1190. tension: 1,
  1191. fillHoles: false
  1192. };
  1193. options = Chartist.extend({}, defaultOptions, options);
  1194. var t = Math.min(1, Math.max(0, options.tension)),
  1195. c = 1 - t;
  1196. return function cardinal(pathCoordinates, valueData) {
  1197. // First we try to split the coordinates into segments
  1198. // This is necessary to treat "holes" in line charts
  1199. var segments = Chartist.splitIntoSegments(pathCoordinates, valueData, {
  1200. fillHoles: options.fillHoles
  1201. });
  1202. if(!segments.length) {
  1203. // If there were no segments return 'Chartist.Interpolation.none'
  1204. return Chartist.Interpolation.none()([]);
  1205. } else if(segments.length > 1) {
  1206. // If the split resulted in more that one segment we need to interpolate each segment individually and join them
  1207. // afterwards together into a single path.
  1208. var paths = [];
  1209. // For each segment we will recurse the cardinal function
  1210. segments.forEach(function(segment) {
  1211. paths.push(cardinal(segment.pathCoordinates, segment.valueData));
  1212. });
  1213. // Join the segment path data into a single path and return
  1214. return Chartist.Svg.Path.join(paths);
  1215. } else {
  1216. // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
  1217. // segment
  1218. pathCoordinates = segments[0].pathCoordinates;
  1219. valueData = segments[0].valueData;
  1220. // If less than two points we need to fallback to no smoothing
  1221. if(pathCoordinates.length <= 4) {
  1222. return Chartist.Interpolation.none()(pathCoordinates, valueData);
  1223. }
  1224. var path = new Chartist.Svg.Path().move(pathCoordinates[0], pathCoordinates[1], false, valueData[0]),
  1225. z;
  1226. for (var i = 0, iLen = pathCoordinates.length; iLen - 2 * !z > i; i += 2) {
  1227. var p = [
  1228. {x: +pathCoordinates[i - 2], y: +pathCoordinates[i - 1]},
  1229. {x: +pathCoordinates[i], y: +pathCoordinates[i + 1]},
  1230. {x: +pathCoordinates[i + 2], y: +pathCoordinates[i + 3]},
  1231. {x: +pathCoordinates[i + 4], y: +pathCoordinates[i + 5]}
  1232. ];
  1233. if (z) {
  1234. if (!i) {
  1235. p[0] = {x: +pathCoordinates[iLen - 2], y: +pathCoordinates[iLen - 1]};
  1236. } else if (iLen - 4 === i) {
  1237. p[3] = {x: +pathCoordinates[0], y: +pathCoordinates[1]};
  1238. } else if (iLen - 2 === i) {
  1239. p[2] = {x: +pathCoordinates[0], y: +pathCoordinates[1]};
  1240. p[3] = {x: +pathCoordinates[2], y: +pathCoordinates[3]};
  1241. }
  1242. } else {
  1243. if (iLen - 4 === i) {
  1244. p[3] = p[2];
  1245. } else if (!i) {
  1246. p[0] = {x: +pathCoordinates[i], y: +pathCoordinates[i + 1]};
  1247. }
  1248. }
  1249. path.curve(
  1250. (t * (-p[0].x + 6 * p[1].x + p[2].x) / 6) + (c * p[2].x),
  1251. (t * (-p[0].y + 6 * p[1].y + p[2].y) / 6) + (c * p[2].y),
  1252. (t * (p[1].x + 6 * p[2].x - p[3].x) / 6) + (c * p[2].x),
  1253. (t * (p[1].y + 6 * p[2].y - p[3].y) / 6) + (c * p[2].y),
  1254. p[2].x,
  1255. p[2].y,
  1256. false,
  1257. valueData[(i + 2) / 2]
  1258. );
  1259. }
  1260. return path;
  1261. }
  1262. };
  1263. };
  1264. /**
  1265. * Monotone Cubic spline interpolation produces a smooth curve which preserves monotonicity. Unlike cardinal splines, the curve will not extend beyond the range of y-values of the original data points.
  1266. *
  1267. * Monotone Cubic splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`.
  1268. *
  1269. * The x-values of subsequent points must be increasing to fit a Monotone Cubic spline. If this condition is not met for a pair of adjacent points, then there will be a break in the curve between those data points.
  1270. *
  1271. * All smoothing functions within Chartist are factory functions that accept an options parameter.
  1272. *
  1273. * @example
  1274. * var chart = new Chartist.Line('.ct-chart', {
  1275. * labels: [1, 2, 3, 4, 5],
  1276. * series: [[1, 2, 8, 1, 7]]
  1277. * }, {
  1278. * lineSmooth: Chartist.Interpolation.monotoneCubic({
  1279. * fillHoles: false
  1280. * })
  1281. * });
  1282. *
  1283. * @memberof Chartist.Interpolation
  1284. * @param {Object} options The options of the monotoneCubic factory function.
  1285. * @return {Function}
  1286. */
  1287. Chartist.Interpolation.monotoneCubic = function(options) {
  1288. var defaultOptions = {
  1289. fillHoles: false
  1290. };
  1291. options = Chartist.extend({}, defaultOptions, options);
  1292. return function monotoneCubic(pathCoordinates, valueData) {
  1293. // First we try to split the coordinates into segments
  1294. // This is necessary to treat "holes" in line charts
  1295. var segments = Chartist.splitIntoSegments(pathCoordinates, valueData, {
  1296. fillHoles: options.fillHoles,
  1297. increasingX: true
  1298. });
  1299. if(!segments.length) {
  1300. // If there were no segments return 'Chartist.Interpolation.none'
  1301. return Chartist.Interpolation.none()([]);
  1302. } else if(segments.length > 1) {
  1303. // If the split resulted in more that one segment we need to interpolate each segment individually and join them
  1304. // afterwards together into a single path.
  1305. var paths = [];
  1306. // For each segment we will recurse the monotoneCubic fn function
  1307. segments.forEach(function(segment) {
  1308. paths.push(monotoneCubic(segment.pathCoordinates, segment.valueData));
  1309. });
  1310. // Join the segment path data into a single path and return
  1311. return Chartist.Svg.Path.join(paths);
  1312. } else {
  1313. // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
  1314. // segment
  1315. pathCoordinates = segments[0].pathCoordinates;
  1316. valueData = segments[0].valueData;
  1317. // If less than three points we need to fallback to no smoothing
  1318. if(pathCoordinates.length <= 4) {
  1319. return Chartist.Interpolation.none()(pathCoordinates, valueData);
  1320. }
  1321. var xs = [],
  1322. ys = [],
  1323. i,
  1324. n = pathCoordinates.length / 2,
  1325. ms = [],
  1326. ds = [], dys = [], dxs = [],
  1327. path;
  1328. // Populate x and y coordinates into separate arrays, for readability
  1329. for(i = 0; i < n; i++) {
  1330. xs[i] = pathCoordinates[i * 2];
  1331. ys[i] = pathCoordinates[i * 2 + 1];
  1332. }
  1333. // Calculate deltas and derivative
  1334. for(i = 0; i < n - 1; i++) {
  1335. dys[i] = ys[i + 1] - ys[i];
  1336. dxs[i] = xs[i + 1] - xs[i];
  1337. ds[i] = dys[i] / dxs[i];
  1338. }
  1339. // Determine desired slope (m) at each point using Fritsch-Carlson method
  1340. // See: http://math.stackexchange.com/questions/45218/implementation-of-monotone-cubic-interpolation
  1341. ms[0] = ds[0];
  1342. ms[n - 1] = ds[n - 2];
  1343. for(i = 1; i < n - 1; i++) {
  1344. if(ds[i] === 0 || ds[i - 1] === 0 || (ds[i - 1] > 0) !== (ds[i] > 0)) {
  1345. ms[i] = 0;
  1346. } else {
  1347. ms[i] = 3 * (dxs[i - 1] + dxs[i]) / (
  1348. (2 * dxs[i] + dxs[i - 1]) / ds[i - 1] +
  1349. (dxs[i] + 2 * dxs[i - 1]) / ds[i]);
  1350. if(!isFinite(ms[i])) {
  1351. ms[i] = 0;
  1352. }
  1353. }
  1354. }
  1355. // Now build a path from the slopes
  1356. path = new Chartist.Svg.Path().move(xs[0], ys[0], false, valueData[0]);
  1357. for(i = 0; i < n - 1; i++) {
  1358. path.curve(
  1359. // First control point
  1360. xs[i] + dxs[i] / 3,
  1361. ys[i] + ms[i] * dxs[i] / 3,
  1362. // Second control point
  1363. xs[i + 1] - dxs[i] / 3,
  1364. ys[i + 1] - ms[i + 1] * dxs[i] / 3,
  1365. // End point
  1366. xs[i + 1],
  1367. ys[i + 1],
  1368. false,
  1369. valueData[i + 1]
  1370. );
  1371. }
  1372. return path;
  1373. }
  1374. };
  1375. };
  1376. /**
  1377. * Step interpolation will cause the line chart to move in steps rather than diagonal or smoothed lines. This interpolation will create additional points that will also be drawn when the `showPoint` option is enabled.
  1378. *
  1379. * All smoothing functions within Chartist are factory functions that accept an options parameter. The step interpolation function accepts one configuration parameter `postpone`, that can be `true` or `false`. The default value is `true` and will cause the step to occur where the value actually changes. If a different behaviour is needed where the step is shifted to the left and happens before the actual value, this option can be set to `false`.
  1380. *
  1381. * @example
  1382. * var chart = new Chartist.Line('.ct-chart', {
  1383. * labels: [1, 2, 3, 4, 5],
  1384. * series: [[1, 2, 8, 1, 7]]
  1385. * }, {
  1386. * lineSmooth: Chartist.Interpolation.step({
  1387. * postpone: true,
  1388. * fillHoles: false
  1389. * })
  1390. * });
  1391. *
  1392. * @memberof Chartist.Interpolation
  1393. * @param options
  1394. * @returns {Function}
  1395. */
  1396. Chartist.Interpolation.step = function(options) {
  1397. var defaultOptions = {
  1398. postpone: true,
  1399. fillHoles: false
  1400. };
  1401. options = Chartist.extend({}, defaultOptions, options);
  1402. return function step(pathCoordinates, valueData) {
  1403. var path = new Chartist.Svg.Path();
  1404. var prevX, prevY, prevData;
  1405. for (var i = 0; i < pathCoordinates.length; i += 2) {
  1406. var currX = pathCoordinates[i];
  1407. var currY = pathCoordinates[i + 1];
  1408. var currData = valueData[i / 2];
  1409. // If the current point is also not a hole we can draw the step lines
  1410. if(currData.value !== undefined) {
  1411. if(prevData === undefined) {
  1412. path.move(currX, currY, false, currData);
  1413. } else {
  1414. if(options.postpone) {
  1415. // If postponed we should draw the step line with the value of the previous value
  1416. path.line(currX, prevY, false, prevData);
  1417. } else {
  1418. // If not postponed we should draw the step line with the value of the current value
  1419. path.line(prevX, currY, false, currData);
  1420. }
  1421. // Line to the actual point (this should only be a Y-Axis movement
  1422. path.line(currX, currY, false, currData);
  1423. }
  1424. prevX = currX;
  1425. prevY = currY;
  1426. prevData = currData;
  1427. } else if(!options.fillHoles) {
  1428. prevX = prevY = prevData = undefined;
  1429. }
  1430. }
  1431. return path;
  1432. };
  1433. };
  1434. }(this || global, Chartist));
  1435. ;/**
  1436. * A very basic event module that helps to generate and catch events.
  1437. *
  1438. * @module Chartist.Event
  1439. */
  1440. /* global Chartist */
  1441. (function (globalRoot, Chartist) {
  1442. 'use strict';
  1443. Chartist.EventEmitter = function () {
  1444. var handlers = [];
  1445. /**
  1446. * Add an event handler for a specific event
  1447. *
  1448. * @memberof Chartist.Event
  1449. * @param {String} event The event name
  1450. * @param {Function} handler A event handler function
  1451. */
  1452. function addEventHandler(event, handler) {
  1453. handlers[event] = handlers[event] || [];
  1454. handlers[event].push(handler);
  1455. }
  1456. /**
  1457. * Remove an event handler of a specific event name or remove all event handlers for a specific event.
  1458. *
  1459. * @memberof Chartist.Event
  1460. * @param {String} event The event name where a specific or all handlers should be removed
  1461. * @param {Function} [handler] An optional event handler function. If specified only this specific handler will be removed and otherwise all handlers are removed.
  1462. */
  1463. function removeEventHandler(event, handler) {
  1464. // Only do something if there are event handlers with this name existing
  1465. if(handlers[event]) {
  1466. // If handler is set we will look for a specific handler and only remove this
  1467. if(handler) {
  1468. handlers[event].splice(handlers[event].indexOf(handler), 1);
  1469. if(handlers[event].length === 0) {
  1470. delete handlers[event];
  1471. }
  1472. } else {
  1473. // If no handler is specified we remove all handlers for this event
  1474. delete handlers[event];
  1475. }
  1476. }
  1477. }
  1478. /**
  1479. * Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter.
  1480. *
  1481. * @memberof Chartist.Event
  1482. * @param {String} event The event name that should be triggered
  1483. * @param {*} data Arbitrary data that will be passed to the event handler callback functions
  1484. */
  1485. function emit(event, data) {
  1486. // Only do something if there are event handlers with this name existing
  1487. if(handlers[event]) {
  1488. handlers[event].forEach(function(handler) {
  1489. handler(data);
  1490. });
  1491. }
  1492. // Emit event to star event handlers
  1493. if(handlers['*']) {
  1494. handlers['*'].forEach(function(starHandler) {
  1495. starHandler(event, data);
  1496. });
  1497. }
  1498. }
  1499. return {
  1500. addEventHandler: addEventHandler,
  1501. removeEventHandler: removeEventHandler,
  1502. emit: emit
  1503. };
  1504. };
  1505. }(this || global, Chartist));
  1506. ;/**
  1507. * This module provides some basic prototype inheritance utilities.
  1508. *
  1509. * @module Chartist.Class
  1510. */
  1511. /* global Chartist */
  1512. (function(globalRoot, Chartist) {
  1513. 'use strict';
  1514. function listToArray(list) {
  1515. var arr = [];
  1516. if (list.length) {
  1517. for (var i = 0; i < list.length; i++) {
  1518. arr.push(list[i]);
  1519. }
  1520. }
  1521. return arr;
  1522. }
  1523. /**
  1524. * Method to extend from current prototype.
  1525. *
  1526. * @memberof Chartist.Class
  1527. * @param {Object} properties The object that serves as definition for the prototype that gets created for the new class. This object should always contain a constructor property that is the desired constructor for the newly created class.
  1528. * @param {Object} [superProtoOverride] By default extens will use the current class prototype or Chartist.class. With this parameter you can specify any super prototype that will be used.
  1529. * @return {Function} Constructor function of the new class
  1530. *
  1531. * @example
  1532. * var Fruit = Class.extend({
  1533. * color: undefined,
  1534. * sugar: undefined,
  1535. *
  1536. * constructor: function(color, sugar) {
  1537. * this.color = color;
  1538. * this.sugar = sugar;
  1539. * },
  1540. *
  1541. * eat: function() {
  1542. * this.sugar = 0;
  1543. * return this;
  1544. * }
  1545. * });
  1546. *
  1547. * var Banana = Fruit.extend({
  1548. * length: undefined,
  1549. *
  1550. * constructor: function(length, sugar) {
  1551. * Banana.super.constructor.call(this, 'Yellow', sugar);
  1552. * this.length = length;
  1553. * }
  1554. * });
  1555. *
  1556. * var banana = new Banana(20, 40);
  1557. * console.log('banana instanceof Fruit', banana instanceof Fruit);
  1558. * console.log('Fruit is prototype of banana', Fruit.prototype.isPrototypeOf(banana));
  1559. * console.log('bananas prototype is Fruit', Object.getPrototypeOf(banana) === Fruit.prototype);
  1560. * console.log(banana.sugar);
  1561. * console.log(banana.eat().sugar);
  1562. * console.log(banana.color);
  1563. */
  1564. function extend(properties, superProtoOverride) {
  1565. var superProto = superProtoOverride || this.prototype || Chartist.Class;
  1566. var proto = Object.create(superProto);
  1567. Chartist.Class.cloneDefinitions(proto, properties);
  1568. var constr = function() {
  1569. var fn = proto.constructor || function () {},
  1570. instance;
  1571. // If this is linked to the Chartist namespace the constructor was not called with new
  1572. // To provide a fallback we will instantiate here and return the instance
  1573. instance = this === Chartist ? Object.create(proto) : this;
  1574. fn.apply(instance, Array.prototype.slice.call(arguments, 0));
  1575. // If this constructor was not called with new we need to return the instance
  1576. // This will not harm when the constructor has been called with new as the returned value is ignored
  1577. return instance;
  1578. };
  1579. constr.prototype = proto;
  1580. constr.super = superProto;
  1581. constr.extend = this.extend;
  1582. return constr;
  1583. }
  1584. // Variable argument list clones args > 0 into args[0] and retruns modified args[0]
  1585. function cloneDefinitions() {
  1586. var args = listToArray(arguments);
  1587. var target = args[0];
  1588. args.splice(1, args.length - 1).forEach(function (source) {
  1589. Object.getOwnPropertyNames(source).forEach(function (propName) {
  1590. // If this property already exist in target we delete it first
  1591. delete target[propName];
  1592. // Define the property with the descriptor from source
  1593. Object.defineProperty(target, propName,
  1594. Object.getOwnPropertyDescriptor(source, propName));
  1595. });
  1596. });
  1597. return target;
  1598. }
  1599. Chartist.Class = {
  1600. extend: extend,
  1601. cloneDefinitions: cloneDefinitions
  1602. };
  1603. }(this || global, Chartist));
  1604. ;/**
  1605. * Base for all chart types. The methods in Chartist.Base are inherited to all chart types.
  1606. *
  1607. * @module Chartist.Base
  1608. */
  1609. /* global Chartist */
  1610. (function(globalRoot, Chartist) {
  1611. 'use strict';
  1612. var window = globalRoot.window;
  1613. // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance.
  1614. // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not
  1615. // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage.
  1616. // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html
  1617. // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj
  1618. // The problem is with the label offsets that can't be converted into percentage and affecting the chart container
  1619. /**
  1620. * Updates the chart which currently does a full reconstruction of the SVG DOM
  1621. *
  1622. * @param {Object} [data] Optional data you'd like to set for the chart before it will update. If not specified the update method will use the data that is already configured with the chart.
  1623. * @param {Object} [options] Optional options you'd like to add to the previous options for the chart before it will update. If not specified the update method will use the options that have been already configured with the chart.
  1624. * @param {Boolean} [override] If set to true, the passed options will be used to extend the options that have been configured already. Otherwise the chart default options will be used as the base
  1625. * @memberof Chartist.Base
  1626. */
  1627. function update(data, options, override) {
  1628. if(data) {
  1629. this.data = data || {};
  1630. this.data.labels = this.data.labels || [];
  1631. this.data.series = this.data.series || [];
  1632. // Event for data transformation that allows to manipulate the data before it gets rendered in the charts
  1633. this.eventEmitter.emit('data', {
  1634. type: 'update',
  1635. data: this.data
  1636. });
  1637. }
  1638. if(options) {
  1639. this.options = Chartist.extend({}, override ? this.options : this.defaultOptions, options);
  1640. // If chartist was not initialized yet, we just set the options and leave the rest to the initialization
  1641. // Otherwise we re-create the optionsProvider at this point
  1642. if(!this.initializeTimeoutId) {
  1643. this.optionsProvider.removeMediaQueryListeners();
  1644. this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
  1645. }
  1646. }
  1647. // Only re-created the chart if it has been initialized yet
  1648. if(!this.initializeTimeoutId) {
  1649. this.createChart(this.optionsProvider.getCurrentOptions());
  1650. }
  1651. // Return a reference to the chart object to chain up calls
  1652. return this;
  1653. }
  1654. /**
  1655. * This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically.
  1656. *
  1657. * @memberof Chartist.Base
  1658. */
  1659. function detach() {
  1660. // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore
  1661. // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout
  1662. if(!this.initializeTimeoutId) {
  1663. window.removeEventListener('resize', this.resizeListener);
  1664. this.optionsProvider.removeMediaQueryListeners();
  1665. } else {
  1666. window.clearTimeout(this.initializeTimeoutId);
  1667. }
  1668. return this;
  1669. }
  1670. /**
  1671. * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.
  1672. *
  1673. * @memberof Chartist.Base
  1674. * @param {String} event Name of the event. Check the examples for supported events.
  1675. * @param {Function} handler The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details.
  1676. */
  1677. function on(event, handler) {
  1678. this.eventEmitter.addEventHandler(event, handler);
  1679. return this;
  1680. }
  1681. /**
  1682. * Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered.
  1683. *
  1684. * @memberof Chartist.Base
  1685. * @param {String} event Name of the event for which a handler should be removed
  1686. * @param {Function} [handler] The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list.
  1687. */
  1688. function off(event, handler) {
  1689. this.eventEmitter.removeEventHandler(event, handler);
  1690. return this;
  1691. }
  1692. function initialize() {
  1693. // Add window resize listener that re-creates the chart
  1694. window.addEventListener('resize', this.resizeListener);
  1695. // Obtain current options based on matching media queries (if responsive options are given)
  1696. // This will also register a listener that is re-creating the chart based on media changes
  1697. this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
  1698. // Register options change listener that will trigger a chart update
  1699. this.eventEmitter.addEventHandler('optionsChanged', function() {
  1700. this.update();
  1701. }.bind(this));
  1702. // Before the first chart creation we need to register us with all plugins that are configured
  1703. // Initialize all relevant plugins with our chart object and the plugin options specified in the config
  1704. if(this.options.plugins) {
  1705. this.options.plugins.forEach(function(plugin) {
  1706. if(plugin instanceof Array) {
  1707. plugin[0](this, plugin[1]);
  1708. } else {
  1709. plugin(this);
  1710. }
  1711. }.bind(this));
  1712. }
  1713. // Event for data transformation that allows to manipulate the data before it gets rendered in the charts
  1714. this.eventEmitter.emit('data', {
  1715. type: 'initial',
  1716. data: this.data
  1717. });
  1718. // Create the first chart
  1719. this.createChart(this.optionsProvider.getCurrentOptions());
  1720. // As chart is initialized from the event loop now we can reset our timeout reference
  1721. // This is important if the chart gets initialized on the same element twice
  1722. this.initializeTimeoutId = undefined;
  1723. }
  1724. /**
  1725. * Constructor of chart base class.
  1726. *
  1727. * @param query
  1728. * @param data
  1729. * @param defaultOptions
  1730. * @param options
  1731. * @param responsiveOptions
  1732. * @constructor
  1733. */
  1734. function Base(query, data, defaultOptions, options, responsiveOptions) {
  1735. this.container = Chartist.querySelector(query);
  1736. this.data = data || {};
  1737. this.data.labels = this.data.labels || [];
  1738. this.data.series = this.data.series || [];
  1739. this.defaultOptions = defaultOptions;
  1740. this.options = options;
  1741. this.responsiveOptions = responsiveOptions;
  1742. this.eventEmitter = Chartist.EventEmitter();
  1743. this.supportsForeignObject = Chartist.Svg.isSupported('Extensibility');
  1744. this.supportsAnimations = Chartist.Svg.isSupported('AnimationEventsAttribute');
  1745. this.resizeListener = function resizeListener(){
  1746. this.update();
  1747. }.bind(this);
  1748. if(this.container) {
  1749. // If chartist was already initialized in this container we are detaching all event listeners first
  1750. if(this.container.__chartist__) {
  1751. this.container.__chartist__.detach();
  1752. }
  1753. this.container.__chartist__ = this;
  1754. }
  1755. // Using event loop for first draw to make it possible to register event listeners in the same call stack where
  1756. // the chart was created.
  1757. this.initializeTimeoutId = setTimeout(initialize.bind(this), 0);
  1758. }
  1759. // Creating the chart base class
  1760. Chartist.Base = Chartist.Class.extend({
  1761. constructor: Base,
  1762. optionsProvider: undefined,
  1763. container: undefined,
  1764. svg: undefined,
  1765. eventEmitter: undefined,
  1766. createChart: function() {
  1767. throw new Error('Base chart type can\'t be instantiated!');
  1768. },
  1769. update: update,
  1770. detach: detach,
  1771. on: on,
  1772. off: off,
  1773. version: Chartist.version,
  1774. supportsForeignObject: false
  1775. });
  1776. }(this || global, Chartist));
  1777. ;/**
  1778. * Chartist SVG module for simple SVG DOM abstraction
  1779. *
  1780. * @module Chartist.Svg
  1781. */
  1782. /* global Chartist */
  1783. (function(globalRoot, Chartist) {
  1784. 'use strict';
  1785. var document = globalRoot.document;
  1786. /**
  1787. * Chartist.Svg creates a new SVG object wrapper with a starting element. You can use the wrapper to fluently create sub-elements and modify them.
  1788. *
  1789. * @memberof Chartist.Svg
  1790. * @constructor
  1791. * @param {String|Element} name The name of the SVG element to create or an SVG dom element which should be wrapped into Chartist.Svg
  1792. * @param {Object} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
  1793. * @param {String} className This class or class list will be added to the SVG element
  1794. * @param {Object} parent The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child
  1795. * @param {Boolean} insertFirst If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
  1796. */
  1797. function Svg(name, attributes, className, parent, insertFirst) {
  1798. // If Svg is getting called with an SVG element we just return the wrapper
  1799. if(name instanceof Element) {
  1800. this._node = name;
  1801. } else {
  1802. this._node = document.createElementNS(Chartist.namespaces.svg, name);
  1803. // If this is an SVG element created then custom namespace
  1804. if(name === 'svg') {
  1805. this.attr({
  1806. 'xmlns:ct': Chartist.namespaces.ct
  1807. });
  1808. }
  1809. }
  1810. if(attributes) {
  1811. this.attr(attributes);
  1812. }
  1813. if(className) {
  1814. this.addClass(className);
  1815. }
  1816. if(parent) {
  1817. if (insertFirst && parent._node.firstChild) {
  1818. parent._node.insertBefore(this._node, parent._node.firstChild);
  1819. } else {
  1820. parent._node.appendChild(this._node);
  1821. }
  1822. }
  1823. }
  1824. /**
  1825. * Set attributes on the current SVG element of the wrapper you're currently working on.
  1826. *
  1827. * @memberof Chartist.Svg
  1828. * @param {Object|String} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. If this parameter is a String then the function is used as a getter and will return the attribute value.
  1829. * @param {String} [ns] If specified, the attribute will be obtained using getAttributeNs. In order to write namepsaced attributes you can use the namespace:attribute notation within the attributes object.
  1830. * @return {Object|String} The current wrapper object will be returned so it can be used for chaining or the attribute value if used as getter function.
  1831. */
  1832. function attr(attributes, ns) {
  1833. if(typeof attributes === 'string') {
  1834. if(ns) {
  1835. return this._node.getAttributeNS(ns, attributes);
  1836. } else {
  1837. return this._node.getAttribute(attributes);
  1838. }
  1839. }
  1840. Object.keys(attributes).forEach(function(key) {
  1841. // If the attribute value is undefined we can skip this one
  1842. if(attributes[key] === undefined) {
  1843. return;
  1844. }
  1845. if (key.indexOf(':') !== -1) {
  1846. var namespacedAttribute = key.split(':');
  1847. this._node.setAttributeNS(Chartist.namespaces[namespacedAttribute[0]], key, attributes[key]);
  1848. } else {
  1849. this._node.setAttribute(key, attributes[key]);
  1850. }
  1851. }.bind(this));
  1852. return this;
  1853. }
  1854. /**
  1855. * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily.
  1856. *
  1857. * @memberof Chartist.Svg
  1858. * @param {String} name The name of the SVG element that should be created as child element of the currently selected element wrapper
  1859. * @param {Object} [attributes] An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
  1860. * @param {String} [className] This class or class list will be added to the SVG element
  1861. * @param {Boolean} [insertFirst] If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
  1862. * @return {Chartist.Svg} Returns a Chartist.Svg wrapper object that can be used to modify the containing SVG data
  1863. */
  1864. function elem(name, attributes, className, insertFirst) {
  1865. return new Chartist.Svg(name, attributes, className, this, insertFirst);
  1866. }
  1867. /**
  1868. * Returns the parent Chartist.SVG wrapper object
  1869. *
  1870. * @memberof Chartist.Svg
  1871. * @return {Chartist.Svg} Returns a Chartist.Svg wrapper around the parent node of the current node. If the parent node is not existing or it's not an SVG node then this function will return null.
  1872. */
  1873. function parent() {
  1874. return this._node.parentNode instanceof SVGElement ? new Chartist.Svg(this._node.parentNode) : null;
  1875. }
  1876. /**
  1877. * This method returns a Chartist.Svg wrapper around the root SVG element of the current tree.
  1878. *
  1879. * @memberof Chartist.Svg
  1880. * @return {Chartist.Svg} The root SVG element wrapped in a Chartist.Svg element
  1881. */
  1882. function root() {
  1883. var node = this._node;
  1884. while(node.nodeName !== 'svg') {
  1885. node = node.parentNode;
  1886. }
  1887. return new Chartist.Svg(node);
  1888. }
  1889. /**
  1890. * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Chartist.Svg wrapper.
  1891. *
  1892. * @memberof Chartist.Svg
  1893. * @param {String} selector A CSS selector that is used to query for child SVG elements
  1894. * @return {Chartist.Svg} The SVG wrapper for the element found or null if no element was found
  1895. */
  1896. function querySelector(selector) {
  1897. var foundNode = this._node.querySelector(selector);
  1898. return foundNode ? new Chartist.Svg(foundNode) : null;
  1899. }
  1900. /**
  1901. * Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Chartist.Svg.List wrapper.
  1902. *
  1903. * @memberof Chartist.Svg
  1904. * @param {String} selector A CSS selector that is used to query for child SVG elements
  1905. * @return {Chartist.Svg.List} The SVG wrapper list for the element found or null if no element was found
  1906. */
  1907. function querySelectorAll(selector) {
  1908. var foundNodes = this._node.querySelectorAll(selector);
  1909. return foundNodes.length ? new Chartist.Svg.List(foundNodes) : null;
  1910. }
  1911. /**
  1912. * Returns the underlying SVG node for the current element.
  1913. *
  1914. * @memberof Chartist.Svg
  1915. * @returns {Node}
  1916. */
  1917. function getNode() {
  1918. return this._node;
  1919. }
  1920. /**
  1921. * This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM.
  1922. *
  1923. * @memberof Chartist.Svg
  1924. * @param {Node|String} content The DOM Node, or HTML string that will be converted to a DOM Node, that is then placed into and wrapped by the foreignObject
  1925. * @param {String} [attributes] An object with properties that will be added as attributes to the foreignObject element that is created. Attributes with undefined values will not be added.
  1926. * @param {String} [className] This class or class list will be added to the SVG element
  1927. * @param {Boolean} [insertFirst] Specifies if the foreignObject should be inserted as first child
  1928. * @return {Chartist.Svg} New wrapper object that wraps the foreignObject element
  1929. */
  1930. function foreignObject(content, attributes, className, insertFirst) {
  1931. // If content is string then we convert it to DOM
  1932. // TODO: Handle case where content is not a string nor a DOM Node
  1933. if(typeof content === 'string') {
  1934. var container = document.createElement('div');
  1935. container.innerHTML = content;
  1936. content = container.firstChild;
  1937. }
  1938. // Adding namespace to content element
  1939. content.setAttribute('xmlns', Chartist.namespaces.xmlns);
  1940. // Creating the foreignObject without required extension attribute (as described here
  1941. // http://www.w3.org/TR/SVG/extend.html#ForeignObjectElement)
  1942. var fnObj = this.elem('foreignObject', attributes, className, insertFirst);
  1943. // Add content to foreignObjectElement
  1944. fnObj._node.appendChild(content);
  1945. return fnObj;
  1946. }
  1947. /**
  1948. * This method adds a new text element to the current Chartist.Svg wrapper.
  1949. *
  1950. * @memberof Chartist.Svg
  1951. * @param {String} t The text that should be added to the text element that is created
  1952. * @return {Chartist.Svg} The same wrapper object that was used to add the newly created element
  1953. */
  1954. function text(t) {
  1955. this._node.appendChild(document.createTextNode(t));
  1956. return this;
  1957. }
  1958. /**
  1959. * This method will clear all child nodes of the current wrapper object.
  1960. *
  1961. * @memberof Chartist.Svg
  1962. * @return {Chartist.Svg} The same wrapper object that got emptied
  1963. */
  1964. function empty() {
  1965. while (this._node.firstChild) {
  1966. this._node.removeChild(this._node.firstChild);
  1967. }
  1968. return this;
  1969. }
  1970. /**
  1971. * This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure.
  1972. *
  1973. * @memberof Chartist.Svg
  1974. * @return {Chartist.Svg} The parent wrapper object of the element that got removed
  1975. */
  1976. function remove() {
  1977. this._node.parentNode.removeChild(this._node);
  1978. return this.parent();
  1979. }
  1980. /**
  1981. * This method will replace the element with a new element that can be created outside of the current DOM.
  1982. *
  1983. * @memberof Chartist.Svg
  1984. * @param {Chartist.Svg} newElement The new Chartist.Svg object that will be used to replace the current wrapper object
  1985. * @return {Chartist.Svg} The wrapper of the new element
  1986. */
  1987. function replace(newElement) {
  1988. this._node.parentNode.replaceChild(newElement._node, this._node);
  1989. return newElement;
  1990. }
  1991. /**
  1992. * This method will append an element to the current element as a child.
  1993. *
  1994. * @memberof Chartist.Svg
  1995. * @param {Chartist.Svg} element The Chartist.Svg element that should be added as a child
  1996. * @param {Boolean} [insertFirst] Specifies if the element should be inserted as first child
  1997. * @return {Chartist.Svg} The wrapper of the appended object
  1998. */
  1999. function append(element, insertFirst) {
  2000. if(insertFirst && this._node.firstChild) {
  2001. this._node.insertBefore(element._node, this._node.firstChild);
  2002. } else {
  2003. this._node.appendChild(element._node);
  2004. }
  2005. return this;
  2006. }
  2007. /**
  2008. * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further.
  2009. *
  2010. * @memberof Chartist.Svg
  2011. * @return {Array} A list of classes or an empty array if there are no classes on the current element
  2012. */
  2013. function classes() {
  2014. return this._node.getAttribute('class') ? this._node.getAttribute('class').trim().split(/\s+/) : [];
  2015. }
  2016. /**
  2017. * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once.
  2018. *
  2019. * @memberof Chartist.Svg
  2020. * @param {String} names A white space separated list of class names
  2021. * @return {Chartist.Svg} The wrapper of the current element
  2022. */
  2023. function addClass(names) {
  2024. this._node.setAttribute('class',
  2025. this.classes(this._node)
  2026. .concat(names.trim().split(/\s+/))
  2027. .filter(function(elem, pos, self) {
  2028. return self.indexOf(elem) === pos;
  2029. }).join(' ')
  2030. );
  2031. return this;
  2032. }
  2033. /**
  2034. * Removes one or a space separated list of classes from the current element.
  2035. *
  2036. * @memberof Chartist.Svg
  2037. * @param {String} names A white space separated list of class names
  2038. * @return {Chartist.Svg} The wrapper of the current element
  2039. */
  2040. function removeClass(names) {
  2041. var removedClasses = names.trim().split(/\s+/);
  2042. this._node.setAttribute('class', this.classes(this._node).filter(function(name) {
  2043. return removedClasses.indexOf(name) === -1;
  2044. }).join(' '));
  2045. return this;
  2046. }
  2047. /**
  2048. * Removes all classes from the current element.
  2049. *
  2050. * @memberof Chartist.Svg
  2051. * @return {Chartist.Svg} The wrapper of the current element
  2052. */
  2053. function removeAllClasses() {
  2054. this._node.setAttribute('class', '');
  2055. return this;
  2056. }
  2057. /**
  2058. * Get element height using `getBoundingClientRect`
  2059. *
  2060. * @memberof Chartist.Svg
  2061. * @return {Number} The elements height in pixels
  2062. */
  2063. function height() {
  2064. return this._node.getBoundingClientRect().height;
  2065. }
  2066. /**
  2067. * Get element width using `getBoundingClientRect`
  2068. *
  2069. * @memberof Chartist.Core
  2070. * @return {Number} The elements width in pixels
  2071. */
  2072. function width() {
  2073. return this._node.getBoundingClientRect().width;
  2074. }
  2075. /**
  2076. * The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. Please refer to http://www.w3.org/TR/SVG/animate.html for a detailed specification about the available animation attributes. Additionally an easing property can be passed in the animation definition object. This can be a string with a name of an easing function in `Chartist.Svg.Easing` or an array with four numbers specifying a cubic Bézier curve.
  2077. * **An animations object could look like this:**
  2078. * ```javascript
  2079. * element.animate({
  2080. * opacity: {
  2081. * dur: 1000,
  2082. * from: 0,
  2083. * to: 1
  2084. * },
  2085. * x1: {
  2086. * dur: '1000ms',
  2087. * from: 100,
  2088. * to: 200,
  2089. * easing: 'easeOutQuart'
  2090. * },
  2091. * y1: {
  2092. * dur: '2s',
  2093. * from: 0,
  2094. * to: 100
  2095. * }
  2096. * });
  2097. * ```
  2098. * **Automatic unit conversion**
  2099. * For the `dur` and the `begin` animate attribute you can also omit a unit by passing a number. The number will automatically be converted to milli seconds.
  2100. * **Guided mode**
  2101. * The default behavior of SMIL animations with offset using the `begin` attribute is that the attribute will keep it's original value until the animation starts. Mostly this behavior is not desired as you'd like to have your element attributes already initialized with the animation `from` value even before the animation starts. Also if you don't specify `fill="freeze"` on an animate element or if you delete the animation after it's done (which is done in guided mode) the attribute will switch back to the initial value. This behavior is also not desired when performing simple one-time animations. For one-time animations you'd want to trigger animations immediately instead of relative to the document begin time. That's why in guided mode Chartist.Svg will also use the `begin` property to schedule a timeout and manually start the animation after the timeout. If you're using multiple SMIL definition objects for an attribute (in an array), guided mode will be disabled for this attribute, even if you explicitly enabled it.
  2102. * If guided mode is enabled the following behavior is added:
  2103. * - Before the animation starts (even when delayed with `begin`) the animated attribute will be set already to the `from` value of the animation
  2104. * - `begin` is explicitly set to `indefinite` so it can be started manually without relying on document begin time (creation)
  2105. * - The animate element will be forced to use `fill="freeze"`
  2106. * - The animation will be triggered with `beginElement()` in a timeout where `begin` of the definition object is interpreted in milli seconds. If no `begin` was specified the timeout is triggered immediately.
  2107. * - After the animation the element attribute value will be set to the `to` value of the animation
  2108. * - The animate element is deleted from the DOM
  2109. *
  2110. * @memberof Chartist.Svg
  2111. * @param {Object} animations An animations object where the property keys are the attributes you'd like to animate. The properties should be objects again that contain the SMIL animation attributes (usually begin, dur, from, and to). The property begin and dur is auto converted (see Automatic unit conversion). You can also schedule multiple animations for the same attribute by passing an Array of SMIL definition objects. Attributes that contain an array of SMIL definition objects will not be executed in guided mode.
  2112. * @param {Boolean} guided Specify if guided mode should be activated for this animation (see Guided mode). If not otherwise specified, guided mode will be activated.
  2113. * @param {Object} eventEmitter If specified, this event emitter will be notified when an animation starts or ends.
  2114. * @return {Chartist.Svg} The current element where the animation was added
  2115. */
  2116. function animate(animations, guided, eventEmitter) {
  2117. if(guided === undefined) {
  2118. guided = true;
  2119. }
  2120. Object.keys(animations).forEach(function createAnimateForAttributes(attribute) {
  2121. function createAnimate(animationDefinition, guided) {
  2122. var attributeProperties = {},
  2123. animate,
  2124. timeout,
  2125. easing;
  2126. // Check if an easing is specified in the definition object and delete it from the object as it will not
  2127. // be part of the animate element attributes.
  2128. if(animationDefinition.easing) {
  2129. // If already an easing Bézier curve array we take it or we lookup a easing array in the Easing object
  2130. easing = animationDefinition.easing instanceof Array ?
  2131. animationDefinition.easing :
  2132. Chartist.Svg.Easing[animationDefinition.easing];
  2133. delete animationDefinition.easing;
  2134. }
  2135. // If numeric dur or begin was provided we assume milli seconds
  2136. animationDefinition.begin = Chartist.ensureUnit(animationDefinition.begin, 'ms');
  2137. animationDefinition.dur = Chartist.ensureUnit(animationDefinition.dur, 'ms');
  2138. if(easing) {
  2139. animationDefinition.calcMode = 'spline';
  2140. animationDefinition.keySplines = easing.join(' ');
  2141. animationDefinition.keyTimes = '0;1';
  2142. }
  2143. // Adding "fill: freeze" if we are in guided mode and set initial attribute values
  2144. if(guided) {
  2145. animationDefinition.fill = 'freeze';
  2146. // Animated property on our element should already be set to the animation from value in guided mode
  2147. attributeProperties[attribute] = animationDefinition.from;
  2148. this.attr(attributeProperties);
  2149. // In guided mode we also set begin to indefinite so we can trigger the start manually and put the begin
  2150. // which needs to be in ms aside
  2151. timeout = Chartist.quantity(animationDefinition.begin || 0).value;
  2152. animationDefinition.begin = 'indefinite';
  2153. }
  2154. animate = this.elem('animate', Chartist.extend({
  2155. attributeName: attribute
  2156. }, animationDefinition));
  2157. if(guided) {
  2158. // If guided we take the value that was put aside in timeout and trigger the animation manually with a timeout
  2159. setTimeout(function() {
  2160. // If beginElement fails we set the animated attribute to the end position and remove the animate element
  2161. // This happens if the SMIL ElementTimeControl interface is not supported or any other problems occured in
  2162. // the browser. (Currently FF 34 does not support animate elements in foreignObjects)
  2163. try {
  2164. animate._node.beginElement();
  2165. } catch(err) {
  2166. // Set animated attribute to current animated value
  2167. attributeProperties[attribute] = animationDefinition.to;
  2168. this.attr(attributeProperties);
  2169. // Remove the animate element as it's no longer required
  2170. animate.remove();
  2171. }
  2172. }.bind(this), timeout);
  2173. }
  2174. if(eventEmitter) {
  2175. animate._node.addEventListener('beginEvent', function handleBeginEvent() {
  2176. eventEmitter.emit('animationBegin', {
  2177. element: this,
  2178. animate: animate._node,
  2179. params: animationDefinition
  2180. });
  2181. }.bind(this));
  2182. }
  2183. animate._node.addEventListener('endEvent', function handleEndEvent() {
  2184. if(eventEmitter) {
  2185. eventEmitter.emit('animationEnd', {
  2186. element: this,
  2187. animate: animate._node,
  2188. params: animationDefinition
  2189. });
  2190. }
  2191. if(guided) {
  2192. // Set animated attribute to current animated value
  2193. attributeProperties[attribute] = animationDefinition.to;
  2194. this.attr(attributeProperties);
  2195. // Remove the animate element as it's no longer required
  2196. animate.remove();
  2197. }
  2198. }.bind(this));
  2199. }
  2200. // If current attribute is an array of definition objects we create an animate for each and disable guided mode
  2201. if(animations[attribute] instanceof Array) {
  2202. animations[attribute].forEach(function(animationDefinition) {
  2203. createAnimate.bind(this)(animationDefinition, false);
  2204. }.bind(this));
  2205. } else {
  2206. createAnimate.bind(this)(animations[attribute], guided);
  2207. }
  2208. }.bind(this));
  2209. return this;
  2210. }
  2211. Chartist.Svg = Chartist.Class.extend({
  2212. constructor: Svg,
  2213. attr: attr,
  2214. elem: elem,
  2215. parent: parent,
  2216. root: root,
  2217. querySelector: querySelector,
  2218. querySelectorAll: querySelectorAll,
  2219. getNode: getNode,
  2220. foreignObject: foreignObject,
  2221. text: text,
  2222. empty: empty,
  2223. remove: remove,
  2224. replace: replace,
  2225. append: append,
  2226. classes: classes,
  2227. addClass: addClass,
  2228. removeClass: removeClass,
  2229. removeAllClasses: removeAllClasses,
  2230. height: height,
  2231. width: width,
  2232. animate: animate
  2233. });
  2234. /**
  2235. * This method checks for support of a given SVG feature like Extensibility, SVG-animation or the like. Check http://www.w3.org/TR/SVG11/feature for a detailed list.
  2236. *
  2237. * @memberof Chartist.Svg
  2238. * @param {String} feature The SVG 1.1 feature that should be checked for support.
  2239. * @return {Boolean} True of false if the feature is supported or not
  2240. */
  2241. Chartist.Svg.isSupported = function(feature) {
  2242. return document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#' + feature, '1.1');
  2243. };
  2244. /**
  2245. * This Object contains some standard easing cubic bezier curves. Then can be used with their name in the `Chartist.Svg.animate`. You can also extend the list and use your own name in the `animate` function. Click the show code button to see the available bezier functions.
  2246. *
  2247. * @memberof Chartist.Svg
  2248. */
  2249. var easingCubicBeziers = {
  2250. easeInSine: [0.47, 0, 0.745, 0.715],
  2251. easeOutSine: [0.39, 0.575, 0.565, 1],
  2252. easeInOutSine: [0.445, 0.05, 0.55, 0.95],
  2253. easeInQuad: [0.55, 0.085, 0.68, 0.53],
  2254. easeOutQuad: [0.25, 0.46, 0.45, 0.94],
  2255. easeInOutQuad: [0.455, 0.03, 0.515, 0.955],
  2256. easeInCubic: [0.55, 0.055, 0.675, 0.19],
  2257. easeOutCubic: [0.215, 0.61, 0.355, 1],
  2258. easeInOutCubic: [0.645, 0.045, 0.355, 1],
  2259. easeInQuart: [0.895, 0.03, 0.685, 0.22],
  2260. easeOutQuart: [0.165, 0.84, 0.44, 1],
  2261. easeInOutQuart: [0.77, 0, 0.175, 1],
  2262. easeInQuint: [0.755, 0.05, 0.855, 0.06],
  2263. easeOutQuint: [0.23, 1, 0.32, 1],
  2264. easeInOutQuint: [0.86, 0, 0.07, 1],
  2265. easeInExpo: [0.95, 0.05, 0.795, 0.035],
  2266. easeOutExpo: [0.19, 1, 0.22, 1],
  2267. easeInOutExpo: [1, 0, 0, 1],
  2268. easeInCirc: [0.6, 0.04, 0.98, 0.335],
  2269. easeOutCirc: [0.075, 0.82, 0.165, 1],
  2270. easeInOutCirc: [0.785, 0.135, 0.15, 0.86],
  2271. easeInBack: [0.6, -0.28, 0.735, 0.045],
  2272. easeOutBack: [0.175, 0.885, 0.32, 1.275],
  2273. easeInOutBack: [0.68, -0.55, 0.265, 1.55]
  2274. };
  2275. Chartist.Svg.Easing = easingCubicBeziers;
  2276. /**
  2277. * This helper class is to wrap multiple `Chartist.Svg` elements into a list where you can call the `Chartist.Svg` functions on all elements in the list with one call. This is helpful when you'd like to perform calls with `Chartist.Svg` on multiple elements.
  2278. * An instance of this class is also returned by `Chartist.Svg.querySelectorAll`.
  2279. *
  2280. * @memberof Chartist.Svg
  2281. * @param {Array<Node>|NodeList} nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll)
  2282. * @constructor
  2283. */
  2284. function SvgList(nodeList) {
  2285. var list = this;
  2286. this.svgElements = [];
  2287. for(var i = 0; i < nodeList.length; i++) {
  2288. this.svgElements.push(new Chartist.Svg(nodeList[i]));
  2289. }
  2290. // Add delegation methods for Chartist.Svg
  2291. Object.keys(Chartist.Svg.prototype).filter(function(prototypeProperty) {
  2292. return ['constructor',
  2293. 'parent',
  2294. 'querySelector',
  2295. 'querySelectorAll',
  2296. 'replace',
  2297. 'append',
  2298. 'classes',
  2299. 'height',
  2300. 'width'].indexOf(prototypeProperty) === -1;
  2301. }).forEach(function(prototypeProperty) {
  2302. list[prototypeProperty] = function() {
  2303. var args = Array.prototype.slice.call(arguments, 0);
  2304. list.svgElements.forEach(function(element) {
  2305. Chartist.Svg.prototype[prototypeProperty].apply(element, args);
  2306. });
  2307. return list;
  2308. };
  2309. });
  2310. }
  2311. Chartist.Svg.List = Chartist.Class.extend({
  2312. constructor: SvgList
  2313. });
  2314. }(this || global, Chartist));
  2315. ;/**
  2316. * Chartist SVG path module for SVG path description creation and modification.
  2317. *
  2318. * @module Chartist.Svg.Path
  2319. */
  2320. /* global Chartist */
  2321. (function(globalRoot, Chartist) {
  2322. 'use strict';
  2323. /**
  2324. * Contains the descriptors of supported element types in a SVG path. Currently only move, line and curve are supported.
  2325. *
  2326. * @memberof Chartist.Svg.Path
  2327. * @type {Object}
  2328. */
  2329. var elementDescriptions = {
  2330. m: ['x', 'y'],
  2331. l: ['x', 'y'],
  2332. c: ['x1', 'y1', 'x2', 'y2', 'x', 'y'],
  2333. a: ['rx', 'ry', 'xAr', 'lAf', 'sf', 'x', 'y']
  2334. };
  2335. /**
  2336. * Default options for newly created SVG path objects.
  2337. *
  2338. * @memberof Chartist.Svg.Path
  2339. * @type {Object}
  2340. */
  2341. var defaultOptions = {
  2342. // The accuracy in digit count after the decimal point. This will be used to round numbers in the SVG path. If this option is set to false then no rounding will be performed.
  2343. accuracy: 3
  2344. };
  2345. function element(command, params, pathElements, pos, relative, data) {
  2346. var pathElement = Chartist.extend({
  2347. command: relative ? command.toLowerCase() : command.toUpperCase()
  2348. }, params, data ? { data: data } : {} );
  2349. pathElements.splice(pos, 0, pathElement);
  2350. }
  2351. function forEachParam(pathElements, cb) {
  2352. pathElements.forEach(function(pathElement, pathElementIndex) {
  2353. elementDescriptions[pathElement.command.toLowerCase()].forEach(function(paramName, paramIndex) {
  2354. cb(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
  2355. });
  2356. });
  2357. }
  2358. /**
  2359. * Used to construct a new path object.
  2360. *
  2361. * @memberof Chartist.Svg.Path
  2362. * @param {Boolean} close If set to true then this path will be closed when stringified (with a Z at the end)
  2363. * @param {Object} options Options object that overrides the default objects. See default options for more details.
  2364. * @constructor
  2365. */
  2366. function SvgPath(close, options) {
  2367. this.pathElements = [];
  2368. this.pos = 0;
  2369. this.close = close;
  2370. this.options = Chartist.extend({}, defaultOptions, options);
  2371. }
  2372. /**
  2373. * Gets or sets the current position (cursor) inside of the path. You can move around the cursor freely but limited to 0 or the count of existing elements. All modifications with element functions will insert new elements at the position of this cursor.
  2374. *
  2375. * @memberof Chartist.Svg.Path
  2376. * @param {Number} [pos] If a number is passed then the cursor is set to this position in the path element array.
  2377. * @return {Chartist.Svg.Path|Number} If the position parameter was passed then the return value will be the path object for easy call chaining. If no position parameter was passed then the current position is returned.
  2378. */
  2379. function position(pos) {
  2380. if(pos !== undefined) {
  2381. this.pos = Math.max(0, Math.min(this.pathElements.length, pos));
  2382. return this;
  2383. } else {
  2384. return this.pos;
  2385. }
  2386. }
  2387. /**
  2388. * Removes elements from the path starting at the current position.
  2389. *
  2390. * @memberof Chartist.Svg.Path
  2391. * @param {Number} count Number of path elements that should be removed from the current position.
  2392. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2393. */
  2394. function remove(count) {
  2395. this.pathElements.splice(this.pos, count);
  2396. return this;
  2397. }
  2398. /**
  2399. * Use this function to add a new move SVG path element.
  2400. *
  2401. * @memberof Chartist.Svg.Path
  2402. * @param {Number} x The x coordinate for the move element.
  2403. * @param {Number} y The y coordinate for the move element.
  2404. * @param {Boolean} [relative] If set to true the move element will be created with relative coordinates (lowercase letter)
  2405. * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
  2406. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2407. */
  2408. function move(x, y, relative, data) {
  2409. element('M', {
  2410. x: +x,
  2411. y: +y
  2412. }, this.pathElements, this.pos++, relative, data);
  2413. return this;
  2414. }
  2415. /**
  2416. * Use this function to add a new line SVG path element.
  2417. *
  2418. * @memberof Chartist.Svg.Path
  2419. * @param {Number} x The x coordinate for the line element.
  2420. * @param {Number} y The y coordinate for the line element.
  2421. * @param {Boolean} [relative] If set to true the line element will be created with relative coordinates (lowercase letter)
  2422. * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
  2423. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2424. */
  2425. function line(x, y, relative, data) {
  2426. element('L', {
  2427. x: +x,
  2428. y: +y
  2429. }, this.pathElements, this.pos++, relative, data);
  2430. return this;
  2431. }
  2432. /**
  2433. * Use this function to add a new curve SVG path element.
  2434. *
  2435. * @memberof Chartist.Svg.Path
  2436. * @param {Number} x1 The x coordinate for the first control point of the bezier curve.
  2437. * @param {Number} y1 The y coordinate for the first control point of the bezier curve.
  2438. * @param {Number} x2 The x coordinate for the second control point of the bezier curve.
  2439. * @param {Number} y2 The y coordinate for the second control point of the bezier curve.
  2440. * @param {Number} x The x coordinate for the target point of the curve element.
  2441. * @param {Number} y The y coordinate for the target point of the curve element.
  2442. * @param {Boolean} [relative] If set to true the curve element will be created with relative coordinates (lowercase letter)
  2443. * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
  2444. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2445. */
  2446. function curve(x1, y1, x2, y2, x, y, relative, data) {
  2447. element('C', {
  2448. x1: +x1,
  2449. y1: +y1,
  2450. x2: +x2,
  2451. y2: +y2,
  2452. x: +x,
  2453. y: +y
  2454. }, this.pathElements, this.pos++, relative, data);
  2455. return this;
  2456. }
  2457. /**
  2458. * Use this function to add a new non-bezier curve SVG path element.
  2459. *
  2460. * @memberof Chartist.Svg.Path
  2461. * @param {Number} rx The radius to be used for the x-axis of the arc.
  2462. * @param {Number} ry The radius to be used for the y-axis of the arc.
  2463. * @param {Number} xAr Defines the orientation of the arc
  2464. * @param {Number} lAf Large arc flag
  2465. * @param {Number} sf Sweep flag
  2466. * @param {Number} x The x coordinate for the target point of the curve element.
  2467. * @param {Number} y The y coordinate for the target point of the curve element.
  2468. * @param {Boolean} [relative] If set to true the curve element will be created with relative coordinates (lowercase letter)
  2469. * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
  2470. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2471. */
  2472. function arc(rx, ry, xAr, lAf, sf, x, y, relative, data) {
  2473. element('A', {
  2474. rx: +rx,
  2475. ry: +ry,
  2476. xAr: +xAr,
  2477. lAf: +lAf,
  2478. sf: +sf,
  2479. x: +x,
  2480. y: +y
  2481. }, this.pathElements, this.pos++, relative, data);
  2482. return this;
  2483. }
  2484. /**
  2485. * Parses an SVG path seen in the d attribute of path elements, and inserts the parsed elements into the existing path object at the current cursor position. Any closing path indicators (Z at the end of the path) will be ignored by the parser as this is provided by the close option in the options of the path object.
  2486. *
  2487. * @memberof Chartist.Svg.Path
  2488. * @param {String} path Any SVG path that contains move (m), line (l) or curve (c) components.
  2489. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2490. */
  2491. function parse(path) {
  2492. // Parsing the SVG path string into an array of arrays [['M', '10', '10'], ['L', '100', '100']]
  2493. var chunks = path.replace(/([A-Za-z])([0-9])/g, '$1 $2')
  2494. .replace(/([0-9])([A-Za-z])/g, '$1 $2')
  2495. .split(/[\s,]+/)
  2496. .reduce(function(result, element) {
  2497. if(element.match(/[A-Za-z]/)) {
  2498. result.push([]);
  2499. }
  2500. result[result.length - 1].push(element);
  2501. return result;
  2502. }, []);
  2503. // If this is a closed path we remove the Z at the end because this is determined by the close option
  2504. if(chunks[chunks.length - 1][0].toUpperCase() === 'Z') {
  2505. chunks.pop();
  2506. }
  2507. // Using svgPathElementDescriptions to map raw path arrays into objects that contain the command and the parameters
  2508. // For example {command: 'M', x: '10', y: '10'}
  2509. var elements = chunks.map(function(chunk) {
  2510. var command = chunk.shift(),
  2511. description = elementDescriptions[command.toLowerCase()];
  2512. return Chartist.extend({
  2513. command: command
  2514. }, description.reduce(function(result, paramName, index) {
  2515. result[paramName] = +chunk[index];
  2516. return result;
  2517. }, {}));
  2518. });
  2519. // Preparing a splice call with the elements array as var arg params and insert the parsed elements at the current position
  2520. var spliceArgs = [this.pos, 0];
  2521. Array.prototype.push.apply(spliceArgs, elements);
  2522. Array.prototype.splice.apply(this.pathElements, spliceArgs);
  2523. // Increase the internal position by the element count
  2524. this.pos += elements.length;
  2525. return this;
  2526. }
  2527. /**
  2528. * This function renders to current SVG path object into a final SVG string that can be used in the d attribute of SVG path elements. It uses the accuracy option to round big decimals. If the close parameter was set in the constructor of this path object then a path closing Z will be appended to the output string.
  2529. *
  2530. * @memberof Chartist.Svg.Path
  2531. * @return {String}
  2532. */
  2533. function stringify() {
  2534. var accuracyMultiplier = Math.pow(10, this.options.accuracy);
  2535. return this.pathElements.reduce(function(path, pathElement) {
  2536. var params = elementDescriptions[pathElement.command.toLowerCase()].map(function(paramName) {
  2537. return this.options.accuracy ?
  2538. (Math.round(pathElement[paramName] * accuracyMultiplier) / accuracyMultiplier) :
  2539. pathElement[paramName];
  2540. }.bind(this));
  2541. return path + pathElement.command + params.join(',');
  2542. }.bind(this), '') + (this.close ? 'Z' : '');
  2543. }
  2544. /**
  2545. * Scales all elements in the current SVG path object. There is an individual parameter for each coordinate. Scaling will also be done for control points of curves, affecting the given coordinate.
  2546. *
  2547. * @memberof Chartist.Svg.Path
  2548. * @param {Number} x The number which will be used to scale the x, x1 and x2 of all path elements.
  2549. * @param {Number} y The number which will be used to scale the y, y1 and y2 of all path elements.
  2550. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2551. */
  2552. function scale(x, y) {
  2553. forEachParam(this.pathElements, function(pathElement, paramName) {
  2554. pathElement[paramName] *= paramName[0] === 'x' ? x : y;
  2555. });
  2556. return this;
  2557. }
  2558. /**
  2559. * Translates all elements in the current SVG path object. The translation is relative and there is an individual parameter for each coordinate. Translation will also be done for control points of curves, affecting the given coordinate.
  2560. *
  2561. * @memberof Chartist.Svg.Path
  2562. * @param {Number} x The number which will be used to translate the x, x1 and x2 of all path elements.
  2563. * @param {Number} y The number which will be used to translate the y, y1 and y2 of all path elements.
  2564. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2565. */
  2566. function translate(x, y) {
  2567. forEachParam(this.pathElements, function(pathElement, paramName) {
  2568. pathElement[paramName] += paramName[0] === 'x' ? x : y;
  2569. });
  2570. return this;
  2571. }
  2572. /**
  2573. * This function will run over all existing path elements and then loop over their attributes. The callback function will be called for every path element attribute that exists in the current path.
  2574. * The method signature of the callback function looks like this:
  2575. * ```javascript
  2576. * function(pathElement, paramName, pathElementIndex, paramIndex, pathElements)
  2577. * ```
  2578. * If something else than undefined is returned by the callback function, this value will be used to replace the old value. This allows you to build custom transformations of path objects that can't be achieved using the basic transformation functions scale and translate.
  2579. *
  2580. * @memberof Chartist.Svg.Path
  2581. * @param {Function} transformFnc The callback function for the transformation. Check the signature in the function description.
  2582. * @return {Chartist.Svg.Path} The current path object for easy call chaining.
  2583. */
  2584. function transform(transformFnc) {
  2585. forEachParam(this.pathElements, function(pathElement, paramName, pathElementIndex, paramIndex, pathElements) {
  2586. var transformed = transformFnc(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
  2587. if(transformed || transformed === 0) {
  2588. pathElement[paramName] = transformed;
  2589. }
  2590. });
  2591. return this;
  2592. }
  2593. /**
  2594. * This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned.
  2595. *
  2596. * @memberof Chartist.Svg.Path
  2597. * @param {Boolean} [close] Optional option to set the new cloned path to closed. If not specified or false, the original path close option will be used.
  2598. * @return {Chartist.Svg.Path}
  2599. */
  2600. function clone(close) {
  2601. var c = new Chartist.Svg.Path(close || this.close);
  2602. c.pos = this.pos;
  2603. c.pathElements = this.pathElements.slice().map(function cloneElements(pathElement) {
  2604. return Chartist.extend({}, pathElement);
  2605. });
  2606. c.options = Chartist.extend({}, this.options);
  2607. return c;
  2608. }
  2609. /**
  2610. * Split a Svg.Path object by a specific command in the path chain. The path chain will be split and an array of newly created paths objects will be returned. This is useful if you'd like to split an SVG path by it's move commands, for example, in order to isolate chunks of drawings.
  2611. *
  2612. * @memberof Chartist.Svg.Path
  2613. * @param {String} command The command you'd like to use to split the path
  2614. * @return {Array<Chartist.Svg.Path>}
  2615. */
  2616. function splitByCommand(command) {
  2617. var split = [
  2618. new Chartist.Svg.Path()
  2619. ];
  2620. this.pathElements.forEach(function(pathElement) {
  2621. if(pathElement.command === command.toUpperCase() && split[split.length - 1].pathElements.length !== 0) {
  2622. split.push(new Chartist.Svg.Path());
  2623. }
  2624. split[split.length - 1].pathElements.push(pathElement);
  2625. });
  2626. return split;
  2627. }
  2628. /**
  2629. * This static function on `Chartist.Svg.Path` is joining multiple paths together into one paths.
  2630. *
  2631. * @memberof Chartist.Svg.Path
  2632. * @param {Array<Chartist.Svg.Path>} paths A list of paths to be joined together. The order is important.
  2633. * @param {boolean} close If the newly created path should be a closed path
  2634. * @param {Object} options Path options for the newly created path.
  2635. * @return {Chartist.Svg.Path}
  2636. */
  2637. function join(paths, close, options) {
  2638. var joinedPath = new Chartist.Svg.Path(close, options);
  2639. for(var i = 0; i < paths.length; i++) {
  2640. var path = paths[i];
  2641. for(var j = 0; j < path.pathElements.length; j++) {
  2642. joinedPath.pathElements.push(path.pathElements[j]);
  2643. }
  2644. }
  2645. return joinedPath;
  2646. }
  2647. Chartist.Svg.Path = Chartist.Class.extend({
  2648. constructor: SvgPath,
  2649. position: position,
  2650. remove: remove,
  2651. move: move,
  2652. line: line,
  2653. curve: curve,
  2654. arc: arc,
  2655. scale: scale,
  2656. translate: translate,
  2657. transform: transform,
  2658. parse: parse,
  2659. stringify: stringify,
  2660. clone: clone,
  2661. splitByCommand: splitByCommand
  2662. });
  2663. Chartist.Svg.Path.elementDescriptions = elementDescriptions;
  2664. Chartist.Svg.Path.join = join;
  2665. }(this || global, Chartist));
  2666. ;/* global Chartist */
  2667. (function (globalRoot, Chartist) {
  2668. 'use strict';
  2669. var window = globalRoot.window;
  2670. var document = globalRoot.document;
  2671. var axisUnits = {
  2672. x: {
  2673. pos: 'x',
  2674. len: 'width',
  2675. dir: 'horizontal',
  2676. rectStart: 'x1',
  2677. rectEnd: 'x2',
  2678. rectOffset: 'y2'
  2679. },
  2680. y: {
  2681. pos: 'y',
  2682. len: 'height',
  2683. dir: 'vertical',
  2684. rectStart: 'y2',
  2685. rectEnd: 'y1',
  2686. rectOffset: 'x1'
  2687. }
  2688. };
  2689. function Axis(units, chartRect, ticks, options) {
  2690. this.units = units;
  2691. this.counterUnits = units === axisUnits.x ? axisUnits.y : axisUnits.x;
  2692. this.chartRect = chartRect;
  2693. this.axisLength = chartRect[units.rectEnd] - chartRect[units.rectStart];
  2694. this.gridOffset = chartRect[units.rectOffset];
  2695. this.ticks = ticks;
  2696. this.options = options;
  2697. }
  2698. function createGridAndLabels(gridGroup, labelGroup, useForeignObject, chartOptions, eventEmitter) {
  2699. var axisOptions = chartOptions['axis' + this.units.pos.toUpperCase()];
  2700. var projectedValues = this.ticks.map(this.projectValue.bind(this));
  2701. var labelValues = this.ticks.map(axisOptions.labelInterpolationFnc);
  2702. projectedValues.forEach(function(projectedValue, index) {
  2703. var labelOffset = {
  2704. x: 0,
  2705. y: 0
  2706. };
  2707. // TODO: Find better solution for solving this problem
  2708. // Calculate how much space we have available for the label
  2709. var labelLength;
  2710. if(projectedValues[index + 1]) {
  2711. // If we still have one label ahead, we can calculate the distance to the next tick / label
  2712. labelLength = projectedValues[index + 1] - projectedValue;
  2713. } else {
  2714. // If we don't have a label ahead and we have only two labels in total, we just take the remaining distance to
  2715. // on the whole axis length. We limit that to a minimum of 30 pixel, so that labels close to the border will
  2716. // still be visible inside of the chart padding.
  2717. labelLength = Math.max(this.axisLength - projectedValue, 30);
  2718. }
  2719. // Skip grid lines and labels where interpolated label values are falsey (execpt for 0)
  2720. if(Chartist.isFalseyButZero(labelValues[index]) && labelValues[index] !== '') {
  2721. return;
  2722. }
  2723. // Transform to global coordinates using the chartRect
  2724. // We also need to set the label offset for the createLabel function
  2725. if(this.units.pos === 'x') {
  2726. projectedValue = this.chartRect.x1 + projectedValue;
  2727. labelOffset.x = chartOptions.axisX.labelOffset.x;
  2728. // If the labels should be positioned in start position (top side for vertical axis) we need to set a
  2729. // different offset as for positioned with end (bottom)
  2730. if(chartOptions.axisX.position === 'start') {
  2731. labelOffset.y = this.chartRect.padding.top + chartOptions.axisX.labelOffset.y + (useForeignObject ? 5 : 20);
  2732. } else {
  2733. labelOffset.y = this.chartRect.y1 + chartOptions.axisX.labelOffset.y + (useForeignObject ? 5 : 20);
  2734. }
  2735. } else {
  2736. projectedValue = this.chartRect.y1 - projectedValue;
  2737. labelOffset.y = chartOptions.axisY.labelOffset.y - (useForeignObject ? labelLength : 0);
  2738. // If the labels should be positioned in start position (left side for horizontal axis) we need to set a
  2739. // different offset as for positioned with end (right side)
  2740. if(chartOptions.axisY.position === 'start') {
  2741. labelOffset.x = useForeignObject ? this.chartRect.padding.left + chartOptions.axisY.labelOffset.x : this.chartRect.x1 - 10;
  2742. } else {
  2743. labelOffset.x = this.chartRect.x2 + chartOptions.axisY.labelOffset.x + 10;
  2744. }
  2745. }
  2746. if(axisOptions.showGrid) {
  2747. Chartist.createGrid(projectedValue, index, this, this.gridOffset, this.chartRect[this.counterUnits.len](), gridGroup, [
  2748. chartOptions.classNames.grid,
  2749. chartOptions.classNames[this.units.dir]
  2750. ], eventEmitter);
  2751. }
  2752. if(axisOptions.showLabel) {
  2753. Chartist.createLabel(projectedValue, labelLength, index, labelValues, this, axisOptions.offset, labelOffset, labelGroup, [
  2754. chartOptions.classNames.label,
  2755. chartOptions.classNames[this.units.dir],
  2756. (axisOptions.position === 'start' ? chartOptions.classNames[axisOptions.position] : chartOptions.classNames['end'])
  2757. ], useForeignObject, eventEmitter);
  2758. }
  2759. }.bind(this));
  2760. }
  2761. Chartist.Axis = Chartist.Class.extend({
  2762. constructor: Axis,
  2763. createGridAndLabels: createGridAndLabels,
  2764. projectValue: function(value, index, data) {
  2765. throw new Error('Base axis can\'t be instantiated!');
  2766. }
  2767. });
  2768. Chartist.Axis.units = axisUnits;
  2769. }(this || global, Chartist));
  2770. ;/**
  2771. * The auto scale axis uses standard linear scale projection of values along an axis. It uses order of magnitude to find a scale automatically and evaluates the available space in order to find the perfect amount of ticks for your chart.
  2772. * **Options**
  2773. * The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
  2774. * ```javascript
  2775. * var options = {
  2776. * // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
  2777. * high: 100,
  2778. * // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
  2779. * low: 0,
  2780. * // This option will be used when finding the right scale division settings. The amount of ticks on the scale will be determined so that as many ticks as possible will be displayed, while not violating this minimum required space (in pixel).
  2781. * scaleMinSpace: 20,
  2782. * // Can be set to true or false. If set to true, the scale will be generated with whole numbers only.
  2783. * onlyInteger: true,
  2784. * // The reference value can be used to make sure that this value will always be on the chart. This is especially useful on bipolar charts where the bipolar center always needs to be part of the chart.
  2785. * referenceValue: 5
  2786. * };
  2787. * ```
  2788. *
  2789. * @module Chartist.AutoScaleAxis
  2790. */
  2791. /* global Chartist */
  2792. (function (globalRoot, Chartist) {
  2793. 'use strict';
  2794. var window = globalRoot.window;
  2795. var document = globalRoot.document;
  2796. function AutoScaleAxis(axisUnit, data, chartRect, options) {
  2797. // Usually we calculate highLow based on the data but this can be overriden by a highLow object in the options
  2798. var highLow = options.highLow || Chartist.getHighLow(data, options, axisUnit.pos);
  2799. this.bounds = Chartist.getBounds(chartRect[axisUnit.rectEnd] - chartRect[axisUnit.rectStart], highLow, options.scaleMinSpace || 20, options.onlyInteger);
  2800. this.range = {
  2801. min: this.bounds.min,
  2802. max: this.bounds.max
  2803. };
  2804. Chartist.AutoScaleAxis.super.constructor.call(this,
  2805. axisUnit,
  2806. chartRect,
  2807. this.bounds.values,
  2808. options);
  2809. }
  2810. function projectValue(value) {
  2811. return this.axisLength * (+Chartist.getMultiValue(value, this.units.pos) - this.bounds.min) / this.bounds.range;
  2812. }
  2813. Chartist.AutoScaleAxis = Chartist.Axis.extend({
  2814. constructor: AutoScaleAxis,
  2815. projectValue: projectValue
  2816. });
  2817. }(this || global, Chartist));
  2818. ;/**
  2819. * The fixed scale axis uses standard linear projection of values along an axis. It makes use of a divisor option to divide the range provided from the minimum and maximum value or the options high and low that will override the computed minimum and maximum.
  2820. * **Options**
  2821. * The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
  2822. * ```javascript
  2823. * var options = {
  2824. * // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
  2825. * high: 100,
  2826. * // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
  2827. * low: 0,
  2828. * // If specified then the value range determined from minimum to maximum (or low and high) will be divided by this number and ticks will be generated at those division points. The default divisor is 1.
  2829. * divisor: 4,
  2830. * // If ticks is explicitly set, then the axis will not compute the ticks with the divisor, but directly use the data in ticks to determine at what points on the axis a tick need to be generated.
  2831. * ticks: [1, 10, 20, 30]
  2832. * };
  2833. * ```
  2834. *
  2835. * @module Chartist.FixedScaleAxis
  2836. */
  2837. /* global Chartist */
  2838. (function (globalRoot, Chartist) {
  2839. 'use strict';
  2840. var window = globalRoot.window;
  2841. var document = globalRoot.document;
  2842. function FixedScaleAxis(axisUnit, data, chartRect, options) {
  2843. var highLow = options.highLow || Chartist.getHighLow(data, options, axisUnit.pos);
  2844. this.divisor = options.divisor || 1;
  2845. this.ticks = options.ticks || Chartist.times(this.divisor).map(function(value, index) {
  2846. return highLow.low + (highLow.high - highLow.low) / this.divisor * index;
  2847. }.bind(this));
  2848. this.ticks.sort(function(a, b) {
  2849. return a - b;
  2850. });
  2851. this.range = {
  2852. min: highLow.low,
  2853. max: highLow.high
  2854. };
  2855. Chartist.FixedScaleAxis.super.constructor.call(this,
  2856. axisUnit,
  2857. chartRect,
  2858. this.ticks,
  2859. options);
  2860. this.stepLength = this.axisLength / this.divisor;
  2861. }
  2862. function projectValue(value) {
  2863. return this.axisLength * (+Chartist.getMultiValue(value, this.units.pos) - this.range.min) / (this.range.max - this.range.min);
  2864. }
  2865. Chartist.FixedScaleAxis = Chartist.Axis.extend({
  2866. constructor: FixedScaleAxis,
  2867. projectValue: projectValue
  2868. });
  2869. }(this || global, Chartist));
  2870. ;/**
  2871. * The step axis for step based charts like bar chart or step based line charts. It uses a fixed amount of ticks that will be equally distributed across the whole axis length. The projection is done using the index of the data value rather than the value itself and therefore it's only useful for distribution purpose.
  2872. * **Options**
  2873. * The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
  2874. * ```javascript
  2875. * var options = {
  2876. * // Ticks to be used to distribute across the axis length. As this axis type relies on the index of the value rather than the value, arbitrary data that can be converted to a string can be used as ticks.
  2877. * ticks: ['One', 'Two', 'Three'],
  2878. * // If set to true the full width will be used to distribute the values where the last value will be at the maximum of the axis length. If false the spaces between the ticks will be evenly distributed instead.
  2879. * stretch: true
  2880. * };
  2881. * ```
  2882. *
  2883. * @module Chartist.StepAxis
  2884. */
  2885. /* global Chartist */
  2886. (function (globalRoot, Chartist) {
  2887. 'use strict';
  2888. var window = globalRoot.window;
  2889. var document = globalRoot.document;
  2890. function StepAxis(axisUnit, data, chartRect, options) {
  2891. Chartist.StepAxis.super.constructor.call(this,
  2892. axisUnit,
  2893. chartRect,
  2894. options.ticks,
  2895. options);
  2896. var calc = Math.max(1, options.ticks.length - (options.stretch ? 1 : 0));
  2897. this.stepLength = this.axisLength / calc;
  2898. }
  2899. function projectValue(value, index) {
  2900. return this.stepLength * index;
  2901. }
  2902. Chartist.StepAxis = Chartist.Axis.extend({
  2903. constructor: StepAxis,
  2904. projectValue: projectValue
  2905. });
  2906. }(this || global, Chartist));
  2907. ;/**
  2908. * The Chartist line chart can be used to draw Line or Scatter charts. If used in the browser you can access the global `Chartist` namespace where you find the `Line` function as a main entry point.
  2909. *
  2910. * For examples on how to use the line chart please check the examples of the `Chartist.Line` method.
  2911. *
  2912. * @module Chartist.Line
  2913. */
  2914. /* global Chartist */
  2915. (function(globalRoot, Chartist){
  2916. 'use strict';
  2917. var window = globalRoot.window;
  2918. var document = globalRoot.document;
  2919. /**
  2920. * Default options in line charts. Expand the code view to see a detailed list of options with comments.
  2921. *
  2922. * @memberof Chartist.Line
  2923. */
  2924. var defaultOptions = {
  2925. // Options for X-Axis
  2926. axisX: {
  2927. // The offset of the labels to the chart area
  2928. offset: 30,
  2929. // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
  2930. position: 'end',
  2931. // Allows you to correct label positioning on this axis by positive or negative x and y offset.
  2932. labelOffset: {
  2933. x: 0,
  2934. y: 0
  2935. },
  2936. // If labels should be shown or not
  2937. showLabel: true,
  2938. // If the axis grid should be drawn or not
  2939. showGrid: true,
  2940. // Interpolation function that allows you to intercept the value from the axis label
  2941. labelInterpolationFnc: Chartist.noop,
  2942. // Set the axis type to be used to project values on this axis. If not defined, Chartist.StepAxis will be used for the X-Axis, where the ticks option will be set to the labels in the data and the stretch option will be set to the global fullWidth option. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
  2943. type: undefined
  2944. },
  2945. // Options for Y-Axis
  2946. axisY: {
  2947. // The offset of the labels to the chart area
  2948. offset: 40,
  2949. // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
  2950. position: 'start',
  2951. // Allows you to correct label positioning on this axis by positive or negative x and y offset.
  2952. labelOffset: {
  2953. x: 0,
  2954. y: 0
  2955. },
  2956. // If labels should be shown or not
  2957. showLabel: true,
  2958. // If the axis grid should be drawn or not
  2959. showGrid: true,
  2960. // Interpolation function that allows you to intercept the value from the axis label
  2961. labelInterpolationFnc: Chartist.noop,
  2962. // Set the axis type to be used to project values on this axis. If not defined, Chartist.AutoScaleAxis will be used for the Y-Axis, where the high and low options will be set to the global high and low options. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
  2963. type: undefined,
  2964. // This value specifies the minimum height in pixel of the scale steps
  2965. scaleMinSpace: 20,
  2966. // Use only integer values (whole numbers) for the scale steps
  2967. onlyInteger: false
  2968. },
  2969. // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
  2970. width: undefined,
  2971. // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
  2972. height: undefined,
  2973. // If the line should be drawn or not
  2974. showLine: true,
  2975. // If dots should be drawn or not
  2976. showPoint: true,
  2977. // If the line chart should draw an area
  2978. showArea: false,
  2979. // The base for the area chart that will be used to close the area shape (is normally 0)
  2980. areaBase: 0,
  2981. // Specify if the lines should be smoothed. This value can be true or false where true will result in smoothing using the default smoothing interpolation function Chartist.Interpolation.cardinal and false results in Chartist.Interpolation.none. You can also choose other smoothing / interpolation functions available in the Chartist.Interpolation module, or write your own interpolation function. Check the examples for a brief description.
  2982. lineSmooth: true,
  2983. // If the line chart should add a background fill to the .ct-grids group.
  2984. showGridBackground: false,
  2985. // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
  2986. low: undefined,
  2987. // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
  2988. high: undefined,
  2989. // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
  2990. chartPadding: {
  2991. top: 15,
  2992. right: 15,
  2993. bottom: 5,
  2994. left: 10
  2995. },
  2996. // When set to true, the last grid line on the x-axis is not drawn and the chart elements will expand to the full available width of the chart. For the last label to be drawn correctly you might need to add chart padding or offset the last label with a draw event handler.
  2997. fullWidth: false,
  2998. // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
  2999. reverseData: false,
  3000. // Override the class names that get used to generate the SVG structure of the chart
  3001. classNames: {
  3002. chart: 'ct-chart-line',
  3003. label: 'ct-label',
  3004. labelGroup: 'ct-labels',
  3005. series: 'ct-series',
  3006. line: 'ct-line',
  3007. point: 'ct-point',
  3008. area: 'ct-area',
  3009. grid: 'ct-grid',
  3010. gridGroup: 'ct-grids',
  3011. gridBackground: 'ct-grid-background',
  3012. vertical: 'ct-vertical',
  3013. horizontal: 'ct-horizontal',
  3014. start: 'ct-start',
  3015. end: 'ct-end'
  3016. }
  3017. };
  3018. /**
  3019. * Creates a new chart
  3020. *
  3021. */
  3022. function createChart(options) {
  3023. var data = Chartist.normalizeData(this.data, options.reverseData, true);
  3024. // Create new svg object
  3025. this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);
  3026. // Create groups for labels, grid and series
  3027. var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);
  3028. var seriesGroup = this.svg.elem('g');
  3029. var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);
  3030. var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);
  3031. var axisX, axisY;
  3032. if(options.axisX.type === undefined) {
  3033. axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {
  3034. ticks: data.normalized.labels,
  3035. stretch: options.fullWidth
  3036. }));
  3037. } else {
  3038. axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);
  3039. }
  3040. if(options.axisY.type === undefined) {
  3041. axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {
  3042. high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,
  3043. low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low
  3044. }));
  3045. } else {
  3046. axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);
  3047. }
  3048. axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
  3049. axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
  3050. if (options.showGridBackground) {
  3051. Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);
  3052. }
  3053. // Draw the series
  3054. data.raw.series.forEach(function(series, seriesIndex) {
  3055. var seriesElement = seriesGroup.elem('g');
  3056. // Write attributes to series group element. If series name or meta is undefined the attributes will not be written
  3057. seriesElement.attr({
  3058. 'ct:series-name': series.name,
  3059. 'ct:meta': Chartist.serialize(series.meta)
  3060. });
  3061. // Use series class from series data or if not set generate one
  3062. seriesElement.addClass([
  3063. options.classNames.series,
  3064. (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))
  3065. ].join(' '));
  3066. var pathCoordinates = [],
  3067. pathData = [];
  3068. data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {
  3069. var p = {
  3070. x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),
  3071. y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])
  3072. };
  3073. pathCoordinates.push(p.x, p.y);
  3074. pathData.push({
  3075. value: value,
  3076. valueIndex: valueIndex,
  3077. meta: Chartist.getMetaData(series, valueIndex)
  3078. });
  3079. }.bind(this));
  3080. var seriesOptions = {
  3081. lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),
  3082. showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),
  3083. showLine: Chartist.getSeriesOption(series, options, 'showLine'),
  3084. showArea: Chartist.getSeriesOption(series, options, 'showArea'),
  3085. areaBase: Chartist.getSeriesOption(series, options, 'areaBase')
  3086. };
  3087. var smoothing = typeof seriesOptions.lineSmooth === 'function' ?
  3088. seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());
  3089. // Interpolating path where pathData will be used to annotate each path element so we can trace back the original
  3090. // index, value and meta data
  3091. var path = smoothing(pathCoordinates, pathData);
  3092. // If we should show points we need to create them now to avoid secondary loop
  3093. // Points are drawn from the pathElements returned by the interpolation function
  3094. // Small offset for Firefox to render squares correctly
  3095. if (seriesOptions.showPoint) {
  3096. path.pathElements.forEach(function(pathElement) {
  3097. var point = seriesElement.elem('line', {
  3098. x1: pathElement.x,
  3099. y1: pathElement.y,
  3100. x2: pathElement.x + 0.01,
  3101. y2: pathElement.y
  3102. }, options.classNames.point).attr({
  3103. 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),
  3104. 'ct:meta': Chartist.serialize(pathElement.data.meta)
  3105. });
  3106. this.eventEmitter.emit('draw', {
  3107. type: 'point',
  3108. value: pathElement.data.value,
  3109. index: pathElement.data.valueIndex,
  3110. meta: pathElement.data.meta,
  3111. series: series,
  3112. seriesIndex: seriesIndex,
  3113. axisX: axisX,
  3114. axisY: axisY,
  3115. group: seriesElement,
  3116. element: point,
  3117. x: pathElement.x,
  3118. y: pathElement.y
  3119. });
  3120. }.bind(this));
  3121. }
  3122. if(seriesOptions.showLine) {
  3123. var line = seriesElement.elem('path', {
  3124. d: path.stringify()
  3125. }, options.classNames.line, true);
  3126. this.eventEmitter.emit('draw', {
  3127. type: 'line',
  3128. values: data.normalized.series[seriesIndex],
  3129. path: path.clone(),
  3130. chartRect: chartRect,
  3131. index: seriesIndex,
  3132. series: series,
  3133. seriesIndex: seriesIndex,
  3134. seriesMeta: series.meta,
  3135. axisX: axisX,
  3136. axisY: axisY,
  3137. group: seriesElement,
  3138. element: line
  3139. });
  3140. }
  3141. // Area currently only works with axes that support a range!
  3142. if(seriesOptions.showArea && axisY.range) {
  3143. // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that
  3144. // the area is not drawn outside the chart area.
  3145. var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);
  3146. // We project the areaBase value into screen coordinates
  3147. var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);
  3148. // In order to form the area we'll first split the path by move commands so we can chunk it up into segments
  3149. path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {
  3150. // We filter only "solid" segments that contain more than one point. Otherwise there's no need for an area
  3151. return pathSegment.pathElements.length > 1;
  3152. }).map(function convertToArea(solidPathSegments) {
  3153. // Receiving the filtered solid path segments we can now convert those segments into fill areas
  3154. var firstElement = solidPathSegments.pathElements[0];
  3155. var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];
  3156. // Cloning the solid path segment with closing option and removing the first move command from the clone
  3157. // We then insert a new move that should start at the area base and draw a straight line up or down
  3158. // at the end of the path we add an additional straight line to the projected area base value
  3159. // As the closing option is set our path will be automatically closed
  3160. return solidPathSegments.clone(true)
  3161. .position(0)
  3162. .remove(1)
  3163. .move(firstElement.x, areaBaseProjected)
  3164. .line(firstElement.x, firstElement.y)
  3165. .position(solidPathSegments.pathElements.length + 1)
  3166. .line(lastElement.x, areaBaseProjected);
  3167. }).forEach(function createArea(areaPath) {
  3168. // For each of our newly created area paths, we'll now create path elements by stringifying our path objects
  3169. // and adding the created DOM elements to the correct series group
  3170. var area = seriesElement.elem('path', {
  3171. d: areaPath.stringify()
  3172. }, options.classNames.area, true);
  3173. // Emit an event for each area that was drawn
  3174. this.eventEmitter.emit('draw', {
  3175. type: 'area',
  3176. values: data.normalized.series[seriesIndex],
  3177. path: areaPath.clone(),
  3178. series: series,
  3179. seriesIndex: seriesIndex,
  3180. axisX: axisX,
  3181. axisY: axisY,
  3182. chartRect: chartRect,
  3183. index: seriesIndex,
  3184. group: seriesElement,
  3185. element: area
  3186. });
  3187. }.bind(this));
  3188. }
  3189. }.bind(this));
  3190. this.eventEmitter.emit('created', {
  3191. bounds: axisY.bounds,
  3192. chartRect: chartRect,
  3193. axisX: axisX,
  3194. axisY: axisY,
  3195. svg: this.svg,
  3196. options: options
  3197. });
  3198. }
  3199. /**
  3200. * This method creates a new line chart.
  3201. *
  3202. * @memberof Chartist.Line
  3203. * @param {String|Node} query A selector query string or directly a DOM element
  3204. * @param {Object} data The data object that needs to consist of a labels and a series array
  3205. * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
  3206. * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
  3207. * @return {Object} An object which exposes the API for the created chart
  3208. *
  3209. * @example
  3210. * // Create a simple line chart
  3211. * var data = {
  3212. * // A labels array that can contain any sort of values
  3213. * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  3214. * // Our series array that contains series objects or in this case series data arrays
  3215. * series: [
  3216. * [5, 2, 4, 2, 0]
  3217. * ]
  3218. * };
  3219. *
  3220. * // As options we currently only set a static size of 300x200 px
  3221. * var options = {
  3222. * width: '300px',
  3223. * height: '200px'
  3224. * };
  3225. *
  3226. * // In the global name space Chartist we call the Line function to initialize a line chart. As a first parameter we pass in a selector where we would like to get our chart created. Second parameter is the actual data object and as a third parameter we pass in our options
  3227. * new Chartist.Line('.ct-chart', data, options);
  3228. *
  3229. * @example
  3230. * // Use specific interpolation function with configuration from the Chartist.Interpolation module
  3231. *
  3232. * var chart = new Chartist.Line('.ct-chart', {
  3233. * labels: [1, 2, 3, 4, 5],
  3234. * series: [
  3235. * [1, 1, 8, 1, 7]
  3236. * ]
  3237. * }, {
  3238. * lineSmooth: Chartist.Interpolation.cardinal({
  3239. * tension: 0.2
  3240. * })
  3241. * });
  3242. *
  3243. * @example
  3244. * // Create a line chart with responsive options
  3245. *
  3246. * var data = {
  3247. * // A labels array that can contain any sort of values
  3248. * labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
  3249. * // Our series array that contains series objects or in this case series data arrays
  3250. * series: [
  3251. * [5, 2, 4, 2, 0]
  3252. * ]
  3253. * };
  3254. *
  3255. * // In addition to the regular options we specify responsive option overrides that will override the default configutation based on the matching media queries.
  3256. * var responsiveOptions = [
  3257. * ['screen and (min-width: 641px) and (max-width: 1024px)', {
  3258. * showPoint: false,
  3259. * axisX: {
  3260. * labelInterpolationFnc: function(value) {
  3261. * // Will return Mon, Tue, Wed etc. on medium screens
  3262. * return value.slice(0, 3);
  3263. * }
  3264. * }
  3265. * }],
  3266. * ['screen and (max-width: 640px)', {
  3267. * showLine: false,
  3268. * axisX: {
  3269. * labelInterpolationFnc: function(value) {
  3270. * // Will return M, T, W etc. on small screens
  3271. * return value[0];
  3272. * }
  3273. * }
  3274. * }]
  3275. * ];
  3276. *
  3277. * new Chartist.Line('.ct-chart', data, null, responsiveOptions);
  3278. *
  3279. */
  3280. function Line(query, data, options, responsiveOptions) {
  3281. Chartist.Line.super.constructor.call(this,
  3282. query,
  3283. data,
  3284. defaultOptions,
  3285. Chartist.extend({}, defaultOptions, options),
  3286. responsiveOptions);
  3287. }
  3288. // Creating line chart type in Chartist namespace
  3289. Chartist.Line = Chartist.Base.extend({
  3290. constructor: Line,
  3291. createChart: createChart
  3292. });
  3293. }(this || global, Chartist));
  3294. ;/**
  3295. * The bar chart module of Chartist that can be used to draw unipolar or bipolar bar and grouped bar charts.
  3296. *
  3297. * @module Chartist.Bar
  3298. */
  3299. /* global Chartist */
  3300. (function(globalRoot, Chartist){
  3301. 'use strict';
  3302. var window = globalRoot.window;
  3303. var document = globalRoot.document;
  3304. /**
  3305. * Default options in bar charts. Expand the code view to see a detailed list of options with comments.
  3306. *
  3307. * @memberof Chartist.Bar
  3308. */
  3309. var defaultOptions = {
  3310. // Options for X-Axis
  3311. axisX: {
  3312. // The offset of the chart drawing area to the border of the container
  3313. offset: 30,
  3314. // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
  3315. position: 'end',
  3316. // Allows you to correct label positioning on this axis by positive or negative x and y offset.
  3317. labelOffset: {
  3318. x: 0,
  3319. y: 0
  3320. },
  3321. // If labels should be shown or not
  3322. showLabel: true,
  3323. // If the axis grid should be drawn or not
  3324. showGrid: true,
  3325. // Interpolation function that allows you to intercept the value from the axis label
  3326. labelInterpolationFnc: Chartist.noop,
  3327. // This value specifies the minimum width in pixel of the scale steps
  3328. scaleMinSpace: 30,
  3329. // Use only integer values (whole numbers) for the scale steps
  3330. onlyInteger: false
  3331. },
  3332. // Options for Y-Axis
  3333. axisY: {
  3334. // The offset of the chart drawing area to the border of the container
  3335. offset: 40,
  3336. // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
  3337. position: 'start',
  3338. // Allows you to correct label positioning on this axis by positive or negative x and y offset.
  3339. labelOffset: {
  3340. x: 0,
  3341. y: 0
  3342. },
  3343. // If labels should be shown or not
  3344. showLabel: true,
  3345. // If the axis grid should be drawn or not
  3346. showGrid: true,
  3347. // Interpolation function that allows you to intercept the value from the axis label
  3348. labelInterpolationFnc: Chartist.noop,
  3349. // This value specifies the minimum height in pixel of the scale steps
  3350. scaleMinSpace: 20,
  3351. // Use only integer values (whole numbers) for the scale steps
  3352. onlyInteger: false
  3353. },
  3354. // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
  3355. width: undefined,
  3356. // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
  3357. height: undefined,
  3358. // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
  3359. high: undefined,
  3360. // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
  3361. low: undefined,
  3362. // Unless low/high are explicitly set, bar chart will be centered at zero by default. Set referenceValue to null to auto scale.
  3363. referenceValue: 0,
  3364. // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
  3365. chartPadding: {
  3366. top: 15,
  3367. right: 15,
  3368. bottom: 5,
  3369. left: 10
  3370. },
  3371. // Specify the distance in pixel of bars in a group
  3372. seriesBarDistance: 15,
  3373. // If set to true this property will cause the series bars to be stacked. Check the `stackMode` option for further stacking options.
  3374. stackBars: false,
  3375. // If set to 'overlap' this property will force the stacked bars to draw from the zero line.
  3376. // If set to 'accumulate' this property will form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect.
  3377. stackMode: 'accumulate',
  3378. // Inverts the axes of the bar chart in order to draw a horizontal bar chart. Be aware that you also need to invert your axis settings as the Y Axis will now display the labels and the X Axis the values.
  3379. horizontalBars: false,
  3380. // If set to true then each bar will represent a series and the data array is expected to be a one dimensional array of data values rather than a series array of series. This is useful if the bar chart should represent a profile rather than some data over time.
  3381. distributeSeries: false,
  3382. // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
  3383. reverseData: false,
  3384. // If the bar chart should add a background fill to the .ct-grids group.
  3385. showGridBackground: false,
  3386. // Override the class names that get used to generate the SVG structure of the chart
  3387. classNames: {
  3388. chart: 'ct-chart-bar',
  3389. horizontalBars: 'ct-horizontal-bars',
  3390. label: 'ct-label',
  3391. labelGroup: 'ct-labels',
  3392. series: 'ct-series',
  3393. bar: 'ct-bar',
  3394. grid: 'ct-grid',
  3395. gridGroup: 'ct-grids',
  3396. gridBackground: 'ct-grid-background',
  3397. vertical: 'ct-vertical',
  3398. horizontal: 'ct-horizontal',
  3399. start: 'ct-start',
  3400. end: 'ct-end'
  3401. }
  3402. };
  3403. /**
  3404. * Creates a new chart
  3405. *
  3406. */
  3407. function createChart(options) {
  3408. var data;
  3409. var highLow;
  3410. if(options.distributeSeries) {
  3411. data = Chartist.normalizeData(this.data, options.reverseData, options.horizontalBars ? 'x' : 'y');
  3412. data.normalized.series = data.normalized.series.map(function(value) {
  3413. return [value];
  3414. });
  3415. } else {
  3416. data = Chartist.normalizeData(this.data, options.reverseData, options.horizontalBars ? 'x' : 'y');
  3417. }
  3418. // Create new svg element
  3419. this.svg = Chartist.createSvg(
  3420. this.container,
  3421. options.width,
  3422. options.height,
  3423. options.classNames.chart + (options.horizontalBars ? ' ' + options.classNames.horizontalBars : '')
  3424. );
  3425. // Drawing groups in correct order
  3426. var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);
  3427. var seriesGroup = this.svg.elem('g');
  3428. var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);
  3429. if(options.stackBars && data.normalized.series.length !== 0) {
  3430. // If stacked bars we need to calculate the high low from stacked values from each series
  3431. var serialSums = Chartist.serialMap(data.normalized.series, function serialSums() {
  3432. return Array.prototype.slice.call(arguments).map(function(value) {
  3433. return value;
  3434. }).reduce(function(prev, curr) {
  3435. return {
  3436. x: prev.x + (curr && curr.x) || 0,
  3437. y: prev.y + (curr && curr.y) || 0
  3438. };
  3439. }, {x: 0, y: 0});
  3440. });
  3441. highLow = Chartist.getHighLow([serialSums], options, options.horizontalBars ? 'x' : 'y');
  3442. } else {
  3443. highLow = Chartist.getHighLow(data.normalized.series, options, options.horizontalBars ? 'x' : 'y');
  3444. }
  3445. // Overrides of high / low from settings
  3446. highLow.high = +options.high || (options.high === 0 ? 0 : highLow.high);
  3447. highLow.low = +options.low || (options.low === 0 ? 0 : highLow.low);
  3448. var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);
  3449. var valueAxis,
  3450. labelAxisTicks,
  3451. labelAxis,
  3452. axisX,
  3453. axisY;
  3454. // We need to set step count based on some options combinations
  3455. if(options.distributeSeries && options.stackBars) {
  3456. // If distributed series are enabled and bars need to be stacked, we'll only have one bar and therefore should
  3457. // use only the first label for the step axis
  3458. labelAxisTicks = data.normalized.labels.slice(0, 1);
  3459. } else {
  3460. // If distributed series are enabled but stacked bars aren't, we should use the series labels
  3461. // If we are drawing a regular bar chart with two dimensional series data, we just use the labels array
  3462. // as the bars are normalized
  3463. labelAxisTicks = data.normalized.labels;
  3464. }
  3465. // Set labelAxis and valueAxis based on the horizontalBars setting. This setting will flip the axes if necessary.
  3466. if(options.horizontalBars) {
  3467. if(options.axisX.type === undefined) {
  3468. valueAxis = axisX = new Chartist.AutoScaleAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {
  3469. highLow: highLow,
  3470. referenceValue: 0
  3471. }));
  3472. } else {
  3473. valueAxis = axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {
  3474. highLow: highLow,
  3475. referenceValue: 0
  3476. }));
  3477. }
  3478. if(options.axisY.type === undefined) {
  3479. labelAxis = axisY = new Chartist.StepAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, {
  3480. ticks: labelAxisTicks
  3481. });
  3482. } else {
  3483. labelAxis = axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);
  3484. }
  3485. } else {
  3486. if(options.axisX.type === undefined) {
  3487. labelAxis = axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, {
  3488. ticks: labelAxisTicks
  3489. });
  3490. } else {
  3491. labelAxis = axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);
  3492. }
  3493. if(options.axisY.type === undefined) {
  3494. valueAxis = axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {
  3495. highLow: highLow,
  3496. referenceValue: 0
  3497. }));
  3498. } else {
  3499. valueAxis = axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {
  3500. highLow: highLow,
  3501. referenceValue: 0
  3502. }));
  3503. }
  3504. }
  3505. // Projected 0 point
  3506. var zeroPoint = options.horizontalBars ? (chartRect.x1 + valueAxis.projectValue(0)) : (chartRect.y1 - valueAxis.projectValue(0));
  3507. // Used to track the screen coordinates of stacked bars
  3508. var stackedBarValues = [];
  3509. labelAxis.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
  3510. valueAxis.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
  3511. if (options.showGridBackground) {
  3512. Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);
  3513. }
  3514. // Draw the series
  3515. data.raw.series.forEach(function(series, seriesIndex) {
  3516. // Calculating bi-polar value of index for seriesOffset. For i = 0..4 biPol will be -1.5, -0.5, 0.5, 1.5 etc.
  3517. var biPol = seriesIndex - (data.raw.series.length - 1) / 2;
  3518. // Half of the period width between vertical grid lines used to position bars
  3519. var periodHalfLength;
  3520. // Current series SVG element
  3521. var seriesElement;
  3522. // We need to set periodHalfLength based on some options combinations
  3523. if(options.distributeSeries && !options.stackBars) {
  3524. // If distributed series are enabled but stacked bars aren't, we need to use the length of the normaizedData array
  3525. // which is the series count and divide by 2
  3526. periodHalfLength = labelAxis.axisLength / data.normalized.series.length / 2;
  3527. } else if(options.distributeSeries && options.stackBars) {
  3528. // If distributed series and stacked bars are enabled we'll only get one bar so we should just divide the axis
  3529. // length by 2
  3530. periodHalfLength = labelAxis.axisLength / 2;
  3531. } else {
  3532. // On regular bar charts we should just use the series length
  3533. periodHalfLength = labelAxis.axisLength / data.normalized.series[seriesIndex].length / 2;
  3534. }
  3535. // Adding the series group to the series element
  3536. seriesElement = seriesGroup.elem('g');
  3537. // Write attributes to series group element. If series name or meta is undefined the attributes will not be written
  3538. seriesElement.attr({
  3539. 'ct:series-name': series.name,
  3540. 'ct:meta': Chartist.serialize(series.meta)
  3541. });
  3542. // Use series class from series data or if not set generate one
  3543. seriesElement.addClass([
  3544. options.classNames.series,
  3545. (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))
  3546. ].join(' '));
  3547. data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {
  3548. var projected,
  3549. bar,
  3550. previousStack,
  3551. labelAxisValueIndex;
  3552. // We need to set labelAxisValueIndex based on some options combinations
  3553. if(options.distributeSeries && !options.stackBars) {
  3554. // If distributed series are enabled but stacked bars aren't, we can use the seriesIndex for later projection
  3555. // on the step axis for label positioning
  3556. labelAxisValueIndex = seriesIndex;
  3557. } else if(options.distributeSeries && options.stackBars) {
  3558. // If distributed series and stacked bars are enabled, we will only get one bar and therefore always use
  3559. // 0 for projection on the label step axis
  3560. labelAxisValueIndex = 0;
  3561. } else {
  3562. // On regular bar charts we just use the value index to project on the label step axis
  3563. labelAxisValueIndex = valueIndex;
  3564. }
  3565. // We need to transform coordinates differently based on the chart layout
  3566. if(options.horizontalBars) {
  3567. projected = {
  3568. x: chartRect.x1 + valueAxis.projectValue(value && value.x ? value.x : 0, valueIndex, data.normalized.series[seriesIndex]),
  3569. y: chartRect.y1 - labelAxis.projectValue(value && value.y ? value.y : 0, labelAxisValueIndex, data.normalized.series[seriesIndex])
  3570. };
  3571. } else {
  3572. projected = {
  3573. x: chartRect.x1 + labelAxis.projectValue(value && value.x ? value.x : 0, labelAxisValueIndex, data.normalized.series[seriesIndex]),
  3574. y: chartRect.y1 - valueAxis.projectValue(value && value.y ? value.y : 0, valueIndex, data.normalized.series[seriesIndex])
  3575. }
  3576. }
  3577. // If the label axis is a step based axis we will offset the bar into the middle of between two steps using
  3578. // the periodHalfLength value. Also we do arrange the different series so that they align up to each other using
  3579. // the seriesBarDistance. If we don't have a step axis, the bar positions can be chosen freely so we should not
  3580. // add any automated positioning.
  3581. if(labelAxis instanceof Chartist.StepAxis) {
  3582. // Offset to center bar between grid lines, but only if the step axis is not stretched
  3583. if(!labelAxis.options.stretch) {
  3584. projected[labelAxis.units.pos] += periodHalfLength * (options.horizontalBars ? -1 : 1);
  3585. }
  3586. // Using bi-polar offset for multiple series if no stacked bars or series distribution is used
  3587. projected[labelAxis.units.pos] += (options.stackBars || options.distributeSeries) ? 0 : biPol * options.seriesBarDistance * (options.horizontalBars ? -1 : 1);
  3588. }
  3589. // Enter value in stacked bar values used to remember previous screen value for stacking up bars
  3590. previousStack = stackedBarValues[valueIndex] || zeroPoint;
  3591. stackedBarValues[valueIndex] = previousStack - (zeroPoint - projected[labelAxis.counterUnits.pos]);
  3592. // Skip if value is undefined
  3593. if(value === undefined) {
  3594. return;
  3595. }
  3596. var positions = {};
  3597. positions[labelAxis.units.pos + '1'] = projected[labelAxis.units.pos];
  3598. positions[labelAxis.units.pos + '2'] = projected[labelAxis.units.pos];
  3599. if(options.stackBars && (options.stackMode === 'accumulate' || !options.stackMode)) {
  3600. // Stack mode: accumulate (default)
  3601. // If bars are stacked we use the stackedBarValues reference and otherwise base all bars off the zero line
  3602. // We want backwards compatibility, so the expected fallback without the 'stackMode' option
  3603. // to be the original behaviour (accumulate)
  3604. positions[labelAxis.counterUnits.pos + '1'] = previousStack;
  3605. positions[labelAxis.counterUnits.pos + '2'] = stackedBarValues[valueIndex];
  3606. } else {
  3607. // Draw from the zero line normally
  3608. // This is also the same code for Stack mode: overlap
  3609. positions[labelAxis.counterUnits.pos + '1'] = zeroPoint;
  3610. positions[labelAxis.counterUnits.pos + '2'] = projected[labelAxis.counterUnits.pos];
  3611. }
  3612. // Limit x and y so that they are within the chart rect
  3613. positions.x1 = Math.min(Math.max(positions.x1, chartRect.x1), chartRect.x2);
  3614. positions.x2 = Math.min(Math.max(positions.x2, chartRect.x1), chartRect.x2);
  3615. positions.y1 = Math.min(Math.max(positions.y1, chartRect.y2), chartRect.y1);
  3616. positions.y2 = Math.min(Math.max(positions.y2, chartRect.y2), chartRect.y1);
  3617. var metaData = Chartist.getMetaData(series, valueIndex);
  3618. // Create bar element
  3619. bar = seriesElement.elem('line', positions, options.classNames.bar).attr({
  3620. 'ct:value': [value.x, value.y].filter(Chartist.isNumeric).join(','),
  3621. 'ct:meta': Chartist.serialize(metaData)
  3622. });
  3623. this.eventEmitter.emit('draw', Chartist.extend({
  3624. type: 'bar',
  3625. value: value,
  3626. index: valueIndex,
  3627. meta: metaData,
  3628. series: series,
  3629. seriesIndex: seriesIndex,
  3630. axisX: axisX,
  3631. axisY: axisY,
  3632. chartRect: chartRect,
  3633. group: seriesElement,
  3634. element: bar
  3635. }, positions));
  3636. }.bind(this));
  3637. }.bind(this));
  3638. this.eventEmitter.emit('created', {
  3639. bounds: valueAxis.bounds,
  3640. chartRect: chartRect,
  3641. axisX: axisX,
  3642. axisY: axisY,
  3643. svg: this.svg,
  3644. options: options
  3645. });
  3646. }
  3647. /**
  3648. * This method creates a new bar chart and returns API object that you can use for later changes.
  3649. *
  3650. * @memberof Chartist.Bar
  3651. * @param {String|Node} query A selector query string or directly a DOM element
  3652. * @param {Object} data The data object that needs to consist of a labels and a series array
  3653. * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
  3654. * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
  3655. * @return {Object} An object which exposes the API for the created chart
  3656. *
  3657. * @example
  3658. * // Create a simple bar chart
  3659. * var data = {
  3660. * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  3661. * series: [
  3662. * [5, 2, 4, 2, 0]
  3663. * ]
  3664. * };
  3665. *
  3666. * // In the global name space Chartist we call the Bar function to initialize a bar chart. As a first parameter we pass in a selector where we would like to get our chart created and as a second parameter we pass our data object.
  3667. * new Chartist.Bar('.ct-chart', data);
  3668. *
  3669. * @example
  3670. * // This example creates a bipolar grouped bar chart where the boundaries are limitted to -10 and 10
  3671. * new Chartist.Bar('.ct-chart', {
  3672. * labels: [1, 2, 3, 4, 5, 6, 7],
  3673. * series: [
  3674. * [1, 3, 2, -5, -3, 1, -6],
  3675. * [-5, -2, -4, -1, 2, -3, 1]
  3676. * ]
  3677. * }, {
  3678. * seriesBarDistance: 12,
  3679. * low: -10,
  3680. * high: 10
  3681. * });
  3682. *
  3683. */
  3684. function Bar(query, data, options, responsiveOptions) {
  3685. Chartist.Bar.super.constructor.call(this,
  3686. query,
  3687. data,
  3688. defaultOptions,
  3689. Chartist.extend({}, defaultOptions, options),
  3690. responsiveOptions);
  3691. }
  3692. // Creating bar chart type in Chartist namespace
  3693. Chartist.Bar = Chartist.Base.extend({
  3694. constructor: Bar,
  3695. createChart: createChart
  3696. });
  3697. }(this || global, Chartist));
  3698. ;/**
  3699. * The pie chart module of Chartist that can be used to draw pie, donut or gauge charts
  3700. *
  3701. * @module Chartist.Pie
  3702. */
  3703. /* global Chartist */
  3704. (function(globalRoot, Chartist) {
  3705. 'use strict';
  3706. var window = globalRoot.window;
  3707. var document = globalRoot.document;
  3708. /**
  3709. * Default options in line charts. Expand the code view to see a detailed list of options with comments.
  3710. *
  3711. * @memberof Chartist.Pie
  3712. */
  3713. var defaultOptions = {
  3714. // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
  3715. width: undefined,
  3716. // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
  3717. height: undefined,
  3718. // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
  3719. chartPadding: 5,
  3720. // Override the class names that are used to generate the SVG structure of the chart
  3721. classNames: {
  3722. chartPie: 'ct-chart-pie',
  3723. chartDonut: 'ct-chart-donut',
  3724. series: 'ct-series',
  3725. slicePie: 'ct-slice-pie',
  3726. sliceDonut: 'ct-slice-donut',
  3727. sliceDonutSolid: 'ct-slice-donut-solid',
  3728. label: 'ct-label'
  3729. },
  3730. // The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise.
  3731. startAngle: 0,
  3732. // An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts.
  3733. total: undefined,
  3734. // If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices.
  3735. donut: false,
  3736. // If specified the donut segments will be drawn as shapes instead of strokes.
  3737. donutSolid: false,
  3738. // Specify the donut stroke width, currently done in javascript for convenience. May move to CSS styles in the future.
  3739. // This option can be set as number or string to specify a relative width (i.e. 100 or '30%').
  3740. donutWidth: 60,
  3741. // If a label should be shown or not
  3742. showLabel: true,
  3743. // Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center.
  3744. labelOffset: 0,
  3745. // This option can be set to 'inside', 'outside' or 'center'. Positioned with 'inside' the labels will be placed on half the distance of the radius to the border of the Pie by respecting the 'labelOffset'. The 'outside' option will place the labels at the border of the pie and 'center' will place the labels in the absolute center point of the chart. The 'center' option only makes sense in conjunction with the 'labelOffset' option.
  3746. labelPosition: 'inside',
  3747. // An interpolation function for the label value
  3748. labelInterpolationFnc: Chartist.noop,
  3749. // Label direction can be 'neutral', 'explode' or 'implode'. The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. Usually explode is useful when labels are positioned far away from the center.
  3750. labelDirection: 'neutral',
  3751. // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
  3752. reverseData: false,
  3753. // If true empty values will be ignored to avoid drawing unncessary slices and labels
  3754. ignoreEmptyValues: false
  3755. };
  3756. /**
  3757. * Determines SVG anchor position based on direction and center parameter
  3758. *
  3759. * @param center
  3760. * @param label
  3761. * @param direction
  3762. * @return {string}
  3763. */
  3764. function determineAnchorPosition(center, label, direction) {
  3765. var toTheRight = label.x > center.x;
  3766. if(toTheRight && direction === 'explode' ||
  3767. !toTheRight && direction === 'implode') {
  3768. return 'start';
  3769. } else if(toTheRight && direction === 'implode' ||
  3770. !toTheRight && direction === 'explode') {
  3771. return 'end';
  3772. } else {
  3773. return 'middle';
  3774. }
  3775. }
  3776. /**
  3777. * Creates the pie chart
  3778. *
  3779. * @param options
  3780. */
  3781. function createChart(options) {
  3782. var data = Chartist.normalizeData(this.data);
  3783. var seriesGroups = [],
  3784. labelsGroup,
  3785. chartRect,
  3786. radius,
  3787. labelRadius,
  3788. totalDataSum,
  3789. startAngle = options.startAngle;
  3790. // Create SVG.js draw
  3791. this.svg = Chartist.createSvg(this.container, options.width, options.height,options.donut ? options.classNames.chartDonut : options.classNames.chartPie);
  3792. // Calculate charting rect
  3793. chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);
  3794. // Get biggest circle radius possible within chartRect
  3795. radius = Math.min(chartRect.width() / 2, chartRect.height() / 2);
  3796. // Calculate total of all series to get reference value or use total reference from optional options
  3797. totalDataSum = options.total || data.normalized.series.reduce(function(previousValue, currentValue) {
  3798. return previousValue + currentValue;
  3799. }, 0);
  3800. var donutWidth = Chartist.quantity(options.donutWidth);
  3801. if (donutWidth.unit === '%') {
  3802. donutWidth.value *= radius / 100;
  3803. }
  3804. // If this is a donut chart we need to adjust our radius to enable strokes to be drawn inside
  3805. // Unfortunately this is not possible with the current SVG Spec
  3806. // See this proposal for more details: http://lists.w3.org/Archives/Public/www-svg/2003Oct/0000.html
  3807. radius -= options.donut && !options.donutSolid ? donutWidth.value / 2 : 0;
  3808. // If labelPosition is set to `outside` or a donut chart is drawn then the label position is at the radius,
  3809. // if regular pie chart it's half of the radius
  3810. if(options.labelPosition === 'outside' || options.donut && !options.donutSolid) {
  3811. labelRadius = radius;
  3812. } else if(options.labelPosition === 'center') {
  3813. // If labelPosition is center we start with 0 and will later wait for the labelOffset
  3814. labelRadius = 0;
  3815. } else if(options.donutSolid) {
  3816. labelRadius = radius - donutWidth.value / 2;
  3817. } else {
  3818. // Default option is 'inside' where we use half the radius so the label will be placed in the center of the pie
  3819. // slice
  3820. labelRadius = radius / 2;
  3821. }
  3822. // Add the offset to the labelRadius where a negative offset means closed to the center of the chart
  3823. labelRadius += options.labelOffset;
  3824. // Calculate end angle based on total sum and current data value and offset with padding
  3825. var center = {
  3826. x: chartRect.x1 + chartRect.width() / 2,
  3827. y: chartRect.y2 + chartRect.height() / 2
  3828. };
  3829. // Check if there is only one non-zero value in the series array.
  3830. var hasSingleValInSeries = data.raw.series.filter(function(val) {
  3831. return val.hasOwnProperty('value') ? val.value !== 0 : val !== 0;
  3832. }).length === 1;
  3833. // Creating the series groups
  3834. data.raw.series.forEach(function(series, index) {
  3835. seriesGroups[index] = this.svg.elem('g', null, null);
  3836. }.bind(this));
  3837. //if we need to show labels we create the label group now
  3838. if(options.showLabel) {
  3839. labelsGroup = this.svg.elem('g', null, null);
  3840. }
  3841. // Draw the series
  3842. // initialize series groups
  3843. data.raw.series.forEach(function(series, index) {
  3844. // If current value is zero and we are ignoring empty values then skip to next value
  3845. if (data.normalized.series[index] === 0 && options.ignoreEmptyValues) return;
  3846. // If the series is an object and contains a name or meta data we add a custom attribute
  3847. seriesGroups[index].attr({
  3848. 'ct:series-name': series.name
  3849. });
  3850. // Use series class from series data or if not set generate one
  3851. seriesGroups[index].addClass([
  3852. options.classNames.series,
  3853. (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(index))
  3854. ].join(' '));
  3855. // If the whole dataset is 0 endAngle should be zero. Can't divide by 0.
  3856. var endAngle = (totalDataSum > 0 ? startAngle + data.normalized.series[index] / totalDataSum * 360 : 0);
  3857. // Use slight offset so there are no transparent hairline issues
  3858. var overlappigStartAngle = Math.max(0, startAngle - (index === 0 || hasSingleValInSeries ? 0 : 0.2));
  3859. // If we need to draw the arc for all 360 degrees we need to add a hack where we close the circle
  3860. // with Z and use 359.99 degrees
  3861. if(endAngle - overlappigStartAngle >= 359.99) {
  3862. endAngle = overlappigStartAngle + 359.99;
  3863. }
  3864. var start = Chartist.polarToCartesian(center.x, center.y, radius, overlappigStartAngle),
  3865. end = Chartist.polarToCartesian(center.x, center.y, radius, endAngle);
  3866. var innerStart,
  3867. innerEnd,
  3868. donutSolidRadius;
  3869. // Create a new path element for the pie chart. If this isn't a donut chart we should close the path for a correct stroke
  3870. var path = new Chartist.Svg.Path(!options.donut || options.donutSolid)
  3871. .move(end.x, end.y)
  3872. .arc(radius, radius, 0, endAngle - startAngle > 180, 0, start.x, start.y);
  3873. // If regular pie chart (no donut) we add a line to the center of the circle for completing the pie
  3874. if(!options.donut) {
  3875. path.line(center.x, center.y);
  3876. } else if (options.donutSolid) {
  3877. donutSolidRadius = radius - donutWidth.value;
  3878. innerStart = Chartist.polarToCartesian(center.x, center.y, donutSolidRadius, startAngle - (index === 0 || hasSingleValInSeries ? 0 : 0.2));
  3879. innerEnd = Chartist.polarToCartesian(center.x, center.y, donutSolidRadius, endAngle);
  3880. path.line(innerStart.x, innerStart.y);
  3881. path.arc(donutSolidRadius, donutSolidRadius, 0, endAngle - startAngle > 180, 1, innerEnd.x, innerEnd.y);
  3882. }
  3883. // Create the SVG path
  3884. // If this is a donut chart we add the donut class, otherwise just a regular slice
  3885. var pathClassName = options.classNames.slicePie;
  3886. if (options.donut) {
  3887. pathClassName = options.classNames.sliceDonut;
  3888. if (options.donutSolid) {
  3889. pathClassName = options.classNames.sliceDonutSolid;
  3890. }
  3891. }
  3892. var pathElement = seriesGroups[index].elem('path', {
  3893. d: path.stringify()
  3894. }, pathClassName);
  3895. // Adding the pie series value to the path
  3896. pathElement.attr({
  3897. 'ct:value': data.normalized.series[index],
  3898. 'ct:meta': Chartist.serialize(series.meta)
  3899. });
  3900. // If this is a donut, we add the stroke-width as style attribute
  3901. if(options.donut && !options.donutSolid) {
  3902. pathElement._node.style.strokeWidth = donutWidth.value + 'px';
  3903. }
  3904. // Fire off draw event
  3905. this.eventEmitter.emit('draw', {
  3906. type: 'slice',
  3907. value: data.normalized.series[index],
  3908. totalDataSum: totalDataSum,
  3909. index: index,
  3910. meta: series.meta,
  3911. series: series,
  3912. group: seriesGroups[index],
  3913. element: pathElement,
  3914. path: path.clone(),
  3915. center: center,
  3916. radius: radius,
  3917. startAngle: startAngle,
  3918. endAngle: endAngle
  3919. });
  3920. // If we need to show labels we need to add the label for this slice now
  3921. if(options.showLabel) {
  3922. var labelPosition;
  3923. if(data.raw.series.length === 1) {
  3924. // If we have only 1 series, we can position the label in the center of the pie
  3925. labelPosition = {
  3926. x: center.x,
  3927. y: center.y
  3928. };
  3929. } else {
  3930. // Position at the labelRadius distance from center and between start and end angle
  3931. labelPosition = Chartist.polarToCartesian(
  3932. center.x,
  3933. center.y,
  3934. labelRadius,
  3935. startAngle + (endAngle - startAngle) / 2
  3936. );
  3937. }
  3938. var rawValue;
  3939. if(data.normalized.labels && !Chartist.isFalseyButZero(data.normalized.labels[index])) {
  3940. rawValue = data.normalized.labels[index];
  3941. } else {
  3942. rawValue = data.normalized.series[index];
  3943. }
  3944. var interpolatedValue = options.labelInterpolationFnc(rawValue, index);
  3945. if(interpolatedValue || interpolatedValue === 0) {
  3946. var labelElement = labelsGroup.elem('text', {
  3947. dx: labelPosition.x,
  3948. dy: labelPosition.y,
  3949. 'text-anchor': determineAnchorPosition(center, labelPosition, options.labelDirection)
  3950. }, options.classNames.label).text('' + interpolatedValue);
  3951. // Fire off draw event
  3952. this.eventEmitter.emit('draw', {
  3953. type: 'label',
  3954. index: index,
  3955. group: labelsGroup,
  3956. element: labelElement,
  3957. text: '' + interpolatedValue,
  3958. x: labelPosition.x,
  3959. y: labelPosition.y
  3960. });
  3961. }
  3962. }
  3963. // Set next startAngle to current endAngle.
  3964. // (except for last slice)
  3965. startAngle = endAngle;
  3966. }.bind(this));
  3967. this.eventEmitter.emit('created', {
  3968. chartRect: chartRect,
  3969. svg: this.svg,
  3970. options: options
  3971. });
  3972. }
  3973. /**
  3974. * This method creates a new pie chart and returns an object that can be used to redraw the chart.
  3975. *
  3976. * @memberof Chartist.Pie
  3977. * @param {String|Node} query A selector query string or directly a DOM element
  3978. * @param {Object} data The data object in the pie chart needs to have a series property with a one dimensional data array. The values will be normalized against each other and don't necessarily need to be in percentage. The series property can also be an array of value objects that contain a value property and a className property to override the CSS class name for the series group.
  3979. * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
  3980. * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
  3981. * @return {Object} An object with a version and an update method to manually redraw the chart
  3982. *
  3983. * @example
  3984. * // Simple pie chart example with four series
  3985. * new Chartist.Pie('.ct-chart', {
  3986. * series: [10, 2, 4, 3]
  3987. * });
  3988. *
  3989. * @example
  3990. * // Drawing a donut chart
  3991. * new Chartist.Pie('.ct-chart', {
  3992. * series: [10, 2, 4, 3]
  3993. * }, {
  3994. * donut: true
  3995. * });
  3996. *
  3997. * @example
  3998. * // Using donut, startAngle and total to draw a gauge chart
  3999. * new Chartist.Pie('.ct-chart', {
  4000. * series: [20, 10, 30, 40]
  4001. * }, {
  4002. * donut: true,
  4003. * donutWidth: 20,
  4004. * startAngle: 270,
  4005. * total: 200
  4006. * });
  4007. *
  4008. * @example
  4009. * // Drawing a pie chart with padding and labels that are outside the pie
  4010. * new Chartist.Pie('.ct-chart', {
  4011. * series: [20, 10, 30, 40]
  4012. * }, {
  4013. * chartPadding: 30,
  4014. * labelOffset: 50,
  4015. * labelDirection: 'explode'
  4016. * });
  4017. *
  4018. * @example
  4019. * // Overriding the class names for individual series as well as a name and meta data.
  4020. * // The name will be written as ct:series-name attribute and the meta data will be serialized and written
  4021. * // to a ct:meta attribute.
  4022. * new Chartist.Pie('.ct-chart', {
  4023. * series: [{
  4024. * value: 20,
  4025. * name: 'Series 1',
  4026. * className: 'my-custom-class-one',
  4027. * meta: 'Meta One'
  4028. * }, {
  4029. * value: 10,
  4030. * name: 'Series 2',
  4031. * className: 'my-custom-class-two',
  4032. * meta: 'Meta Two'
  4033. * }, {
  4034. * value: 70,
  4035. * name: 'Series 3',
  4036. * className: 'my-custom-class-three',
  4037. * meta: 'Meta Three'
  4038. * }]
  4039. * });
  4040. */
  4041. function Pie(query, data, options, responsiveOptions) {
  4042. Chartist.Pie.super.constructor.call(this,
  4043. query,
  4044. data,
  4045. defaultOptions,
  4046. Chartist.extend({}, defaultOptions, options),
  4047. responsiveOptions);
  4048. }
  4049. // Creating pie chart type in Chartist namespace
  4050. Chartist.Pie = Chartist.Base.extend({
  4051. constructor: Pie,
  4052. createChart: createChart,
  4053. determineAnchorPosition: determineAnchorPosition
  4054. });
  4055. }(this || global, Chartist));
  4056. return Chartist;
  4057. }));