uPlot.iife.js 122 KB

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