uPlot.cjs.js 77 KB

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