uPlot.iife.js 122 KB

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