uPlot.esm.js 89 KB

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