uPlot.esm.js 75 KB

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