uPlot.iife.js 80 KB

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