Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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