uPlot.cjs.js 118 KB

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