uPlot.cjs.js 76 KB

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