Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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