uPlot.esm.js 75 KB

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