Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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