|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293 |
- function $(expr, con) {
- return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
- }
-
-
-
- $.create = (tag, o) => {
- var element = document.createElement(tag);
-
- for (var i in o) {
- var val = o[i];
-
- if (i === "inside") {
- $(val).appendChild(element);
- }
- else if (i === "around") {
- var ref = $(val);
- ref.parentNode.insertBefore(element, ref);
- element.appendChild(ref);
-
- } else if (i === "styles") {
- if(typeof val === "object") {
- Object.keys(val).map(prop => {
- element.style[prop] = val[prop];
- });
- }
- } else if (i in element ) {
- element[i] = val;
- }
- else {
- element.setAttribute(i, val);
- }
- }
-
- return element;
- };
-
- function getOffset(element) {
- let rect = element.getBoundingClientRect();
- return {
- // https://stackoverflow.com/a/7436602/6495043
- // rect.top varies with scroll, so we add whatever has been
- // scrolled to it to get absolute distance from actual page top
- top: rect.top + (document.documentElement.scrollTop || document.body.scrollTop),
- left: rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft)
- };
- }
-
- function isElementInViewport(el) {
- // Although straightforward: https://stackoverflow.com/a/7557433/6495043
- var rect = el.getBoundingClientRect();
-
- return (
- rect.top >= 0 &&
- rect.left >= 0 &&
- rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
- rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
- );
- }
-
- function getElementContentWidth(element) {
- var styles = window.getComputedStyle(element);
- var padding = parseFloat(styles.paddingLeft) +
- parseFloat(styles.paddingRight);
-
- return element.clientWidth - padding;
- }
-
-
-
-
-
- function fire(target, type, properties) {
- var evt = document.createEvent("HTMLEvents");
-
- evt.initEvent(type, true, true );
-
- for (var j in properties) {
- evt[j] = properties[j];
- }
-
- return target.dispatchEvent(evt);
- }
-
- class SvgTip {
- constructor({
- parent = null,
- colors = []
- }) {
- this.parent = parent;
- this.colors = colors;
- this.titleName = '';
- this.titleValue = '';
- this.listValues = [];
- this.titleValueFirst = 0;
-
- this.x = 0;
- this.y = 0;
-
- this.top = 0;
- this.left = 0;
-
- this.setup();
- }
-
- setup() {
- this.makeTooltip();
- }
-
- refresh() {
- this.fill();
- this.calcPosition();
- // this.showTip();
- }
-
- makeTooltip() {
- this.container = $.create('div', {
- inside: this.parent,
- className: 'graph-svg-tip comparison',
- innerHTML: `<span class="title"></span>
- <ul class="data-point-list"></ul>
- <div class="svg-pointer"></div>`
- });
- this.hideTip();
-
- this.title = this.container.querySelector('.title');
- this.dataPointList = this.container.querySelector('.data-point-list');
-
- this.parent.addEventListener('mouseleave', () => {
- this.hideTip();
- });
- }
-
- fill() {
- let title;
- if(this.index) {
- this.container.setAttribute('data-point-index', this.index);
- }
- if(this.titleValueFirst) {
- title = `<strong>${this.titleValue}</strong>${this.titleName}`;
- } else {
- title = `${this.titleName}<strong>${this.titleValue}</strong>`;
- }
- this.title.innerHTML = title;
- this.dataPointList.innerHTML = '';
-
- this.listValues.map((set, i) => {
- const color = this.colors[i] || 'black';
-
- let li = $.create('li', {
- styles: {
- 'border-top': `3px solid ${color}`
- },
- innerHTML: `<strong style="display: block;">${ set.value === 0 || set.value ? set.value : '' }</strong>
- ${set.title ? set.title : '' }`
- });
-
- this.dataPointList.appendChild(li);
- });
- }
-
- calcPosition() {
- let width = this.container.offsetWidth;
-
- this.top = this.y - this.container.offsetHeight;
- this.left = this.x - width/2;
- let maxLeft = this.parent.offsetWidth - width;
-
- let pointer = this.container.querySelector('.svg-pointer');
-
- if(this.left < 0) {
- pointer.style.left = `calc(50% - ${-1 * this.left}px)`;
- this.left = 0;
- } else if(this.left > maxLeft) {
- let delta = this.left - maxLeft;
- let pointerOffset = `calc(50% + ${delta}px)`;
- pointer.style.left = pointerOffset;
-
- this.left = maxLeft;
- } else {
- pointer.style.left = `50%`;
- }
- }
-
- setValues(x, y, title = {}, listValues = [], index = -1) {
- this.titleName = title.name;
- this.titleValue = title.value;
- this.listValues = listValues;
- this.x = x;
- this.y = y;
- this.titleValueFirst = title.valueFirst || 0;
- this.index = index;
- this.refresh();
- }
-
- hideTip() {
- this.container.style.top = '0px';
- this.container.style.left = '0px';
- this.container.style.opacity = '0';
- }
-
- showTip() {
- this.container.style.top = this.top + 'px';
- this.container.style.left = this.left + 'px';
- this.container.style.opacity = '1';
- }
- }
-
- const VERT_SPACE_OUTSIDE_BASE_CHART = 50;
- const TRANSLATE_Y_BASE_CHART = 20;
- const LEFT_MARGIN_BASE_CHART = 60;
- const RIGHT_MARGIN_BASE_CHART = 40;
- const Y_AXIS_MARGIN = 60;
-
- const INIT_CHART_UPDATE_TIMEOUT = 700;
- const CHART_POST_ANIMATE_TIMEOUT = 400;
-
- const DEFAULT_AXIS_CHART_TYPE = 'line';
- const AXIS_DATASET_CHART_TYPES = ['line', 'bar'];
-
- const BAR_CHART_SPACE_RATIO = 0.5;
- const MIN_BAR_PERCENT_HEIGHT = 0.01;
-
- const LINE_CHART_DOT_SIZE = 4;
- const DOT_OVERLAY_SIZE_INCR = 4;
-
- const DEFAULT_CHAR_WIDTH = 7;
-
- // Universal constants
- const ANGLE_RATIO = Math.PI / 180;
- const FULL_ANGLE = 360;
-
- /**
- * Returns the value of a number upto 2 decimal places.
- * @param {Number} d Any number
- */
- function floatTwo(d) {
- return parseFloat(d.toFixed(2));
- }
-
- /**
- * Returns whether or not two given arrays are equal.
- * @param {Array} arr1 First array
- * @param {Array} arr2 Second array
- */
-
-
- /**
- * Shuffles array in place. ES6 version
- * @param {Array} array An array containing the items.
- */
-
-
- /**
- * Fill an array with extra points
- * @param {Array} array Array
- * @param {Number} count number of filler elements
- * @param {Object} element element to fill with
- * @param {Boolean} start fill at start?
- */
- function fillArray(array, count, element, start=false) {
- if(!element) {
- element = start ? array[0] : array[array.length - 1];
- }
- let fillerArray = new Array(Math.abs(count)).fill(element);
- array = start ? fillerArray.concat(array) : array.concat(fillerArray);
- return array;
- }
-
- /**
- * Returns pixel width of string.
- * @param {String} string
- * @param {Number} charWidth Width of single char in pixels
- */
- function getStringWidth(string, charWidth) {
- return (string+"").length * charWidth;
- }
-
-
-
- function getPositionByAngle(angle, radius) {
- return {
- x:Math.sin(angle * ANGLE_RATIO) * radius,
- y:Math.cos(angle * ANGLE_RATIO) * radius,
- };
- }
-
- function getBarHeightAndYAttr(yTop, zeroLine) {
- let height, y;
- if (yTop <= zeroLine) {
- height = zeroLine - yTop;
- y = yTop;
- } else {
- height = yTop - zeroLine;
- y = zeroLine;
- }
-
- return [height, y];
- }
-
- function equilizeNoOfElements(array1, array2,
- extraCount = array2.length - array1.length) {
-
- // Doesn't work if either has zero elements.
- if(extraCount > 0) {
- array1 = fillArray(array1, extraCount);
- } else {
- array2 = fillArray(array2, extraCount);
- }
- return [array1, array2];
- }
-
- const AXIS_TICK_LENGTH = 6;
- const LABEL_MARGIN = 4;
- const FONT_SIZE = 10;
- const BASE_LINE_COLOR = '#dadada';
-
- function $$1(expr, con) {
- return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
- }
-
- function createSVG(tag, o) {
- var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
-
- for (var i in o) {
- var val = o[i];
-
- if (i === "inside") {
- $$1(val).appendChild(element);
- }
- else if (i === "around") {
- var ref = $$1(val);
- ref.parentNode.insertBefore(element, ref);
- element.appendChild(ref);
-
- } else if (i === "styles") {
- if(typeof val === "object") {
- Object.keys(val).map(prop => {
- element.style[prop] = val[prop];
- });
- }
- } else {
- if(i === "className") { i = "class"; }
- if(i === "innerHTML") {
- element['textContent'] = val;
- } else {
- element.setAttribute(i, val);
- }
- }
- }
-
- return element;
- }
-
- function renderVerticalGradient(svgDefElem, gradientId) {
- return createSVG('linearGradient', {
- inside: svgDefElem,
- id: gradientId,
- x1: 0,
- x2: 0,
- y1: 0,
- y2: 1
- });
- }
-
- function setGradientStop(gradElem, offset, color, opacity) {
- return createSVG('stop', {
- 'inside': gradElem,
- 'style': `stop-color: ${color}`,
- 'offset': offset,
- 'stop-opacity': opacity
- });
- }
-
- function makeSVGContainer(parent, className, width, height) {
- return createSVG('svg', {
- className: className,
- inside: parent,
- width: width,
- height: height
- });
- }
-
- function makeSVGDefs(svgContainer) {
- return createSVG('defs', {
- inside: svgContainer,
- });
- }
-
- function makeSVGGroup(parent, className, transform='') {
- return createSVG('g', {
- className: className,
- inside: parent,
- transform: transform
- });
- }
-
-
-
- function makePath(pathStr, className='', stroke='none', fill='none') {
- return createSVG('path', {
- className: className,
- d: pathStr,
- styles: {
- stroke: stroke,
- fill: fill
- }
- });
- }
-
- function makeArcPathStr(startPosition, endPosition, center, radius, clockWise=1){
- let [arcStartX, arcStartY] = [center.x + startPosition.x, center.y + startPosition.y];
- let [arcEndX, arcEndY] = [center.x + endPosition.x, center.y + endPosition.y];
-
- return `M${center.x} ${center.y}
- L${arcStartX} ${arcStartY}
- A ${radius} ${radius} 0 0 ${clockWise ? 1 : 0}
- ${arcEndX} ${arcEndY} z`;
- }
-
- function makeGradient(svgDefElem, color, lighter = false) {
- let gradientId ='path-fill-gradient' + '-' + color + '-' +(lighter ? 'lighter' : 'default');
- let gradientDef = renderVerticalGradient(svgDefElem, gradientId);
- let opacities = [1, 0.6, 0.2];
- if(lighter) {
- opacities = [0.4, 0.2, 0];
- }
-
- setGradientStop(gradientDef, "0%", color, opacities[0]);
- setGradientStop(gradientDef, "50%", color, opacities[1]);
- setGradientStop(gradientDef, "100%", color, opacities[2]);
-
- return gradientId;
- }
-
- function makeHeatSquare(className, x, y, size, fill='none', data={}) {
- let args = {
- className: className,
- x: x,
- y: y,
- width: size,
- height: size,
- fill: fill
- };
-
- Object.keys(data).map(key => {
- args[key] = data[key];
- });
-
- return createSVG("rect", args);
- }
-
- function makeText(className, x, y, content) {
- return createSVG('text', {
- className: className,
- x: x,
- y: y,
- dy: (FONT_SIZE / 2) + 'px',
- 'font-size': FONT_SIZE + 'px',
- innerHTML: content
- });
- }
-
- function makeVertLine(x, label, y1, y2, options={}) {
- if(!options.stroke) options.stroke = BASE_LINE_COLOR;
- let l = createSVG('line', {
- className: 'line-vertical ' + options.className,
- x1: 0,
- x2: 0,
- y1: y1,
- y2: y2,
- styles: {
- stroke: options.stroke
- }
- });
-
- let text = createSVG('text', {
- x: 0,
- y: y1 > y2 ? y1 + LABEL_MARGIN : y1 - LABEL_MARGIN - FONT_SIZE,
- dy: FONT_SIZE + 'px',
- 'font-size': FONT_SIZE + 'px',
- 'text-anchor': 'middle',
- innerHTML: label + ""
- });
-
- let line = createSVG('g', {
- transform: `translate(${ x }, 0)`
- });
-
- line.appendChild(l);
- line.appendChild(text);
-
- return line;
- }
-
- function makeHoriLine(y, label, x1, x2, options={}) {
- if(!options.stroke) options.stroke = BASE_LINE_COLOR;
- if(!options.lineType) options.lineType = '';
- let className = 'line-horizontal ' + options.className +
- (options.lineType === "dashed" ? "dashed": "");
-
- let l = createSVG('line', {
- className: className,
- x1: x1,
- x2: x2,
- y1: 0,
- y2: 0,
- styles: {
- stroke: options.stroke
- }
- });
-
- let text = createSVG('text', {
- x: x1 < x2 ? x1 - LABEL_MARGIN : x1 + LABEL_MARGIN,
- y: 0,
- dy: (FONT_SIZE / 2 - 2) + 'px',
- 'font-size': FONT_SIZE + 'px',
- 'text-anchor': x1 < x2 ? 'end' : 'start',
- innerHTML: label+""
- });
-
- let line = createSVG('g', {
- transform: `translate(0, ${y})`,
- 'stroke-opacity': 1
- });
-
- if(text === 0 || text === '0') {
- line.style.stroke = "rgba(27, 31, 35, 0.6)";
- }
-
- line.appendChild(l);
- line.appendChild(text);
-
- return line;
- }
-
- function yLine(y, label, width, options={}) {
- if(!options.pos) options.pos = 'left';
- if(!options.offset) options.offset = 0;
- if(!options.mode) options.mode = 'span';
- if(!options.stroke) options.stroke = BASE_LINE_COLOR;
- if(!options.className) options.className = '';
-
- let x1 = -1 * AXIS_TICK_LENGTH;
- let x2 = options.mode === 'span' ? width + AXIS_TICK_LENGTH : 0;
-
- if(options.mode === 'tick' && options.pos === 'right') {
- x1 = width + AXIS_TICK_LENGTH;
- x2 = width;
- }
-
- // let offset = options.pos === 'left' ? -1 * options.offset : options.offset;
-
- x1 += options.offset;
- x2 += options.offset;
-
- return makeHoriLine(y, label, x1, x2, {
- stroke: options.stroke,
- className: options.className,
- lineType: options.lineType
- });
- }
-
- function xLine(x, label, height, options={}) {
- if(!options.pos) options.pos = 'bottom';
- if(!options.offset) options.offset = 0;
- if(!options.mode) options.mode = 'span';
- if(!options.stroke) options.stroke = BASE_LINE_COLOR;
- if(!options.className) options.className = '';
-
- // Draw X axis line in span/tick mode with optional label
- // y2(span)
- // |
- // |
- // x line |
- // |
- // |
- // ---------------------+-- y2(tick)
- // |
- // y1
-
- let y1 = height + AXIS_TICK_LENGTH;
- let y2 = options.mode === 'span' ? -1 * AXIS_TICK_LENGTH : height;
-
- if(options.mode === 'tick' && options.pos === 'top') {
- // top axis ticks
- y1 = -1 * AXIS_TICK_LENGTH;
- y2 = 0;
- }
-
- return makeVertLine(x, label, y1, y2, {
- stroke: options.stroke,
- className: options.className,
- lineType: options.lineType
- });
- }
-
- function yMarker(y, label, width, options={}) {
- let labelSvg = createSVG('text', {
- className: 'chart-label',
- x: width - getStringWidth(label, 5) - LABEL_MARGIN,
- y: 0,
- dy: (FONT_SIZE / -2) + 'px',
- 'font-size': FONT_SIZE + 'px',
- 'text-anchor': 'start',
- innerHTML: label+""
- });
-
- let line = makeHoriLine(y, '', 0, width, {
- stroke: options.stroke || BASE_LINE_COLOR,
- className: options.className || '',
- lineType: options.lineType
- });
-
- line.appendChild(labelSvg);
-
- return line;
- }
-
- function yRegion(y1, y2, width, label) {
- // return a group
- let height = y1 - y2;
-
- let rect = createSVG('rect', {
- className: `bar mini`, // remove class
- styles: {
- fill: `rgba(228, 234, 239, 0.49)`,
- stroke: BASE_LINE_COLOR,
- 'stroke-dasharray': `${width}, ${height}`
- },
- // 'data-point-index': index,
- x: 0,
- y: 0,
- width: width,
- height: height
- });
-
- let labelSvg = createSVG('text', {
- className: 'chart-label',
- x: width - getStringWidth(label+"", 4.5) - LABEL_MARGIN,
- y: 0,
- dy: (FONT_SIZE / -2) + 'px',
- 'font-size': FONT_SIZE + 'px',
- 'text-anchor': 'start',
- innerHTML: label+""
- });
-
- let region = createSVG('g', {
- transform: `translate(0, ${y2})`
- });
-
- region.appendChild(rect);
- region.appendChild(labelSvg);
-
- return region;
- }
-
- function datasetBar(x, yTop, width, color, label='', index=0, offset=0, meta={}) {
- let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
- y -= offset;
-
- let rect = createSVG('rect', {
- className: `bar mini`,
- style: `fill: ${color}`,
- 'data-point-index': index,
- x: x,
- y: y,
- width: width,
- height: height || meta.minHeight // TODO: correct y for positive min height
- });
-
- label += "";
-
- if(!label && !label.length) {
- return rect;
- } else {
- rect.setAttribute('y', 0);
- rect.setAttribute('x', 0);
- let text = createSVG('text', {
- className: 'data-point-value',
- x: width/2,
- y: 0,
- dy: (FONT_SIZE / 2 * -1) + 'px',
- 'font-size': FONT_SIZE + 'px',
- 'text-anchor': 'middle',
- innerHTML: label
- });
-
- let group = createSVG('g', {
- 'data-point-index': index,
- transform: `translate(${x}, ${y})`
- });
- group.appendChild(rect);
- group.appendChild(text);
-
- return group;
- }
- }
-
- function datasetDot(x, y, radius, color, label='', index=0) {
- let dot = createSVG('circle', {
- style: `fill: ${color}`,
- 'data-point-index': index,
- cx: x,
- cy: y,
- r: radius
- });
-
- label += "";
-
- if(!label && !label.length) {
- return dot;
- } else {
- dot.setAttribute('cy', 0);
- dot.setAttribute('cx', 0);
-
- let text = createSVG('text', {
- className: 'data-point-value',
- x: 0,
- y: 0,
- dy: (FONT_SIZE / 2 * -1 - radius) + 'px',
- 'font-size': FONT_SIZE + 'px',
- 'text-anchor': 'middle',
- innerHTML: label
- });
-
- let group = createSVG('g', {
- 'data-point-index': index,
- transform: `translate(${x}, ${y})`
- });
- group.appendChild(dot);
- group.appendChild(text);
-
- return group;
- }
- }
-
- function getPaths(xList, yList, color, options={}, meta={}) {
- let pointsList = yList.map((y, i) => (xList[i] + ',' + y));
- let pointsStr = pointsList.join("L");
- let path = makePath("M"+pointsStr, 'line-graph-path', color);
-
- // HeatLine
- if(options.heatline) {
- let gradient_id = makeGradient(meta.svgDefs, color);
- path.style.stroke = `url(#${gradient_id})`;
- }
-
- let paths = {
- path: path
- };
-
- // Region
- if(options.regionFill) {
- let gradient_id_region = makeGradient(meta.svgDefs, color, true);
-
- // TODO: use zeroLine OR minimum
- let pathStr = "M" + `${xList[0]},${meta.zeroLine}L` + pointsStr + `L${xList.slice(-1)[0]},${meta.zeroLine}`;
- paths.region = makePath(pathStr, `region-fill`, 'none', `url(#${gradient_id_region})`);
- }
-
- return paths;
- }
-
- let makeOverlay = {
- 'bar': (unit) => {
- let transformValue;
- if(unit.nodeName !== 'rect') {
- transformValue = unit.getAttribute('transform');
- unit = unit.childNodes[0];
- }
- let overlay = unit.cloneNode();
- overlay.style.fill = '#000000';
- overlay.style.opacity = '0.4';
-
- if(transformValue) {
- overlay.setAttribute('transform', transformValue);
- }
- return overlay;
- },
-
- 'dot': (unit) => {
- let transformValue;
- if(unit.nodeName !== 'circle') {
- transformValue = unit.getAttribute('transform');
- unit = unit.childNodes[0];
- }
- let overlay = unit.cloneNode();
- let radius = unit.getAttribute('r');
- let fill = unit.getAttribute('fill');
- overlay.setAttribute('r', parseInt(radius) + DOT_OVERLAY_SIZE_INCR);
- overlay.setAttribute('fill', fill);
- overlay.style.opacity = '0.6';
-
- if(transformValue) {
- overlay.setAttribute('transform', transformValue);
- }
- return overlay;
- }
- };
-
- let updateOverlay = {
- 'bar': (unit, overlay) => {
- let transformValue;
- if(unit.nodeName !== 'rect') {
- transformValue = unit.getAttribute('transform');
- unit = unit.childNodes[0];
- }
- let attributes = ['x', 'y', 'width', 'height'];
- Object.values(unit.attributes)
- .filter(attr => attributes.includes(attr.name) && attr.specified)
- .map(attr => {
- overlay.setAttribute(attr.name, attr.nodeValue);
- });
-
- if(transformValue) {
- overlay.setAttribute('transform', transformValue);
- }
- },
-
- 'dot': (unit, overlay) => {
- let transformValue;
- if(unit.nodeName !== 'circle') {
- transformValue = unit.getAttribute('transform');
- unit = unit.childNodes[0];
- }
- let attributes = ['cx', 'cy'];
- Object.values(unit.attributes)
- .filter(attr => attributes.includes(attr.name) && attr.specified)
- .map(attr => {
- overlay.setAttribute(attr.name, attr.nodeValue);
- });
-
- if(transformValue) {
- overlay.setAttribute('transform', transformValue);
- }
- }
- };
-
- const PRESET_COLOR_MAP = {
- 'light-blue': '#7cd6fd',
- 'blue': '#5e64ff',
- 'violet': '#743ee2',
- 'red': '#ff5858',
- 'orange': '#ffa00a',
- 'yellow': '#feef72',
- 'green': '#28a745',
- 'light-green': '#98d85b',
- 'purple': '#b554ff',
- 'magenta': '#ffa3ef',
- 'black': '#36114C',
- 'grey': '#bdd3e6',
- 'light-grey': '#f0f4f7',
- 'dark-grey': '#b8c2cc'
- };
-
- const DEFAULT_COLORS = ['light-blue', 'blue', 'violet', 'red', 'orange',
- 'yellow', 'green', 'light-green', 'purple', 'magenta', 'light-grey', 'dark-grey'];
-
- function limitColor(r){
- if (r > 255) return 255;
- else if (r < 0) return 0;
- return r;
- }
-
- function lightenDarkenColor(color, amt) {
- let col = getColor(color);
- let usePound = false;
- if (col[0] == "#") {
- col = col.slice(1);
- usePound = true;
- }
- let num = parseInt(col,16);
- let r = limitColor((num >> 16) + amt);
- let b = limitColor(((num >> 8) & 0x00FF) + amt);
- let g = limitColor((num & 0x0000FF) + amt);
- return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
- }
-
- function isValidColor(string) {
- // https://stackoverflow.com/a/8027444/6495043
- return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(string);
- }
-
- const getColor = (color) => {
- return PRESET_COLOR_MAP[color] || color;
- };
-
- const ALL_CHART_TYPES = ['line', 'scatter', 'bar', 'percentage', 'heatmap', 'pie'];
-
- const COMPATIBLE_CHARTS = {
- bar: ['line', 'scatter', 'percentage', 'pie'],
- line: ['scatter', 'bar', 'percentage', 'pie'],
- pie: ['line', 'scatter', 'percentage', 'bar'],
- scatter: ['line', 'bar', 'percentage', 'pie'],
- percentage: ['bar', 'line', 'scatter', 'pie'],
- heatmap: []
- };
-
- // Needs structure as per only labels/datasets
- const COLOR_COMPATIBLE_CHARTS = {
- bar: ['line', 'scatter'],
- line: ['scatter', 'bar'],
- pie: ['percentage'],
- scatter: ['line', 'bar'],
- percentage: ['pie'],
- heatmap: []
- };
-
- function getDifferentChart(type, current_type, parent, args) {
- if(type === current_type) return;
-
- if(!ALL_CHART_TYPES.includes(type)) {
- console.error(`'${type}' is not a valid chart type.`);
- }
-
- if(!COMPATIBLE_CHARTS[current_type].includes(type)) {
- console.error(`'${current_type}' chart cannot be converted to a '${type}' chart.`);
- }
-
- // whether the new chart can use the existing colors
- const useColor = COLOR_COMPATIBLE_CHARTS[current_type].includes(type);
-
- // Okay, this is anticlimactic
- // this function will need to actually be 'changeChartType(type)'
- // that will update only the required elements, but for now ...
-
- args.type = type;
- args.colors = useColor ? args.colors : undefined;
-
- return new Chart(parent, args);
- }
-
- const UNIT_ANIM_DUR = 350;
- const PATH_ANIM_DUR = 350;
- const MARKER_LINE_ANIM_DUR = UNIT_ANIM_DUR;
- const REPLACE_ALL_NEW_DUR = 250;
-
- const STD_EASING = 'easein';
-
- function translate(unit, oldCoord, newCoord, duration) {
- let old = typeof oldCoord === 'string' ? oldCoord : oldCoord.join(', ');
- return [
- unit,
- {transform: newCoord.join(', ')},
- duration,
- STD_EASING,
- "translate",
- {transform: old}
- ];
- }
-
- function translateVertLine(xLine, newX, oldX) {
- return translate(xLine, [oldX, 0], [newX, 0], MARKER_LINE_ANIM_DUR);
- }
-
- function translateHoriLine(yLine, newY, oldY) {
- return translate(yLine, [0, oldY], [0, newY], MARKER_LINE_ANIM_DUR);
- }
-
- function animateRegion(rectGroup, newY1, newY2, oldY2) {
- let newHeight = newY1 - newY2;
- let rect = rectGroup.childNodes[0];
- let width = rect.getAttribute("width");
- let rectAnim = [
- rect,
- { height: newHeight, 'stroke-dasharray': `${width}, ${newHeight}` },
- MARKER_LINE_ANIM_DUR,
- STD_EASING
- ];
-
- let groupAnim = translate(rectGroup, [0, oldY2], [0, newY2], MARKER_LINE_ANIM_DUR);
- return [rectAnim, groupAnim];
- }
-
- function animateBar(bar, x, yTop, width, offset=0, meta={}) {
- let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
- y -= offset;
- if(bar.nodeName !== 'rect') {
- let rect = bar.childNodes[0];
- let rectAnim = [
- rect,
- {width: width, height: height},
- UNIT_ANIM_DUR,
- STD_EASING
- ];
-
- let oldCoordStr = bar.getAttribute("transform").split("(")[1].slice(0, -1);
- let groupAnim = translate(bar, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
- return [rectAnim, groupAnim];
- } else {
- return [[bar, {width: width, height: height, x: x, y: y}, UNIT_ANIM_DUR, STD_EASING]];
- }
- // bar.animate({height: args.newHeight, y: yTop}, UNIT_ANIM_DUR, mina.easein);
- }
-
- function animateDot(dot, x, y) {
- if(dot.nodeName !== 'circle') {
- let oldCoordStr = dot.getAttribute("transform").split("(")[1].slice(0, -1);
- let groupAnim = translate(dot, oldCoordStr, [x, y], MARKER_LINE_ANIM_DUR);
- return [groupAnim];
- } else {
- return [[dot, {cx: x, cy: y}, UNIT_ANIM_DUR, STD_EASING]];
- }
- // dot.animate({cy: yTop}, UNIT_ANIM_DUR, mina.easein);
- }
-
- function animatePath(paths, newXList, newYList, zeroLine) {
- let pathComponents = [];
-
- let pointsStr = newYList.map((y, i) => (newXList[i] + ',' + y));
- let pathStr = pointsStr.join("L");
-
- const animPath = [paths.path, {d:"M"+pathStr}, PATH_ANIM_DUR, STD_EASING];
- pathComponents.push(animPath);
-
- if(paths.region) {
- let regStartPt = `${newXList[0]},${zeroLine}L`;
- let regEndPt = `L${newXList.slice(-1)[0]}, ${zeroLine}`;
-
- const animRegion = [
- paths.region,
- {d:"M" + regStartPt + pathStr + regEndPt},
- PATH_ANIM_DUR,
- STD_EASING
- ];
- pathComponents.push(animRegion);
- }
-
- return pathComponents;
- }
-
- function animatePathStr(oldPath, pathStr) {
- return [oldPath, {d: pathStr}, UNIT_ANIM_DUR, STD_EASING];
- }
-
- // Leveraging SMIL Animations
-
- const EASING = {
- ease: "0.25 0.1 0.25 1",
- linear: "0 0 1 1",
- // easein: "0.42 0 1 1",
- easein: "0.1 0.8 0.2 1",
- easeout: "0 0 0.58 1",
- easeinout: "0.42 0 0.58 1"
- };
-
- function animateSVGElement(element, props, dur, easingType="linear", type=undefined, oldValues={}) {
-
- let animElement = element.cloneNode(true);
- let newElement = element.cloneNode(true);
-
- for(var attributeName in props) {
- let animateElement;
- if(attributeName === 'transform') {
- animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
- } else {
- animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
- }
- let currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
- let value = props[attributeName];
-
- let animAttr = {
- attributeName: attributeName,
- from: currentValue,
- to: value,
- begin: "0s",
- dur: dur/1000 + "s",
- values: currentValue + ";" + value,
- keySplines: EASING[easingType],
- keyTimes: "0;1",
- calcMode: "spline",
- fill: 'freeze'
- };
-
- if(type) {
- animAttr["type"] = type;
- }
-
- for (var i in animAttr) {
- animateElement.setAttribute(i, animAttr[i]);
- }
-
- animElement.appendChild(animateElement);
-
- if(type) {
- newElement.setAttribute(attributeName, `translate(${value})`);
- } else {
- newElement.setAttribute(attributeName, value);
- }
- }
-
- return [animElement, newElement];
- }
-
- function transform(element, style) { // eslint-disable-line no-unused-vars
- element.style.transform = style;
- element.style.webkitTransform = style;
- element.style.msTransform = style;
- element.style.mozTransform = style;
- element.style.oTransform = style;
- }
-
- function animateSVG(svgContainer, elements) {
- let newElements = [];
- let animElements = [];
-
- elements.map(element => {
- let unit = element[0];
- let parent = unit.parentNode;
-
- let animElement, newElement;
-
- element[0] = unit;
- [animElement, newElement] = animateSVGElement(...element);
-
- newElements.push(newElement);
- animElements.push([animElement, parent]);
-
- parent.replaceChild(animElement, unit);
- });
-
- let animSvg = svgContainer.cloneNode(true);
-
- animElements.map((animElement, i) => {
- animElement[1].replaceChild(newElements[i], animElement[0]);
- elements[i][0] = newElements[i];
- });
-
- return animSvg;
- }
-
- function runSMILAnimation(parent, svgElement, elementsToAnimate) {
- if(elementsToAnimate.length === 0) return;
-
- let animSvgElement = animateSVG(svgElement, elementsToAnimate);
- if(svgElement.parentNode == parent) {
- parent.removeChild(svgElement);
- parent.appendChild(animSvgElement);
-
- }
-
- // Replace the new svgElement (data has already been replaced)
- setTimeout(() => {
- if(animSvgElement.parentNode == parent) {
- parent.removeChild(animSvgElement);
- parent.appendChild(svgElement);
- }
- }, REPLACE_ALL_NEW_DUR);
- }
-
- class BaseChart {
- constructor(parent, options) {
- this.rawChartArgs = options;
-
- this.parent = typeof parent === 'string' ? document.querySelector(parent) : parent;
- if (!(this.parent instanceof HTMLElement)) {
- throw new Error('No `parent` element to render on was provided.');
- }
-
- this.title = options.title || '';
- this.subtitle = options.subtitle || '';
- this.argHeight = options.height || 240;
- this.type = options.type || '';
-
- this.realData = this.prepareData(options.data);
- this.data = this.prepareFirstData(this.realData);
- this.colors = [];
- this.config = {
- showTooltip: 1, // calculate
- showLegend: options.showLegend || 1,
- isNavigable: options.isNavigable || 0,
- animate: 1
- };
- this.state = {};
- this.options = {};
-
- this.initTimeout = INIT_CHART_UPDATE_TIMEOUT;
-
- if(this.config.isNavigable) {
- this.overlays = [];
- }
-
- this.configure(options);
- }
-
- configure(args) {
- this.setColors(args);
- this.setMargins();
-
- // Bind window events
- window.addEventListener('resize', () => this.draw(true));
- window.addEventListener('orientationchange', () => this.draw(true));
- }
-
- setColors() {
- let args = this.rawChartArgs;
-
- // Needs structure as per only labels/datasets, from config
- const list = args.type === 'percentage' || args.type === 'pie'
- ? args.data.labels
- : args.data.datasets;
-
- if(!args.colors || (list && args.colors.length < list.length)) {
- this.colors = DEFAULT_COLORS;
- } else {
- this.colors = args.colors;
- }
-
- this.colors = this.colors.map(color => getColor(color));
- }
-
- setMargins() {
- let height = this.argHeight;
- this.baseHeight = height;
- this.height = height - VERT_SPACE_OUTSIDE_BASE_CHART;
- this.translateY = TRANSLATE_Y_BASE_CHART;
-
- // Horizontal margins
- this.leftMargin = LEFT_MARGIN_BASE_CHART;
- this.rightMargin = RIGHT_MARGIN_BASE_CHART;
- }
-
- validate() {
- return true;
- }
-
- setup() {
- if(this.validate()) {
- this._setup();
- }
- }
-
- _setup() {
- this.makeContainer();
- this.makeTooltip();
-
- this.draw(false, true);
- }
-
- setupComponents() {
- this.components = new Map();
- }
-
- makeContainer() {
- this.container = $.create('div', {
- className: 'chart-container',
- innerHTML: `<h6 class="title">${this.title}</h6>
- <h6 class="sub-title uppercase">${this.subtitle}</h6>
- <div class="frappe-chart graphics"></div>
- <div class="graph-stats-container"></div>`
- });
-
- // Chart needs a dedicated parent element
- this.parent.innerHTML = '';
- this.parent.appendChild(this.container);
-
- this.chartWrapper = this.container.querySelector('.frappe-chart');
- this.statsWrapper = this.container.querySelector('.graph-stats-container');
- }
-
- makeTooltip() {
- this.tip = new SvgTip({
- parent: this.chartWrapper,
- colors: this.colors
- });
- this.bindTooltip();
- }
-
- bindTooltip() {}
-
- draw(onlyWidthChange=false, init=false) {
- this.calcWidth();
- this.calc(onlyWidthChange);
- this.makeChartArea();
- this.setupComponents();
-
- this.components.forEach(c => c.setup(this.drawArea));
- // this.components.forEach(c => c.make());
- this.render(this.components, false);
-
- if(init) {
- this.data = this.realData;
- setTimeout(() => {this.update();}, this.initTimeout);
- }
-
- if(!onlyWidthChange) {
- this.renderLegend();
- }
-
- this.setupNavigation(init);
- }
-
- calcWidth() {
- this.baseWidth = getElementContentWidth(this.parent);
- this.width = this.baseWidth - (this.leftMargin + this.rightMargin);
- }
-
- update(data=this.data) {
- this.data = this.prepareData(data);
- this.calc(); // builds state
- this.render();
- }
-
- prepareData(data=this.data) {
- return data;
- }
-
- prepareFirstData(data=this.data) {
- return data;
- }
-
- calc() {} // builds state
-
- render(components=this.components, animate=true) {
- if(this.config.isNavigable) {
- // Remove all existing overlays
- this.overlays.map(o => o.parentNode.removeChild(o));
- // ref.parentNode.insertBefore(element, ref);
- }
- let elementsToAnimate = [];
- // Can decouple to this.refreshComponents() first to save animation timeout
- components.forEach(c => {
- elementsToAnimate = elementsToAnimate.concat(c.update(animate));
- });
- if(elementsToAnimate.length > 0) {
- runSMILAnimation(this.chartWrapper, this.svg, elementsToAnimate);
- setTimeout(() => {
- components.forEach(c => c.make());
- this.updateNav();
- }, CHART_POST_ANIMATE_TIMEOUT);
- } else {
- components.forEach(c => c.make());
- this.updateNav();
- }
- }
-
- updateNav() {
- if(this.config.isNavigable) {
- // if(!this.overlayGuides){
- this.makeOverlay();
- this.bindUnits();
- // } else {
- // this.updateOverlay();
- // }
- }
- }
-
- makeChartArea() {
- if(this.svg) {
- this.chartWrapper.removeChild(this.svg);
- }
- this.svg = makeSVGContainer(
- this.chartWrapper,
- 'chart',
- this.baseWidth,
- this.baseHeight
- );
- this.svgDefs = makeSVGDefs(this.svg);
-
- // I WISH !!!
- // this.svg = makeSVGGroup(
- // svgContainer,
- // 'flipped-coord-system',
- // `translate(0, ${this.baseHeight}) scale(1, -1)`
- // );
-
- this.drawArea = makeSVGGroup(
- this.svg,
- this.type + '-chart',
- `translate(${this.leftMargin}, ${this.translateY})`
- );
- }
-
- renderLegend() {}
-
- setupNavigation(init=false) {
- if(!this.config.isNavigable) return;
-
- if(init) {
- this.bindOverlay();
-
- this.keyActions = {
- '13': this.onEnterKey.bind(this),
- '37': this.onLeftArrow.bind(this),
- '38': this.onUpArrow.bind(this),
- '39': this.onRightArrow.bind(this),
- '40': this.onDownArrow.bind(this),
- };
-
- document.addEventListener('keydown', (e) => {
- if(isElementInViewport(this.chartWrapper)) {
- e = e || window.event;
- if(this.keyActions[e.keyCode]) {
- this.keyActions[e.keyCode]();
- }
- }
- });
- }
- }
-
- makeOverlay() {}
- updateOverlay() {}
- bindOverlay() {}
- bindUnits() {}
-
- onLeftArrow() {}
- onRightArrow() {}
- onUpArrow() {}
- onDownArrow() {}
- onEnterKey() {}
-
- addDataPoint() {}
- removeDataPoint() {}
-
- getDataPoint() {}
- setCurrentDataPoint() {}
-
- updateDataset() {}
-
- getDifferentChart(type) {
- return getDifferentChart(type, this.type, this.parent, this.rawChartArgs);
- }
- }
-
- class AggregationChart extends BaseChart {
- constructor(parent, args) {
- super(parent, args);
- }
-
- configure(args) {
- super.configure(args);
-
- this.config.maxSlices = args.maxSlices || 20;
- this.config.maxLegendPoints = args.maxLegendPoints || 20;
- }
-
- calc() {
- let s = this.state;
- let maxSlices = this.config.maxSlices;
- s.sliceTotals = [];
-
- let allTotals = this.data.labels.map((label, i) => {
- let total = 0;
- this.data.datasets.map(e => {
- total += e.values[i];
- });
- return [total, label];
- }).filter(d => { return d[0] > 0; }); // keep only positive results
-
- let totals = allTotals;
- if(allTotals.length > maxSlices) {
- // Prune and keep a grey area for rest as per maxSlices
- allTotals.sort((a, b) => { return b[0] - a[0]; });
-
- totals = allTotals.slice(0, maxSlices-1);
- let remaining = allTotals.slice(maxSlices-1);
-
- let sumOfRemaining = 0;
- remaining.map(d => {sumOfRemaining += d[0];});
- totals.push([sumOfRemaining, 'Rest']);
- this.colors[maxSlices-1] = 'grey';
- }
-
- s.labels = [];
- totals.map(d => {
- s.sliceTotals.push(d[0]);
- s.labels.push(d[1]);
- });
- }
-
- renderLegend() {
- let s = this.state;
-
- this.statsWrapper.textContent = '';
-
- this.legendTotals = s.sliceTotals.slice(0, this.config.maxLegendPoints);
-
- let xValues = s.labels;
- this.legendTotals.map((d, i) => {
- if(d) {
- let stats = $.create('div', {
- className: 'stats',
- inside: this.statsWrapper
- });
- stats.innerHTML = `<span class="indicator">
- <i style="background: ${this.colors[i]}"></i>
- <span class="text-muted">${xValues[i]}:</span>
- ${d}
- </span>`;
- }
- });
- }
- }
-
- class PercentageChart extends AggregationChart {
- constructor(parent, args) {
- super(parent, args);
- this.type = 'percentage';
-
- this.setup();
- }
-
- makeChartArea() {
- this.chartWrapper.className += ' ' + 'graph-focus-margin';
- this.chartWrapper.style.marginTop = '45px';
-
- this.statsWrapper.className += ' ' + 'graph-focus-margin';
- this.statsWrapper.style.marginBottom = '30px';
- this.statsWrapper.style.paddingTop = '0px';
-
- this.svg = $.create('div', {
- className: 'div',
- inside: this.chartWrapper
- });
-
- this.chart = $.create('div', {
- className: 'progress-chart',
- inside: this.svg
- });
-
- this.percentageBar = $.create('div', {
- className: 'progress',
- inside: this.chart
- });
- }
-
- render() {
- let s = this.state;
- this.grandTotal = s.sliceTotals.reduce((a, b) => a + b, 0);
- s.slices = [];
- s.sliceTotals.map((total, i) => {
- let slice = $.create('div', {
- className: `progress-bar`,
- 'data-index': i,
- inside: this.percentageBar,
- styles: {
- background: this.colors[i],
- width: total*100/this.grandTotal + "%"
- }
- });
- s.slices.push(slice);
- });
- }
-
- bindTooltip() {
- let s = this.state;
-
- this.chartWrapper.addEventListener('mousemove', (e) => {
- let slice = e.target;
- if(slice.classList.contains('progress-bar')) {
-
- let i = slice.getAttribute('data-index');
- let gOff = getOffset(this.chartWrapper), pOff = getOffset(slice);
-
- let x = pOff.left - gOff.left + slice.offsetWidth/2;
- let y = pOff.top - gOff.top - 6;
- let title = (this.formattedLabels && this.formattedLabels.length>0
- ? this.formattedLabels[i] : this.state.labels[i]) + ': ';
- let percent = (s.sliceTotals[i]*100/this.grandTotal).toFixed(1);
-
- this.tip.setValues(x, y, {name: title, value: percent + "%"});
- this.tip.showTip();
- }
- });
- }
- }
-
- class ChartComponent {
- constructor({
- layerClass = '',
- layerTransform = '',
- constants,
-
- getData,
- makeElements,
- animateElements
- }) {
- this.layerTransform = layerTransform;
- this.constants = constants;
-
- this.makeElements = makeElements;
- this.getData = getData;
-
- this.animateElements = animateElements;
-
- this.store = [];
-
- this.layerClass = layerClass;
- this.layerClass = typeof(this.layerClass) === 'function'
- ? this.layerClass() : this.layerClass;
-
- this.refresh();
- }
-
- refresh(data) {
- this.data = data || this.getData();
- }
-
- setup(parent) {
- this.layer = makeSVGGroup(parent, this.layerClass, this.layerTransform);
- }
-
- make() {
- this.render(this.data);
- this.oldData = this.data;
- }
-
- render(data) {
- this.store = this.makeElements(data);
-
- this.layer.textContent = '';
- this.store.forEach(element => {
- this.layer.appendChild(element);
- });
- }
-
- update(animate = true) {
- this.refresh();
- let animateElements = [];
- if(animate) {
- animateElements = this.animateElements(this.data);
- }
- return animateElements;
- }
- }
-
- let componentConfigs = {
- pieSlices: {
- layerClass: 'pie-slices',
- makeElements(data) {
- return data.sliceStrings.map((s, i) =>{
- let slice = makePath(s, 'pie-path', 'none', data.colors[i]);
- slice.style.transition = 'transform .3s;';
- return slice;
- });
- },
-
- animateElements(newData) {
- return this.store.map((slice, i) =>
- animatePathStr(slice, newData.sliceStrings[i])
- );
- }
- },
- yAxis: {
- layerClass: 'y axis',
- makeElements(data) {
- return data.positions.map((position, i) =>
- yLine(position, data.labels[i], this.constants.width,
- {mode: this.constants.mode, pos: this.constants.pos})
- );
- },
-
- animateElements(newData) {
- let newPos = newData.positions;
- let newLabels = newData.labels;
- let oldPos = this.oldData.positions;
- let oldLabels = this.oldData.labels;
-
- [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
- [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
-
- this.render({
- positions: oldPos,
- labels: newLabels
- });
-
- return this.store.map((line, i) => {
- return translateHoriLine(
- line, newPos[i], oldPos[i]
- );
- });
- }
- },
-
- xAxis: {
- layerClass: 'x axis',
- makeElements(data) {
- return data.positions.map((position, i) =>
- xLine(position, data.calcLabels[i], this.constants.height,
- {mode: this.constants.mode, pos: this.constants.pos})
- );
- },
-
- animateElements(newData) {
- let newPos = newData.positions;
- let newLabels = newData.calcLabels;
- let oldPos = this.oldData.positions;
- let oldLabels = this.oldData.calcLabels;
-
- [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
- [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
-
- this.render({
- positions: oldPos,
- calcLabels: newLabels
- });
-
- return this.store.map((line, i) => {
- return translateVertLine(
- line, newPos[i], oldPos[i]
- );
- });
- }
- },
-
- yMarkers: {
- layerClass: 'y-markers',
- makeElements(data) {
- return data.map(marker =>
- yMarker(marker.position, marker.label, this.constants.width,
- {pos:'right', mode: 'span', lineType: 'dashed'})
- );
- },
- animateElements(newData) {
- [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
-
- let newPos = newData.map(d => d.position);
- let newLabels = newData.map(d => d.label);
-
- let oldPos = this.oldData.map(d => d.position);
-
- this.render(oldPos.map((pos, i) => {
- return {
- position: oldPos[i],
- label: newLabels[i]
- };
- }));
-
- return this.store.map((line, i) => {
- return translateHoriLine(
- line, newPos[i], oldPos[i]
- );
- });
- }
- },
-
- yRegions: {
- layerClass: 'y-regions',
- makeElements(data) {
- return data.map(region =>
- yRegion(region.startPos, region.endPos, this.constants.width,
- region.label)
- );
- },
- animateElements(newData) {
- [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
-
- let newPos = newData.map(d => d.endPos);
- let newLabels = newData.map(d => d.label);
- let newStarts = newData.map(d => d.startPos);
-
- let oldPos = this.oldData.map(d => d.endPos);
- let oldStarts = this.oldData.map(d => d.startPos);
-
- this.render(oldPos.map((pos, i) => {
- return {
- startPos: oldStarts[i],
- endPos: oldPos[i],
- label: newLabels[i]
- };
- }));
-
- let animateElements = [];
-
- this.store.map((rectGroup, i) => {
- animateElements = animateElements.concat(animateRegion(
- rectGroup, newStarts[i], newPos[i], oldPos[i]
- ));
- });
-
- return animateElements;
- }
- },
-
- barGraph: {
- layerClass: function() { return 'dataset-units dataset-bars dataset-' + this.constants.index; },
- makeElements(data) {
- let c = this.constants;
- this.unitType = 'bar';
- this.units = data.yPositions.map((y, j) => {
- return datasetBar(
- data.xPositions[j],
- y,
- data.barWidth,
- c.color,
- data.labels[j],
- j,
- data.offsets[j],
- {
- zeroLine: data.zeroLine,
- barsWidth: data.barsWidth,
- minHeight: c.minHeight
- }
- );
- });
- return this.units;
- },
- animateElements(newData) {
- let newXPos = newData.xPositions;
- let newYPos = newData.yPositions;
- let newOffsets = newData.offsets;
- let newLabels = newData.labels;
-
- let oldXPos = this.oldData.xPositions;
- let oldYPos = this.oldData.yPositions;
- let oldOffsets = this.oldData.offsets;
- let oldLabels = this.oldData.labels;
-
- [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
- [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
- [oldOffsets, newOffsets] = equilizeNoOfElements(oldOffsets, newOffsets);
- [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
-
- this.render({
- xPositions: oldXPos,
- yPositions: oldYPos,
- offsets: oldOffsets,
- labels: newLabels,
-
- zeroLine: this.oldData.zeroLine,
- barsWidth: this.oldData.barsWidth,
- barWidth: this.oldData.barWidth,
- });
-
- let animateElements = [];
-
- this.store.map((bar, i) => {
- animateElements = animateElements.concat(animateBar(
- bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i],
- {zeroLine: newData.zeroLine}
- ));
- });
-
- return animateElements;
- }
- },
-
- lineGraph: {
- layerClass: function() { return 'dataset-units dataset-line dataset-' + this.constants.index; },
- makeElements(data) {
- let c = this.constants;
- this.unitType = 'dot';
- this.paths = {};
- if(!c.hideLine) {
- this.paths = getPaths(
- data.xPositions,
- data.yPositions,
- c.color,
- {
- heatline: c.heatline,
- regionFill: c.regionFill
- },
- {
- svgDefs: c.svgDefs,
- zeroLine: data.zeroLine
- }
- );
- }
-
- this.units = [];
- if(!c.hideDots) {
- this.units = data.yPositions.map((y, j) => {
- return datasetDot(
- data.xPositions[j],
- y,
- data.radius,
- c.color,
- (c.valuesOverPoints ? data.values[j] : ''),
- j
- );
- });
- }
-
- return Object.values(this.paths).concat(this.units);
- },
- animateElements(newData) {
- let newXPos = newData.xPositions;
- let newYPos = newData.yPositions;
- let newValues = newData.values;
-
- let oldXPos = this.oldData.xPositions;
- let oldYPos = this.oldData.yPositions;
- let oldValues = this.oldData.values;
-
- [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
- [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
- [oldValues, newValues] = equilizeNoOfElements(oldValues, newValues);
-
- this.render({
- xPositions: oldXPos,
- yPositions: oldYPos,
- values: newValues,
-
- zeroLine: this.oldData.zeroLine,
- radius: this.oldData.radius,
- });
-
- let animateElements = [];
-
- if(Object.keys(this.paths).length) {
- animateElements = animateElements.concat(animatePath(
- this.paths, newXPos, newYPos, newData.zeroLine));
- }
-
- if(this.units.length) {
- this.units.map((dot, i) => {
- animateElements = animateElements.concat(animateDot(
- dot, newXPos[i], newYPos[i]));
- });
- }
-
- return animateElements;
- }
- }
- };
-
- function getComponent(name, constants, getData) {
- let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
- let config = componentConfigs[keys[0]];
- Object.assign(config, {
- constants: constants,
- getData: getData
- });
- return new ChartComponent(config);
- }
-
- class PieChart extends AggregationChart {
- constructor(parent, args) {
- super(parent, args);
- this.type = 'pie';
- this.initTimeout = 0;
-
- this.setup();
- }
-
- configure(args) {
- super.configure(args);
- this.mouseMove = this.mouseMove.bind(this);
- this.mouseLeave = this.mouseLeave.bind(this);
-
- this.hoverRadio = args.hoverRadio || 0.1;
- this.config.startAngle = args.startAngle || 0;
-
- this.clockWise = args.clockWise || false;
- }
-
- prepareFirstData(data=this.data) {
- this.init = 1;
- return data;
- }
-
- calc() {
- super.calc();
- let s = this.state;
-
- this.center = {
- x: this.width / 2,
- y: this.height / 2
- };
- this.radius = (this.height > this.width ? this.center.x : this.center.y);
-
- s.grandTotal = s.sliceTotals.reduce((a, b) => a + b, 0);
-
- this.calcSlices();
- }
-
- calcSlices() {
- let s = this.state;
- const { radius, clockWise } = this;
-
- const prevSlicesProperties = s.slicesProperties || [];
- s.sliceStrings = [];
- s.slicesProperties = [];
- let curAngle = 180 - this.config.startAngle;
-
- s.sliceTotals.map((total, i) => {
- const startAngle = curAngle;
- const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
- const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
- const endAngle = curAngle = curAngle + diffAngle;
- const startPosition = getPositionByAngle(startAngle, radius);
- const endPosition = getPositionByAngle(endAngle, radius);
-
- const prevProperty = this.init && prevSlicesProperties[i];
-
- let curStart,curEnd;
- if(this.init) {
- curStart = prevProperty ? prevProperty.startPosition : startPosition;
- curEnd = prevProperty ? prevProperty.endPosition : startPosition;
- } else {
- curStart = startPosition;
- curEnd = endPosition;
- }
- const curPath = makeArcPathStr(curStart, curEnd, this.center, this.radius, this.clockWise);
-
- s.sliceStrings.push(curPath);
- s.slicesProperties.push({
- startPosition,
- endPosition,
- value: total,
- total: s.grandTotal,
- startAngle,
- endAngle,
- angle: diffAngle
- });
-
- });
- this.init = 0;
- }
-
- setupComponents() {
- let s = this.state;
-
- let componentConfigs = [
- [
- 'pieSlices',
- { },
- function() {
- return {
- sliceStrings: s.sliceStrings,
- colors: this.colors
- };
- }.bind(this)
- ]
- ];
-
- this.components = new Map(componentConfigs
- .map(args => {
- let component = getComponent(...args);
- return [args[0], component];
- }));
- }
-
- calTranslateByAngle(property){
- const{radius,hoverRadio} = this;
- const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
- return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
- }
-
- hoverSlice(path,i,flag,e){
- if(!path) return;
- const color = this.colors[i];
- if(flag) {
- transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
- path.style.fill = lightenDarkenColor(color, 50);
- let g_off = getOffset(this.svg);
- let x = e.pageX - g_off.left + 10;
- let y = e.pageY - g_off.top - 10;
- let title = (this.formatted_labels && this.formatted_labels.length > 0
- ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
- let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
- this.tip.setValues(x, y, {name: title, value: percent + "%"});
- this.tip.showTip();
- } else {
- transform(path,'translate3d(0,0,0)');
- this.tip.hideTip();
- path.style.fill = color;
- }
- }
-
- bindTooltip() {
- this.chartWrapper.addEventListener('mousemove', this.mouseMove);
- this.chartWrapper.addEventListener('mouseleave', this.mouseLeave);
- }
-
- mouseMove(e){
- const target = e.target;
- let slices = this.components.get('pieSlices').store;
- let prevIndex = this.curActiveSliceIndex;
- let prevAcitve = this.curActiveSlice;
- if(slices.includes(target)) {
- let i = slices.indexOf(target);
- this.hoverSlice(prevAcitve, prevIndex,false);
- this.curActiveSlice = target;
- this.curActiveSliceIndex = i;
- this.hoverSlice(target, i, true, e);
- } else {
- this.mouseLeave();
- }
- }
-
- mouseLeave(){
- this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
- }
- }
-
- // Playing around with dates
-
- // https://stackoverflow.com/a/11252167/6495043
- function treatAsUtc(dateStr) {
- let result = new Date(dateStr);
- result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
- return result;
- }
-
- function getDdMmYyyy(date) {
- let dd = date.getDate();
- let mm = date.getMonth() + 1; // getMonth() is zero-based
- return [
- (dd>9 ? '' : '0') + dd,
- (mm>9 ? '' : '0') + mm,
- date.getFullYear()
- ].join('-');
- }
-
- function getWeeksBetween(startDateStr, endDateStr) {
- return Math.ceil(getDaysBetween(startDateStr, endDateStr) / 7);
- }
-
- function getDaysBetween(startDateStr, endDateStr) {
- let millisecondsPerDay = 24 * 60 * 60 * 1000;
- return (treatAsUtc(endDateStr) - treatAsUtc(startDateStr)) / millisecondsPerDay;
- }
-
- // mutates
- function addDays(date, numberOfDays) {
- date.setDate(date.getDate() + numberOfDays);
- }
-
- function normalize(x) {
- // Calculates mantissa and exponent of a number
- // Returns normalized number and exponent
- // https://stackoverflow.com/q/9383593/6495043
-
- if(x===0) {
- return [0, 0];
- }
- if(isNaN(x)) {
- return {mantissa: -6755399441055744, exponent: 972};
- }
- var sig = x > 0 ? 1 : -1;
- if(!isFinite(x)) {
- return {mantissa: sig * 4503599627370496, exponent: 972};
- }
-
- x = Math.abs(x);
- var exp = Math.floor(Math.log10(x));
- var man = x/Math.pow(10, exp);
-
- return [sig * man, exp];
- }
-
- function getChartRangeIntervals(max, min=0) {
- let upperBound = Math.ceil(max);
- let lowerBound = Math.floor(min);
- let range = upperBound - lowerBound;
-
- let noOfParts = range;
- let partSize = 1;
-
- // To avoid too many partitions
- if(range > 5) {
- if(range % 2 !== 0) {
- upperBound++;
- // Recalc range
- range = upperBound - lowerBound;
- }
- noOfParts = range/2;
- partSize = 2;
- }
-
- // Special case: 1 and 2
- if(range <= 2) {
- noOfParts = 4;
- partSize = range/noOfParts;
- }
-
- // Special case: 0
- if(range === 0) {
- noOfParts = 5;
- partSize = 1;
- }
-
- let intervals = [];
- for(var i = 0; i <= noOfParts; i++){
- intervals.push(lowerBound + partSize * i);
- }
- return intervals;
- }
-
- function getChartIntervals(maxValue, minValue=0) {
- let [normalMaxValue, exponent] = normalize(maxValue);
- let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
-
- // Allow only 7 significant digits
- normalMaxValue = normalMaxValue.toFixed(6);
-
- let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
- intervals = intervals.map(value => value * Math.pow(10, exponent));
- return intervals;
- }
-
- function calcChartIntervals(values, withMinimum=false) {
- //*** Where the magic happens ***
-
- // Calculates best-fit y intervals from given values
- // and returns the interval array
-
- let maxValue = Math.max(...values);
- let minValue = Math.min(...values);
-
- // Exponent to be used for pretty print
- let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
-
- function getPositiveFirstIntervals(maxValue, absMinValue) {
- let intervals = getChartIntervals(maxValue);
-
- let intervalSize = intervals[1] - intervals[0];
-
- // Then unshift the negative values
- let value = 0;
- for(var i = 1; value < absMinValue; i++) {
- value += intervalSize;
- intervals.unshift((-1) * value);
- }
- return intervals;
- }
-
- // CASE I: Both non-negative
-
- if(maxValue >= 0 && minValue >= 0) {
- exponent = normalize(maxValue)[1];
- if(!withMinimum) {
- intervals = getChartIntervals(maxValue);
- } else {
- intervals = getChartIntervals(maxValue, minValue);
- }
- }
-
- // CASE II: Only minValue negative
-
- else if(maxValue > 0 && minValue < 0) {
- // `withMinimum` irrelevant in this case,
- // We'll be handling both sides of zero separately
- // (both starting from zero)
- // Because ceil() and floor() behave differently
- // in those two regions
-
- let absMinValue = Math.abs(minValue);
-
- if(maxValue >= absMinValue) {
- exponent = normalize(maxValue)[1];
- intervals = getPositiveFirstIntervals(maxValue, absMinValue);
- } else {
- // Mirror: maxValue => absMinValue, then change sign
- exponent = normalize(absMinValue)[1];
- let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
- intervals = posIntervals.map(d => d * (-1));
- }
-
- }
-
- // CASE III: Both non-positive
-
- else if(maxValue <= 0 && minValue <= 0) {
- // Mirrored Case I:
- // Work with positives, then reverse the sign and array
-
- let pseudoMaxValue = Math.abs(minValue);
- let pseudoMinValue = Math.abs(maxValue);
-
- exponent = normalize(pseudoMaxValue)[1];
- if(!withMinimum) {
- intervals = getChartIntervals(pseudoMaxValue);
- } else {
- intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
- }
-
- intervals = intervals.reverse().map(d => d * (-1));
- }
-
- return intervals;
- }
-
- function getZeroIndex(yPts) {
- let zeroIndex;
- let interval = getIntervalSize(yPts);
- if(yPts.indexOf(0) >= 0) {
- // the range has a given zero
- // zero-line on the chart
- zeroIndex = yPts.indexOf(0);
- } else if(yPts[0] > 0) {
- // Minimum value is positive
- // zero-line is off the chart: below
- let min = yPts[0];
- zeroIndex = (-1) * min / interval;
- } else {
- // Maximum value is negative
- // zero-line is off the chart: above
- let max = yPts[yPts.length - 1];
- zeroIndex = (-1) * max / interval + (yPts.length - 1);
- }
- return zeroIndex;
- }
-
-
-
- function getIntervalSize(orderedArray) {
- return orderedArray[1] - orderedArray[0];
- }
-
- function getValueRange(orderedArray) {
- return orderedArray[orderedArray.length-1] - orderedArray[0];
- }
-
- function scale(val, yAxis) {
- return floatTwo(yAxis.zeroLine - val * yAxis.scaleMultiplier);
- }
-
- function calcDistribution(values, distributionSize) {
- // Assume non-negative values,
- // implying distribution minimum at zero
-
- let dataMaxValue = Math.max(...values);
-
- let distributionStep = 1 / (distributionSize - 1);
- let distribution = [];
-
- for(var i = 0; i < distributionSize; i++) {
- let checkpoint = dataMaxValue * (distributionStep * i);
- distribution.push(checkpoint);
- }
-
- return distribution;
- }
-
- function getMaxCheckpoint(value, distribution) {
- return distribution.filter(d => d < value).length;
- }
-
- class Heatmap extends BaseChart {
- constructor(parent, options) {
- super(parent, options);
-
- this.type = 'heatmap';
-
- this.domain = options.domain || '';
- this.subdomain = options.subdomain || '';
- this.data = options.data || {};
- this.discreteDomains = options.discreteDomains === 0 ? 0 : 1;
- this.countLabel = options.countLabel || '';
-
- let today = new Date();
- this.start = options.start || addDays(today, 365);
-
- let legendColors = (options.legendColors || []).slice(0, 5);
- this.legendColors = this.validate_colors(legendColors)
- ? legendColors
- : ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
-
- // Fixed 5-color theme,
- // More colors are difficult to parse visually
- this.distribution_size = 5;
-
- this.translateX = 0;
- this.setup();
- }
-
- setMargins() {
- super.setMargins();
- this.leftMargin = 10;
- this.translateY = 10;
- }
-
- validate_colors(colors) {
- if(colors.length < 5) return 0;
-
- let valid = 1;
- colors.forEach(function(string) {
- if(!isValidColor(string)) {
- valid = 0;
- console.warn('"' + string + '" is not a valid color.');
- }
- }, this);
-
- return valid;
- }
-
- configure() {
- super.configure();
- this.today = new Date();
-
- if(!this.start) {
- this.start = new Date();
- this.start.setFullYear( this.start.getFullYear() - 1 );
- }
- this.firstWeekStart = new Date(this.start.toDateString());
- this.lastWeekStart = new Date(this.today.toDateString());
- if(this.firstWeekStart.getDay() !== 7) {
- addDays(this.firstWeekStart, (-1) * this.firstWeekStart.getDay());
- }
- if(this.lastWeekStart.getDay() !== 7) {
- addDays(this.lastWeekStart, (-1) * this.lastWeekStart.getDay());
- }
- this.no_of_cols = getWeeksBetween(this.firstWeekStart + '', this.lastWeekStart + '') + 1;
- }
-
- calcWidth() {
- this.baseWidth = (this.no_of_cols + 3) * 12 ;
-
- if(this.discreteDomains) {
- this.baseWidth += (12 * 12);
- }
- }
-
- makeChartArea() {
- super.makeChartArea();
- this.domainLabelGroup = makeSVGGroup(this.drawArea,
- 'domain-label-group chart-label');
-
- this.dataGroups = makeSVGGroup(this.drawArea,
- 'data-groups',
- `translate(0, 20)`
- );
-
- this.container.querySelector('.title').style.display = 'None';
- this.container.querySelector('.sub-title').style.display = 'None';
- this.container.querySelector('.graph-stats-container').style.display = 'None';
- this.chartWrapper.style.marginTop = '0px';
- this.chartWrapper.style.paddingTop = '0px';
- }
-
- calc() {
-
- let dataValues = Object.keys(this.data).map(key => this.data[key]);
- this.distribution = calcDistribution(dataValues, this.distribution_size);
-
- this.monthNames = ["January", "February", "March", "April", "May", "June",
- "July", "August", "September", "October", "November", "December"
- ];
- }
-
- render() {
- this.renderAllWeeksAndStoreXValues(this.no_of_cols);
- }
-
- renderAllWeeksAndStoreXValues(no_of_weeks) {
- // renderAllWeeksAndStoreXValues
- this.domainLabelGroup.textContent = '';
- this.dataGroups.textContent = '';
-
- let currentWeekSunday = new Date(this.firstWeekStart);
- this.weekCol = 0;
- this.currentMonth = currentWeekSunday.getMonth();
-
- this.months = [this.currentMonth + ''];
- this.monthWeeks = {}, this.monthStartPoints = [];
- this.monthWeeks[this.currentMonth] = 0;
- this.monthStartPoints.push(13);
-
- for(var i = 0; i < no_of_weeks; i++) {
- let dataGroup, monthChange = 0;
- let day = new Date(currentWeekSunday);
-
- [dataGroup, monthChange] = this.get_week_squares_group(day, this.weekCol);
- this.dataGroups.appendChild(dataGroup);
- this.weekCol += 1 + parseInt(this.discreteDomains && monthChange);
- this.monthWeeks[this.currentMonth]++;
- if(monthChange) {
- this.currentMonth = (this.currentMonth + 1) % 12;
- this.months.push(this.currentMonth + '');
- this.monthWeeks[this.currentMonth] = 1;
- }
- addDays(currentWeekSunday, 7);
- }
- this.render_month_labels();
- }
-
- get_week_squares_group(currentDate, index) {
- const noOfWeekdays = 7;
- const squareSide = 10;
- const cellPadding = 2;
- const step = 1;
- const todayTime = this.today.getTime();
-
- let monthChange = 0;
- let weekColChange = 0;
-
- let dataGroup = makeSVGGroup(this.dataGroups, 'data-group');
-
- for(var y = 0, i = 0; i < noOfWeekdays; i += step, y += (squareSide + cellPadding)) {
- let dataValue = 0;
- let colorIndex = 0;
-
- let currentTimestamp = currentDate.getTime()/1000;
- let timestamp = Math.floor(currentTimestamp - (currentTimestamp % 86400)).toFixed(1);
-
- if(this.data[timestamp]) {
- dataValue = this.data[timestamp];
- }
-
- if(this.data[Math.round(timestamp)]) {
- dataValue = this.data[Math.round(timestamp)];
- }
-
- if(dataValue) {
- colorIndex = getMaxCheckpoint(dataValue, this.distribution);
- }
-
- let x = 13 + (index + weekColChange) * 12;
-
- let dataAttr = {
- 'data-date': getDdMmYyyy(currentDate),
- 'data-value': dataValue,
- 'data-day': currentDate.getDay()
- };
-
- let heatSquare = makeHeatSquare('day', x, y, squareSide,
- this.legendColors[colorIndex], dataAttr);
-
- dataGroup.appendChild(heatSquare);
-
- let nextDate = new Date(currentDate);
- addDays(nextDate, 1);
- if(nextDate.getTime() > todayTime) break;
-
-
- if(nextDate.getMonth() - currentDate.getMonth()) {
- monthChange = 1;
- if(this.discreteDomains) {
- weekColChange = 1;
- }
-
- this.monthStartPoints.push(13 + (index + weekColChange) * 12);
- }
- currentDate = nextDate;
- }
-
- return [dataGroup, monthChange];
- }
-
- render_month_labels() {
- // this.first_month_label = 1;
- // if (this.firstWeekStart.getDate() > 8) {
- // this.first_month_label = 0;
- // }
- // this.last_month_label = 1;
-
- // let first_month = this.months.shift();
- // let first_month_start = this.monthStartPoints.shift();
- // render first month if
-
- // let last_month = this.months.pop();
- // let last_month_start = this.monthStartPoints.pop();
- // render last month if
-
- this.months.shift();
- this.monthStartPoints.shift();
- this.months.pop();
- this.monthStartPoints.pop();
-
- this.monthStartPoints.map((start, i) => {
- let month_name = this.monthNames[this.months[i]].substring(0, 3);
- let text = makeText('y-value-text', start+12, 10, month_name);
- this.domainLabelGroup.appendChild(text);
- });
- }
-
- bindTooltip() {
- Array.prototype.slice.call(
- document.querySelectorAll(".data-group .day")
- ).map(el => {
- el.addEventListener('mouseenter', (e) => {
- let count = e.target.getAttribute('data-value');
- let dateParts = e.target.getAttribute('data-date').split('-');
-
- let month = this.monthNames[parseInt(dateParts[1])-1].substring(0, 3);
-
- let gOff = this.chartWrapper.getBoundingClientRect(), pOff = e.target.getBoundingClientRect();
-
- let width = parseInt(e.target.getAttribute('width'));
- let x = pOff.left - gOff.left + (width+2)/2;
- let y = pOff.top - gOff.top - (width+2)/2;
- let value = count + ' ' + this.countLabel;
- let name = ' on ' + month + ' ' + dateParts[0] + ', ' + dateParts[2];
-
- this.tip.setValues(x, y, {name: name, value: value, valueFirst: 1}, []);
- this.tip.showTip();
- });
- });
- }
-
- update(data) {
- super.update(data);
- this.bindTooltip();
- }
- }
-
- function dataPrep(data, type) {
- data.labels = data.labels || [];
-
- let datasetLength = data.labels.length;
-
- // Datasets
- let datasets = data.datasets;
- let zeroArray = new Array(datasetLength).fill(0);
- if(!datasets) {
- // default
- datasets = [{
- values: zeroArray
- }];
- }
-
- datasets.map(d=> {
- // Set values
- if(!d.values) {
- d.values = zeroArray;
- } else {
- // Check for non values
- let vals = d.values;
- vals = vals.map(val => (!isNaN(val) ? val : 0));
-
- // Trim or extend
- if(vals.length > datasetLength) {
- vals = vals.slice(0, datasetLength);
- } else {
- vals = fillArray(vals, datasetLength - vals.length, 0);
- }
- }
-
- // Set labels
- //
-
- // Set type
- if(!d.chartType ) {
- if(!AXIS_DATASET_CHART_TYPES.includes(type)) type === DEFAULT_AXIS_CHART_TYPE;
- d.chartType = type;
- }
-
- });
-
- // Markers
-
- // Regions
- // data.yRegions = data.yRegions || [];
- if(data.yRegions) {
- data.yRegions.map(d => {
- if(d.end < d.start) {
- [d.start, d.end] = [d.end, d.start];
- }
- });
- }
-
- return data;
- }
-
- function zeroDataPrep(realData) {
- let datasetLength = realData.labels.length;
- let zeroArray = new Array(datasetLength).fill(0);
-
- let zeroData = {
- labels: realData.labels.slice(0, -1),
- datasets: realData.datasets.map(d => {
- return {
- name: '',
- values: zeroArray.slice(0, -1),
- chartType: d.chartType
- };
- }),
- };
-
- if(realData.yMarkers) {
- zeroData.yMarkers = [
- {
- value: 0,
- label: ''
- }
- ];
- }
-
- if(realData.yRegions) {
- zeroData.yRegions = [
- {
- start: 0,
- end: 0,
- label: ''
- }
- ];
- }
-
- return zeroData;
- }
-
- function getShortenedLabels(chartWidth, labels=[], isSeries=true) {
- let allowedSpace = chartWidth / labels.length;
- let allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH;
-
- let calcLabels = labels.map((label, i) => {
- label += "";
- if(label.length > allowedLetters) {
-
- if(!isSeries) {
- if(allowedLetters-3 > 0) {
- label = label.slice(0, allowedLetters-3) + " ...";
- } else {
- label = label.slice(0, allowedLetters) + '..';
- }
- } else {
- let multiple = Math.ceil(label.length/allowedLetters);
- if(i % multiple !== 0) {
- label = "";
- }
- }
- }
- return label;
- });
-
- return calcLabels;
- }
-
- class AxisChart extends BaseChart {
- constructor(parent, args) {
- super(parent, args);
-
- this.barOptions = args.barOptions || {};
- this.lineOptions = args.lineOptions || {};
-
- this.type = args.type || 'line';
- this.init = 1;
-
- this.setup();
- }
-
- configure(args) {
- super.configure();
-
- args.axisOptions = args.axisOptions || {};
- args.tooltipOptions = args.tooltipOptions || {};
-
- this.config.xAxisMode = args.axisOptions.xAxisMode || 'span';
- this.config.yAxisMode = args.axisOptions.yAxisMode || 'span';
- this.config.xIsSeries = args.axisOptions.xIsSeries || 0;
-
- this.config.formatTooltipX = args.tooltipOptions.formatTooltipX;
- this.config.formatTooltipY = args.tooltipOptions.formatTooltipY;
-
- this.config.valuesOverPoints = args.valuesOverPoints;
- }
-
- setMargins() {
- super.setMargins();
- this.leftMargin = Y_AXIS_MARGIN;
- this.rightMargin = Y_AXIS_MARGIN;
- }
-
- prepareData(data=this.data) {
- return dataPrep(data, this.type);
- }
-
- prepareFirstData(data=this.data) {
- return zeroDataPrep(data);
- }
-
- calc(onlyWidthChange = false) {
- this.calcXPositions();
- if(onlyWidthChange) return;
- this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
- }
-
- calcXPositions() {
- let s = this.state;
- let labels = this.data.labels;
- s.datasetLength = labels.length;
-
- s.unitWidth = this.width/(s.datasetLength);
- // Default, as per bar, and mixed. Only line will be a special case
- s.xOffset = s.unitWidth/2;
-
- // // For a pure Line Chart
- // s.unitWidth = this.width/(s.datasetLength - 1);
- // s.xOffset = 0;
-
- s.xAxis = {
- labels: labels,
- positions: labels.map((d, i) =>
- floatTwo(s.xOffset + i * s.unitWidth)
- )
- };
- }
-
- calcYAxisParameters(dataValues, withMinimum = 'false') {
- const yPts = calcChartIntervals(dataValues, withMinimum);
- const scaleMultiplier = this.height / getValueRange(yPts);
- const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
- const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
-
- this.state.yAxis = {
- labels: yPts,
- positions: yPts.map(d => zeroLine - d * scaleMultiplier),
- scaleMultiplier: scaleMultiplier,
- zeroLine: zeroLine,
- };
-
- // Dependent if above changes
- this.calcDatasetPoints();
- this.calcYExtremes();
- this.calcYRegions();
- }
-
- calcDatasetPoints() {
- let s = this.state;
- let scaleAll = values => values.map(val => scale(val, s.yAxis));
-
- s.datasets = this.data.datasets.map((d, i) => {
- let values = d.values;
- let cumulativeYs = d.cumulativeYs || [];
- return {
- name: d.name,
- index: i,
- chartType: d.chartType,
-
- values: values,
- yPositions: scaleAll(values),
-
- cumulativeYs: cumulativeYs,
- cumulativeYPos: scaleAll(cumulativeYs),
- };
- });
- }
-
- calcYExtremes() {
- let s = this.state;
- if(this.barOptions.stacked) {
- s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
- return;
- }
- s.yExtremes = new Array(s.datasetLength).fill(9999);
- s.datasets.map(d => {
- d.yPositions.map((pos, j) => {
- if(pos < s.yExtremes[j]) {
- s.yExtremes[j] = pos;
- }
- });
- });
- }
-
- calcYRegions() {
- let s = this.state;
- if(this.data.yMarkers) {
- this.state.yMarkers = this.data.yMarkers.map(d => {
- d.position = scale(d.value, s.yAxis);
- // if(!d.label.includes(':')) {
- // d.label += ': ' + d.value;
- // }
- return d;
- });
- }
- if(this.data.yRegions) {
- this.state.yRegions = this.data.yRegions.map(d => {
- d.startPos = scale(d.start, s.yAxis);
- d.endPos = scale(d.end, s.yAxis);
- return d;
- });
- }
- }
-
- getAllYValues() {
- // TODO: yMarkers, regions, sums, every Y value ever
- let key = 'values';
-
- if(this.barOptions.stacked) {
- key = 'cumulativeYs';
- let cumulative = new Array(this.state.datasetLength).fill(0);
- this.data.datasets.map((d, i) => {
- let values = this.data.datasets[i].values;
- d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
- });
- }
-
- let allValueLists = this.data.datasets.map(d => d[key]);
- if(this.data.yMarkers) {
- allValueLists.push(this.data.yMarkers.map(d => d.value));
- }
- if(this.data.yRegions) {
- this.data.yRegions.map(d => {
- allValueLists.push([d.end, d.start]);
- });
- }
-
- return [].concat(...allValueLists);
- }
-
- setupComponents() {
- let componentConfigs = [
- [
- 'yAxis',
- {
- mode: this.config.yAxisMode,
- width: this.width,
- // pos: 'right'
- },
- function() {
- return this.state.yAxis;
- }.bind(this)
- ],
-
- [
- 'xAxis',
- {
- mode: this.config.xAxisMode,
- height: this.height,
- // pos: 'right'
- },
- function() {
- let s = this.state;
- s.xAxis.calcLabels = getShortenedLabels(this.width,
- s.xAxis.labels, this.config.xIsSeries);
-
- return s.xAxis;
- }.bind(this)
- ],
-
- [
- 'yRegions',
- {
- width: this.width,
- pos: 'right'
- },
- function() {
- return this.state.yRegions;
- }.bind(this)
- ],
- ];
-
- let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
- let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
-
- let barsConfigs = barDatasets.map(d => {
- let index = d.index;
- return [
- 'barGraph' + '-' + d.index,
- {
- index: index,
- color: this.colors[index],
- stacked: this.barOptions.stacked,
-
- // same for all datasets
- valuesOverPoints: this.config.valuesOverPoints,
- minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
- },
- function() {
- let s = this.state;
- let d = s.datasets[index];
- let stacked = this.barOptions.stacked;
-
- let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
- let barsWidth = s.unitWidth * (1 - spaceRatio);
- let barWidth = barsWidth/(stacked ? 1 : barDatasets.length);
-
- let xPositions = s.xAxis.positions.map(x => x - barsWidth/2);
- if(!stacked) {
- xPositions = xPositions.map(p => p + barWidth * index);
- }
-
- let labels = new Array(s.datasetLength).fill('');
- if(this.config.valuesOverPoints) {
- if(stacked && d.index === s.datasets.length - 1) {
- labels = d.cumulativeYs;
- } else {
- labels = d.values;
- }
- }
-
- let offsets = new Array(s.datasetLength).fill(0);
- if(stacked) {
- offsets = d.yPositions.map((y, j) => y - d.cumulativeYPos[j]);
- }
-
- return {
- xPositions: xPositions,
- yPositions: d.yPositions,
- offsets: offsets,
- // values: d.values,
- labels: labels,
-
- zeroLine: s.yAxis.zeroLine,
- barsWidth: barsWidth,
- barWidth: barWidth,
- };
- }.bind(this)
- ];
- });
-
- let lineConfigs = lineDatasets.map(d => {
- let index = d.index;
- return [
- 'lineGraph' + '-' + d.index,
- {
- index: index,
- color: this.colors[index],
- svgDefs: this.svgDefs,
- heatline: this.lineOptions.heatline,
- regionFill: this.lineOptions.regionFill,
- hideDots: this.lineOptions.hideDots,
- hideLine: this.lineOptions.hideLine,
-
- // same for all datasets
- valuesOverPoints: this.config.valuesOverPoints,
- },
- function() {
- let s = this.state;
- let d = s.datasets[index];
-
- return {
- xPositions: s.xAxis.positions,
- yPositions: d.yPositions,
-
- values: d.values,
-
- zeroLine: s.yAxis.zeroLine,
- radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE,
- };
- }.bind(this)
- ];
- });
-
- let markerConfigs = [
- [
- 'yMarkers',
- {
- width: this.width,
- pos: 'right'
- },
- function() {
- return this.state.yMarkers;
- }.bind(this)
- ]
- ];
-
- componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
-
- let optionals = ['yMarkers', 'yRegions'];
- this.dataUnitComponents = [];
-
- this.components = new Map(componentConfigs
- .filter(args => !optionals.includes(args[0]) || this.state[args[0]])
- .map(args => {
- let component = getComponent(...args);
- if(args[0].includes('lineGraph') || args[0].includes('barGraph')) {
- this.dataUnitComponents.push(component);
- }
- return [args[0], component];
- }));
- }
-
- bindTooltip() {
- // NOTE: could be in tooltip itself, as it is a given functionality for its parent
- this.chartWrapper.addEventListener('mousemove', (e) => {
- let o = getOffset(this.chartWrapper);
- let relX = e.pageX - o.left - this.leftMargin;
- let relY = e.pageY - o.top - this.translateY;
-
- if(relY < this.height + this.translateY * 2) {
- this.mapTooltipXPosition(relX);
- } else {
- this.tip.hideTip();
- }
- });
- }
-
- mapTooltipXPosition(relX) {
- let s = this.state;
- if(!s.yExtremes) return;
-
- let formatY = this.config.formatTooltipY;
- let formatX = this.config.formatTooltipX;
-
- let titles = s.xAxis.labels;
- if(formatX && formatX(titles[0])) {
- titles = titles.map(d=>formatX(d));
- }
-
- formatY = formatY && formatY(s.yAxis.labels[0]) ? formatY : 0;
-
- for(var i=s.datasetLength - 1; i >= 0 ; i--) {
- let xVal = s.xAxis.positions[i];
- // let delta = i === 0 ? s.unitWidth : xVal - s.xAxis.positions[i-1];
- if(relX > xVal - s.unitWidth/2) {
- let x = xVal + this.leftMargin;
- let y = s.yExtremes[i] + this.translateY;
-
- let values = this.data.datasets.map((set, j) => {
- return {
- title: set.name,
- value: formatY ? formatY(set.values[i]) : set.values[i],
- color: this.colors[j],
- };
- });
-
- this.tip.setValues(x, y, {name: titles[i], value: ''}, values, i);
- this.tip.showTip();
- break;
- }
- }
- }
-
- renderLegend() {
- let s = this.data;
- this.statsWrapper.textContent = '';
-
- if(s.datasets.length > 1) {
- s.datasets.map((d, i) => {
- let stats = $.create('div', {
- className: 'stats',
- inside: this.statsWrapper
- });
- stats.innerHTML = `<span class="indicator">
- <i style="background: ${this.colors[i]}"></i>
- ${d.name}
- </span>`;
- });
- }
- }
-
- makeOverlay() {
- if(this.init) {
- this.init = 0;
- return;
- }
- if(this.overlayGuides) {
- this.overlayGuides.forEach(g => {
- let o = g.overlay;
- o.parentNode.removeChild(o);
- });
- }
-
- this.overlayGuides = this.dataUnitComponents.map(c => {
- return {
- type: c.unitType,
- overlay: undefined,
- units: c.units,
- };
- });
-
- if(this.state.currentIndex === undefined) {
- this.state.currentIndex = this.state.datasetLength - 1;
- }
-
- // Render overlays
- this.overlayGuides.map(d => {
- let currentUnit = d.units[this.state.currentIndex];
-
- d.overlay = makeOverlay[d.type](currentUnit);
- this.drawArea.appendChild(d.overlay);
- });
- }
-
- updateOverlayGuides() {
- if(this.overlayGuides) {
- this.overlayGuides.forEach(g => {
- let o = g.overlay;
- o.parentNode.removeChild(o);
- });
- }
- }
-
- bindOverlay() {
- this.parent.addEventListener('data-select', () => {
- this.updateOverlay();
- });
- }
-
- bindUnits() {
- this.dataUnitComponents.map(c => {
- c.units.map(unit => {
- unit.addEventListener('click', () => {
- let index = unit.getAttribute('data-point-index');
- this.setCurrentDataPoint(index);
- });
- });
- });
-
- // Note: Doesn't work as tooltip is absolutely positioned
- this.tip.container.addEventListener('click', () => {
- let index = this.tip.container.getAttribute('data-point-index');
- this.setCurrentDataPoint(index);
- });
- }
-
- updateOverlay() {
- this.overlayGuides.map(d => {
- let currentUnit = d.units[this.state.currentIndex];
- updateOverlay[d.type](currentUnit, d.overlay);
- });
- }
-
- onLeftArrow() {
- this.setCurrentDataPoint(this.state.currentIndex - 1);
- }
-
- onRightArrow() {
- this.setCurrentDataPoint(this.state.currentIndex + 1);
- }
-
- getDataPoint(index=this.state.currentIndex) {
- let s = this.state;
- let data_point = {
- index: index,
- label: s.xAxis.labels[index],
- values: s.datasets.map(d => d.values[index])
- };
- return data_point;
- }
-
- setCurrentDataPoint(index) {
- let s = this.state;
- index = parseInt(index);
- if(index < 0) index = 0;
- if(index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
- if(index === s.currentIndex) return;
- s.currentIndex = index;
- fire(this.parent, "data-select", this.getDataPoint());
- }
-
- // API
- addDataPoint(label, datasetValues, index=this.state.datasetLength) {
- super.addDataPoint(label, datasetValues, index);
- this.data.labels.splice(index, 0, label);
- this.data.datasets.map((d, i) => {
- d.values.splice(index, 0, datasetValues[i]);
- });
- this.update(this.data);
- }
-
- removeDataPoint(index = this.state.datasetLength-1) {
- if (this.data.labels.length <= 1) {
- return;
- }
- super.removeDataPoint(index);
- this.data.labels.splice(index, 1);
- this.data.datasets.map(d => {
- d.values.splice(index, 1);
- });
- this.update(this.data);
- }
-
- updateDataset(datasetValues, index=0) {
- this.data.datasets[index].values = datasetValues;
- this.update(this.data);
- }
- // addDataset(dataset, index) {}
- // removeDataset(index = 0) {}
-
- updateDatasets(datasets) {
- this.data.datasets.map((d, i) => {
- if(datasets[i]) {
- d.values = datasets[i];
- }
- });
- this.update(this.data);
- }
-
- // updateDataPoint(dataPoint, index = 0) {}
- // addDataPoint(dataPoint, index = 0) {}
- // removeDataPoint(index = 0) {}
- }
-
- // import MultiAxisChart from './charts/MultiAxisChart';
- const chartTypes = {
- // multiaxis: MultiAxisChart,
- percentage: PercentageChart,
- heatmap: Heatmap,
- pie: PieChart
- };
-
- function getChartByType(chartType = 'line', parent, options) {
- if(chartType === 'line') {
- options.type = 'line';
- return new AxisChart(parent, options);
- } else if (chartType === 'bar') {
- options.type = 'bar';
- return new AxisChart(parent, options);
- } else if (chartType === 'axis-mixed') {
- options.type = 'line';
- return new AxisChart(parent, options);
- }
-
- if (!chartTypes[chartType]) {
- console.error("Undefined chart type: " + chartType);
- return;
- }
-
- return new chartTypes[chartType](parent, options);
- }
-
- class Chart {
- constructor(parent, options) {
- return getChartByType(options.type, parent, options);
- }
- }
-
- export { Chart, PercentageChart, PieChart, Heatmap, AxisChart };
|