Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

uPlot.esm.js 118KB

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