uPlot.iife.js 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455
  1. /**
  2. * Copyright (c) 2020, Leon Sorokin
  3. * All rights reserved. (MIT Licensed)
  4. *
  5. * uPlot.js (μPlot)
  6. * A small, fast chart for time series, lines, areas, ohlc & bars
  7. * https://github.com/leeoniya/uPlot (v1.4.4)
  8. */
  9. var uPlot = (function () {
  10. 'use strict';
  11. function debounce(fn, time) {
  12. var pending = null;
  13. function run() {
  14. pending = null;
  15. fn();
  16. }
  17. return function() {
  18. clearTimeout(pending);
  19. pending = setTimeout(run, time);
  20. }
  21. }
  22. // binary search for index of closest value
  23. function closestIdx(num, arr, lo, hi) {
  24. var mid;
  25. lo = lo || 0;
  26. hi = hi || arr.length - 1;
  27. var bitwise = hi <= 2147483647;
  28. while (hi - lo > 1) {
  29. mid = bitwise ? (lo + hi) >> 1 : floor((lo + hi) / 2);
  30. if (arr[mid] < num)
  31. { lo = mid; }
  32. else
  33. { hi = mid; }
  34. }
  35. if (num - arr[lo] <= arr[hi] - num)
  36. { return lo; }
  37. return hi;
  38. }
  39. function getMinMax(data, _i0, _i1, sorted) {
  40. // console.log("getMinMax()");
  41. var _min = inf;
  42. var _max = -inf;
  43. if (sorted == 1) {
  44. _min = data[_i0];
  45. _max = data[_i1];
  46. }
  47. else if (sorted == -1) {
  48. _min = data[_i1];
  49. _max = data[_i0];
  50. }
  51. else {
  52. for (var i = _i0; i <= _i1; i++) {
  53. if (data[i] != null) {
  54. _min = min(_min, data[i]);
  55. _max = max(_max, data[i]);
  56. }
  57. }
  58. }
  59. return [_min, _max];
  60. }
  61. var _fixedTuple = [0, 0];
  62. function fixIncr(minIncr, maxIncr, minExp, maxExp) {
  63. _fixedTuple[0] = minExp < 0 ? roundDec(minIncr, -minExp) : minIncr;
  64. _fixedTuple[1] = maxExp < 0 ? roundDec(maxIncr, -maxExp) : maxIncr;
  65. return _fixedTuple;
  66. }
  67. function rangeLog(min, max, base, fullMags) {
  68. var logFn = base == 10 ? log10 : log2;
  69. if (min == max) {
  70. min /= base;
  71. max *= base;
  72. }
  73. var minExp, maxExp, minMaxIncrs;
  74. if (fullMags) {
  75. minExp = floor(logFn(min));
  76. maxExp = ceil(logFn(max));
  77. minMaxIncrs = fixIncr(pow(base, minExp), pow(base, maxExp), minExp, maxExp);
  78. min = minMaxIncrs[0];
  79. max = minMaxIncrs[1];
  80. }
  81. else {
  82. minExp = floor(logFn(min));
  83. maxExp = floor(logFn(max));
  84. minMaxIncrs = fixIncr(pow(base, minExp), pow(base, maxExp), minExp, maxExp);
  85. min = incrRoundDn(min, minMaxIncrs[0]);
  86. max = incrRoundUp(max, minMaxIncrs[1]);
  87. }
  88. return [min, max];
  89. }
  90. var _eqRangePart = {
  91. pad: 0,
  92. soft: null,
  93. mode: 0,
  94. };
  95. var _eqRange = {
  96. min: _eqRangePart,
  97. max: _eqRangePart,
  98. };
  99. // this ensures that non-temporal/numeric y-axes get multiple-snapped padding added above/below
  100. // TODO: also account for incrs when snapping to ensure top of axis gets a tick & value
  101. function rangeNum(_min, _max, mult, extra) {
  102. if (isObj(mult))
  103. { return _rangeNum(_min, _max, mult); }
  104. _eqRangePart.pad = mult;
  105. _eqRangePart.soft = extra ? 0 : null;
  106. _eqRangePart.mode = extra ? 2 : 0;
  107. return _rangeNum(_min, _max, _eqRange);
  108. }
  109. // nullish coalesce
  110. function ifNull(lh, rh) {
  111. return lh == null ? rh : lh;
  112. }
  113. function _rangeNum(_min, _max, cfg) {
  114. var cmin = cfg.min;
  115. var cmax = cfg.max;
  116. var padMin = ifNull(cmin.pad, 0);
  117. var padMax = ifNull(cmax.pad, 0);
  118. var hardMin = ifNull(cmin.hard, -inf);
  119. var hardMax = ifNull(cmax.hard, inf);
  120. var softMin = ifNull(cmin.soft, inf);
  121. var softMax = ifNull(cmax.soft, -inf);
  122. var softMinMode = ifNull(cmin.mode, 0);
  123. var softMaxMode = ifNull(cmax.mode, 0);
  124. var delta = _max - _min;
  125. var nonZeroDelta = delta || abs(_max) || 1e3;
  126. var mag = log10(nonZeroDelta);
  127. var base = pow(10, floor(mag));
  128. var _padMin = nonZeroDelta * (delta == 0 ? (_min == 0 ? .1 : 1) : padMin);
  129. var _newMin = roundDec(incrRoundDn(_min - _padMin, base/100), 6);
  130. var _softMin = _min >= softMin && (softMinMode == 1 || softMinMode == 2 && _newMin < softMin) ? softMin : inf;
  131. var minLim = max(hardMin, _newMin < _softMin && _min >= _softMin ? _softMin : min(_softMin, _newMin));
  132. var _padMax = nonZeroDelta * (delta == 0 ? (_max == 0 ? .1 : 1) : padMax);
  133. var _newMax = roundDec(incrRoundUp(_max + _padMax, base/100), 6);
  134. var _softMax = _max <= softMax && (softMaxMode == 1 || softMaxMode == 2 && _newMax > softMax) ? softMax : -inf;
  135. var maxLim = min(hardMax, _newMax > _softMax && _max <= _softMax ? _softMax : max(_softMax, _newMax));
  136. if (minLim == maxLim && minLim == 0)
  137. { maxLim = 100; }
  138. return [minLim, maxLim];
  139. }
  140. // alternative: https://stackoverflow.com/a/2254896
  141. var fmtNum = new Intl.NumberFormat(navigator.language).format;
  142. var M = Math;
  143. var abs = M.abs;
  144. var floor = M.floor;
  145. var round = M.round;
  146. var ceil = M.ceil;
  147. var min = M.min;
  148. var max = M.max;
  149. var pow = M.pow;
  150. var log10 = M.log10;
  151. var log2 = M.log2;
  152. var PI = M.PI;
  153. var inf = Infinity;
  154. function incrRound(num, incr) {
  155. return round(num/incr)*incr;
  156. }
  157. function clamp(num, _min, _max) {
  158. return min(max(num, _min), _max);
  159. }
  160. function fnOrSelf(v) {
  161. return typeof v == "function" ? v : function () { return v; };
  162. }
  163. function retArg1(_0, _1) {
  164. return _1;
  165. }
  166. function incrRoundUp(num, incr) {
  167. return ceil(num/incr)*incr;
  168. }
  169. function incrRoundDn(num, incr) {
  170. return floor(num/incr)*incr;
  171. }
  172. function roundDec(val, dec) {
  173. return round(val * (dec = Math.pow( 10, dec ))) / dec;
  174. }
  175. var fixedDec = new Map();
  176. function guessDec(num) {
  177. return ((""+num).split(".")[1] || "").length;
  178. }
  179. function genIncrs(base, minExp, maxExp, mults) {
  180. var incrs = [];
  181. var multDec = mults.map(guessDec);
  182. for (var exp = minExp; exp < maxExp; exp++) {
  183. var expa = abs(exp);
  184. var mag = roundDec(pow(base, exp), expa);
  185. for (var i = 0; i < mults.length; i++) {
  186. var _incr = mults[i] * mag;
  187. var dec = (_incr >= 0 && exp >= 0 ? 0 : expa) + (exp >= multDec[i] ? 0 : multDec[i]);
  188. var incr = roundDec(_incr, dec);
  189. incrs.push(incr);
  190. fixedDec.set(incr, dec);
  191. }
  192. }
  193. return incrs;
  194. }
  195. //export const assign = Object.assign;
  196. var EMPTY_OBJ = {};
  197. var isArr = Array.isArray;
  198. function isStr(v) {
  199. return typeof v === 'string';
  200. }
  201. function isObj(v) {
  202. return typeof v === 'object' && v !== null;
  203. }
  204. function copy(o) {
  205. var out;
  206. if (isArr(o))
  207. { out = o.map(copy); }
  208. else if (isObj(o)) {
  209. out = {};
  210. for (var k in o)
  211. { out[k] = copy(o[k]); }
  212. }
  213. else
  214. { out = o; }
  215. return out;
  216. }
  217. function assign(targ) {
  218. var args = arguments;
  219. for (var i = 1; i < args.length; i++) {
  220. var src = args[i];
  221. for (var key in src) {
  222. if (isObj(targ[key]))
  223. { assign(targ[key], copy(src[key])); }
  224. else
  225. { targ[key] = copy(src[key]); }
  226. }
  227. }
  228. return targ;
  229. }
  230. var microTask = typeof queueMicrotask == "undefined" ? function (fn) { return Promise.resolve().then(fn); } : queueMicrotask;
  231. var WIDTH = "width";
  232. var HEIGHT = "height";
  233. var TOP = "top";
  234. var BOTTOM = "bottom";
  235. var LEFT = "left";
  236. var RIGHT = "right";
  237. var firstChild = "firstChild";
  238. var createElement = "createElement";
  239. var hexBlack = "#000";
  240. var transparent = hexBlack + "0";
  241. var classList = "classList";
  242. var mousemove = "mousemove";
  243. var mousedown = "mousedown";
  244. var mouseup = "mouseup";
  245. var mouseenter = "mouseenter";
  246. var mouseleave = "mouseleave";
  247. var dblclick = "dblclick";
  248. var resize = "resize";
  249. var scroll = "scroll";
  250. var pre = "u-";
  251. var UPLOT = "uplot";
  252. var TITLE = pre + "title";
  253. var WRAP = pre + "wrap";
  254. var UNDER = pre + "under";
  255. var OVER = pre + "over";
  256. var OFF = pre + "off";
  257. var SELECT = pre + "select";
  258. var CURSOR_X = pre + "cursor-x";
  259. var CURSOR_Y = pre + "cursor-y";
  260. var CURSOR_PT = pre + "cursor-pt";
  261. var LEGEND = pre + "legend";
  262. var LEGEND_LIVE = pre + "live";
  263. var LEGEND_INLINE = pre + "inline";
  264. var LEGEND_THEAD = pre + "thead";
  265. var LEGEND_SERIES = pre + "series";
  266. var LEGEND_MARKER = pre + "marker";
  267. var LEGEND_LABEL = pre + "label";
  268. var LEGEND_VALUE = pre + "value";
  269. var rAF = requestAnimationFrame;
  270. var doc = document;
  271. var win = window;
  272. var pxRatio = devicePixelRatio;
  273. function addClass(el, c) {
  274. c != null && el[classList].add(c);
  275. }
  276. function remClass(el, c) {
  277. el[classList].remove(c);
  278. }
  279. function setStylePx(el, name, value) {
  280. el.style[name] = value + "px";
  281. }
  282. function placeTag(tag, cls, targ, refEl) {
  283. var el = doc[createElement](tag);
  284. if (cls != null)
  285. { addClass(el, cls); }
  286. if (targ != null)
  287. { targ.insertBefore(el, refEl); }
  288. return el;
  289. }
  290. function placeDiv(cls, targ) {
  291. return placeTag("div", cls, targ);
  292. }
  293. function trans(el, xPos, yPos, xMax, yMax) {
  294. el.style.transform = "translate(" + xPos + "px," + yPos + "px)";
  295. if (xPos < 0 || yPos < 0 || xPos > xMax || yPos > yMax)
  296. { addClass(el, OFF); }
  297. else
  298. { remClass(el, OFF); }
  299. }
  300. var evOpts = {passive: true};
  301. function on(ev, el, cb) {
  302. el.addEventListener(ev, cb, evOpts);
  303. }
  304. function off(ev, el, cb) {
  305. el.removeEventListener(ev, cb, evOpts);
  306. }
  307. var months = [
  308. "January",
  309. "February",
  310. "March",
  311. "April",
  312. "May",
  313. "June",
  314. "July",
  315. "August",
  316. "September",
  317. "October",
  318. "November",
  319. "December" ];
  320. var days = [
  321. "Sunday",
  322. "Monday",
  323. "Tuesday",
  324. "Wednesday",
  325. "Thursday",
  326. "Friday",
  327. "Saturday" ];
  328. function slice3(str) {
  329. return str.slice(0, 3);
  330. }
  331. var days3 = days.map(slice3);
  332. var months3 = months.map(slice3);
  333. var engNames = {
  334. MMMM: months,
  335. MMM: months3,
  336. WWWW: days,
  337. WWW: days3,
  338. };
  339. function zeroPad2(int) {
  340. return (int < 10 ? '0' : '') + int;
  341. }
  342. function zeroPad3(int) {
  343. return (int < 10 ? '00' : int < 100 ? '0' : '') + int;
  344. }
  345. /*
  346. function suffix(int) {
  347. let mod10 = int % 10;
  348. return int + (
  349. mod10 == 1 && int != 11 ? "st" :
  350. mod10 == 2 && int != 12 ? "nd" :
  351. mod10 == 3 && int != 13 ? "rd" : "th"
  352. );
  353. }
  354. */
  355. var getFullYear = 'getFullYear';
  356. var getMonth = 'getMonth';
  357. var getDate = 'getDate';
  358. var getDay = 'getDay';
  359. var getHours = 'getHours';
  360. var getMinutes = 'getMinutes';
  361. var getSeconds = 'getSeconds';
  362. var getMilliseconds = 'getMilliseconds';
  363. var subs = {
  364. // 2019
  365. YYYY: function (d) { return d[getFullYear](); },
  366. // 19
  367. YY: function (d) { return (d[getFullYear]()+'').slice(2); },
  368. // July
  369. MMMM: function (d, names) { return names.MMMM[d[getMonth]()]; },
  370. // Jul
  371. MMM: function (d, names) { return names.MMM[d[getMonth]()]; },
  372. // 07
  373. MM: function (d) { return zeroPad2(d[getMonth]()+1); },
  374. // 7
  375. M: function (d) { return d[getMonth]()+1; },
  376. // 09
  377. DD: function (d) { return zeroPad2(d[getDate]()); },
  378. // 9
  379. D: function (d) { return d[getDate](); },
  380. // Monday
  381. WWWW: function (d, names) { return names.WWWW[d[getDay]()]; },
  382. // Mon
  383. WWW: function (d, names) { return names.WWW[d[getDay]()]; },
  384. // 03
  385. HH: function (d) { return zeroPad2(d[getHours]()); },
  386. // 3
  387. H: function (d) { return d[getHours](); },
  388. // 9 (12hr, unpadded)
  389. h: function (d) {var h = d[getHours](); return h == 0 ? 12 : h > 12 ? h - 12 : h;},
  390. // AM
  391. AA: function (d) { return d[getHours]() >= 12 ? 'PM' : 'AM'; },
  392. // am
  393. aa: function (d) { return d[getHours]() >= 12 ? 'pm' : 'am'; },
  394. // a
  395. a: function (d) { return d[getHours]() >= 12 ? 'p' : 'a'; },
  396. // 09
  397. mm: function (d) { return zeroPad2(d[getMinutes]()); },
  398. // 9
  399. m: function (d) { return d[getMinutes](); },
  400. // 09
  401. ss: function (d) { return zeroPad2(d[getSeconds]()); },
  402. // 9
  403. s: function (d) { return d[getSeconds](); },
  404. // 374
  405. fff: function (d) { return zeroPad3(d[getMilliseconds]()); },
  406. };
  407. function fmtDate(tpl, names) {
  408. names = names || engNames;
  409. var parts = [];
  410. var R = /\{([a-z]+)\}|[^{]+/gi, m;
  411. while (m = R.exec(tpl))
  412. { parts.push(m[0][0] == '{' ? subs[m[1]] : m[0]); }
  413. return function (d) {
  414. var out = '';
  415. for (var i = 0; i < parts.length; i++)
  416. { out += typeof parts[i] == "string" ? parts[i] : parts[i](d, names); }
  417. return out;
  418. }
  419. }
  420. var localTz = new Intl.DateTimeFormat().resolvedOptions().timeZone;
  421. // https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone/53652131#53652131
  422. function tzDate(date, tz) {
  423. var date2;
  424. // perf optimization
  425. if (tz == 'Etc/UTC')
  426. { date2 = new Date(+date + date.getTimezoneOffset() * 6e4); }
  427. else if (tz == localTz)
  428. { date2 = date; }
  429. else {
  430. date2 = new Date(date.toLocaleString('en-US', {timeZone: tz}));
  431. date2.setMilliseconds(date[getMilliseconds]());
  432. }
  433. return date2;
  434. }
  435. //export const series = [];
  436. // default formatters:
  437. var onlyWhole = function (v) { return v % 1 == 0; };
  438. var allMults = [1,2,2.5,5];
  439. var wholeMults = allMults.filter(onlyWhole);
  440. // ...0.01, 0.02, 0.025, 0.05, 0.1, 0.2, 0.25, 0.5
  441. var decIncrs = genIncrs(10, -16, 0, allMults);
  442. // 1, 2, 2.5, 5, 10, 20, 25, 50...
  443. var oneIncrs = genIncrs(10, 0, 16, allMults);
  444. // 1, 2, 5, 10, 20, 25, 50...
  445. var wholeIncrs = oneIncrs.filter(onlyWhole);
  446. var numIncrs = decIncrs.concat(oneIncrs);
  447. var s = 1,
  448. m = 60,
  449. h = m * m,
  450. d = h * 24,
  451. mo = d * 30,
  452. y = d * 365;
  453. // min of 1e-3 prevents setting a temporal x ticks too small since Date objects cannot advance ticks smaller than 1ms
  454. var timeIncrs = genIncrs(10, -3, 0, wholeMults).concat([
  455. // minute divisors (# of secs)
  456. 1,
  457. 5,
  458. 10,
  459. 15,
  460. 30,
  461. // hour divisors (# of mins)
  462. m,
  463. m * 5,
  464. m * 10,
  465. m * 15,
  466. m * 30,
  467. // day divisors (# of hrs)
  468. h,
  469. h * 2,
  470. h * 3,
  471. h * 4,
  472. h * 6,
  473. h * 8,
  474. h * 12,
  475. // month divisors TODO: need more?
  476. d,
  477. d * 2,
  478. d * 3,
  479. d * 4,
  480. d * 5,
  481. d * 6,
  482. d * 7,
  483. d * 8,
  484. d * 9,
  485. d * 10,
  486. d * 15,
  487. // year divisors (# months, approx)
  488. mo,
  489. mo * 2,
  490. mo * 3,
  491. mo * 4,
  492. mo * 6,
  493. // century divisors
  494. y,
  495. y * 2,
  496. y * 5,
  497. y * 10,
  498. y * 25,
  499. y * 50,
  500. y * 100 ]);
  501. // base 2
  502. var binIncrs = genIncrs(2, -53, 53, [1]);
  503. /*
  504. console.log({
  505. decIncrs,
  506. oneIncrs,
  507. wholeIncrs,
  508. numIncrs,
  509. timeIncrs,
  510. fixedDec,
  511. });
  512. */
  513. function timeAxisStamps(stampCfg, fmtDate) {
  514. return stampCfg.map(function (s) { return s.map(function (v, i) { return i == 0 || i == 8 || v == null ? v : fmtDate(i == 1 || s[8] == 0 ? v : s[1] + v); }
  515. ); });
  516. }
  517. var NL = "\n";
  518. var yyyy = "{YYYY}";
  519. var NLyyyy = NL + yyyy;
  520. var md = "{M}/{D}";
  521. var NLmd = NL + md;
  522. var NLmdyy = NLmd + "/{YY}";
  523. var aa = "{aa}";
  524. var hmm = "{h}:{mm}";
  525. var hmmaa = hmm + aa;
  526. var NLhmmaa = NL + hmmaa;
  527. var ss = ":{ss}";
  528. var _ = null;
  529. // [0]: minimum num secs in the tick incr
  530. // [1]: default tick format
  531. // [2-7]: rollover tick formats
  532. // [8]: mode: 0: replace [1] -> [2-7], 1: concat [1] + [2-7]
  533. var _timeAxisStamps = [
  534. // tick incr default year month day hour min sec mode
  535. [y, yyyy, _, _, _, _, _, _, 1],
  536. [d * 28, "{MMM}", NLyyyy, _, _, _, _, _, 1],
  537. [d, md, NLyyyy, _, _, _, _, _, 1],
  538. [h, "{h}" + aa, NLmdyy, _, NLmd, _, _, _, 1],
  539. [m, hmmaa, NLmdyy, _, NLmd, _, _, _, 1],
  540. [s, ss, NLmdyy + " " + hmmaa, _, NLmd + " " + hmmaa, _, NLhmmaa, _, 1],
  541. [1e-3, ss + ".{fff}", NLmdyy + " " + hmmaa, _, NLmd + " " + hmmaa, _, NLhmmaa, _, 1] ];
  542. // TODO: will need to accept spaces[] and pull incr into the loop when grid will be non-uniform, eg for log scales.
  543. // currently we ignore this for months since they're *nearly* uniform and the added complexity is not worth it
  544. function timeAxisVals(tzDate, stamps) {
  545. return function (self, splits, axisIdx, foundSpace, foundIncr) {
  546. var s = stamps.find(function (s) { return foundIncr >= s[0]; }) || stamps[stamps.length - 1];
  547. // these track boundaries when a full label is needed again
  548. var prevYear;
  549. var prevMnth;
  550. var prevDate;
  551. var prevHour;
  552. var prevMins;
  553. var prevSecs;
  554. return splits.map(function (split) {
  555. var date = tzDate(split);
  556. var newYear = date[getFullYear]();
  557. var newMnth = date[getMonth]();
  558. var newDate = date[getDate]();
  559. var newHour = date[getHours]();
  560. var newMins = date[getMinutes]();
  561. var newSecs = date[getSeconds]();
  562. var stamp = (
  563. newYear != prevYear && s[2] ||
  564. newMnth != prevMnth && s[3] ||
  565. newDate != prevDate && s[4] ||
  566. newHour != prevHour && s[5] ||
  567. newMins != prevMins && s[6] ||
  568. newSecs != prevSecs && s[7] ||
  569. s[1]
  570. );
  571. prevYear = newYear;
  572. prevMnth = newMnth;
  573. prevDate = newDate;
  574. prevHour = newHour;
  575. prevMins = newMins;
  576. prevSecs = newSecs;
  577. return stamp(date);
  578. });
  579. }
  580. }
  581. // for when axis.values is defined as a static fmtDate template string
  582. function timeAxisVal(tzDate, dateTpl) {
  583. var stamp = fmtDate(dateTpl);
  584. return function (self, splits, axisIdx, foundSpace, foundIncr) { return splits.map(function (split) { return stamp(tzDate(split)); }); };
  585. }
  586. function mkDate(y, m, d) {
  587. return new Date(y, m, d);
  588. }
  589. // the ensures that axis ticks, values & grid are aligned to logical temporal breakpoints and not an arbitrary timestamp
  590. // https://www.timeanddate.com/time/dst/
  591. // https://www.timeanddate.com/time/dst/2019.html
  592. // https://www.epochconverter.com/timezones
  593. function timeAxisSplits(tzDate) {
  594. return function (self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace) {
  595. var splits = [];
  596. var isYr = foundIncr >= y;
  597. var isMo = foundIncr >= mo && foundIncr < y;
  598. // get the timezone-adjusted date
  599. var minDate = tzDate(scaleMin);
  600. var minDateTs = minDate / 1e3;
  601. // get ts of 12am (this lands us at or before the original scaleMin)
  602. var minMin = mkDate(minDate[getFullYear](), isYr ? 0 : minDate[getMonth](), isMo || isYr ? 1 : minDate[getDate]());
  603. var minMinTs = minMin / 1e3;
  604. if (isMo || isYr) {
  605. var moIncr = isMo ? foundIncr / mo : 0;
  606. var yrIncr = isYr ? foundIncr / y : 0;
  607. // let tzOffset = scaleMin - minDateTs; // needed?
  608. var split = minDateTs == minMinTs ? minDateTs : mkDate(minMin[getFullYear]() + yrIncr, minMin[getMonth]() + moIncr, 1) / 1e3;
  609. var splitDate = new Date(split * 1e3);
  610. var baseYear = splitDate[getFullYear]();
  611. var baseMonth = splitDate[getMonth]();
  612. for (var i = 0; split <= scaleMax; i++) {
  613. var next = mkDate(baseYear + yrIncr * i, baseMonth + moIncr * i, 1);
  614. var offs = next - tzDate(next / 1e3);
  615. split = (+next + offs) / 1e3;
  616. if (split <= scaleMax)
  617. { splits.push(split); }
  618. }
  619. }
  620. else {
  621. var incr0 = foundIncr >= d ? d : foundIncr;
  622. var tzOffset = floor(scaleMin) - floor(minDateTs);
  623. var split$1 = minMinTs + tzOffset + incrRoundUp(minDateTs - minMinTs, incr0);
  624. splits.push(split$1);
  625. var date0 = tzDate(split$1);
  626. var prevHour = date0[getHours]() + (date0[getMinutes]() / m) + (date0[getSeconds]() / h);
  627. var incrHours = foundIncr / h;
  628. var minSpace = self.axes[axisIdx]._space;
  629. var pctSpace = foundSpace / minSpace;
  630. while (1) {
  631. split$1 = roundDec(split$1 + foundIncr, 3);
  632. if (split$1 > scaleMax)
  633. { break; }
  634. if (incrHours > 1) {
  635. var expectedHour = floor(roundDec(prevHour + incrHours, 6)) % 24;
  636. var splitDate$1 = tzDate(split$1);
  637. var actualHour = splitDate$1.getHours();
  638. var dstShift = actualHour - expectedHour;
  639. if (dstShift > 1)
  640. { dstShift = -1; }
  641. split$1 -= dstShift * h;
  642. prevHour = (prevHour + incrHours) % 24;
  643. // add a tick only if it's further than 70% of the min allowed label spacing
  644. var prevSplit = splits[splits.length - 1];
  645. var pctIncr = roundDec((split$1 - prevSplit) / foundIncr, 3);
  646. if (pctIncr * pctSpace >= .7)
  647. { splits.push(split$1); }
  648. }
  649. else
  650. { splits.push(split$1); }
  651. }
  652. }
  653. return splits;
  654. }
  655. }
  656. function timeSeriesStamp(stampCfg, fmtDate) {
  657. return fmtDate(stampCfg);
  658. }
  659. var _timeSeriesStamp = '{YYYY}-{MM}-{DD} {h}:{mm}{aa}';
  660. function timeSeriesVal(tzDate, stamp) {
  661. return function (self, val) { return stamp(tzDate(val)); };
  662. }
  663. function cursorPoint(self, si) {
  664. var s = self.series[si];
  665. var pt = placeDiv();
  666. pt.style.background = s.stroke || hexBlack;
  667. var dia = ptDia(s.width, 1);
  668. var mar = (dia - 1) / -2;
  669. setStylePx(pt, WIDTH, dia);
  670. setStylePx(pt, HEIGHT, dia);
  671. setStylePx(pt, "marginLeft", mar);
  672. setStylePx(pt, "marginTop", mar);
  673. return pt;
  674. }
  675. function dataIdx(self, seriesIdx, cursorIdx) {
  676. return cursorIdx;
  677. }
  678. var moveTuple = [0,0];
  679. function cursorMove(self, mouseLeft1, mouseTop1) {
  680. moveTuple[0] = mouseLeft1;
  681. moveTuple[1] = mouseTop1;
  682. return moveTuple;
  683. }
  684. function filtBtn0(self, targ, handle) {
  685. return function (e) {
  686. e.button == 0 && handle(e);
  687. };
  688. }
  689. function passThru(self, targ, handle) {
  690. return handle;
  691. }
  692. var cursorOpts = {
  693. show: true,
  694. x: true,
  695. y: true,
  696. lock: false,
  697. move: cursorMove,
  698. points: {
  699. show: cursorPoint,
  700. },
  701. bind: {
  702. mousedown: filtBtn0,
  703. mouseup: filtBtn0,
  704. click: filtBtn0,
  705. dblclick: filtBtn0,
  706. mousemove: passThru,
  707. mouseleave: passThru,
  708. mouseenter: passThru,
  709. },
  710. drag: {
  711. setScale: true,
  712. x: true,
  713. y: false,
  714. dist: 0,
  715. uni: null,
  716. _x: false,
  717. _y: false,
  718. },
  719. focus: {
  720. prox: -1,
  721. },
  722. left: -10,
  723. top: -10,
  724. idx: null,
  725. dataIdx: dataIdx,
  726. };
  727. var grid = {
  728. show: true,
  729. stroke: "rgba(0,0,0,0.07)",
  730. width: 2,
  731. // dash: [],
  732. filter: retArg1,
  733. };
  734. var ticks = assign({}, grid, {size: 10});
  735. var font = '12px system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"';
  736. var labelFont = "bold " + font;
  737. var lineMult = 1.5; // font-size multiplier
  738. var xAxisOpts = {
  739. show: true,
  740. scale: "x",
  741. space: 50,
  742. gap: 5,
  743. size: 50,
  744. labelSize: 30,
  745. labelFont: labelFont,
  746. side: 2,
  747. // class: "x-vals",
  748. // incrs: timeIncrs,
  749. // values: timeVals,
  750. // filter: retArg1,
  751. grid: grid,
  752. ticks: ticks,
  753. font: font,
  754. rotate: 0,
  755. };
  756. var numSeriesLabel = "Value";
  757. var timeSeriesLabel = "Time";
  758. var xSeriesOpts = {
  759. show: true,
  760. scale: "x",
  761. auto: false,
  762. sorted: 1,
  763. // label: "Time",
  764. // value: v => stamp(new Date(v * 1e3)),
  765. // internal caches
  766. min: inf,
  767. max: -inf,
  768. idxs: [],
  769. };
  770. function numAxisVals(self, splits, axisIdx, foundSpace, foundIncr) {
  771. return splits.map(function (v) { return v == null ? "" : fmtNum(v); });
  772. }
  773. function numAxisSplits(self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace, forceMin) {
  774. var splits = [];
  775. var numDec = fixedDec.get(foundIncr) || 0;
  776. scaleMin = forceMin ? scaleMin : roundDec(incrRoundUp(scaleMin, foundIncr), numDec);
  777. for (var val = scaleMin; val <= scaleMax; val = roundDec(val + foundIncr, numDec))
  778. { splits.push(Object.is(val, -0) ? 0 : val); } // coalesces -0
  779. return splits;
  780. }
  781. function logAxisSplits(self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace, forceMin) {
  782. var splits = [];
  783. var logBase = self.scales[self.axes[axisIdx].scale].log;
  784. var logFn = logBase == 10 ? log10 : log2;
  785. var exp = floor(logFn(scaleMin));
  786. foundIncr = pow(logBase, exp);
  787. if (exp < 0)
  788. { foundIncr = roundDec(foundIncr, -exp); }
  789. var split = scaleMin;
  790. do {
  791. splits.push(split);
  792. split = roundDec(split + foundIncr, fixedDec.get(foundIncr));
  793. if (split >= foundIncr * logBase)
  794. { foundIncr = split; }
  795. } while (split <= scaleMax);
  796. return splits;
  797. }
  798. var RE_ALL = /./;
  799. var RE_12357 = /[12357]/;
  800. var RE_125 = /[125]/;
  801. var RE_1 = /1/;
  802. function logAxisValsFilt(self, splits, axisIdx, foundSpace, foundIncr) {
  803. var axis = self.axes[axisIdx];
  804. var scaleKey = axis.scale;
  805. if (self.scales[scaleKey].log == 2)
  806. { return splits; }
  807. var valToPos = self.valToPos;
  808. var minSpace = axis._space;
  809. var _10 = valToPos(10, scaleKey);
  810. var re = (
  811. valToPos(9, scaleKey) - _10 >= minSpace ? RE_ALL :
  812. valToPos(7, scaleKey) - _10 >= minSpace ? RE_12357 :
  813. valToPos(5, scaleKey) - _10 >= minSpace ? RE_125 :
  814. RE_1
  815. );
  816. return splits.map(function (v) { return re.test(v) ? v : null; });
  817. }
  818. function numSeriesVal(self, val) {
  819. return val == null ? "" : fmtNum(val);
  820. }
  821. var yAxisOpts = {
  822. show: true,
  823. scale: "y",
  824. space: 30,
  825. gap: 5,
  826. size: 50,
  827. labelSize: 30,
  828. labelFont: labelFont,
  829. side: 3,
  830. // class: "y-vals",
  831. // incrs: numIncrs,
  832. // values: (vals, space) => vals,
  833. // filter: retArg1,
  834. grid: grid,
  835. ticks: ticks,
  836. font: font,
  837. rotate: 0,
  838. };
  839. // takes stroke width
  840. function ptDia(width, mult) {
  841. var dia = 3 + (width || 1) * 2;
  842. return roundDec(dia * mult, 3);
  843. }
  844. function seriesPoints(self, si) {
  845. var s = self.series[si];
  846. var dia = ptDia(s.width, pxRatio);
  847. var maxPts = self.bbox.width / (s.points.space * pxRatio);
  848. var idxs = self.series[0].idxs;
  849. return idxs[1] - idxs[0] <= maxPts;
  850. }
  851. function seriesFillTo(self, seriesIdx, dataMin, dataMax) {
  852. var scale = self.scales[self.series[seriesIdx].scale];
  853. return scale.distr == 3 ? scale.min : 0;
  854. }
  855. var ySeriesOpts = {
  856. scale: "y",
  857. auto: true,
  858. sorted: 0,
  859. show: true,
  860. band: false,
  861. spanGaps: false,
  862. isGap: function (self, seriesIdx, dataIdx) { return true; },
  863. alpha: 1,
  864. points: {
  865. show: seriesPoints,
  866. // stroke: "#000",
  867. // fill: "#fff",
  868. // width: 1,
  869. // size: 10,
  870. },
  871. // label: "Value",
  872. // value: v => v,
  873. values: null,
  874. // internal caches
  875. min: inf,
  876. max: -inf,
  877. idxs: [],
  878. path: null,
  879. clip: null,
  880. };
  881. var xScaleOpts = {
  882. time: true,
  883. auto: true,
  884. distr: 1,
  885. log: 10,
  886. min: null,
  887. max: null,
  888. };
  889. var yScaleOpts = assign({}, xScaleOpts, {
  890. time: false,
  891. });
  892. var syncs = {};
  893. function _sync(opts) {
  894. var clients = [];
  895. return {
  896. sub: function sub(client) {
  897. clients.push(client);
  898. },
  899. unsub: function unsub(client) {
  900. clients = clients.filter(function (c) { return c != client; });
  901. },
  902. pub: function pub(type, self, x, y, w, h, i) {
  903. if (clients.length > 1) {
  904. clients.forEach(function (client) {
  905. client != self && client.pub(type, self, x, y, w, h, i);
  906. });
  907. }
  908. }
  909. };
  910. }
  911. function setDefaults(d, xo, yo, initY) {
  912. var d2 = initY ? [d[0], d[1]].concat(d.slice(2)) : [d[0]].concat(d.slice(1));
  913. return d2.map(function (o, i) { return setDefault(o, i, xo, yo); });
  914. }
  915. function setDefault(o, i, xo, yo) {
  916. return assign({}, (i == 0 || o && o.side % 2 == 0 ? xo : yo), o);
  917. }
  918. function getValPct(val, scale) {
  919. return (
  920. scale.distr == 3
  921. ? log10(val / scale.min) / log10(scale.max / scale.min)
  922. : (val - scale.min) / (scale.max - scale.min)
  923. );
  924. }
  925. function getYPos(val, scale, hgt, top) {
  926. var pctY = getValPct(val, scale);
  927. return top + (1 - pctY) * hgt;
  928. }
  929. function getXPos(val, scale, wid, lft) {
  930. var pctX = getValPct(val, scale);
  931. return lft + pctX * wid;
  932. }
  933. var nullMinMax = [null, null];
  934. function snapNumX(self, dataMin, dataMax) {
  935. return dataMin == null ? nullMinMax : [dataMin, dataMax];
  936. }
  937. var snapTimeX = snapNumX;
  938. // this ensures that non-temporal/numeric y-axes get multiple-snapped padding added above/below
  939. // TODO: also account for incrs when snapping to ensure top of axis gets a tick & value
  940. function snapNumY(self, dataMin, dataMax) {
  941. return dataMin == null ? nullMinMax : rangeNum(dataMin, dataMax, 0.1, true);
  942. }
  943. function snapLogY(self, dataMin, dataMax, scale) {
  944. return dataMin == null ? nullMinMax : rangeLog(dataMin, dataMax, self.scales[scale].log, false);
  945. }
  946. var snapLogX = snapLogY;
  947. // dim is logical (getClientBoundingRect) pixels, not canvas pixels
  948. function findIncr(min, max, incrs, dim, minSpace) {
  949. var pxPerUnit = dim / (max - min);
  950. var minDec = (""+floor(min)).length;
  951. for (var i = 0; i < incrs.length; i++) {
  952. var space = incrs[i] * pxPerUnit;
  953. var incrDec = incrs[i] < 10 ? fixedDec.get(incrs[i]) : 0;
  954. if (space >= minSpace && minDec + incrDec < 17)
  955. { return [incrs[i], space]; }
  956. }
  957. return [0, 0];
  958. }
  959. function pxRatioFont(font) {
  960. var fontSize;
  961. font = font.replace(/(\d+)px/, function (m, p1) { return (fontSize = round(p1 * pxRatio)) + 'px'; });
  962. return [font, fontSize];
  963. }
  964. function uPlot(opts, data, then) {
  965. var self = {};
  966. var ready = false;
  967. self.status = 0;
  968. var root = self.root = placeDiv(UPLOT);
  969. if (opts.id != null)
  970. { root.id = opts.id; }
  971. addClass(root, opts.class);
  972. if (opts.title) {
  973. var title = placeDiv(TITLE, root);
  974. title.textContent = opts.title;
  975. }
  976. var can = placeTag("canvas");
  977. var ctx = self.ctx = can.getContext("2d");
  978. var wrap = placeDiv(WRAP, root);
  979. var under = placeDiv(UNDER, wrap);
  980. wrap.appendChild(can);
  981. var over = placeDiv(OVER, wrap);
  982. opts = copy(opts);
  983. (opts.plugins || []).forEach(function (p) {
  984. if (p.opts)
  985. { opts = p.opts(self, opts) || opts; }
  986. });
  987. var series = self.series = setDefaults(opts.series || [], xSeriesOpts, ySeriesOpts, false);
  988. var axes = self.axes = setDefaults(opts.axes || [], xAxisOpts, yAxisOpts, true);
  989. var scales = self.scales = {};
  990. var xScaleKey = series[0].scale;
  991. function initScale(scaleKey) {
  992. var sc = scales[scaleKey];
  993. if (sc == null) {
  994. var scaleOpts = (opts.scales || EMPTY_OBJ)[scaleKey] || EMPTY_OBJ;
  995. if (scaleOpts.from != null) {
  996. // ensure parent is initialized
  997. initScale(scaleOpts.from);
  998. // dependent scales inherit
  999. scales[scaleKey] = assign({}, scales[scaleOpts.from], scaleOpts);
  1000. }
  1001. else {
  1002. sc = scales[scaleKey] = assign({}, (scaleKey == xScaleKey ? xScaleOpts : yScaleOpts), scaleOpts);
  1003. var isTime = sc.time;
  1004. var isLog = sc.distr == 3;
  1005. var rn = sc.range;
  1006. if (scaleKey != xScaleKey && !isArr(rn) && isObj(rn)) {
  1007. var cfg = rn;
  1008. // this is similar to snapNumY
  1009. rn = function (self, dataMin, dataMax) { return dataMin == null ? nullMinMax : rangeNum(dataMin, dataMax, cfg); };
  1010. }
  1011. sc.range = fnOrSelf(rn || (isTime ? snapTimeX : scaleKey == xScaleKey ? (isLog ? snapLogX : snapNumX) : (isLog ? snapLogY : snapNumY)));
  1012. sc.auto = fnOrSelf(sc.auto);
  1013. }
  1014. }
  1015. }
  1016. initScale("x");
  1017. initScale("y");
  1018. series.forEach(function (s, i) {
  1019. initScale(s.scale);
  1020. });
  1021. for (var k in opts.scales)
  1022. { initScale(k); }
  1023. var xScaleDistr = scales[xScaleKey].distr;
  1024. var pendScales = {};
  1025. // explicitly-set initial scales
  1026. for (var k$1 in scales) {
  1027. var sc = scales[k$1];
  1028. if (sc.min != null || sc.max != null)
  1029. { pendScales[k$1] = {min: sc.min, max: sc.max}; }
  1030. }
  1031. var gutters = self.gutters = assign({
  1032. x: round(yAxisOpts.size / 2),
  1033. y: round(xAxisOpts.size / 3),
  1034. _x: null,
  1035. _y: null,
  1036. }, opts.gutters);
  1037. gutters.x = fnOrSelf(gutters.x);
  1038. gutters.y = fnOrSelf(gutters.y);
  1039. gutters._x = gutters.x(self);
  1040. gutters._y = gutters.y(self);
  1041. // self.tz = opts.tz || Intl.DateTimeFormat().resolvedOptions().timeZone;
  1042. var _tzDate = (opts.tzDate || (function (ts) { return new Date(ts * 1e3); }));
  1043. var _fmtDate = (opts.fmtDate || fmtDate);
  1044. var _timeAxisSplits = timeAxisSplits(_tzDate);
  1045. var _timeAxisVals = timeAxisVals(_tzDate, timeAxisStamps(_timeAxisStamps, _fmtDate));
  1046. var _timeSeriesVal = timeSeriesVal(_tzDate, timeSeriesStamp(_timeSeriesStamp, _fmtDate));
  1047. var legend = assign({show: true, live: true}, opts.legend);
  1048. var showLegend = legend.show;
  1049. var legendEl;
  1050. var legendRows = [];
  1051. var legendCols;
  1052. var multiValLegend = false;
  1053. if (showLegend) {
  1054. legendEl = placeTag("table", LEGEND, root);
  1055. var getMultiVals = series[1] ? series[1].values : null;
  1056. multiValLegend = getMultiVals != null;
  1057. if (multiValLegend) {
  1058. var head = placeTag("tr", LEGEND_THEAD, legendEl);
  1059. placeTag("th", null, head);
  1060. legendCols = getMultiVals(self, 1, 0);
  1061. for (var key in legendCols)
  1062. { placeTag("th", LEGEND_LABEL, head).textContent = key; }
  1063. }
  1064. else {
  1065. legendCols = {_: 0};
  1066. addClass(legendEl, LEGEND_INLINE);
  1067. legend.live && addClass(legendEl, LEGEND_LIVE);
  1068. }
  1069. }
  1070. function initLegendRow(s, i) {
  1071. if (i == 0 && (multiValLegend || !legend.live))
  1072. { return null; }
  1073. var _row = [];
  1074. var row = placeTag("tr", LEGEND_SERIES, legendEl, legendEl.childNodes[i]);
  1075. addClass(row, s.class);
  1076. if (!s.show)
  1077. { addClass(row, OFF); }
  1078. var label = placeTag("th", null, row);
  1079. var indic = placeDiv(LEGEND_MARKER, label);
  1080. indic.style.borderColor = s.width ? s.stroke : i > 0 && s.points.width ? s.points.stroke : null;
  1081. indic.style.backgroundColor = s.fill || null;
  1082. var text = placeDiv(LEGEND_LABEL, label);
  1083. text.textContent = s.label;
  1084. if (i > 0) {
  1085. onMouse("click", label, function (e) {
  1086. if ( cursor._lock)
  1087. { return; }
  1088. setSeries(series.indexOf(s), {show: !s.show}, syncOpts.setSeries);
  1089. });
  1090. if (cursorFocus) {
  1091. onMouse(mouseenter, label, function (e) {
  1092. if (cursor._lock)
  1093. { return; }
  1094. setSeries(series.indexOf(s), {focus: true}, syncOpts.setSeries);
  1095. });
  1096. }
  1097. }
  1098. for (var key in legendCols) {
  1099. var v = placeTag("td", LEGEND_VALUE, row);
  1100. v.textContent = "--";
  1101. _row.push(v);
  1102. }
  1103. return _row;
  1104. }
  1105. var mouseListeners = new Map();
  1106. function onMouse(ev, targ, fn) {
  1107. var targListeners = mouseListeners.get(targ) || {};
  1108. var listener = cursor.bind[ev](self, targ, fn);
  1109. if (listener) {
  1110. on(ev, targ, targListeners[ev] = listener);
  1111. mouseListeners.set(targ, targListeners);
  1112. }
  1113. }
  1114. function offMouse(ev, targ, fn) {
  1115. var targListeners = mouseListeners.get(targ) || {};
  1116. off(ev, targ, targListeners[ev]);
  1117. targListeners[ev] = null;
  1118. }
  1119. var fullWidCss = 0;
  1120. var fullHgtCss = 0;
  1121. var plotWidCss = 0;
  1122. var plotHgtCss = 0;
  1123. // plot margins to account for axes
  1124. var plotLftCss = 0;
  1125. var plotTopCss = 0;
  1126. var plotLft = 0;
  1127. var plotTop = 0;
  1128. var plotWid = 0;
  1129. var plotHgt = 0;
  1130. self.bbox = {};
  1131. var shouldSetScales = false;
  1132. var shouldSetSize = false;
  1133. var shouldConvergeSize = false;
  1134. var shouldSetCursor = false;
  1135. var shouldSetLegend = false;
  1136. function _setSize(width, height) {
  1137. if (width != self.width || height != self.height)
  1138. { calcSize(width, height); }
  1139. resetYSeries(false);
  1140. shouldConvergeSize = true;
  1141. shouldSetSize = true;
  1142. shouldSetCursor = true;
  1143. shouldSetLegend = true;
  1144. commit();
  1145. }
  1146. function calcSize(width, height) {
  1147. // log("calcSize()", arguments);
  1148. self.width = fullWidCss = plotWidCss = width;
  1149. self.height = fullHgtCss = plotHgtCss = height;
  1150. plotLftCss = plotTopCss = 0;
  1151. calcPlotRect();
  1152. calcAxesRects();
  1153. var bb = self.bbox;
  1154. plotLft = bb[LEFT] = incrRound(plotLftCss * pxRatio, 0.5);
  1155. plotTop = bb[TOP] = incrRound(plotTopCss * pxRatio, 0.5);
  1156. plotWid = bb[WIDTH] = incrRound(plotWidCss * pxRatio, 0.5);
  1157. plotHgt = bb[HEIGHT] = incrRound(plotHgtCss * pxRatio, 0.5);
  1158. }
  1159. function convergeSize() {
  1160. var converged = false;
  1161. while (!converged) {
  1162. var axesConverged = axesCalc();
  1163. var guttersConverged = guttersCalc();
  1164. converged = axesConverged && guttersConverged;
  1165. if (!converged) {
  1166. calcSize(self.width, self.height);
  1167. shouldSetSize = true;
  1168. }
  1169. }
  1170. }
  1171. function setSize(ref) {
  1172. var width = ref.width;
  1173. var height = ref.height;
  1174. _setSize(width, height);
  1175. }
  1176. self.setSize = setSize;
  1177. // accumulate axis offsets, reduce canvas width
  1178. function calcPlotRect() {
  1179. // easements for edge labels
  1180. var hasTopAxis = false;
  1181. var hasBtmAxis = false;
  1182. var hasRgtAxis = false;
  1183. var hasLftAxis = false;
  1184. axes.forEach(function (axis, i) {
  1185. if (axis.show && axis._show) {
  1186. var side = axis.side;
  1187. var _size = axis._size;
  1188. var isVt = side % 2;
  1189. var labelSize = axis.labelSize = (axis.label != null ? (axis.labelSize || 30) : 0);
  1190. var fullSize = _size + labelSize;
  1191. if (fullSize > 0) {
  1192. if (isVt) {
  1193. plotWidCss -= fullSize;
  1194. if (side == 3) {
  1195. plotLftCss += fullSize;
  1196. hasLftAxis = true;
  1197. }
  1198. else
  1199. { hasRgtAxis = true; }
  1200. }
  1201. else {
  1202. plotHgtCss -= fullSize;
  1203. if (side == 0) {
  1204. plotTopCss += fullSize;
  1205. hasTopAxis = true;
  1206. }
  1207. else
  1208. { hasBtmAxis = true; }
  1209. }
  1210. }
  1211. }
  1212. });
  1213. // hz gutters
  1214. if (hasTopAxis || hasBtmAxis) {
  1215. if (!hasRgtAxis)
  1216. { plotWidCss -= gutters._x; }
  1217. if (!hasLftAxis) {
  1218. plotWidCss -= gutters._x;
  1219. plotLftCss += gutters._x;
  1220. }
  1221. }
  1222. // vt gutters
  1223. if (hasLftAxis || hasRgtAxis) {
  1224. if (!hasBtmAxis)
  1225. { plotHgtCss -= gutters._y; }
  1226. if (!hasTopAxis) {
  1227. plotHgtCss -= gutters._y;
  1228. plotTopCss += gutters._y;
  1229. }
  1230. }
  1231. }
  1232. function calcAxesRects() {
  1233. // will accum +
  1234. var off1 = plotLftCss + plotWidCss;
  1235. var off2 = plotTopCss + plotHgtCss;
  1236. // will accum -
  1237. var off3 = plotLftCss;
  1238. var off0 = plotTopCss;
  1239. function incrOffset(side, size) {
  1240. switch (side) {
  1241. case 1: off1 += size; return off1 - size;
  1242. case 2: off2 += size; return off2 - size;
  1243. case 3: off3 -= size; return off3 + size;
  1244. case 0: off0 -= size; return off0 + size;
  1245. }
  1246. }
  1247. axes.forEach(function (axis, i) {
  1248. if (axis.show && axis._show) {
  1249. var side = axis.side;
  1250. axis._pos = incrOffset(side, axis._size);
  1251. if (axis.label != null)
  1252. { axis._lpos = incrOffset(side, axis.labelSize); }
  1253. }
  1254. });
  1255. }
  1256. var cursor = (self.cursor = assign({}, cursorOpts, opts.cursor));
  1257. (cursor._lock = false);
  1258. (cursor.points.show = fnOrSelf(cursor.points.show));
  1259. var focus = self.focus = assign({}, opts.focus || {alpha: 0.3}, cursor.focus);
  1260. var cursorFocus = focus.prox >= 0;
  1261. // series-intersection markers
  1262. var cursorPts = [null];
  1263. function initCursorPt(s, si) {
  1264. if (si > 0) {
  1265. var pt = cursor.points.show(self, si);
  1266. if (pt) {
  1267. addClass(pt, CURSOR_PT);
  1268. addClass(pt, s.class);
  1269. trans(pt, -10, -10, plotWidCss, plotHgtCss);
  1270. over.insertBefore(pt, cursorPts[si]);
  1271. return pt;
  1272. }
  1273. }
  1274. }
  1275. function initSeries(s, i) {
  1276. var isTime = scales[s.scale].time;
  1277. var sv = s.value;
  1278. s.value = isTime ? (isStr(sv) ? timeSeriesVal(_tzDate, timeSeriesStamp(sv, _fmtDate)) : sv || _timeSeriesVal) : sv || numSeriesVal;
  1279. s.label = s.label || (isTime ? timeSeriesLabel : numSeriesLabel);
  1280. if (i > 0) {
  1281. s.width = s.width == null ? 1 : s.width;
  1282. s.paths = s.paths || ( buildPaths);
  1283. s.fillTo = s.fillTo || seriesFillTo;
  1284. var _ptDia = ptDia(s.width, 1);
  1285. s.points = assign({}, {
  1286. size: _ptDia,
  1287. width: max(1, _ptDia * .2),
  1288. stroke: s.stroke,
  1289. space: _ptDia * 2,
  1290. }, s.points);
  1291. s.points.show = fnOrSelf(s.points.show);
  1292. s._paths = null;
  1293. }
  1294. if (showLegend)
  1295. { legendRows.splice(i, 0, initLegendRow(s, i)); }
  1296. if ( cursor.show) {
  1297. var pt = initCursorPt(s, i);
  1298. pt && cursorPts.splice(i, 0, pt);
  1299. }
  1300. }
  1301. function addSeries(opts, si) {
  1302. si = si == null ? series.length : si;
  1303. opts = setDefault(opts, si, xSeriesOpts, ySeriesOpts);
  1304. series.splice(si, 0, opts);
  1305. initSeries(series[si], si);
  1306. }
  1307. self.addSeries = addSeries;
  1308. function delSeries(i) {
  1309. series.splice(i, 1);
  1310. showLegend && legendRows.splice(i, 1)[0][0].parentNode.remove();
  1311. cursorPts.length > 1 && cursorPts.splice(i, 1)[0].remove();
  1312. // TODO: de-init no-longer-needed scales?
  1313. }
  1314. self.delSeries = delSeries;
  1315. series.forEach(initSeries);
  1316. function initAxis(axis, i) {
  1317. axis._show = axis.show;
  1318. if (axis.show) {
  1319. var isVt = axis.side % 2;
  1320. var sc = scales[axis.scale];
  1321. // this can occur if all series specify non-default scales
  1322. if (sc == null) {
  1323. axis.scale = isVt ? series[1].scale : xScaleKey;
  1324. sc = scales[axis.scale];
  1325. }
  1326. // also set defaults for incrs & values based on axis distr
  1327. var isTime = sc.time;
  1328. axis.size = fnOrSelf(axis.size);
  1329. axis.space = fnOrSelf(axis.space);
  1330. axis.rotate = fnOrSelf(axis.rotate);
  1331. axis.incrs = fnOrSelf(axis.incrs || ( sc.distr == 2 ? wholeIncrs : (isTime ? timeIncrs : numIncrs)));
  1332. axis.splits = fnOrSelf(axis.splits || (isTime && sc.distr == 1 ? _timeAxisSplits : sc.distr == 3 ? logAxisSplits : numAxisSplits));
  1333. var av = axis.values;
  1334. axis.values = (
  1335. isTime ? (
  1336. isArr(av) ?
  1337. timeAxisVals(_tzDate, timeAxisStamps(av, _fmtDate)) :
  1338. isStr(av) ?
  1339. timeAxisVal(_tzDate, av) :
  1340. av || _timeAxisVals
  1341. ) : av || numAxisVals
  1342. );
  1343. axis.filter = fnOrSelf(axis.filter || ( sc.distr == 3 ? logAxisValsFilt : retArg1));
  1344. axis.font = pxRatioFont(axis.font);
  1345. axis.labelFont = pxRatioFont(axis.labelFont);
  1346. axis._size = axis.size(self, null, i);
  1347. axis._space =
  1348. axis._rotate =
  1349. axis._incrs =
  1350. axis._found = // foundIncrSpace
  1351. axis._splits =
  1352. axis._values = null;
  1353. }
  1354. }
  1355. // set axis defaults
  1356. axes.forEach(initAxis);
  1357. var dataLen;
  1358. var dataIsGap;
  1359. // rendered data window
  1360. var i0 = null;
  1361. var i1 = null;
  1362. var idxs = series[0].idxs;
  1363. var data0 = null;
  1364. var viaAutoScaleX = false;
  1365. function setData(_data, _resetScales) {
  1366. if (!isArr(_data) && isObj(_data)) {
  1367. dataIsGap = _data.isGap;
  1368. _data = _data.data;
  1369. }
  1370. _data = _data || [];
  1371. _data[0] = _data[0] || [];
  1372. self.data = _data;
  1373. data = _data.slice();
  1374. data0 = data[0];
  1375. dataLen = data0.length;
  1376. if (xScaleDistr == 2)
  1377. { data[0] = data0.map(function (v, i) { return i; }); }
  1378. resetYSeries(true);
  1379. fire("setData");
  1380. if (_resetScales !== false) {
  1381. var xsc = scales[xScaleKey];
  1382. if (xsc.auto(self, viaAutoScaleX))
  1383. { autoScaleX(); }
  1384. else
  1385. { _setScale(xScaleKey, xsc.min, xsc.max); }
  1386. shouldSetCursor = true;
  1387. shouldSetLegend = true;
  1388. commit();
  1389. }
  1390. }
  1391. self.setData = setData;
  1392. function autoScaleX() {
  1393. var assign, assign$1;
  1394. viaAutoScaleX = true;
  1395. var _min, _max;
  1396. if (dataLen > 0) {
  1397. i0 = idxs[0] = 0;
  1398. i1 = idxs[1] = dataLen - 1;
  1399. _min = data[0][i0];
  1400. _max = data[0][i1];
  1401. if (xScaleDistr == 2) {
  1402. _min = i0;
  1403. _max = i1;
  1404. }
  1405. else if (dataLen == 1) {
  1406. if (xScaleDistr == 3)
  1407. { (assign = rangeLog(_min, _min, scales[xScaleKey].log, false), _min = assign[0], _max = assign[1]); }
  1408. else if (scales[xScaleKey].time)
  1409. { _max = _min + 86400; }
  1410. else
  1411. { (assign$1 = rangeNum(_min, _max, 0.1, true), _min = assign$1[0], _max = assign$1[1]); }
  1412. }
  1413. }
  1414. else {
  1415. i0 = idxs[0] = _min = null;
  1416. i1 = idxs[1] = _max = null;
  1417. }
  1418. _setScale(xScaleKey, _min, _max);
  1419. viaAutoScaleX = false;
  1420. }
  1421. function setCtxStyle(stroke, width, dash, fill) {
  1422. ctx.strokeStyle = stroke || transparent;
  1423. ctx.lineWidth = width;
  1424. ctx.lineJoin = "round";
  1425. ctx.setLineDash(dash || []);
  1426. ctx.fillStyle = fill || transparent;
  1427. }
  1428. function setScales() {
  1429. // log("setScales()", arguments);
  1430. // wip scales
  1431. var wipScales = copy(scales);
  1432. for (var k in wipScales) {
  1433. var wsc = wipScales[k];
  1434. var psc = pendScales[k];
  1435. if (psc != null && psc.min != null) {
  1436. assign(wsc, psc);
  1437. // explicitly setting the x-scale invalidates everything (acts as redraw)
  1438. if (k == xScaleKey)
  1439. { resetYSeries(true); }
  1440. }
  1441. else if (k != xScaleKey) {
  1442. if (dataLen == 0 && wsc.from == null) {
  1443. var minMax = wsc.range(self, null, null, k);
  1444. wsc.min = minMax[0];
  1445. wsc.max = minMax[1];
  1446. }
  1447. else {
  1448. wsc.min = inf;
  1449. wsc.max = -inf;
  1450. }
  1451. }
  1452. }
  1453. if (dataLen > 0) {
  1454. // pre-range y-scales from y series' data values
  1455. series.forEach(function (s, i) {
  1456. var k = s.scale;
  1457. var wsc = wipScales[k];
  1458. var psc = pendScales[k];
  1459. if (i == 0) {
  1460. var minMax = wsc.range(self, wsc.min, wsc.max, k);
  1461. wsc.min = minMax[0];
  1462. wsc.max = minMax[1];
  1463. i0 = closestIdx(wsc.min, data[0]);
  1464. i1 = closestIdx(wsc.max, data[0]);
  1465. // closest indices can be outside of view
  1466. if (data[0][i0] < wsc.min)
  1467. { i0++; }
  1468. if (data[0][i1] > wsc.max)
  1469. { i1--; }
  1470. s.min = data0[i0];
  1471. s.max = data0[i1];
  1472. }
  1473. else if (s.show && s.auto && wsc.auto(self, viaAutoScaleX) && (psc == null || psc.min == null)) {
  1474. // only run getMinMax() for invalidated series data, else reuse
  1475. var minMax$1 = s.min == null ? getMinMax(data[i], i0, i1, s.sorted) : [s.min, s.max];
  1476. // initial min/max
  1477. wsc.min = min(wsc.min, s.min = minMax$1[0]);
  1478. wsc.max = max(wsc.max, s.max = minMax$1[1]);
  1479. }
  1480. s.idxs[0] = i0;
  1481. s.idxs[1] = i1;
  1482. });
  1483. // range independent scales
  1484. for (var k$1 in wipScales) {
  1485. var wsc$1 = wipScales[k$1];
  1486. var psc$1 = pendScales[k$1];
  1487. if (wsc$1.from == null && (psc$1 == null || psc$1.min == null)) {
  1488. var minMax$1 = wsc$1.range(
  1489. self,
  1490. wsc$1.min == inf ? null : wsc$1.min,
  1491. wsc$1.max == -inf ? null : wsc$1.max,
  1492. k$1
  1493. );
  1494. wsc$1.min = minMax$1[0];
  1495. wsc$1.max = minMax$1[1];
  1496. }
  1497. }
  1498. }
  1499. // range dependent scales
  1500. for (var k$2 in wipScales) {
  1501. var wsc$2 = wipScales[k$2];
  1502. if (wsc$2.from != null) {
  1503. var base = wipScales[wsc$2.from];
  1504. var minMax$2 = wsc$2.range(self, base.min, base.max, k$2);
  1505. wsc$2.min = minMax$2[0];
  1506. wsc$2.max = minMax$2[1];
  1507. }
  1508. }
  1509. var changed = {};
  1510. var anyChanged = false;
  1511. for (var k$3 in wipScales) {
  1512. var wsc$3 = wipScales[k$3];
  1513. var sc = scales[k$3];
  1514. if (sc.min != wsc$3.min || sc.max != wsc$3.max) {
  1515. sc.min = wsc$3.min;
  1516. sc.max = wsc$3.max;
  1517. changed[k$3] = anyChanged = true;
  1518. }
  1519. }
  1520. if (anyChanged) {
  1521. // invalidate paths of all series on changed scales
  1522. series.forEach(function (s) {
  1523. if (changed[s.scale])
  1524. { s._paths = null; }
  1525. });
  1526. for (var k$4 in changed) {
  1527. shouldConvergeSize = true;
  1528. fire("setScale", k$4);
  1529. }
  1530. if ( cursor.show)
  1531. { shouldSetCursor = true; }
  1532. }
  1533. for (var k$5 in pendScales)
  1534. { pendScales[k$5] = null; }
  1535. }
  1536. // TODO: drawWrap(si, drawPoints) (save, restore, translate, clip)
  1537. function drawPoints(si) {
  1538. // log("drawPoints()", arguments);
  1539. var s = series[si];
  1540. var p = s.points;
  1541. var width = roundDec(p.width * pxRatio, 3);
  1542. var offset = (width % 2) / 2;
  1543. var isStroked = p.width > 0;
  1544. var rad = (p.size - p.width) / 2 * pxRatio;
  1545. var dia = roundDec(rad * 2, 3);
  1546. ctx.translate(offset, offset);
  1547. ctx.save();
  1548. ctx.beginPath();
  1549. ctx.rect(
  1550. plotLft - dia,
  1551. plotTop - dia,
  1552. plotWid + dia * 2,
  1553. plotHgt + dia * 2
  1554. );
  1555. ctx.clip();
  1556. ctx.globalAlpha = s.alpha;
  1557. var path = new Path2D();
  1558. for (var pi = i0; pi <= i1; pi++) {
  1559. if (data[si][pi] != null) {
  1560. var x = round(getXPos(data[0][pi], scales[xScaleKey], plotWid, plotLft));
  1561. var y = round(getYPos(data[si][pi], scales[s.scale], plotHgt, plotTop));
  1562. path.moveTo(x + rad, y);
  1563. path.arc(x, y, rad, 0, PI * 2);
  1564. }
  1565. }
  1566. setCtxStyle(
  1567. p.stroke,
  1568. width,
  1569. null,
  1570. p.fill || (isStroked ? "#fff" : s.stroke)
  1571. );
  1572. ctx.fill(path);
  1573. isStroked && ctx.stroke(path);
  1574. ctx.globalAlpha = 1;
  1575. ctx.restore();
  1576. ctx.translate(-offset, -offset);
  1577. }
  1578. // grabs the nearest indices with y data outside of x-scale limits
  1579. function getOuterIdxs(ydata) {
  1580. var _i0 = clamp(i0 - 1, 0, dataLen - 1);
  1581. var _i1 = clamp(i1 + 1, 0, dataLen - 1);
  1582. while (ydata[_i0] == null && _i0 > 0)
  1583. { _i0--; }
  1584. while (ydata[_i1] == null && _i1 < dataLen - 1)
  1585. { _i1++; }
  1586. return [_i0, _i1];
  1587. }
  1588. var dir = 1;
  1589. function drawSeries() {
  1590. // path building loop must be before draw loop to ensure that all bands are fully constructed
  1591. series.forEach(function (s, i) {
  1592. if (i > 0 && s.show && s._paths == null) {
  1593. var _idxs = getOuterIdxs(data[i]);
  1594. s._paths = s.paths(self, i, _idxs[0], _idxs[1]);
  1595. }
  1596. });
  1597. series.forEach(function (s, i) {
  1598. if (i > 0 && s.show) {
  1599. if (s._paths)
  1600. { drawPath(i); }
  1601. if (s.points.show(self, i, i0, i1))
  1602. { drawPoints(i); }
  1603. fire("drawSeries", i);
  1604. }
  1605. });
  1606. }
  1607. function drawPath(si) {
  1608. var s = series[si];
  1609. if (dir == 1) {
  1610. var ref = s._paths;
  1611. var stroke = ref.stroke;
  1612. var fill = ref.fill;
  1613. var clip = ref.clip;
  1614. var width = roundDec(s[WIDTH] * pxRatio, 3);
  1615. var offset = (width % 2) / 2;
  1616. setCtxStyle(s.stroke, width, s.dash, s.fill);
  1617. ctx.globalAlpha = s.alpha;
  1618. ctx.translate(offset, offset);
  1619. ctx.save();
  1620. var lft = plotLft,
  1621. top = plotTop,
  1622. wid = plotWid,
  1623. hgt = plotHgt;
  1624. var halfWid = width * pxRatio / 2;
  1625. if (s.min == 0)
  1626. { hgt += halfWid; }
  1627. if (s.max == 0) {
  1628. top -= halfWid;
  1629. hgt += halfWid;
  1630. }
  1631. ctx.beginPath();
  1632. ctx.rect(lft, top, wid, hgt);
  1633. ctx.clip();
  1634. if (clip != null)
  1635. { ctx.clip(clip); }
  1636. if (s.band) {
  1637. ctx.fill(stroke);
  1638. width && ctx.stroke(stroke);
  1639. }
  1640. else {
  1641. width && ctx.stroke(stroke);
  1642. if (s.fill != null)
  1643. { ctx.fill(fill); }
  1644. }
  1645. ctx.restore();
  1646. ctx.translate(-offset, -offset);
  1647. ctx.globalAlpha = 1;
  1648. }
  1649. if (s.band)
  1650. { dir *= -1; }
  1651. }
  1652. function buildClip(is, gaps, nullHead, nullTail) {
  1653. var s = series[is];
  1654. var clip = null;
  1655. // create clip path (invert gaps and non-gaps)
  1656. if (gaps.length > 0 && !s.spanGaps) {
  1657. clip = new Path2D();
  1658. var prevGapEnd = plotLft;
  1659. for (var i = 0; i < gaps.length; i++) {
  1660. var g = gaps[i];
  1661. clip.rect(prevGapEnd, plotTop, g[0] - prevGapEnd, plotTop + plotHgt);
  1662. prevGapEnd = g[1];
  1663. }
  1664. clip.rect(prevGapEnd, plotTop, plotLft + plotWid - prevGapEnd, plotTop + plotHgt);
  1665. }
  1666. return clip;
  1667. }
  1668. function addGap(gaps, fromX, toX) {
  1669. if (toX > fromX) {
  1670. var prevGap = gaps[gaps.length - 1];
  1671. if (prevGap && prevGap[0] == fromX) // TODO: gaps must be encoded at stroke widths?
  1672. { prevGap[1] = toX; }
  1673. else
  1674. { gaps.push([fromX, toX]); }
  1675. }
  1676. }
  1677. function nonNullIdx(data, _i0, _i1, dir) {
  1678. for (var i = dir == 1 ? _i0 : _i1; i >= _i0 && i <= _i1; i += dir) {
  1679. if (data[i] != null)
  1680. { return i; }
  1681. }
  1682. return -1;
  1683. }
  1684. function buildPaths(self, is, _i0, _i1) {
  1685. var s = series[is];
  1686. var isGap = dataIsGap || s.isGap;
  1687. var xdata = data[0];
  1688. var ydata = data[is];
  1689. var scaleX = scales[xScaleKey];
  1690. var scaleY = scales[s.scale];
  1691. var _paths = dir == 1 ? {stroke: new Path2D(), fill: null, clip: null} : series[is-1]._paths;
  1692. var stroke = _paths.stroke;
  1693. var width = roundDec(s[WIDTH] * pxRatio, 3);
  1694. var minY = inf,
  1695. maxY = -inf,
  1696. outY, outX;
  1697. // todo: don't build gaps on dir = -1 pass
  1698. var gaps = [];
  1699. var accX = round(getXPos(xdata[dir == 1 ? _i0 : _i1], scaleX, plotWid, plotLft));
  1700. var accGaps = false;
  1701. // data edges
  1702. var lftIdx = nonNullIdx(ydata, _i0, _i1, 1);
  1703. var rgtIdx = nonNullIdx(ydata, _i0, _i1, -1);
  1704. var lftX = incrRound(getXPos(xdata[lftIdx], scaleX, plotWid, plotLft), 0.5);
  1705. var rgtX = incrRound(getXPos(xdata[rgtIdx], scaleX, plotWid, plotLft), 0.5);
  1706. if (lftX > plotLft)
  1707. { addGap(gaps, plotLft, lftX); }
  1708. // the moves the shape edge outside the canvas so stroke doesnt bleed in
  1709. if (s.band && dir == 1)
  1710. { stroke.lineTo(lftX - width * 2, round(getYPos(ydata[_i0], scaleY, plotHgt, plotTop))); }
  1711. for (var i = dir == 1 ? _i0 : _i1; i >= _i0 && i <= _i1; i += dir) {
  1712. var x = round(getXPos(xdata[i], scaleX, plotWid, plotLft));
  1713. if (x == accX) {
  1714. if (ydata[i] != null) {
  1715. outY = round(getYPos(ydata[i], scaleY, plotHgt, plotTop));
  1716. minY = min(outY, minY);
  1717. maxY = max(outY, maxY);
  1718. }
  1719. else if (!accGaps && isGap(self, is, i))
  1720. { accGaps = true; }
  1721. }
  1722. else {
  1723. var _addGap = false;
  1724. if (minY != inf) {
  1725. stroke.lineTo(accX, minY);
  1726. stroke.lineTo(accX, maxY);
  1727. stroke.lineTo(accX, outY);
  1728. outX = accX;
  1729. }
  1730. else if (accGaps) {
  1731. _addGap = true;
  1732. accGaps = false;
  1733. }
  1734. if (ydata[i] != null) {
  1735. outY = round(getYPos(ydata[i], scaleY, plotHgt, plotTop));
  1736. stroke.lineTo(x, outY);
  1737. minY = maxY = outY;
  1738. // prior pixel can have data but still start a gap if ends with null
  1739. if (x - accX > 1 && ydata[i-1] == null && isGap(self, is, i-1))
  1740. { _addGap = true; }
  1741. }
  1742. else {
  1743. minY = inf;
  1744. maxY = -inf;
  1745. if (!accGaps && isGap(self, is, i))
  1746. { accGaps = true; }
  1747. }
  1748. _addGap && addGap(gaps, outX, x);
  1749. accX = x;
  1750. }
  1751. }
  1752. if (rgtX < plotLft + plotWid)
  1753. { addGap(gaps, rgtX, plotLft + plotWid); }
  1754. if (s.band) {
  1755. var _x, _iy, ydata2;
  1756. // the moves the shape edge outside the canvas so stroke doesnt bleed in
  1757. if (dir == 1) {
  1758. _x = rgtX + width * 2;
  1759. _iy = rgtIdx;
  1760. ydata2 = data[is + 1];
  1761. }
  1762. else {
  1763. _x = lftX - width * 2;
  1764. _iy = lftIdx;
  1765. ydata2 = data[is - 1];
  1766. }
  1767. stroke.lineTo(_x, round(getYPos(ydata[_iy], scaleY, plotHgt, plotTop)));
  1768. stroke.lineTo(_x, round(getYPos(ydata2[_iy], scaleY, plotHgt, plotTop)));
  1769. }
  1770. if (dir == 1) {
  1771. _paths.clip = buildClip(is, gaps, ydata[_i0] == null, ydata[_i1] == null);
  1772. if (s.fill != null) {
  1773. var fill = _paths.fill = new Path2D(stroke);
  1774. var fillTo = round(getYPos(s.fillTo(self, is, s.min, s.max), scaleY, plotHgt, plotTop));
  1775. fill.lineTo(rgtX, fillTo);
  1776. fill.lineTo(lftX, fillTo);
  1777. }
  1778. }
  1779. if (s.band)
  1780. { dir *= -1; }
  1781. return _paths;
  1782. }
  1783. self.paths = buildPaths;
  1784. function getIncrSpace(axisIdx, min, max, fullDim) {
  1785. var axis = axes[axisIdx];
  1786. var incrSpace;
  1787. if (fullDim <= 0)
  1788. { incrSpace = [0, 0]; }
  1789. else {
  1790. var minSpace = axis._space = axis.space(self, axisIdx, min, max, fullDim);
  1791. var incrs = axis._incrs = axis.incrs(self, axisIdx, min, max, fullDim, minSpace);
  1792. incrSpace = axis._found = findIncr(min, max, incrs, fullDim, minSpace);
  1793. }
  1794. return incrSpace;
  1795. }
  1796. function drawOrthoLines(offs, filts, ori, side, pos0, len, width, stroke, dash) {
  1797. var offset = (width % 2) / 2;
  1798. ctx.translate(offset, offset);
  1799. setCtxStyle(stroke, width, dash);
  1800. ctx.beginPath();
  1801. var x0, y0, x1, y1, pos1 = pos0 + (side == 0 || side == 3 ? -len : len);
  1802. if (ori == 0) {
  1803. y0 = pos0;
  1804. y1 = pos1;
  1805. }
  1806. else {
  1807. x0 = pos0;
  1808. x1 = pos1;
  1809. }
  1810. offs.forEach(function (off, i) {
  1811. if (filts[i] == null)
  1812. { return; }
  1813. if (ori == 0)
  1814. { x0 = x1 = off; }
  1815. else
  1816. { y0 = y1 = off; }
  1817. ctx.moveTo(x0, y0);
  1818. ctx.lineTo(x1, y1);
  1819. });
  1820. ctx.stroke();
  1821. ctx.translate(-offset, -offset);
  1822. }
  1823. function axesCalc() {
  1824. // log("axesCalc()", arguments);
  1825. var converged = true;
  1826. axes.forEach(function (axis, i) {
  1827. if (!axis.show)
  1828. { return; }
  1829. var scale = scales[axis.scale];
  1830. if (scale.min == null) {
  1831. if (axis._show) {
  1832. converged = false;
  1833. axis._show = false;
  1834. resetYSeries(false);
  1835. }
  1836. return;
  1837. }
  1838. else {
  1839. if (!axis._show) {
  1840. converged = false;
  1841. axis._show = true;
  1842. resetYSeries(false);
  1843. }
  1844. }
  1845. var side = axis.side;
  1846. var ori = side % 2;
  1847. var min = scale.min;
  1848. var max = scale.max; // // should this toggle them ._show = false
  1849. var ref = getIncrSpace(i, min, max, ori == 0 ? plotWidCss : plotHgtCss);
  1850. var _incr = ref[0];
  1851. var _space = ref[1];
  1852. if (_space == 0)
  1853. { return; }
  1854. // if we're using index positions, force first tick to match passed index
  1855. var forceMin = scale.distr == 2;
  1856. var _splits = axis._splits = axis.splits(self, i, min, max, _incr, _space, forceMin);
  1857. // tick labels
  1858. // BOO this assumes a specific data/series
  1859. var splits = scale.distr == 2 ? _splits.map(function (i) { return data0[i]; }) : _splits;
  1860. var incr = scale.distr == 2 ? data0[_splits[1]] - data0[_splits[0]] : _incr;
  1861. var values = axis._values = axis.values(self, axis.filter(self, splits, i, _space, incr), i, _space, incr);
  1862. // rotating of labels only supported on bottom x axis
  1863. axis._rotate = side == 2 ? axis.rotate(self, values, i, _space) : 0;
  1864. var oldSize = axis._size;
  1865. axis._size = axis.size(self, values, i);
  1866. if (oldSize != null && axis._size != oldSize) // ready && ?
  1867. { converged = false; }
  1868. });
  1869. return converged;
  1870. }
  1871. function guttersCalc() {
  1872. var converged = true;
  1873. var _x = gutters._x;
  1874. var _y = gutters._y;
  1875. gutters._x = gutters.x(self);
  1876. gutters._y = gutters.y(self);
  1877. if (gutters._x != _x || gutters._y != _y)
  1878. { converged = false; }
  1879. return converged;
  1880. }
  1881. function drawAxesGrid() {
  1882. axes.forEach(function (axis, i) {
  1883. if (!axis.show || !axis._show)
  1884. { return; }
  1885. var scale = scales[axis.scale];
  1886. var side = axis.side;
  1887. var ori = side % 2;
  1888. var getPos = ori == 0 ? getXPos : getYPos;
  1889. var plotDim = ori == 0 ? plotWid : plotHgt;
  1890. var plotOff = ori == 0 ? plotLft : plotTop;
  1891. var axisGap = round(axis.gap * pxRatio);
  1892. var ticks = axis.ticks;
  1893. var tickSize = ticks.show ? round(ticks.size * pxRatio) : 0;
  1894. var ref = axis._found;
  1895. var _incr = ref[0];
  1896. var _space = ref[1];
  1897. var _splits = axis._splits;
  1898. // tick labels
  1899. // BOO this assumes a specific data/series
  1900. var splits = scale.distr == 2 ? _splits.map(function (i) { return data0[i]; }) : _splits;
  1901. var incr = scale.distr == 2 ? data0[_splits[1]] - data0[_splits[0]] : _incr;
  1902. // rotating of labels only supported on bottom x axis
  1903. var angle = axis._rotate * -PI/180;
  1904. var basePos = round(axis._pos * pxRatio);
  1905. var shiftAmt = tickSize + axisGap;
  1906. var shiftDir = ori == 0 && side == 0 || ori == 1 && side == 3 ? -1 : 1;
  1907. var finalPos = basePos + shiftAmt * shiftDir;
  1908. var y = ori == 0 ? finalPos : 0;
  1909. var x = ori == 1 ? finalPos : 0;
  1910. ctx.font = axis.font[0];
  1911. ctx.fillStyle = axis.stroke || hexBlack; // rgba?
  1912. ctx.textAlign = axis.align == 1 ? LEFT :
  1913. axis.align == 2 ? RIGHT :
  1914. angle > 0 ? LEFT :
  1915. angle < 0 ? RIGHT :
  1916. ori == 0 ? "center" : side == 3 ? RIGHT : LEFT;
  1917. ctx.textBaseline = angle ||
  1918. ori == 1 ? "middle" : side == 2 ? TOP : BOTTOM;
  1919. var lineHeight = axis.font[1] * lineMult;
  1920. var canOffs = _splits.map(function (val) { return round(getPos(val, scale, plotDim, plotOff)); });
  1921. axis._values.forEach(function (val, i) {
  1922. if (val == null)
  1923. { return; }
  1924. if (ori == 0)
  1925. { x = canOffs[i]; }
  1926. else
  1927. { y = canOffs[i]; }
  1928. (""+val).split(/\n/gm).forEach(function (text, j) {
  1929. if (angle) {
  1930. ctx.save();
  1931. ctx.translate(x, y + j * lineHeight);
  1932. ctx.rotate(angle);
  1933. ctx.fillText(text, 0, 0);
  1934. ctx.restore();
  1935. }
  1936. else
  1937. { ctx.fillText(text, x, y + j * lineHeight); }
  1938. });
  1939. });
  1940. // axis label
  1941. if (axis.label) {
  1942. ctx.save();
  1943. var baseLpos = round(axis._lpos * pxRatio);
  1944. if (ori == 1) {
  1945. x = y = 0;
  1946. ctx.translate(
  1947. baseLpos,
  1948. round(plotTop + plotHgt / 2)
  1949. );
  1950. ctx.rotate((side == 3 ? -PI : PI) / 2);
  1951. }
  1952. else {
  1953. x = round(plotLft + plotWid / 2);
  1954. y = baseLpos;
  1955. }
  1956. ctx.font = axis.labelFont[0];
  1957. // ctx.fillStyle = axis.labelStroke || hexBlack; // rgba?
  1958. ctx.textAlign = "center";
  1959. ctx.textBaseline = side == 2 ? TOP : BOTTOM;
  1960. ctx.fillText(axis.label, x, y);
  1961. ctx.restore();
  1962. }
  1963. // ticks
  1964. if (ticks.show) {
  1965. drawOrthoLines(
  1966. canOffs,
  1967. ticks.filter(self, splits, i, _space, incr),
  1968. ori,
  1969. side,
  1970. basePos,
  1971. tickSize,
  1972. roundDec(ticks[WIDTH] * pxRatio, 3),
  1973. ticks.stroke
  1974. );
  1975. }
  1976. // grid
  1977. var grid = axis.grid;
  1978. if (grid.show) {
  1979. drawOrthoLines(
  1980. canOffs,
  1981. grid.filter(self, splits, i, _space, incr),
  1982. ori,
  1983. ori == 0 ? 2 : 1,
  1984. ori == 0 ? plotTop : plotLft,
  1985. ori == 0 ? plotHgt : plotWid,
  1986. roundDec(grid[WIDTH] * pxRatio, 3),
  1987. grid.stroke,
  1988. grid.dash
  1989. );
  1990. }
  1991. });
  1992. fire("drawAxes");
  1993. }
  1994. function resetYSeries(minMax) {
  1995. // log("resetYSeries()", arguments);
  1996. series.forEach(function (s, i) {
  1997. if (i > 0) {
  1998. s._paths = null;
  1999. if (minMax) {
  2000. s.min = null;
  2001. s.max = null;
  2002. }
  2003. }
  2004. });
  2005. }
  2006. var queuedCommit = false;
  2007. // could do rAF instead of microTask, or Promose.resolve().then()
  2008. function commit() {
  2009. if (!queuedCommit) {
  2010. microTask(_commit);
  2011. queuedCommit = true;
  2012. }
  2013. }
  2014. function _commit() {
  2015. // log("_commit()", arguments);
  2016. if (shouldSetScales) {
  2017. setScales();
  2018. shouldSetScales = false;
  2019. }
  2020. if (shouldConvergeSize) {
  2021. convergeSize();
  2022. shouldConvergeSize = false;
  2023. }
  2024. if (shouldSetSize) {
  2025. setStylePx(under, LEFT, plotLftCss);
  2026. setStylePx(under, TOP, plotTopCss);
  2027. setStylePx(under, WIDTH, plotWidCss);
  2028. setStylePx(under, HEIGHT, plotHgtCss);
  2029. setStylePx(over, LEFT, plotLftCss);
  2030. setStylePx(over, TOP, plotTopCss);
  2031. setStylePx(over, WIDTH, plotWidCss);
  2032. setStylePx(over, HEIGHT, plotHgtCss);
  2033. setStylePx(wrap, WIDTH, fullWidCss);
  2034. setStylePx(wrap, HEIGHT, fullHgtCss);
  2035. can[WIDTH] = round(fullWidCss * pxRatio);
  2036. can[HEIGHT] = round(fullHgtCss * pxRatio);
  2037. syncRect();
  2038. fire("setSize");
  2039. shouldSetSize = false;
  2040. }
  2041. // if (shouldSetSelect) {
  2042. // TODO: update .u-select metrics (if visible)
  2043. // setStylePx(selectDiv, TOP, select[TOP] = 0);
  2044. // setStylePx(selectDiv, LEFT, select[LEFT] = 0);
  2045. // setStylePx(selectDiv, WIDTH, select[WIDTH] = 0);
  2046. // setStylePx(selectDiv, HEIGHT, select[HEIGHT] = 0);
  2047. // shouldSetSelect = false;
  2048. // }
  2049. if ( cursor.show && shouldSetCursor) {
  2050. updateCursor();
  2051. shouldSetCursor = false;
  2052. }
  2053. // if (true && legend.show && legend.live && shouldSetLegend) {}
  2054. if (fullWidCss > 0 && fullHgtCss > 0) {
  2055. ctx.clearRect(0, 0, can[WIDTH], can[HEIGHT]);
  2056. fire("drawClear");
  2057. drawAxesGrid();
  2058. dataLen > 0 && drawSeries();
  2059. fire("draw");
  2060. }
  2061. if (!ready) {
  2062. ready = true;
  2063. self.status = 1;
  2064. fire("ready");
  2065. }
  2066. queuedCommit = false;
  2067. }
  2068. self.redraw = function (rebuildPaths) {
  2069. if (rebuildPaths !== false)
  2070. { _setScale(xScaleKey, scales[xScaleKey].min, scales[xScaleKey].max); }
  2071. else
  2072. { commit(); }
  2073. };
  2074. // redraw() => setScale('x', scales.x.min, scales.x.max);
  2075. // explicit, never re-ranged (is this actually true? for x and y)
  2076. function setScale(key, opts) {
  2077. var sc = scales[key];
  2078. if (sc.from == null) {
  2079. if (dataLen == 0) {
  2080. var minMax = sc.range(self, opts.min, opts.max, key);
  2081. opts.min = minMax[0];
  2082. opts.max = minMax[1];
  2083. }
  2084. if (dataLen > 1 && opts.min != null && opts.max != null && opts.max - opts.min < 1e-16)
  2085. { return; }
  2086. if (key == xScaleKey) {
  2087. if (sc.distr == 2 && dataLen > 0) {
  2088. opts.min = closestIdx(opts.min, data[0]);
  2089. opts.max = closestIdx(opts.max, data[0]);
  2090. }
  2091. }
  2092. // log("setScale()", arguments);
  2093. pendScales[key] = opts;
  2094. shouldSetScales = true;
  2095. commit();
  2096. }
  2097. }
  2098. self.setScale = setScale;
  2099. // INTERACTION
  2100. var vt;
  2101. var hz;
  2102. // starting position before cursor.move
  2103. var rawMouseLeft0;
  2104. var rawMouseTop0;
  2105. // starting position
  2106. var mouseLeft0;
  2107. var mouseTop0;
  2108. // current position before cursor.move
  2109. var rawMouseLeft1;
  2110. var rawMouseTop1;
  2111. // current position
  2112. var mouseLeft1;
  2113. var mouseTop1;
  2114. var dragging = false;
  2115. var drag = cursor.drag;
  2116. var dragX = drag.x;
  2117. var dragY = drag.y;
  2118. if ( cursor.show) {
  2119. if (cursor.x) {
  2120. mouseLeft1 = cursor.left;
  2121. vt = placeDiv(CURSOR_X, over);
  2122. }
  2123. if (cursor.y) {
  2124. mouseTop1 = cursor.top;
  2125. hz = placeDiv(CURSOR_Y, over);
  2126. }
  2127. }
  2128. var select = self.select = assign({
  2129. show: true,
  2130. over: true,
  2131. left: 0,
  2132. width: 0,
  2133. top: 0,
  2134. height: 0,
  2135. }, opts.select);
  2136. var selectDiv = select.show ? placeDiv(SELECT, select.over ? over : under) : null;
  2137. function setSelect(opts, _fire) {
  2138. if (select.show) {
  2139. for (var prop in opts)
  2140. { setStylePx(selectDiv, prop, select[prop] = opts[prop]); }
  2141. _fire !== false && fire("setSelect");
  2142. }
  2143. }
  2144. self.setSelect = setSelect;
  2145. function toggleDOM(i, onOff) {
  2146. var s = series[i];
  2147. var label = showLegend ? legendRows[i][0].parentNode : null;
  2148. if (s.show)
  2149. { label && remClass(label, OFF); }
  2150. else {
  2151. label && addClass(label, OFF);
  2152. cursorPts.length > 1 && trans(cursorPts[i], -10, -10, plotWidCss, plotHgtCss);
  2153. }
  2154. }
  2155. function _setScale(key, min, max) {
  2156. setScale(key, {min: min, max: max});
  2157. }
  2158. function setSeries(i, opts, pub) {
  2159. // log("setSeries()", arguments);
  2160. var s = series[i];
  2161. // will this cause redundant commit() if both show and focus are set?
  2162. if (opts.focus != null)
  2163. { setFocus(i); }
  2164. if (opts.show != null) {
  2165. s.show = opts.show;
  2166. toggleDOM(i, opts.show);
  2167. if (s.band) {
  2168. // not super robust, will break if two bands are adjacent
  2169. var ip = series[i+1] && series[i+1].band ? i+1 : i-1;
  2170. series[ip].show = s.show;
  2171. toggleDOM(ip, opts.show);
  2172. }
  2173. _setScale(s.scale, null, null);
  2174. commit();
  2175. }
  2176. fire("setSeries", i, opts);
  2177. pub && sync.pub("setSeries", self, i, opts);
  2178. }
  2179. self.setSeries = setSeries;
  2180. function _alpha(i, value) {
  2181. series[i].alpha = value;
  2182. if ( cursor.show && cursorPts[i])
  2183. { cursorPts[i].style.opacity = value; }
  2184. if ( showLegend && legendRows[i])
  2185. { legendRows[i][0].parentNode.style.opacity = value; }
  2186. }
  2187. function _setAlpha(i, value) {
  2188. var s = series[i];
  2189. _alpha(i, value);
  2190. if (s.band) {
  2191. // not super robust, will break if two bands are adjacent
  2192. var ip = series[i+1].band ? i+1 : i-1;
  2193. _alpha(ip, value);
  2194. }
  2195. }
  2196. // y-distance
  2197. var closestDist;
  2198. var closestSeries;
  2199. var focusedSeries;
  2200. function setFocus(i) {
  2201. if (i != focusedSeries) {
  2202. // log("setFocus()", arguments);
  2203. series.forEach(function (s, i2) {
  2204. _setAlpha(i2, i == null || i2 == 0 || i2 == i ? 1 : focus.alpha);
  2205. });
  2206. focusedSeries = i;
  2207. commit();
  2208. }
  2209. }
  2210. if (showLegend && cursorFocus) {
  2211. on(mouseleave, legendEl, function (e) {
  2212. if (cursor._lock)
  2213. { return; }
  2214. setSeries(null, {focus: false}, syncOpts.setSeries);
  2215. updateCursor();
  2216. });
  2217. }
  2218. function scaleValueAtPos(pos, scale) {
  2219. var dim = plotWidCss;
  2220. if (scale != xScaleKey) {
  2221. dim = plotHgtCss;
  2222. pos = dim - pos;
  2223. }
  2224. var pct = pos / dim;
  2225. var sc = scales[scale],
  2226. _min = sc.min,
  2227. _max = sc.max;
  2228. if (sc.distr == 3) {
  2229. _min = log10(_min);
  2230. _max = log10(_max);
  2231. return pow(10, _min + (_max - _min) * pct);
  2232. }
  2233. else
  2234. { return _min + (_max - _min) * pct; }
  2235. }
  2236. function closestIdxFromXpos(pos) {
  2237. var v = scaleValueAtPos(pos, xScaleKey);
  2238. return closestIdx(v, data[0], i0, i1);
  2239. }
  2240. self.valToIdx = function (val) { return closestIdx(val, data[0]); };
  2241. self.posToIdx = closestIdxFromXpos;
  2242. self.posToVal = scaleValueAtPos;
  2243. self.valToPos = function (val, scale, can) { return (
  2244. scale == xScaleKey ?
  2245. getXPos(val, scales[scale],
  2246. can ? plotWid : plotWidCss,
  2247. can ? plotLft : 0
  2248. ) :
  2249. getYPos(val, scales[scale],
  2250. can ? plotHgt : plotHgtCss,
  2251. can ? plotTop : 0
  2252. )
  2253. ); };
  2254. // defers calling expensive functions
  2255. function batch(fn) {
  2256. fn(self);
  2257. commit();
  2258. }
  2259. self.batch = batch;
  2260. (self.setCursor = function (opts) {
  2261. mouseLeft1 = opts.left;
  2262. mouseTop1 = opts.top;
  2263. // assign(cursor, opts);
  2264. updateCursor();
  2265. });
  2266. var cursorRaf = 0;
  2267. function updateCursor(ts, src) {
  2268. var assign;
  2269. // ts == null && log("updateCursor()", arguments);
  2270. cursorRaf = 0;
  2271. rawMouseLeft1 = mouseLeft1;
  2272. rawMouseTop1 = mouseTop1;
  2273. (assign = cursor.move(self, mouseLeft1, mouseTop1), mouseLeft1 = assign[0], mouseTop1 = assign[1]);
  2274. if (cursor.show) {
  2275. cursor.x && trans(vt, round(mouseLeft1), 0, plotWidCss, plotHgtCss);
  2276. cursor.y && trans(hz, 0, round(mouseTop1), plotWidCss, plotHgtCss);
  2277. }
  2278. var idx;
  2279. // when zooming to an x scale range between datapoints the binary search
  2280. // for nearest min/max indices results in this condition. cheap hack :D
  2281. var noDataInRange = i0 > i1;
  2282. closestDist = inf;
  2283. // if cursor hidden, hide points & clear legend vals
  2284. if (mouseLeft1 < 0 || dataLen == 0 || noDataInRange) {
  2285. idx = null;
  2286. for (var i = 0; i < series.length; i++) {
  2287. if (i > 0) {
  2288. cursorPts.length > 1 && trans(cursorPts[i], -10, -10, plotWidCss, plotHgtCss);
  2289. }
  2290. if (showLegend && legend.live) {
  2291. if (i == 0 && multiValLegend)
  2292. { continue; }
  2293. for (var j = 0; j < legendRows[i].length; j++)
  2294. { legendRows[i][j][firstChild].nodeValue = '--'; }
  2295. }
  2296. }
  2297. if (cursorFocus)
  2298. { setSeries(null, {focus: true}, syncOpts.setSeries); }
  2299. }
  2300. else {
  2301. // let pctY = 1 - (y / rect[HEIGHT]);
  2302. var valAtPos = scaleValueAtPos(mouseLeft1, xScaleKey);
  2303. idx = closestIdx(valAtPos, data[0], i0, i1);
  2304. var scX = scales[xScaleKey];
  2305. var xPos = roundDec(getXPos(data[0][idx], scX, plotWidCss, 0), 3);
  2306. for (var i$1 = 0; i$1 < series.length; i$1++) {
  2307. var s = series[i$1];
  2308. var idx2 = cursor.dataIdx(self, i$1, idx, valAtPos);
  2309. var xPos2 = idx2 == idx ? xPos : roundDec(getXPos(data[0][idx2], scX, plotWidCss, 0), 3);
  2310. if (i$1 > 0 && s.show) {
  2311. var valAtIdx = data[i$1][idx2];
  2312. var yPos = valAtIdx == null ? -10 : roundDec(getYPos(valAtIdx, scales[s.scale], plotHgtCss, 0), 3);
  2313. if (yPos > 0) {
  2314. var dist = abs(yPos - mouseTop1);
  2315. if (dist <= closestDist) {
  2316. closestDist = dist;
  2317. closestSeries = i$1;
  2318. }
  2319. }
  2320. cursorPts.length > 1 && trans(cursorPts[i$1], xPos2, yPos, plotWidCss, plotHgtCss);
  2321. }
  2322. if (showLegend && legend.live) {
  2323. if ((idx2 == cursor.idx && !shouldSetLegend) || i$1 == 0 && multiValLegend)
  2324. { continue; }
  2325. var src$1 = i$1 == 0 && xScaleDistr == 2 ? data0 : data[i$1];
  2326. var vals = multiValLegend ? s.values(self, i$1, idx2) : {_: s.value(self, src$1[idx2], i$1, idx2)};
  2327. var j$1 = 0;
  2328. for (var k in vals)
  2329. { legendRows[i$1][j$1++][firstChild].nodeValue = vals[k]; }
  2330. }
  2331. }
  2332. shouldSetLegend = false;
  2333. }
  2334. // nit: cursor.drag.setSelect is assumed always true
  2335. if (select.show && dragging) {
  2336. if (src != null) {
  2337. var ref = syncOpts.scales;
  2338. var xKey = ref[0];
  2339. var yKey = ref[1];
  2340. // match the dragX/dragY implicitness/explicitness of src
  2341. var sdrag = src.cursor.drag;
  2342. dragX = sdrag._x;
  2343. dragY = sdrag._y;
  2344. if (xKey) {
  2345. var sc = scales[xKey];
  2346. var srcLeft = src.posToVal(src.select[LEFT], xKey);
  2347. var srcRight = src.posToVal(src.select[LEFT] + src.select[WIDTH], xKey);
  2348. select[LEFT] = getXPos(srcLeft, sc, plotWidCss, 0);
  2349. select[WIDTH] = abs(select[LEFT] - getXPos(srcRight, sc, plotWidCss, 0));
  2350. setStylePx(selectDiv, LEFT, select[LEFT]);
  2351. setStylePx(selectDiv, WIDTH, select[WIDTH]);
  2352. if (!yKey) {
  2353. setStylePx(selectDiv, TOP, select[TOP] = 0);
  2354. setStylePx(selectDiv, HEIGHT, select[HEIGHT] = plotHgtCss);
  2355. }
  2356. }
  2357. if (yKey) {
  2358. var sc$1 = scales[yKey];
  2359. var srcTop = src.posToVal(src.select[TOP], yKey);
  2360. var srcBottom = src.posToVal(src.select[TOP] + src.select[HEIGHT], yKey);
  2361. select[TOP] = getYPos(srcTop, sc$1, plotHgtCss, 0);
  2362. select[HEIGHT] = abs(select[TOP] - getYPos(srcBottom, sc$1, plotHgtCss, 0));
  2363. setStylePx(selectDiv, TOP, select[TOP]);
  2364. setStylePx(selectDiv, HEIGHT, select[HEIGHT]);
  2365. if (!xKey) {
  2366. setStylePx(selectDiv, LEFT, select[LEFT] = 0);
  2367. setStylePx(selectDiv, WIDTH, select[WIDTH] = plotWidCss);
  2368. }
  2369. }
  2370. }
  2371. else {
  2372. var rawDX = abs(rawMouseLeft1 - rawMouseLeft0);
  2373. var rawDY = abs(rawMouseTop1 - rawMouseTop0);
  2374. dragX = drag.x && rawDX >= drag.dist;
  2375. dragY = drag.y && rawDY >= drag.dist;
  2376. var uni = drag.uni;
  2377. if (uni != null) {
  2378. // only calc drag status if they pass the dist thresh
  2379. if (dragX && dragY) {
  2380. dragX = rawDX >= uni;
  2381. dragY = rawDY >= uni;
  2382. // force unidirectionality when both are under uni limit
  2383. if (!dragX && !dragY) {
  2384. if (rawDY > rawDX)
  2385. { dragY = true; }
  2386. else
  2387. { dragX = true; }
  2388. }
  2389. }
  2390. }
  2391. else if (drag.x && drag.y && (dragX || dragY))
  2392. // if omni with no uni then both dragX / dragY should be true if either is true
  2393. { dragX = dragY = true; }
  2394. if (dragX) {
  2395. var minX = min(mouseLeft0, mouseLeft1);
  2396. var dx = abs(mouseLeft1 - mouseLeft0);
  2397. setStylePx(selectDiv, LEFT, select[LEFT] = minX);
  2398. setStylePx(selectDiv, WIDTH, select[WIDTH] = dx);
  2399. if (!dragY) {
  2400. setStylePx(selectDiv, TOP, select[TOP] = 0);
  2401. setStylePx(selectDiv, HEIGHT, select[HEIGHT] = plotHgtCss);
  2402. }
  2403. }
  2404. if (dragY) {
  2405. var minY = min(mouseTop0, mouseTop1);
  2406. var dy = abs(mouseTop1 - mouseTop0);
  2407. setStylePx(selectDiv, TOP, select[TOP] = minY);
  2408. setStylePx(selectDiv, HEIGHT, select[HEIGHT] = dy);
  2409. if (!dragX) {
  2410. setStylePx(selectDiv, LEFT, select[LEFT] = 0);
  2411. setStylePx(selectDiv, WIDTH, select[WIDTH] = plotWidCss);
  2412. }
  2413. }
  2414. if (!dragX && !dragY) {
  2415. // the drag didn't pass the dist requirement
  2416. setStylePx(selectDiv, HEIGHT, select[HEIGHT] = 0);
  2417. setStylePx(selectDiv, WIDTH, select[WIDTH] = 0);
  2418. }
  2419. }
  2420. }
  2421. cursor.idx = idx;
  2422. cursor.left = mouseLeft1;
  2423. cursor.top = mouseTop1;
  2424. drag._x = dragX;
  2425. drag._y = dragY;
  2426. // if ts is present, means we're implicitly syncing own cursor as a result of debounced rAF
  2427. if (ts != null) {
  2428. // this is not technically a "mousemove" event, since it's debounced, rename to setCursor?
  2429. // since this is internal, we can tweak it later
  2430. sync.pub(mousemove, self, mouseLeft1, mouseTop1, plotWidCss, plotHgtCss, idx);
  2431. if (cursorFocus) {
  2432. setSeries(closestDist <= focus.prox ? closestSeries : null, {focus: true}, syncOpts.setSeries);
  2433. }
  2434. }
  2435. ready && fire("setCursor");
  2436. }
  2437. var rect = null;
  2438. function syncRect() {
  2439. rect = over.getBoundingClientRect();
  2440. }
  2441. function mouseMove(e, src, _x, _y, _w, _h, _i) {
  2442. if (cursor._lock)
  2443. { return; }
  2444. cacheMouse(e, src, _x, _y, _w, _h, _i, false, e != null);
  2445. if (e != null) {
  2446. if (cursorRaf == 0)
  2447. { cursorRaf = rAF(updateCursor); }
  2448. }
  2449. else
  2450. { updateCursor(null, src); }
  2451. }
  2452. function cacheMouse(e, src, _x, _y, _w, _h, _i, initial, snap) {
  2453. var assign;
  2454. if (e != null) {
  2455. _x = e.clientX - rect.left;
  2456. _y = e.clientY - rect.top;
  2457. }
  2458. else {
  2459. if (_x < 0 || _y < 0) {
  2460. mouseLeft1 = -10;
  2461. mouseTop1 = -10;
  2462. return;
  2463. }
  2464. var ref = syncOpts.scales;
  2465. var xKey = ref[0];
  2466. var yKey = ref[1];
  2467. if (xKey != null)
  2468. { _x = getXPos(src.posToVal(_x, xKey), scales[xKey], plotWidCss, 0); }
  2469. else
  2470. { _x = plotWidCss * (_x/_w); }
  2471. if (yKey != null)
  2472. { _y = getYPos(src.posToVal(_y, yKey), scales[yKey], plotHgtCss, 0); }
  2473. else
  2474. { _y = plotHgtCss * (_y/_h); }
  2475. }
  2476. if (snap) {
  2477. if (_x <= 1 || _x >= plotWidCss - 1)
  2478. { _x = incrRound(_x, plotWidCss); }
  2479. if (_y <= 1 || _y >= plotHgtCss - 1)
  2480. { _y = incrRound(_y, plotHgtCss); }
  2481. }
  2482. if (initial) {
  2483. rawMouseLeft0 = _x;
  2484. rawMouseTop0 = _y;
  2485. (assign = cursor.move(self, _x, _y), mouseLeft0 = assign[0], mouseTop0 = assign[1]);
  2486. }
  2487. else {
  2488. mouseLeft1 = _x;
  2489. mouseTop1 = _y;
  2490. }
  2491. }
  2492. function hideSelect() {
  2493. setSelect({
  2494. width: 0,
  2495. height: 0,
  2496. }, false);
  2497. }
  2498. function mouseDown(e, src, _x, _y, _w, _h, _i) {
  2499. dragging = true;
  2500. dragX = dragY = drag._x = drag._y = false;
  2501. cacheMouse(e, src, _x, _y, _w, _h, _i, true, false);
  2502. if (e != null) {
  2503. onMouse(mouseup, doc, mouseUp);
  2504. sync.pub(mousedown, self, mouseLeft0, mouseTop0, plotWidCss, plotHgtCss, null);
  2505. }
  2506. }
  2507. function mouseUp(e, src, _x, _y, _w, _h, _i) {
  2508. dragging = drag._x = drag._y = false;
  2509. cacheMouse(e, src, _x, _y, _w, _h, _i, false, true);
  2510. var hasSelect = select[WIDTH] > 0 || select[HEIGHT] > 0;
  2511. hasSelect && setSelect(select);
  2512. if (drag.setScale && hasSelect) {
  2513. // if (syncKey != null) {
  2514. // dragX = drag.x;
  2515. // dragY = drag.y;
  2516. // }
  2517. if (dragX) {
  2518. _setScale(xScaleKey,
  2519. scaleValueAtPos(select[LEFT], xScaleKey),
  2520. scaleValueAtPos(select[LEFT] + select[WIDTH], xScaleKey)
  2521. );
  2522. }
  2523. if (dragY) {
  2524. for (var k in scales) {
  2525. var sc = scales[k];
  2526. if (k != xScaleKey && sc.from == null && sc.min != inf) {
  2527. _setScale(k,
  2528. scaleValueAtPos(select[TOP] + select[HEIGHT], k),
  2529. scaleValueAtPos(select[TOP], k)
  2530. );
  2531. }
  2532. }
  2533. }
  2534. hideSelect();
  2535. }
  2536. else if (cursor.lock) {
  2537. cursor._lock = !cursor._lock;
  2538. if (!cursor._lock)
  2539. { updateCursor(); }
  2540. }
  2541. if (e != null) {
  2542. offMouse(mouseup, doc);
  2543. sync.pub(mouseup, self, mouseLeft1, mouseTop1, plotWidCss, plotHgtCss, null);
  2544. }
  2545. }
  2546. function mouseLeave(e, src, _x, _y, _w, _h, _i) {
  2547. if (!cursor._lock) {
  2548. var _dragging = dragging;
  2549. if (dragging) {
  2550. // handle case when mousemove aren't fired all the way to edges by browser
  2551. var snapX = true;
  2552. var snapY = true;
  2553. var snapProx = 10;
  2554. if (dragX && dragY) {
  2555. // maybe omni corner snap
  2556. snapX = mouseLeft1 <= snapProx || mouseLeft1 >= plotWidCss - snapProx;
  2557. snapY = mouseTop1 <= snapProx || mouseTop1 >= plotHgtCss - snapProx;
  2558. }
  2559. if (dragX && snapX) {
  2560. var dLft = mouseLeft1;
  2561. var dRgt = plotWidCss - mouseLeft1;
  2562. var xMin = min(dLft, dRgt);
  2563. if (xMin == dLft)
  2564. { mouseLeft1 = 0; }
  2565. if (xMin == dRgt)
  2566. { mouseLeft1 = plotWidCss; }
  2567. }
  2568. if (dragY && snapY) {
  2569. var dTop = mouseTop1;
  2570. var dBtm = plotHgtCss - mouseTop1;
  2571. var yMin = min(dTop, dBtm);
  2572. if (yMin == dTop)
  2573. { mouseTop1 = 0; }
  2574. if (yMin == dBtm)
  2575. { mouseTop1 = plotHgtCss; }
  2576. }
  2577. updateCursor(1);
  2578. dragging = false;
  2579. }
  2580. mouseLeft1 = -10;
  2581. mouseTop1 = -10;
  2582. // passing a non-null timestamp to force sync/mousemove event
  2583. updateCursor(1);
  2584. if (_dragging)
  2585. { dragging = _dragging; }
  2586. }
  2587. }
  2588. function dblClick(e, src, _x, _y, _w, _h, _i) {
  2589. autoScaleX();
  2590. hideSelect();
  2591. if (e != null)
  2592. { sync.pub(dblclick, self, mouseLeft1, mouseTop1, plotWidCss, plotHgtCss, null); }
  2593. }
  2594. // internal pub/sub
  2595. var events = {};
  2596. events[mousedown] = mouseDown;
  2597. events[mousemove] = mouseMove;
  2598. events[mouseup] = mouseUp;
  2599. events[dblclick] = dblClick;
  2600. events["setSeries"] = function (e, src, idx, opts) {
  2601. setSeries(idx, opts);
  2602. };
  2603. var deb;
  2604. if ( cursor.show) {
  2605. onMouse(mousedown, over, mouseDown);
  2606. onMouse(mousemove, over, mouseMove);
  2607. onMouse(mouseenter, over, syncRect);
  2608. // this has to be rAF'd so it always fires after the last queued/rAF'd updateCursor
  2609. onMouse(mouseleave, over, function (e) { rAF(mouseLeave); });
  2610. onMouse(dblclick, over, dblClick);
  2611. deb = debounce(syncRect, 100);
  2612. on(resize, win, deb);
  2613. on(scroll, win, deb);
  2614. self.syncRect = syncRect;
  2615. }
  2616. // external on/off
  2617. var hooks = self.hooks = opts.hooks || {};
  2618. function fire(evName, a1, a2) {
  2619. if (evName in hooks) {
  2620. hooks[evName].forEach(function (fn) {
  2621. fn.call(null, self, a1, a2);
  2622. });
  2623. }
  2624. }
  2625. (opts.plugins || []).forEach(function (p) {
  2626. for (var evName in p.hooks)
  2627. { hooks[evName] = (hooks[evName] || []).concat(p.hooks[evName]); }
  2628. });
  2629. var syncOpts = assign({
  2630. key: null,
  2631. setSeries: false,
  2632. scales: [xScaleKey, null]
  2633. }, cursor.sync);
  2634. var syncKey = syncOpts.key;
  2635. var sync = (syncKey != null ? (syncs[syncKey] = syncs[syncKey] || _sync()) : _sync());
  2636. sync.sub(self);
  2637. function pub(type, src, x, y, w, h, i) {
  2638. events[type](null, src, x, y, w, h, i);
  2639. }
  2640. (self.pub = pub);
  2641. function destroy() {
  2642. sync.unsub(self);
  2643. off(resize, win, deb);
  2644. off(scroll, win, deb);
  2645. root.remove();
  2646. fire("destroy");
  2647. }
  2648. self.destroy = destroy;
  2649. function _init() {
  2650. fire("init", opts, data);
  2651. setData(data || opts.data, false);
  2652. if (pendScales[xScaleKey])
  2653. { setScale(xScaleKey, pendScales[xScaleKey]); }
  2654. else
  2655. { autoScaleX(); }
  2656. _setSize(opts[WIDTH], opts[HEIGHT]);
  2657. setSelect(select, false);
  2658. }
  2659. if (then) {
  2660. if (then instanceof HTMLElement) {
  2661. then.appendChild(root);
  2662. _init();
  2663. }
  2664. else
  2665. { then(self, _init); }
  2666. }
  2667. else
  2668. { _init(); }
  2669. return self;
  2670. }
  2671. uPlot.assign = assign;
  2672. uPlot.fmtNum = fmtNum;
  2673. uPlot.rangeNum = rangeNum;
  2674. uPlot.rangeLog = rangeLog;
  2675. {
  2676. uPlot.fmtDate = fmtDate;
  2677. uPlot.tzDate = tzDate;
  2678. }
  2679. return uPlot;
  2680. }());