uPlot.esm.js 74 KB

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