uPlot.esm.js 98 KB

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