uPlot.esm.js 74 KB

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