LaravelTest
5215 строк · 122.2 Кб
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
10var uPlot = (function () {11'use strict';12
13const FEAT_TIME = true;14
15// binary search for index of closest value16function closestIdx(num, arr, lo, hi) {17let mid;18lo = lo || 0;19hi = hi || arr.length - 1;20let bitwise = hi <= 2147483647;21
22while (hi - lo > 1) {23mid = bitwise ? (lo + hi) >> 1 : floor((lo + hi) / 2);24
25if (arr[mid] < num)26lo = mid;27else28hi = mid;29}30
31if (num - arr[lo] <= arr[hi] - num)32return lo;33
34return hi;35}36
37function nonNullIdx(data, _i0, _i1, dir) {38for (let i = dir == 1 ? _i0 : _i1; i >= _i0 && i <= _i1; i += dir) {39if (data[i] != null)40return i;41}42
43return -1;44}45
46function getMinMax(data, _i0, _i1, sorted) {47// console.log("getMinMax()");48
49let _min = inf;50let _max = -inf;51
52if (sorted == 1) {53_min = data[_i0];54_max = data[_i1];55}56else if (sorted == -1) {57_min = data[_i1];58_max = data[_i0];59}60else {61for (let i = _i0; i <= _i1; i++) {62if (data[i] != null) {63_min = min(_min, data[i]);64_max = max(_max, data[i]);65}66}67}68
69return [_min, _max];70}71
72function getMinMaxLog(data, _i0, _i1) {73// console.log("getMinMax()");74
75let _min = inf;76let _max = -inf;77
78for (let i = _i0; i <= _i1; i++) {79if (data[i] > 0) {80_min = min(_min, data[i]);81_max = max(_max, data[i]);82}83}84
85return [86_min == inf ? 1 : _min,87_max == -inf ? 10 : _max,88];89}90
91const _fixedTuple = [0, 0];92
93function fixIncr(minIncr, maxIncr, minExp, maxExp) {94_fixedTuple[0] = minExp < 0 ? roundDec(minIncr, -minExp) : minIncr;95_fixedTuple[1] = maxExp < 0 ? roundDec(maxIncr, -maxExp) : maxIncr;96return _fixedTuple;97}98
99function rangeLog(min, max, base, fullMags) {100let minSign = sign(min);101
102let logFn = base == 10 ? log10 : log2;103
104if (min == max) {105if (minSign == -1) {106min *= base;107max /= base;108}109else {110min /= base;111max *= base;112}113}114
115let minExp, maxExp, minMaxIncrs;116
117if (fullMags) {118minExp = floor(logFn(min));119maxExp = ceil(logFn(max));120
121minMaxIncrs = fixIncr(pow(base, minExp), pow(base, maxExp), minExp, maxExp);122
123min = minMaxIncrs[0];124max = minMaxIncrs[1];125}126else {127minExp = floor(logFn(abs(min)));128maxExp = floor(logFn(abs(max)));129
130minMaxIncrs = fixIncr(pow(base, minExp), pow(base, maxExp), minExp, maxExp);131
132min = incrRoundDn(min, minMaxIncrs[0]);133max = incrRoundUp(max, minMaxIncrs[1]);134}135
136return [min, max];137}138
139function rangeAsinh(min, max, base, fullMags) {140let minMax = rangeLog(min, max, base, fullMags);141
142if (min == 0)143minMax[0] = 0;144
145if (max == 0)146minMax[1] = 0;147
148return minMax;149}150
151const rangePad = 0.1;152
153const autoRangePart = {154mode: 3,155pad: rangePad,156};157
158const _eqRangePart = {159pad: 0,160soft: null,161mode: 0,162};163
164const _eqRange = {165min: _eqRangePart,166max: _eqRangePart,167};168
169// this ensures that non-temporal/numeric y-axes get multiple-snapped padding added above/below170// TODO: also account for incrs when snapping to ensure top of axis gets a tick & value171function rangeNum(_min, _max, mult, extra) {172if (isObj(mult))173return _rangeNum(_min, _max, mult);174
175_eqRangePart.pad = mult;176_eqRangePart.soft = extra ? 0 : null;177_eqRangePart.mode = extra ? 3 : 0;178
179return _rangeNum(_min, _max, _eqRange);180}181
182// nullish coalesce183function ifNull(lh, rh) {184return lh == null ? rh : lh;185}186
187// checks if given index range in an array contains a non-null value188// aka a range-bounded Array.some()189function hasData(data, idx0, idx1) {190idx0 = ifNull(idx0, 0);191idx1 = ifNull(idx1, data.length - 1);192
193while (idx0 <= idx1) {194if (data[idx0] != null)195return true;196idx0++;197}198
199return false;200}201
202function _rangeNum(_min, _max, cfg) {203let cmin = cfg.min;204let cmax = cfg.max;205
206let padMin = ifNull(cmin.pad, 0);207let padMax = ifNull(cmax.pad, 0);208
209let hardMin = ifNull(cmin.hard, -inf);210let hardMax = ifNull(cmax.hard, inf);211
212let softMin = ifNull(cmin.soft, inf);213let softMax = ifNull(cmax.soft, -inf);214
215let softMinMode = ifNull(cmin.mode, 0);216let softMaxMode = ifNull(cmax.mode, 0);217
218let delta = _max - _min;219
220// this handles situations like 89.7, 89.69999999999999221// by assuming 0.001x deltas are precision errors222// if (delta > 0 && delta < abs(_max) / 1e3)223// delta = 0;224
225// treat data as flat if delta is less than 1 billionth226if (delta < 1e-9) {227delta = 0;228
229// if soft mode is 2 and all vals are flat at 0, avoid the 0.1 * 1e3 fallback230// this prevents 0,0,0 from ranging to -100,100 when softMin/softMax are -1,1231if (_min == 0 || _max == 0) {232delta = 1e-9;233
234if (softMinMode == 2 && softMin != inf)235padMin = 0;236
237if (softMaxMode == 2 && softMax != -inf)238padMax = 0;239}240}241
242let nonZeroDelta = delta || abs(_max) || 1e3;243let mag = log10(nonZeroDelta);244let base = pow(10, floor(mag));245
246let _padMin = nonZeroDelta * (delta == 0 ? (_min == 0 ? .1 : 1) : padMin);247let _newMin = roundDec(incrRoundDn(_min - _padMin, base/10), 9);248let _softMin = _min >= softMin && (softMinMode == 1 || softMinMode == 3 && _newMin <= softMin || softMinMode == 2 && _newMin >= softMin) ? softMin : inf;249let minLim = max(hardMin, _newMin < _softMin && _min >= _softMin ? _softMin : min(_softMin, _newMin));250
251let _padMax = nonZeroDelta * (delta == 0 ? (_max == 0 ? .1 : 1) : padMax);252let _newMax = roundDec(incrRoundUp(_max + _padMax, base/10), 9);253let _softMax = _max <= softMax && (softMaxMode == 1 || softMaxMode == 3 && _newMax >= softMax || softMaxMode == 2 && _newMax <= softMax) ? softMax : -inf;254let maxLim = min(hardMax, _newMax > _softMax && _max <= _softMax ? _softMax : max(_softMax, _newMax));255
256if (minLim == maxLim && minLim == 0)257maxLim = 100;258
259return [minLim, maxLim];260}261
262// alternative: https://stackoverflow.com/a/2254896263const fmtNum = new Intl.NumberFormat(navigator.language).format;264
265const M = Math;266
267const PI = M.PI;268const abs = M.abs;269const floor = M.floor;270const round = M.round;271const ceil = M.ceil;272const min = M.min;273const max = M.max;274const pow = M.pow;275const sign = M.sign;276const log10 = M.log10;277const log2 = M.log2;278// TODO: seems like this needs to match asinh impl if the passed v is tweaked?279const sinh = (v, linthresh = 1) => M.sinh(v) * linthresh;280const asinh = (v, linthresh = 1) => M.asinh(v / linthresh);281
282const inf = Infinity;283
284function numIntDigits(x) {285return (log10((x ^ (x >> 31)) - (x >> 31)) | 0) + 1;286}287
288function incrRound(num, incr) {289return round(num/incr)*incr;290}291
292function clamp(num, _min, _max) {293return min(max(num, _min), _max);294}295
296function fnOrSelf(v) {297return typeof v == "function" ? v : () => v;298}299
300const retArg0 = _0 => _0;301
302const retArg1 = (_0, _1) => _1;303
304const retNull = _ => null;305
306const retTrue = _ => true;307
308const retEq = (a, b) => a == b;309
310function incrRoundUp(num, incr) {311return ceil(num/incr)*incr;312}313
314function incrRoundDn(num, incr) {315return floor(num/incr)*incr;316}317
318function roundDec(val, dec) {319return round(val * (dec = 10**dec)) / dec;320}321
322const fixedDec = new Map();323
324function guessDec(num) {325return ((""+num).split(".")[1] || "").length;326}327
328function genIncrs(base, minExp, maxExp, mults) {329let incrs = [];330
331let multDec = mults.map(guessDec);332
333for (let exp = minExp; exp < maxExp; exp++) {334let expa = abs(exp);335let mag = roundDec(pow(base, exp), expa);336
337for (let i = 0; i < mults.length; i++) {338let _incr = mults[i] * mag;339let dec = (_incr >= 0 && exp >= 0 ? 0 : expa) + (exp >= multDec[i] ? 0 : multDec[i]);340let incr = roundDec(_incr, dec);341incrs.push(incr);342fixedDec.set(incr, dec);343}344}345
346return incrs;347}348
349//export const assign = Object.assign;350
351const EMPTY_OBJ = {};352const EMPTY_ARR = [];353
354const nullNullTuple = [null, null];355
356const isArr = Array.isArray;357
358function isStr(v) {359return typeof v == 'string';360}361
362function isObj(v) {363let is = false;364
365if (v != null) {366let c = v.constructor;367is = c == null || c == Object;368}369
370return is;371}372
373function fastIsObj(v) {374return v != null && typeof v == 'object';375}376
377function copy(o, _isObj = isObj) {378let out;379
380if (isArr(o)) {381let val = o.find(v => v != null);382
383if (isArr(val) || _isObj(val)) {384out = Array(o.length);385for (let i = 0; i < o.length; i++)386out[i] = copy(o[i], _isObj);387}388else389out = o.slice();390}391else if (_isObj(o)) {392out = {};393for (let k in o)394out[k] = copy(o[k], _isObj);395}396else397out = o;398
399return out;400}401
402function assign(targ) {403let args = arguments;404
405for (let i = 1; i < args.length; i++) {406let src = args[i];407
408for (let key in src) {409if (isObj(targ[key]))410assign(targ[key], copy(src[key]));411else412targ[key] = copy(src[key]);413}414}415
416return targ;417}418
419// nullModes420const NULL_REMOVE = 0; // nulls are converted to undefined (e.g. for spanGaps: true)421const NULL_RETAIN = 1; // nulls are retained, with alignment artifacts set to undefined (default)422const NULL_EXPAND = 2; // nulls are expanded to include any adjacent alignment artifacts423
424// sets undefined values to nulls when adjacent to existing nulls (minesweeper)425function nullExpand(yVals, nullIdxs, alignedLen) {426for (let i = 0, xi, lastNullIdx = -1; i < nullIdxs.length; i++) {427let nullIdx = nullIdxs[i];428
429if (nullIdx > lastNullIdx) {430xi = nullIdx - 1;431while (xi >= 0 && yVals[xi] == null)432yVals[xi--] = null;433
434xi = nullIdx + 1;435while (xi < alignedLen && yVals[xi] == null)436yVals[lastNullIdx = xi++] = null;437}438}439}440
441// nullModes is a tables-matched array indicating how to treat nulls in each series442// output is sorted ASC on the joined field (table[0]) and duplicate join values are collapsed443function join(tables, nullModes) {444let xVals = new Set();445
446for (let ti = 0; ti < tables.length; ti++) {447let t = tables[ti];448let xs = t[0];449let len = xs.length;450
451for (let i = 0; i < len; i++)452xVals.add(xs[i]);453}454
455let data = [Array.from(xVals).sort((a, b) => a - b)];456
457let alignedLen = data[0].length;458
459let xIdxs = new Map();460
461for (let i = 0; i < alignedLen; i++)462xIdxs.set(data[0][i], i);463
464for (let ti = 0; ti < tables.length; ti++) {465let t = tables[ti];466let xs = t[0];467
468for (let si = 1; si < t.length; si++) {469let ys = t[si];470
471let yVals = Array(alignedLen).fill(undefined);472
473let nullMode = nullModes ? nullModes[ti][si] : NULL_RETAIN;474
475let nullIdxs = [];476
477for (let i = 0; i < ys.length; i++) {478let yVal = ys[i];479let alignedIdx = xIdxs.get(xs[i]);480
481if (yVal === null) {482if (nullMode != NULL_REMOVE) {483yVals[alignedIdx] = yVal;484
485if (nullMode == NULL_EXPAND)486nullIdxs.push(alignedIdx);487}488}489else490yVals[alignedIdx] = yVal;491}492
493nullExpand(yVals, nullIdxs, alignedLen);494
495data.push(yVals);496}497}498
499return data;500}501
502const microTask = typeof queueMicrotask == "undefined" ? fn => Promise.resolve().then(fn) : queueMicrotask;503
504const WIDTH = "width";505const HEIGHT = "height";506const TOP = "top";507const BOTTOM = "bottom";508const LEFT = "left";509const RIGHT = "right";510const hexBlack = "#000";511const transparent = hexBlack + "0";512
513const mousemove = "mousemove";514const mousedown = "mousedown";515const mouseup = "mouseup";516const mouseenter = "mouseenter";517const mouseleave = "mouseleave";518const dblclick = "dblclick";519const resize = "resize";520const scroll = "scroll";521
522const change = "change";523const dppxchange = "dppxchange";524
525const pre = "u-";526
527const UPLOT = "uplot";528const ORI_HZ = pre + "hz";529const ORI_VT = pre + "vt";530const TITLE = pre + "title";531const WRAP = pre + "wrap";532const UNDER = pre + "under";533const OVER = pre + "over";534const AXIS = pre + "axis";535const OFF = pre + "off";536const SELECT = pre + "select";537const CURSOR_X = pre + "cursor-x";538const CURSOR_Y = pre + "cursor-y";539const CURSOR_PT = pre + "cursor-pt";540const LEGEND = pre + "legend";541const LEGEND_LIVE = pre + "live";542const LEGEND_INLINE = pre + "inline";543const LEGEND_THEAD = pre + "thead";544const LEGEND_SERIES = pre + "series";545const LEGEND_MARKER = pre + "marker";546const LEGEND_LABEL = pre + "label";547const LEGEND_VALUE = pre + "value";548
549const doc = document;550const win = window;551let pxRatio;552
553let query;554
555function setPxRatio() {556let _pxRatio = devicePixelRatio;557
558// during print preview, Chrome fires off these dppx queries even without changes559if (pxRatio != _pxRatio) {560pxRatio = _pxRatio;561
562query && off(change, query, setPxRatio);563query = matchMedia(`(min-resolution: ${pxRatio - 0.001}dppx) and (max-resolution: ${pxRatio + 0.001}dppx)`);564on(change, query, setPxRatio);565
566win.dispatchEvent(new CustomEvent(dppxchange));567}568}569
570function addClass(el, c) {571if (c != null) {572let cl = el.classList;573!cl.contains(c) && cl.add(c);574}575}576
577function remClass(el, c) {578let cl = el.classList;579cl.contains(c) && cl.remove(c);580}581
582function setStylePx(el, name, value) {583el.style[name] = value + "px";584}585
586function placeTag(tag, cls, targ, refEl) {587let el = doc.createElement(tag);588
589if (cls != null)590addClass(el, cls);591
592if (targ != null)593targ.insertBefore(el, refEl);594
595return el;596}597
598function placeDiv(cls, targ) {599return placeTag("div", cls, targ);600}601
602const xformCache = new WeakMap();603
604function elTrans(el, xPos, yPos, xMax, yMax) {605let xform = "translate(" + xPos + "px," + yPos + "px)";606let xformOld = xformCache.get(el);607
608if (xform != xformOld) {609el.style.transform = xform;610xformCache.set(el, xform);611
612if (xPos < 0 || yPos < 0 || xPos > xMax || yPos > yMax)613addClass(el, OFF);614else615remClass(el, OFF);616}617}618
619const colorCache = new WeakMap();620
621function elColor(el, background, borderColor) {622let newColor = background + borderColor;623let oldColor = colorCache.get(el);624
625if (newColor != oldColor) {626colorCache.set(el, newColor);627el.style.background = background;628el.style.borderColor = borderColor;629}630}631
632const sizeCache = new WeakMap();633
634function elSize(el, newWid, newHgt, centered) {635let newSize = newWid + "" + newHgt;636let oldSize = sizeCache.get(el);637
638if (newSize != oldSize) {639sizeCache.set(el, newSize);640el.style.height = newHgt + "px";641el.style.width = newWid + "px";642el.style.marginLeft = centered ? -newWid/2 + "px" : 0;643el.style.marginTop = centered ? -newHgt/2 + "px" : 0;644}645}646
647const evOpts = {passive: true};648const evOpts2 = assign({capture: true}, evOpts);649
650function on(ev, el, cb, capt) {651el.addEventListener(ev, cb, capt ? evOpts2 : evOpts);652}653
654function off(ev, el, cb, capt) {655el.removeEventListener(ev, cb, capt ? evOpts2 : evOpts);656}657
658setPxRatio();659
660const months = [661"January",662"February",663"March",664"April",665"May",666"June",667"July",668"August",669"September",670"October",671"November",672"December",673];674
675const days = [676"Sunday",677"Monday",678"Tuesday",679"Wednesday",680"Thursday",681"Friday",682"Saturday",683];684
685function slice3(str) {686return str.slice(0, 3);687}688
689const days3 = days.map(slice3);690
691const months3 = months.map(slice3);692
693const engNames = {694MMMM: months,695MMM: months3,696WWWW: days,697WWW: days3,698};699
700function zeroPad2(int) {701return (int < 10 ? '0' : '') + int;702}703
704function zeroPad3(int) {705return (int < 10 ? '00' : int < 100 ? '0' : '') + int;706}707
708/*709function suffix(int) {
710let mod10 = int % 10;
711
712return int + (
713mod10 == 1 && int != 11 ? "st" :
714mod10 == 2 && int != 12 ? "nd" :
715mod10 == 3 && int != 13 ? "rd" : "th"
716);
717}
718*/
719
720const subs = {721// 2019722YYYY: d => d.getFullYear(),723// 19724YY: d => (d.getFullYear()+'').slice(2),725// July726MMMM: (d, names) => names.MMMM[d.getMonth()],727// Jul728MMM: (d, names) => names.MMM[d.getMonth()],729// 07730MM: d => zeroPad2(d.getMonth()+1),731// 7732M: d => d.getMonth()+1,733// 09734DD: d => zeroPad2(d.getDate()),735// 9736D: d => d.getDate(),737// Monday738WWWW: (d, names) => names.WWWW[d.getDay()],739// Mon740WWW: (d, names) => names.WWW[d.getDay()],741// 03742HH: d => zeroPad2(d.getHours()),743// 3744H: d => d.getHours(),745// 9 (12hr, unpadded)746h: d => {let h = d.getHours(); return h == 0 ? 12 : h > 12 ? h - 12 : h;},747// AM748AA: d => d.getHours() >= 12 ? 'PM' : 'AM',749// am750aa: d => d.getHours() >= 12 ? 'pm' : 'am',751// a752a: d => d.getHours() >= 12 ? 'p' : 'a',753// 09754mm: d => zeroPad2(d.getMinutes()),755// 9756m: d => d.getMinutes(),757// 09758ss: d => zeroPad2(d.getSeconds()),759// 9760s: d => d.getSeconds(),761// 374762fff: d => zeroPad3(d.getMilliseconds()),763};764
765function fmtDate(tpl, names) {766names = names || engNames;767let parts = [];768
769let R = /\{([a-z]+)\}|[^{]+/gi, m;770
771while (m = R.exec(tpl))772parts.push(m[0][0] == '{' ? subs[m[1]] : m[0]);773
774return d => {775let out = '';776
777for (let i = 0; i < parts.length; i++)778out += typeof parts[i] == "string" ? parts[i] : parts[i](d, names);779
780return out;781}782}783
784const localTz = new Intl.DateTimeFormat().resolvedOptions().timeZone;785
786// https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone/53652131#53652131787function tzDate(date, tz) {788let date2;789
790// perf optimization791if (tz == 'UTC' || tz == 'Etc/UTC')792date2 = new Date(+date + date.getTimezoneOffset() * 6e4);793else if (tz == localTz)794date2 = date;795else {796date2 = new Date(date.toLocaleString('en-US', {timeZone: tz}));797date2.setMilliseconds(date.getMilliseconds());798}799
800return date2;801}802
803//export const series = [];804
805// default formatters:806
807const onlyWhole = v => v % 1 == 0;808
809const allMults = [1,2,2.5,5];810
811// ...0.01, 0.02, 0.025, 0.05, 0.1, 0.2, 0.25, 0.5812const decIncrs = genIncrs(10, -16, 0, allMults);813
814// 1, 2, 2.5, 5, 10, 20, 25, 50...815const oneIncrs = genIncrs(10, 0, 16, allMults);816
817// 1, 2, 5, 10, 20, 25, 50...818const wholeIncrs = oneIncrs.filter(onlyWhole);819
820const numIncrs = decIncrs.concat(oneIncrs);821
822const NL = "\n";823
824const yyyy = "{YYYY}";825const NLyyyy = NL + yyyy;826const md = "{M}/{D}";827const NLmd = NL + md;828const NLmdyy = NLmd + "/{YY}";829
830const aa = "{aa}";831const hmm = "{h}:{mm}";832const hmmaa = hmm + aa;833const NLhmmaa = NL + hmmaa;834const ss = ":{ss}";835
836const _ = null;837
838function genTimeStuffs(ms) {839let s = ms * 1e3,840m = s * 60,841h = m * 60,842d = h * 24,843mo = d * 30,844y = d * 365;845
846// min of 1e-3 prevents setting a temporal x ticks too small since Date objects cannot advance ticks smaller than 1ms847let subSecIncrs = ms == 1 ? genIncrs(10, 0, 3, allMults).filter(onlyWhole) : genIncrs(10, -3, 0, allMults);848
849let timeIncrs = subSecIncrs.concat([850// minute divisors (# of secs)851s,852s * 5,853s * 10,854s * 15,855s * 30,856// hour divisors (# of mins)857m,858m * 5,859m * 10,860m * 15,861m * 30,862// day divisors (# of hrs)863h,864h * 2,865h * 3,866h * 4,867h * 6,868h * 8,869h * 12,870// month divisors TODO: need more?871d,872d * 2,873d * 3,874d * 4,875d * 5,876d * 6,877d * 7,878d * 8,879d * 9,880d * 10,881d * 15,882// year divisors (# months, approx)883mo,884mo * 2,885mo * 3,886mo * 4,887mo * 6,888// century divisors889y,890y * 2,891y * 5,892y * 10,893y * 25,894y * 50,895y * 100,896]);897
898// [0]: minimum num secs in the tick incr899// [1]: default tick format900// [2-7]: rollover tick formats901// [8]: mode: 0: replace [1] -> [2-7], 1: concat [1] + [2-7]902const _timeAxisStamps = [903// tick incr default year month day hour min sec mode904[y, yyyy, _, _, _, _, _, _, 1],905[d * 28, "{MMM}", NLyyyy, _, _, _, _, _, 1],906[d, md, NLyyyy, _, _, _, _, _, 1],907[h, "{h}" + aa, NLmdyy, _, NLmd, _, _, _, 1],908[m, hmmaa, NLmdyy, _, NLmd, _, _, _, 1],909[s, ss, NLmdyy + " " + hmmaa, _, NLmd + " " + hmmaa, _, NLhmmaa, _, 1],910[ms, ss + ".{fff}", NLmdyy + " " + hmmaa, _, NLmd + " " + hmmaa, _, NLhmmaa, _, 1],911];912
913// the ensures that axis ticks, values & grid are aligned to logical temporal breakpoints and not an arbitrary timestamp914// https://www.timeanddate.com/time/dst/915// https://www.timeanddate.com/time/dst/2019.html916// https://www.epochconverter.com/timezones917function timeAxisSplits(tzDate) {918return (self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace) => {919let splits = [];920let isYr = foundIncr >= y;921let isMo = foundIncr >= mo && foundIncr < y;922
923// get the timezone-adjusted date924let minDate = tzDate(scaleMin);925let minDateTs = roundDec(minDate * ms, 3);926
927// get ts of 12am (this lands us at or before the original scaleMin)928let minMin = mkDate(minDate.getFullYear(), isYr ? 0 : minDate.getMonth(), isMo || isYr ? 1 : minDate.getDate());929let minMinTs = roundDec(minMin * ms, 3);930
931if (isMo || isYr) {932let moIncr = isMo ? foundIncr / mo : 0;933let yrIncr = isYr ? foundIncr / y : 0;934// let tzOffset = scaleMin - minDateTs; // needed?935let split = minDateTs == minMinTs ? minDateTs : roundDec(mkDate(minMin.getFullYear() + yrIncr, minMin.getMonth() + moIncr, 1) * ms, 3);936let splitDate = new Date(round(split / ms));937let baseYear = splitDate.getFullYear();938let baseMonth = splitDate.getMonth();939
940for (let i = 0; split <= scaleMax; i++) {941let next = mkDate(baseYear + yrIncr * i, baseMonth + moIncr * i, 1);942let offs = next - tzDate(roundDec(next * ms, 3));943
944split = roundDec((+next + offs) * ms, 3);945
946if (split <= scaleMax)947splits.push(split);948}949}950else {951let incr0 = foundIncr >= d ? d : foundIncr;952let tzOffset = floor(scaleMin) - floor(minDateTs);953let split = minMinTs + tzOffset + incrRoundUp(minDateTs - minMinTs, incr0);954splits.push(split);955
956let date0 = tzDate(split);957
958let prevHour = date0.getHours() + (date0.getMinutes() / m) + (date0.getSeconds() / h);959let incrHours = foundIncr / h;960
961let minSpace = self.axes[axisIdx]._space;962let pctSpace = foundSpace / minSpace;963
964while (1) {965split = roundDec(split + foundIncr, ms == 1 ? 0 : 3);966
967if (split > scaleMax)968break;969
970if (incrHours > 1) {971let expectedHour = floor(roundDec(prevHour + incrHours, 6)) % 24;972let splitDate = tzDate(split);973let actualHour = splitDate.getHours();974
975let dstShift = actualHour - expectedHour;976
977if (dstShift > 1)978dstShift = -1;979
980split -= dstShift * h;981
982prevHour = (prevHour + incrHours) % 24;983
984// add a tick only if it's further than 70% of the min allowed label spacing985let prevSplit = splits[splits.length - 1];986let pctIncr = roundDec((split - prevSplit) / foundIncr, 3);987
988if (pctIncr * pctSpace >= .7)989splits.push(split);990}991else992splits.push(split);993}994}995
996return splits;997}998}999
1000return [1001timeIncrs,1002_timeAxisStamps,1003timeAxisSplits,1004];1005}1006
1007const [ timeIncrsMs, _timeAxisStampsMs, timeAxisSplitsMs ] = genTimeStuffs(1);1008const [ timeIncrsS, _timeAxisStampsS, timeAxisSplitsS ] = genTimeStuffs(1e-3);1009
1010// base 21011genIncrs(2, -53, 53, [1]);1012
1013/*1014console.log({
1015decIncrs,
1016oneIncrs,
1017wholeIncrs,
1018numIncrs,
1019timeIncrs,
1020fixedDec,
1021});
1022*/
1023
1024function timeAxisStamps(stampCfg, fmtDate) {1025return stampCfg.map(s => s.map((v, i) =>1026i == 0 || i == 8 || v == null ? v : fmtDate(i == 1 || s[8] == 0 ? v : s[1] + v)1027));1028}1029
1030// TODO: will need to accept spaces[] and pull incr into the loop when grid will be non-uniform, eg for log scales.1031// currently we ignore this for months since they're *nearly* uniform and the added complexity is not worth it1032function timeAxisVals(tzDate, stamps) {1033return (self, splits, axisIdx, foundSpace, foundIncr) => {1034let s = stamps.find(s => foundIncr >= s[0]) || stamps[stamps.length - 1];1035
1036// these track boundaries when a full label is needed again1037let prevYear;1038let prevMnth;1039let prevDate;1040let prevHour;1041let prevMins;1042let prevSecs;1043
1044return splits.map(split => {1045let date = tzDate(split);1046
1047let newYear = date.getFullYear();1048let newMnth = date.getMonth();1049let newDate = date.getDate();1050let newHour = date.getHours();1051let newMins = date.getMinutes();1052let newSecs = date.getSeconds();1053
1054let stamp = (1055newYear != prevYear && s[2] ||1056newMnth != prevMnth && s[3] ||1057newDate != prevDate && s[4] ||1058newHour != prevHour && s[5] ||1059newMins != prevMins && s[6] ||1060newSecs != prevSecs && s[7] ||1061s[1]1062);1063
1064prevYear = newYear;1065prevMnth = newMnth;1066prevDate = newDate;1067prevHour = newHour;1068prevMins = newMins;1069prevSecs = newSecs;1070
1071return stamp(date);1072});1073}1074}1075
1076// for when axis.values is defined as a static fmtDate template string1077function timeAxisVal(tzDate, dateTpl) {1078let stamp = fmtDate(dateTpl);1079return (self, splits, axisIdx, foundSpace, foundIncr) => splits.map(split => stamp(tzDate(split)));1080}1081
1082function mkDate(y, m, d) {1083return new Date(y, m, d);1084}1085
1086function timeSeriesStamp(stampCfg, fmtDate) {1087return fmtDate(stampCfg);1088}1089const _timeSeriesStamp = '{YYYY}-{MM}-{DD} {h}:{mm}{aa}';1090
1091function timeSeriesVal(tzDate, stamp) {1092return (self, val) => stamp(tzDate(val));1093}1094
1095function legendStroke(self, seriesIdx) {1096let s = self.series[seriesIdx];1097return s.width ? s.stroke(self, seriesIdx) : s.points.width ? s.points.stroke(self, seriesIdx) : null;1098}1099
1100function legendFill(self, seriesIdx) {1101return self.series[seriesIdx].fill(self, seriesIdx);1102}1103
1104const legendOpts = {1105show: true,1106live: true,1107isolate: false,1108markers: {1109show: true,1110width: 2,1111stroke: legendStroke,1112fill: legendFill,1113dash: "solid",1114},1115idx: null,1116idxs: null,1117values: [],1118};1119
1120function cursorPointShow(self, si) {1121let o = self.cursor.points;1122
1123let pt = placeDiv();1124
1125let size = o.size(self, si);1126setStylePx(pt, WIDTH, size);1127setStylePx(pt, HEIGHT, size);1128
1129let mar = size / -2;1130setStylePx(pt, "marginLeft", mar);1131setStylePx(pt, "marginTop", mar);1132
1133let width = o.width(self, si, size);1134width && setStylePx(pt, "borderWidth", width);1135
1136return pt;1137}1138
1139function cursorPointFill(self, si) {1140let sp = self.series[si].points;1141return sp._fill || sp._stroke;1142}1143
1144function cursorPointStroke(self, si) {1145let sp = self.series[si].points;1146return sp._stroke || sp._fill;1147}1148
1149function cursorPointSize(self, si) {1150let sp = self.series[si].points;1151return ptDia(sp.width, 1);1152}1153
1154function dataIdx(self, seriesIdx, cursorIdx) {1155return cursorIdx;1156}1157
1158const moveTuple = [0,0];1159
1160function cursorMove(self, mouseLeft1, mouseTop1) {1161moveTuple[0] = mouseLeft1;1162moveTuple[1] = mouseTop1;1163return moveTuple;1164}1165
1166function filtBtn0(self, targ, handle) {1167return e => {1168e.button == 0 && handle(e);1169};1170}1171
1172function passThru(self, targ, handle) {1173return handle;1174}1175
1176const cursorOpts = {1177show: true,1178x: true,1179y: true,1180lock: false,1181move: cursorMove,1182points: {1183show: cursorPointShow,1184size: cursorPointSize,1185width: 0,1186stroke: cursorPointStroke,1187fill: cursorPointFill,1188},1189
1190bind: {1191mousedown: filtBtn0,1192mouseup: filtBtn0,1193click: filtBtn0,1194dblclick: filtBtn0,1195
1196mousemove: passThru,1197mouseleave: passThru,1198mouseenter: passThru,1199},1200
1201drag: {1202setScale: true,1203x: true,1204y: false,1205dist: 0,1206uni: null,1207_x: false,1208_y: false,1209},1210
1211focus: {1212prox: -1,1213},1214
1215left: -10,1216top: -10,1217idx: null,1218dataIdx,1219idxs: null,1220};1221
1222const grid = {1223show: true,1224stroke: "rgba(0,0,0,0.07)",1225width: 2,1226// dash: [],1227filter: retArg1,1228};1229
1230const ticks = assign({}, grid, {size: 10});1231
1232const 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"';1233const labelFont = "bold " + font;1234const lineMult = 1.5; // font-size multiplier1235
1236const xAxisOpts = {1237show: true,1238scale: "x",1239stroke: hexBlack,1240space: 50,1241gap: 5,1242size: 50,1243labelGap: 0,1244labelSize: 30,1245labelFont,1246side: 2,1247// class: "x-vals",1248// incrs: timeIncrs,1249// values: timeVals,1250// filter: retArg1,1251grid,1252ticks,1253font,1254rotate: 0,1255};1256
1257const numSeriesLabel = "Value";1258const timeSeriesLabel = "Time";1259
1260const xSeriesOpts = {1261show: true,1262scale: "x",1263auto: false,1264sorted: 1,1265// label: "Time",1266// value: v => stamp(new Date(v * 1e3)),1267
1268// internal caches1269min: inf,1270max: -inf,1271idxs: [],1272};1273
1274function numAxisVals(self, splits, axisIdx, foundSpace, foundIncr) {1275return splits.map(v => v == null ? "" : fmtNum(v));1276}1277
1278function numAxisSplits(self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace, forceMin) {1279let splits = [];1280
1281let numDec = fixedDec.get(foundIncr) || 0;1282
1283scaleMin = forceMin ? scaleMin : roundDec(incrRoundUp(scaleMin, foundIncr), numDec);1284
1285for (let val = scaleMin; val <= scaleMax; val = roundDec(val + foundIncr, numDec))1286splits.push(Object.is(val, -0) ? 0 : val); // coalesces -01287
1288return splits;1289}1290
1291// this doesnt work for sin, which needs to come off from 0 independently in pos and neg dirs1292function logAxisSplits(self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace, forceMin) {1293const splits = [];1294
1295const logBase = self.scales[self.axes[axisIdx].scale].log;1296
1297const logFn = logBase == 10 ? log10 : log2;1298
1299const exp = floor(logFn(scaleMin));1300
1301foundIncr = pow(logBase, exp);1302
1303if (exp < 0)1304foundIncr = roundDec(foundIncr, -exp);1305
1306let split = scaleMin;1307
1308do {1309splits.push(split);1310split = roundDec(split + foundIncr, fixedDec.get(foundIncr));1311
1312if (split >= foundIncr * logBase)1313foundIncr = split;1314
1315} while (split <= scaleMax);1316
1317return splits;1318}1319
1320function asinhAxisSplits(self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace, forceMin) {1321let sc = self.scales[self.axes[axisIdx].scale];1322
1323let linthresh = sc.asinh;1324
1325let posSplits = scaleMax > linthresh ? logAxisSplits(self, axisIdx, max(linthresh, scaleMin), scaleMax, foundIncr) : [linthresh];1326let zero = scaleMax >= 0 && scaleMin <= 0 ? [0] : [];1327let negSplits = scaleMin < -linthresh ? logAxisSplits(self, axisIdx, max(linthresh, -scaleMax), -scaleMin, foundIncr): [linthresh];1328
1329return negSplits.reverse().map(v => -v).concat(zero, posSplits);1330}1331
1332const RE_ALL = /./;1333const RE_12357 = /[12357]/;1334const RE_125 = /[125]/;1335const RE_1 = /1/;1336
1337function logAxisValsFilt(self, splits, axisIdx, foundSpace, foundIncr) {1338let axis = self.axes[axisIdx];1339let scaleKey = axis.scale;1340let sc = self.scales[scaleKey];1341
1342if (sc.distr == 3 && sc.log == 2)1343return splits;1344
1345let valToPos = self.valToPos;1346
1347let minSpace = axis._space;1348
1349let _10 = valToPos(10, scaleKey);1350
1351let re = (1352valToPos(9, scaleKey) - _10 >= minSpace ? RE_ALL :1353valToPos(7, scaleKey) - _10 >= minSpace ? RE_12357 :1354valToPos(5, scaleKey) - _10 >= minSpace ? RE_125 :1355RE_11356);1357
1358return splits.map(v => ((sc.distr == 4 && v == 0) || re.test(v)) ? v : null);1359}1360
1361function numSeriesVal(self, val) {1362return val == null ? "" : fmtNum(val);1363}1364
1365const yAxisOpts = {1366show: true,1367scale: "y",1368stroke: hexBlack,1369space: 30,1370gap: 5,1371size: 50,1372labelGap: 0,1373labelSize: 30,1374labelFont,1375side: 3,1376// class: "y-vals",1377// incrs: numIncrs,1378// values: (vals, space) => vals,1379// filter: retArg1,1380grid,1381ticks,1382font,1383rotate: 0,1384};1385
1386// takes stroke width1387function ptDia(width, mult) {1388let dia = 3 + (width || 1) * 2;1389return roundDec(dia * mult, 3);1390}1391
1392function seriesPointsShow(self, si) {1393let { scale, idxs } = self.series[0];1394let xData = self._data[0];1395let p0 = self.valToPos(xData[idxs[0]], scale, true);1396let p1 = self.valToPos(xData[idxs[1]], scale, true);1397let dim = abs(p1 - p0);1398
1399let s = self.series[si];1400// const dia = ptDia(s.width, pxRatio);1401let maxPts = dim / (s.points.space * pxRatio);1402return idxs[1] - idxs[0] <= maxPts;1403}1404
1405function seriesFillTo(self, seriesIdx, dataMin, dataMax) {1406let scale = self.scales[self.series[seriesIdx].scale];1407let isUpperBandEdge = self.bands && self.bands.some(b => b.series[0] == seriesIdx);1408return scale.distr == 3 || isUpperBandEdge ? scale.min : 0;1409}1410
1411const facet = {1412scale: null,1413auto: true,1414
1415// internal caches1416min: inf,1417max: -inf,1418};1419
1420const xySeriesOpts = {1421show: true,1422auto: true,1423sorted: 0,1424alpha: 1,1425facets: [1426assign({}, facet, {scale: 'x'}),1427assign({}, facet, {scale: 'y'}),1428],1429};1430
1431const ySeriesOpts = {1432scale: "y",1433auto: true,1434sorted: 0,1435show: true,1436spanGaps: false,1437gaps: (self, seriesIdx, idx0, idx1, nullGaps) => nullGaps,1438alpha: 1,1439points: {1440show: seriesPointsShow,1441filter: null,1442// paths:1443// stroke: "#000",1444// fill: "#fff",1445// width: 1,1446// size: 10,1447},1448// label: "Value",1449// value: v => v,1450values: null,1451
1452// internal caches1453min: inf,1454max: -inf,1455idxs: [],1456
1457path: null,1458clip: null,1459};1460
1461function clampScale(self, val, scaleMin, scaleMax, scaleKey) {1462/*1463if (val < 0) {
1464let cssHgt = self.bbox.height / pxRatio;
1465let absPos = self.valToPos(abs(val), scaleKey);
1466let fromBtm = cssHgt - absPos;
1467return self.posToVal(cssHgt + fromBtm, scaleKey);
1468}
1469*/
1470return scaleMin / 10;1471}1472
1473const xScaleOpts = {1474time: FEAT_TIME,1475auto: true,1476distr: 1,1477log: 10,1478asinh: 1,1479min: null,1480max: null,1481dir: 1,1482ori: 0,1483};1484
1485const yScaleOpts = assign({}, xScaleOpts, {1486time: false,1487ori: 1,1488});1489
1490const syncs = {};1491
1492function _sync(key, opts) {1493let s = syncs[key];1494
1495if (!s) {1496s = {1497key,1498plots: [],1499sub(plot) {1500s.plots.push(plot);1501},1502unsub(plot) {1503s.plots = s.plots.filter(c => c != plot);1504},1505pub(type, self, x, y, w, h, i) {1506for (let j = 0; j < s.plots.length; j++)1507s.plots[j] != self && s.plots[j].pub(type, self, x, y, w, h, i);1508},1509};1510
1511if (key != null)1512syncs[key] = s;1513}1514
1515return s;1516}1517
1518const BAND_CLIP_FILL = 1 << 0;1519const BAND_CLIP_STROKE = 1 << 1;1520
1521function orient(u, seriesIdx, cb) {1522const series = u.series[seriesIdx];1523const scales = u.scales;1524const bbox = u.bbox;1525const scaleX = u.mode == 2 ? scales[series.facets[0].scale] : scales[u.series[0].scale];1526
1527let dx = u._data[0],1528dy = u._data[seriesIdx],1529sx = scaleX,1530sy = u.mode == 2 ? scales[series.facets[1].scale] : scales[series.scale],1531l = bbox.left,1532t = bbox.top,1533w = bbox.width,1534h = bbox.height,1535H = u.valToPosH,1536V = u.valToPosV;1537
1538return (sx.ori == 01539? cb(1540series,1541dx,1542dy,1543sx,1544sy,1545H,1546V,1547l,1548t,1549w,1550h,1551moveToH,1552lineToH,1553rectH,1554arcH,1555bezierCurveToH,1556)1557: cb(1558series,1559dx,1560dy,1561sx,1562sy,1563V,1564H,1565t,1566l,1567h,1568w,1569moveToV,1570lineToV,1571rectV,1572arcV,1573bezierCurveToV,1574)1575);1576}1577
1578// creates inverted band clip path (towards from stroke path -> yMax)1579function clipBandLine(self, seriesIdx, idx0, idx1, strokePath) {1580return orient(self, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {1581let pxRound = series.pxRound;1582
1583const dir = scaleX.dir * (scaleX.ori == 0 ? 1 : -1);1584const lineTo = scaleX.ori == 0 ? lineToH : lineToV;1585
1586let frIdx, toIdx;1587
1588if (dir == 1) {1589frIdx = idx0;1590toIdx = idx1;1591}1592else {1593frIdx = idx1;1594toIdx = idx0;1595}1596
1597// path start1598let x0 = pxRound(valToPosX(dataX[frIdx], scaleX, xDim, xOff));1599let y0 = pxRound(valToPosY(dataY[frIdx], scaleY, yDim, yOff));1600// path end x1601let x1 = pxRound(valToPosX(dataX[toIdx], scaleX, xDim, xOff));1602// upper y limit1603let yLimit = pxRound(valToPosY(scaleY.max, scaleY, yDim, yOff));1604
1605let clip = new Path2D(strokePath);1606
1607lineTo(clip, x1, yLimit);1608lineTo(clip, x0, yLimit);1609lineTo(clip, x0, y0);1610
1611return clip;1612});1613}1614
1615function clipGaps(gaps, ori, plotLft, plotTop, plotWid, plotHgt) {1616let clip = null;1617
1618// create clip path (invert gaps and non-gaps)1619if (gaps.length > 0) {1620clip = new Path2D();1621
1622const rect = ori == 0 ? rectH : rectV;1623
1624let prevGapEnd = plotLft;1625
1626for (let i = 0; i < gaps.length; i++) {1627let g = gaps[i];1628
1629if (g[1] > g[0]) {1630let w = g[0] - prevGapEnd;1631
1632w > 0 && rect(clip, prevGapEnd, plotTop, w, plotTop + plotHgt);1633
1634prevGapEnd = g[1];1635}1636}1637
1638let w = plotLft + plotWid - prevGapEnd;1639
1640w > 0 && rect(clip, prevGapEnd, plotTop, w, plotTop + plotHgt);1641}1642
1643return clip;1644}1645
1646function addGap(gaps, fromX, toX) {1647let prevGap = gaps[gaps.length - 1];1648
1649if (prevGap && prevGap[0] == fromX) // TODO: gaps must be encoded at stroke widths?1650prevGap[1] = toX;1651else1652gaps.push([fromX, toX]);1653}1654
1655function pxRoundGen(pxAlign) {1656return pxAlign == 0 ? retArg0 : pxAlign == 1 ? round : v => incrRound(v, pxAlign);1657}1658
1659function rect(ori) {1660let moveTo = ori == 0 ?1661moveToH :1662moveToV;1663
1664let arcTo = ori == 0 ?1665(p, x1, y1, x2, y2, r) => { p.arcTo(x1, y1, x2, y2, r); } :1666(p, y1, x1, y2, x2, r) => { p.arcTo(x1, y1, x2, y2, r); };1667
1668let rect = ori == 0 ?1669(p, x, y, w, h) => { p.rect(x, y, w, h); } :1670(p, y, x, h, w) => { p.rect(x, y, w, h); };1671
1672return (p, x, y, w, h, r = 0) => {1673if (r == 0)1674rect(p, x, y, w, h);1675else {1676r = min(r, w / 2, h / 2);1677
1678// adapted from https://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-using-html-canvas/7838871#78388711679moveTo(p, x + r, y);1680arcTo(p, x + w, y, x + w, y + h, r);1681arcTo(p, x + w, y + h, x, y + h, r);1682arcTo(p, x, y + h, x, y, r);1683arcTo(p, x, y, x + w, y, r);1684p.closePath();1685}1686};1687}1688
1689// orientation-inverting canvas functions1690const moveToH = (p, x, y) => { p.moveTo(x, y); };1691const moveToV = (p, y, x) => { p.moveTo(x, y); };1692const lineToH = (p, x, y) => { p.lineTo(x, y); };1693const lineToV = (p, y, x) => { p.lineTo(x, y); };1694const rectH = rect(0);1695const rectV = rect(1);1696const arcH = (p, x, y, r, startAngle, endAngle) => { p.arc(x, y, r, startAngle, endAngle); };1697const arcV = (p, y, x, r, startAngle, endAngle) => { p.arc(x, y, r, startAngle, endAngle); };1698const bezierCurveToH = (p, bp1x, bp1y, bp2x, bp2y, p2x, p2y) => { p.bezierCurveTo(bp1x, bp1y, bp2x, bp2y, p2x, p2y); };1699const bezierCurveToV = (p, bp1y, bp1x, bp2y, bp2x, p2y, p2x) => { p.bezierCurveTo(bp1x, bp1y, bp2x, bp2y, p2x, p2y); };1700
1701// TODO: drawWrap(seriesIdx, drawPoints) (save, restore, translate, clip)1702function points(opts) {1703return (u, seriesIdx, idx0, idx1, filtIdxs) => {1704// log("drawPoints()", arguments);1705
1706return orient(u, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {1707let { pxRound, points } = series;1708
1709let moveTo, arc;1710
1711if (scaleX.ori == 0) {1712moveTo = moveToH;1713arc = arcH;1714}1715else {1716moveTo = moveToV;1717arc = arcV;1718}1719
1720const width = roundDec(points.width * pxRatio, 3);1721
1722let rad = (points.size - points.width) / 2 * pxRatio;1723let dia = roundDec(rad * 2, 3);1724
1725let fill = new Path2D();1726let clip = new Path2D();1727
1728let { left: lft, top: top, width: wid, height: hgt } = u.bbox;1729
1730rectH(clip,1731lft - dia,1732top - dia,1733wid + dia * 2,1734hgt + dia * 2,1735);1736
1737const drawPoint = pi => {1738if (dataY[pi] != null) {1739let x = pxRound(valToPosX(dataX[pi], scaleX, xDim, xOff));1740let y = pxRound(valToPosY(dataY[pi], scaleY, yDim, yOff));1741
1742moveTo(fill, x + rad, y);1743arc(fill, x, y, rad, 0, PI * 2);1744}1745};1746
1747if (filtIdxs)1748filtIdxs.forEach(drawPoint);1749else {1750for (let pi = idx0; pi <= idx1; pi++)1751drawPoint(pi);1752}1753
1754return {1755stroke: width > 0 ? fill : null,1756fill,1757clip,1758flags: BAND_CLIP_FILL | BAND_CLIP_STROKE,1759};1760});1761};1762}1763
1764function _drawAcc(lineTo) {1765return (stroke, accX, minY, maxY, inY, outY) => {1766if (minY != maxY) {1767if (inY != minY && outY != minY)1768lineTo(stroke, accX, minY);1769if (inY != maxY && outY != maxY)1770lineTo(stroke, accX, maxY);1771
1772lineTo(stroke, accX, outY);1773}1774};1775}1776
1777const drawAccH = _drawAcc(lineToH);1778const drawAccV = _drawAcc(lineToV);1779
1780function linear() {1781return (u, seriesIdx, idx0, idx1) => {1782return orient(u, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {1783let pxRound = series.pxRound;1784
1785let lineTo, drawAcc;1786
1787if (scaleX.ori == 0) {1788lineTo = lineToH;1789drawAcc = drawAccH;1790}1791else {1792lineTo = lineToV;1793drawAcc = drawAccV;1794}1795
1796const dir = scaleX.dir * (scaleX.ori == 0 ? 1 : -1);1797
1798const _paths = {stroke: new Path2D(), fill: null, clip: null, band: null, gaps: null, flags: BAND_CLIP_FILL};1799const stroke = _paths.stroke;1800
1801let minY = inf,1802maxY = -inf,1803inY, outY, outX, drawnAtX;1804
1805let gaps = [];1806
1807let accX = pxRound(valToPosX(dataX[dir == 1 ? idx0 : idx1], scaleX, xDim, xOff));1808let accGaps = false;1809let prevYNull = false;1810
1811// data edges1812let lftIdx = nonNullIdx(dataY, idx0, idx1, 1 * dir);1813let rgtIdx = nonNullIdx(dataY, idx0, idx1, -1 * dir);1814let lftX = pxRound(valToPosX(dataX[lftIdx], scaleX, xDim, xOff));1815let rgtX = pxRound(valToPosX(dataX[rgtIdx], scaleX, xDim, xOff));1816
1817if (lftX > xOff)1818addGap(gaps, xOff, lftX);1819
1820for (let i = dir == 1 ? idx0 : idx1; i >= idx0 && i <= idx1; i += dir) {1821let x = pxRound(valToPosX(dataX[i], scaleX, xDim, xOff));1822
1823if (x == accX) {1824if (dataY[i] != null) {1825outY = pxRound(valToPosY(dataY[i], scaleY, yDim, yOff));1826
1827if (minY == inf) {1828lineTo(stroke, x, outY);1829inY = outY;1830}1831
1832minY = min(outY, minY);1833maxY = max(outY, maxY);1834}1835else if (dataY[i] === null)1836accGaps = prevYNull = true;1837}1838else {1839let _addGap = false;1840
1841if (minY != inf) {1842drawAcc(stroke, accX, minY, maxY, inY, outY);1843outX = drawnAtX = accX;1844}1845else if (accGaps) {1846_addGap = true;1847accGaps = false;1848}1849
1850if (dataY[i] != null) {1851outY = pxRound(valToPosY(dataY[i], scaleY, yDim, yOff));1852lineTo(stroke, x, outY);1853minY = maxY = inY = outY;1854
1855// prior pixel can have data but still start a gap if ends with null1856if (prevYNull && x - accX > 1)1857_addGap = true;1858
1859prevYNull = false;1860}1861else {1862minY = inf;1863maxY = -inf;1864
1865if (dataY[i] === null) {1866accGaps = true;1867
1868if (x - accX > 1)1869_addGap = true;1870}1871}1872
1873_addGap && addGap(gaps, outX, x);1874
1875accX = x;1876}1877}1878
1879if (minY != inf && minY != maxY && drawnAtX != accX)1880drawAcc(stroke, accX, minY, maxY, inY, outY);1881
1882if (rgtX < xOff + xDim)1883addGap(gaps, rgtX, xOff + xDim);1884
1885if (series.fill != null) {1886let fill = _paths.fill = new Path2D(stroke);1887
1888let fillTo = pxRound(valToPosY(series.fillTo(u, seriesIdx, series.min, series.max), scaleY, yDim, yOff));1889
1890lineTo(fill, rgtX, fillTo);1891lineTo(fill, lftX, fillTo);1892}1893
1894_paths.gaps = gaps = series.gaps(u, seriesIdx, idx0, idx1, gaps);1895
1896if (!series.spanGaps)1897_paths.clip = clipGaps(gaps, scaleX.ori, xOff, yOff, xDim, yDim);1898
1899if (u.bands.length > 0) {1900// ADDL OPT: only create band clips for series that are band lower edges1901// if (b.series[1] == i && _paths.band == null)1902_paths.band = clipBandLine(u, seriesIdx, idx0, idx1, stroke);1903}1904
1905return _paths;1906});1907};1908}1909
1910function stepped(opts) {1911const align = ifNull(opts.align, 1);1912// whether to draw ascenders/descenders at null/gap bondaries1913const ascDesc = ifNull(opts.ascDesc, false);1914
1915return (u, seriesIdx, idx0, idx1) => {1916return orient(u, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {1917let pxRound = series.pxRound;1918
1919let lineTo = scaleX.ori == 0 ? lineToH : lineToV;1920
1921const _paths = {stroke: new Path2D(), fill: null, clip: null, band: null, gaps: null, flags: BAND_CLIP_FILL};1922const stroke = _paths.stroke;1923
1924const _dir = 1 * scaleX.dir * (scaleX.ori == 0 ? 1 : -1);1925
1926idx0 = nonNullIdx(dataY, idx0, idx1, 1);1927idx1 = nonNullIdx(dataY, idx0, idx1, -1);1928
1929let gaps = [];1930let inGap = false;1931let prevYPos = pxRound(valToPosY(dataY[_dir == 1 ? idx0 : idx1], scaleY, yDim, yOff));1932let firstXPos = pxRound(valToPosX(dataX[_dir == 1 ? idx0 : idx1], scaleX, xDim, xOff));1933let prevXPos = firstXPos;1934
1935lineTo(stroke, firstXPos, prevYPos);1936
1937for (let i = _dir == 1 ? idx0 : idx1; i >= idx0 && i <= idx1; i += _dir) {1938let yVal1 = dataY[i];1939
1940let x1 = pxRound(valToPosX(dataX[i], scaleX, xDim, xOff));1941
1942if (yVal1 == null) {1943if (yVal1 === null) {1944addGap(gaps, prevXPos, x1);1945inGap = true;1946}1947continue;1948}1949
1950let y1 = pxRound(valToPosY(yVal1, scaleY, yDim, yOff));1951
1952if (inGap) {1953addGap(gaps, prevXPos, x1);1954inGap = false;1955}1956
1957if (align == 1)1958lineTo(stroke, x1, prevYPos);1959else1960lineTo(stroke, prevXPos, y1);1961
1962lineTo(stroke, x1, y1);1963
1964prevYPos = y1;1965prevXPos = x1;1966}1967
1968if (series.fill != null) {1969let fill = _paths.fill = new Path2D(stroke);1970
1971let fillTo = series.fillTo(u, seriesIdx, series.min, series.max);1972let minY = pxRound(valToPosY(fillTo, scaleY, yDim, yOff));1973
1974lineTo(fill, prevXPos, minY);1975lineTo(fill, firstXPos, minY);1976}1977
1978_paths.gaps = gaps = series.gaps(u, seriesIdx, idx0, idx1, gaps);1979
1980// expand/contract clips for ascenders/descenders1981let halfStroke = (series.width * pxRatio) / 2;1982let startsOffset = (ascDesc || align == 1) ? halfStroke : -halfStroke;1983let endsOffset = (ascDesc || align == -1) ? -halfStroke : halfStroke;1984
1985gaps.forEach(g => {1986g[0] += startsOffset;1987g[1] += endsOffset;1988});1989
1990if (!series.spanGaps)1991_paths.clip = clipGaps(gaps, scaleX.ori, xOff, yOff, xDim, yDim);1992
1993if (u.bands.length > 0) {1994// ADDL OPT: only create band clips for series that are band lower edges1995// if (b.series[1] == i && _paths.band == null)1996_paths.band = clipBandLine(u, seriesIdx, idx0, idx1, stroke);1997}1998
1999return _paths;2000});2001};2002}2003
2004function bars(opts) {2005opts = opts || EMPTY_OBJ;2006const size = ifNull(opts.size, [0.6, inf, 1]);2007const align = opts.align || 0;2008const extraGap = (opts.gap || 0) * pxRatio;2009
2010const radius = ifNull(opts.radius, 0);2011
2012const gapFactor = 1 - size[0];2013const maxWidth = ifNull(size[1], inf) * pxRatio;2014const minWidth = ifNull(size[2], 1) * pxRatio;2015
2016const disp = ifNull(opts.disp, EMPTY_OBJ);2017const _each = ifNull(opts.each, _ => {});2018
2019const { fill: dispFills, stroke: dispStrokes } = disp;2020
2021return (u, seriesIdx, idx0, idx1) => {2022return orient(u, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {2023let pxRound = series.pxRound;2024
2025const _dirX = scaleX.dir * (scaleX.ori == 0 ? 1 : -1);2026const _dirY = scaleY.dir * (scaleY.ori == 1 ? 1 : -1);2027
2028let rect = scaleX.ori == 0 ? rectH : rectV;2029
2030let each = scaleX.ori == 0 ? _each : (u, seriesIdx, i, top, lft, hgt, wid) => {2031_each(u, seriesIdx, i, lft, top, wid, hgt);2032};2033
2034let fillToY = series.fillTo(u, seriesIdx, series.min, series.max);2035
2036let y0Pos = valToPosY(fillToY, scaleY, yDim, yOff);2037
2038// barWid is to center of stroke2039let xShift, barWid;2040
2041let strokeWidth = pxRound(series.width * pxRatio);2042
2043let multiPath = false;2044
2045let fillColors = null;2046let fillPaths = null;2047let strokeColors = null;2048let strokePaths = null;2049
2050if (dispFills != null && dispStrokes != null) {2051multiPath = true;2052
2053fillColors = dispFills.values(u, seriesIdx, idx0, idx1);2054fillPaths = new Map();2055(new Set(fillColors)).forEach(color => {2056if (color != null)2057fillPaths.set(color, new Path2D());2058});2059
2060strokeColors = dispStrokes.values(u, seriesIdx, idx0, idx1);2061strokePaths = new Map();2062(new Set(strokeColors)).forEach(color => {2063if (color != null)2064strokePaths.set(color, new Path2D());2065});2066}2067
2068let { x0, size } = disp;2069
2070if (x0 != null && size != null) {2071dataX = x0.values(u, seriesIdx, idx0, idx1);2072
2073if (x0.unit == 2)2074dataX = dataX.map(pct => u.posToVal(xOff + pct * xDim, scaleX.key, true));2075
2076// assumes uniform sizes, for now2077let sizes = size.values(u, seriesIdx, idx0, idx1);2078
2079if (size.unit == 2)2080barWid = sizes[0] * xDim;2081else2082barWid = valToPosX(sizes[0], scaleX, xDim, xOff) - valToPosX(0, scaleX, xDim, xOff); // assumes linear scale (delta from 0)2083
2084barWid = pxRound(barWid - strokeWidth);2085
2086xShift = (_dirX == 1 ? -strokeWidth / 2 : barWid + strokeWidth / 2);2087}2088else {2089let colWid = xDim;2090
2091if (dataX.length > 1) {2092// prior index with non-undefined y data2093let prevIdx = null;2094
2095// scan full dataset for smallest adjacent delta2096// will not work properly for non-linear x scales, since does not do expensive valToPosX calcs till end2097for (let i = 0, minDelta = Infinity; i < dataX.length; i++) {2098if (dataY[i] !== undefined) {2099if (prevIdx != null) {2100let delta = abs(dataX[i] - dataX[prevIdx]);2101
2102if (delta < minDelta) {2103minDelta = delta;2104colWid = abs(valToPosX(dataX[i], scaleX, xDim, xOff) - valToPosX(dataX[prevIdx], scaleX, xDim, xOff));2105}2106}2107
2108prevIdx = i;2109}2110}2111}2112
2113let gapWid = colWid * gapFactor;2114
2115barWid = pxRound(min(maxWidth, max(minWidth, colWid - gapWid)) - strokeWidth - extraGap);2116
2117xShift = (align == 0 ? barWid / 2 : align == _dirX ? 0 : barWid) - align * _dirX * extraGap / 2;2118}2119
2120const _paths = {stroke: null, fill: null, clip: null, band: null, gaps: null, flags: BAND_CLIP_FILL | BAND_CLIP_STROKE}; // disp, geom2121
2122const hasBands = u.bands.length > 0;2123let yLimit;2124
2125if (hasBands) {2126// ADDL OPT: only create band clips for series that are band lower edges2127// if (b.series[1] == i && _paths.band == null)2128_paths.band = new Path2D();2129yLimit = pxRound(valToPosY(scaleY.max, scaleY, yDim, yOff));2130}2131
2132const stroke = multiPath ? null : new Path2D();2133const band = _paths.band;2134
2135for (let i = _dirX == 1 ? idx0 : idx1; i >= idx0 && i <= idx1; i += _dirX) {2136let yVal = dataY[i];2137
2138/*2139// interpolate upwards band clips
2140if (yVal == null) {
2141// if (hasBands)
2142// yVal = costlyLerp(i, idx0, idx1, _dirX, dataY);
2143// else
2144continue;
2145}
2146*/
2147
2148let xVal = scaleX.distr != 2 || disp != null ? dataX[i] : i;2149
2150// TODO: all xPos can be pre-computed once for all series in aligned set2151let xPos = valToPosX(xVal, scaleX, xDim, xOff);2152let yPos = valToPosY(ifNull(yVal, fillToY) , scaleY, yDim, yOff);2153
2154let lft = pxRound(xPos - xShift);2155let btm = pxRound(max(yPos, y0Pos));2156let top = pxRound(min(yPos, y0Pos));2157// this includes the stroke2158let barHgt = btm - top;2159
2160let r = radius * barWid;2161
2162if (yVal != null) { // && yVal != fillToY (0 height bar)2163if (multiPath) {2164if (strokeWidth > 0 && strokeColors[i] != null)2165rect(strokePaths.get(strokeColors[i]), lft, top + floor(strokeWidth / 2), barWid, max(0, barHgt - strokeWidth), r);2166
2167if (fillColors[i] != null)2168rect(fillPaths.get(fillColors[i]), lft, top + floor(strokeWidth / 2), barWid, max(0, barHgt - strokeWidth), r);2169}2170else2171rect(stroke, lft, top + floor(strokeWidth / 2), barWid, max(0, barHgt - strokeWidth), r);2172
2173each(u, seriesIdx, i,2174lft - strokeWidth / 2,2175top,2176barWid + strokeWidth,2177barHgt,2178);2179}2180
2181if (hasBands) {2182if (_dirY == 1) {2183btm = top;2184top = yLimit;2185}2186else {2187top = btm;2188btm = yLimit;2189}2190
2191barHgt = btm - top;2192
2193rect(band, lft - strokeWidth / 2, top, barWid + strokeWidth, max(0, barHgt), 0);2194}2195}2196
2197if (strokeWidth > 0)2198_paths.stroke = multiPath ? strokePaths : stroke;2199
2200_paths.fill = multiPath ? fillPaths : stroke;2201
2202return _paths;2203});2204};2205}2206
2207function splineInterp(interp, opts) {2208return (u, seriesIdx, idx0, idx1) => {2209return orient(u, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {2210let pxRound = series.pxRound;2211
2212let moveTo, bezierCurveTo, lineTo;2213
2214if (scaleX.ori == 0) {2215moveTo = moveToH;2216lineTo = lineToH;2217bezierCurveTo = bezierCurveToH;2218}2219else {2220moveTo = moveToV;2221lineTo = lineToV;2222bezierCurveTo = bezierCurveToV;2223}2224
2225const _dir = 1 * scaleX.dir * (scaleX.ori == 0 ? 1 : -1);2226
2227idx0 = nonNullIdx(dataY, idx0, idx1, 1);2228idx1 = nonNullIdx(dataY, idx0, idx1, -1);2229
2230let gaps = [];2231let inGap = false;2232let firstXPos = pxRound(valToPosX(dataX[_dir == 1 ? idx0 : idx1], scaleX, xDim, xOff));2233let prevXPos = firstXPos;2234
2235let xCoords = [];2236let yCoords = [];2237
2238for (let i = _dir == 1 ? idx0 : idx1; i >= idx0 && i <= idx1; i += _dir) {2239let yVal = dataY[i];2240let xVal = dataX[i];2241let xPos = valToPosX(xVal, scaleX, xDim, xOff);2242
2243if (yVal == null) {2244if (yVal === null) {2245addGap(gaps, prevXPos, xPos);2246inGap = true;2247}2248continue;2249}2250else {2251if (inGap) {2252addGap(gaps, prevXPos, xPos);2253inGap = false;2254}2255
2256xCoords.push((prevXPos = xPos));2257yCoords.push(valToPosY(dataY[i], scaleY, yDim, yOff));2258}2259}2260
2261const _paths = {stroke: interp(xCoords, yCoords, moveTo, lineTo, bezierCurveTo, pxRound), fill: null, clip: null, band: null, gaps: null, flags: BAND_CLIP_FILL};2262const stroke = _paths.stroke;2263
2264if (series.fill != null && stroke != null) {2265let fill = _paths.fill = new Path2D(stroke);2266
2267let fillTo = series.fillTo(u, seriesIdx, series.min, series.max);2268let minY = pxRound(valToPosY(fillTo, scaleY, yDim, yOff));2269
2270lineTo(fill, prevXPos, minY);2271lineTo(fill, firstXPos, minY);2272}2273
2274_paths.gaps = gaps = series.gaps(u, seriesIdx, idx0, idx1, gaps);2275
2276if (!series.spanGaps)2277_paths.clip = clipGaps(gaps, scaleX.ori, xOff, yOff, xDim, yDim);2278
2279if (u.bands.length > 0) {2280// ADDL OPT: only create band clips for series that are band lower edges2281// if (b.series[1] == i && _paths.band == null)2282_paths.band = clipBandLine(u, seriesIdx, idx0, idx1, stroke);2283}2284
2285return _paths;2286
2287// if FEAT_PATHS: false in rollup.config.js2288// u.ctx.save();2289// u.ctx.beginPath();2290// u.ctx.rect(u.bbox.left, u.bbox.top, u.bbox.width, u.bbox.height);2291// u.ctx.clip();2292// u.ctx.strokeStyle = u.series[sidx].stroke;2293// u.ctx.stroke(stroke);2294// u.ctx.fillStyle = u.series[sidx].fill;2295// u.ctx.fill(fill);2296// u.ctx.restore();2297// return null;2298});2299};2300}2301
2302function monotoneCubic(opts) {2303return splineInterp(_monotoneCubic);2304}2305
2306// Monotone Cubic Spline interpolation, adapted from the Chartist.js implementation:2307// https://github.com/gionkunz/chartist-js/blob/e7e78201bffe9609915e5e53cfafa29a5d6c49f9/src/scripts/interpolation.js#L240-L3692308function _monotoneCubic(xs, ys, moveTo, lineTo, bezierCurveTo, pxRound) {2309const n = xs.length;2310
2311if (n < 2)2312return null;2313
2314const path = new Path2D();2315
2316moveTo(path, xs[0], ys[0]);2317
2318if (n == 2)2319lineTo(path, xs[1], ys[1]);2320else {2321let ms = Array(n),2322ds = Array(n - 1),2323dys = Array(n - 1),2324dxs = Array(n - 1);2325
2326// calc deltas and derivative2327for (let i = 0; i < n - 1; i++) {2328dys[i] = ys[i + 1] - ys[i];2329dxs[i] = xs[i + 1] - xs[i];2330ds[i] = dys[i] / dxs[i];2331}2332
2333// determine desired slope (m) at each point using Fritsch-Carlson method2334// http://math.stackexchange.com/questions/45218/implementation-of-monotone-cubic-interpolation2335ms[0] = ds[0];2336
2337for (let i = 1; i < n - 1; i++) {2338if (ds[i] === 0 || ds[i - 1] === 0 || (ds[i - 1] > 0) !== (ds[i] > 0))2339ms[i] = 0;2340else {2341ms[i] = 3 * (dxs[i - 1] + dxs[i]) / (2342(2 * dxs[i] + dxs[i - 1]) / ds[i - 1] +2343(dxs[i] + 2 * dxs[i - 1]) / ds[i]2344);2345
2346if (!isFinite(ms[i]))2347ms[i] = 0;2348}2349}2350
2351ms[n - 1] = ds[n - 2];2352
2353for (let i = 0; i < n - 1; i++) {2354bezierCurveTo(2355path,2356xs[i] + dxs[i] / 3,2357ys[i] + ms[i] * dxs[i] / 3,2358xs[i + 1] - dxs[i] / 3,2359ys[i + 1] - ms[i + 1] * dxs[i] / 3,2360xs[i + 1],2361ys[i + 1],2362);2363}2364}2365
2366return path;2367}2368
2369const cursorPlots = new Set();2370
2371function invalidateRects() {2372cursorPlots.forEach(u => {2373u.syncRect(true);2374});2375}2376
2377on(resize, win, invalidateRects);2378on(scroll, win, invalidateRects, true);2379
2380const linearPath = linear() ;2381const pointsPath = points() ;2382
2383function setDefaults(d, xo, yo, initY) {2384let d2 = initY ? [d[0], d[1]].concat(d.slice(2)) : [d[0]].concat(d.slice(1));2385return d2.map((o, i) => setDefault(o, i, xo, yo));2386}2387
2388function setDefaults2(d, xyo) {2389return d.map((o, i) => i == 0 ? null : assign({}, xyo, o)); // todo: assign() will not merge facet arrays2390}2391
2392function setDefault(o, i, xo, yo) {2393return assign({}, (i == 0 ? xo : yo), o);2394}2395
2396function snapNumX(self, dataMin, dataMax) {2397return dataMin == null ? nullNullTuple : [dataMin, dataMax];2398}2399
2400const snapTimeX = snapNumX;2401
2402// this ensures that non-temporal/numeric y-axes get multiple-snapped padding added above/below2403// TODO: also account for incrs when snapping to ensure top of axis gets a tick & value2404function snapNumY(self, dataMin, dataMax) {2405return dataMin == null ? nullNullTuple : rangeNum(dataMin, dataMax, rangePad, true);2406}2407
2408function snapLogY(self, dataMin, dataMax, scale) {2409return dataMin == null ? nullNullTuple : rangeLog(dataMin, dataMax, self.scales[scale].log, false);2410}2411
2412const snapLogX = snapLogY;2413
2414function snapAsinhY(self, dataMin, dataMax, scale) {2415return dataMin == null ? nullNullTuple : rangeAsinh(dataMin, dataMax, self.scales[scale].log, false);2416}2417
2418const snapAsinhX = snapAsinhY;2419
2420// dim is logical (getClientBoundingRect) pixels, not canvas pixels2421function findIncr(minVal, maxVal, incrs, dim, minSpace) {2422let intDigits = max(numIntDigits(minVal), numIntDigits(maxVal));2423
2424let delta = maxVal - minVal;2425
2426let incrIdx = closestIdx((minSpace / dim) * delta, incrs);2427
2428do {2429let foundIncr = incrs[incrIdx];2430let foundSpace = dim * foundIncr / delta;2431
2432if (foundSpace >= minSpace && intDigits + (foundIncr < 5 ? fixedDec.get(foundIncr) : 0) <= 17)2433return [foundIncr, foundSpace];2434} while (++incrIdx < incrs.length);2435
2436return [0, 0];2437}2438
2439function pxRatioFont(font) {2440let fontSize, fontSizeCss;2441font = font.replace(/(\d+)px/, (m, p1) => (fontSize = round((fontSizeCss = +p1) * pxRatio)) + 'px');2442return [font, fontSize, fontSizeCss];2443}2444
2445function syncFontSize(axis) {2446if (axis.show) {2447[axis.font, axis.labelFont].forEach(f => {2448let size = roundDec(f[2] * pxRatio, 1);2449f[0] = f[0].replace(/[0-9.]+px/, size + 'px');2450f[1] = size;2451});2452}2453}2454
2455function uPlot(opts, data, then) {2456const self = {2457mode: ifNull(opts.mode, 1),2458};2459
2460const mode = self.mode;2461
2462// TODO: cache denoms & mins scale.cache = {r, min, }2463function getValPct(val, scale) {2464let _val = (2465scale.distr == 3 ? log10(val > 0 ? val : scale.clamp(self, val, scale.min, scale.max, scale.key)) :2466scale.distr == 4 ? asinh(val, scale.asinh) :2467val
2468);2469
2470return (_val - scale._min) / (scale._max - scale._min);2471}2472
2473function getHPos(val, scale, dim, off) {2474let pct = getValPct(val, scale);2475return off + dim * (scale.dir == -1 ? (1 - pct) : pct);2476}2477
2478function getVPos(val, scale, dim, off) {2479let pct = getValPct(val, scale);2480return off + dim * (scale.dir == -1 ? pct : (1 - pct));2481}2482
2483function getPos(val, scale, dim, off) {2484return scale.ori == 0 ? getHPos(val, scale, dim, off) : getVPos(val, scale, dim, off);2485}2486
2487self.valToPosH = getHPos;2488self.valToPosV = getVPos;2489
2490let ready = false;2491self.status = 0;2492
2493const root = self.root = placeDiv(UPLOT);2494
2495if (opts.id != null)2496root.id = opts.id;2497
2498addClass(root, opts.class);2499
2500if (opts.title) {2501let title = placeDiv(TITLE, root);2502title.textContent = opts.title;2503}2504
2505const can = placeTag("canvas");2506const ctx = self.ctx = can.getContext("2d");2507
2508const wrap = placeDiv(WRAP, root);2509const under = self.under = placeDiv(UNDER, wrap);2510wrap.appendChild(can);2511const over = self.over = placeDiv(OVER, wrap);2512
2513opts = copy(opts);2514
2515const pxAlign = +ifNull(opts.pxAlign, 1);2516
2517const pxRound = pxRoundGen(pxAlign);2518
2519(opts.plugins || []).forEach(p => {2520if (p.opts)2521opts = p.opts(self, opts) || opts;2522});2523
2524const ms = opts.ms || 1e-3;2525
2526const series = self.series = mode == 1 ?2527setDefaults(opts.series || [], xSeriesOpts, ySeriesOpts, false) :2528setDefaults2(opts.series || [null], xySeriesOpts);2529const axes = self.axes = setDefaults(opts.axes || [], xAxisOpts, yAxisOpts, true);2530const scales = self.scales = {};2531const bands = self.bands = opts.bands || [];2532
2533bands.forEach(b => {2534b.fill = fnOrSelf(b.fill || null);2535});2536
2537const xScaleKey = mode == 2 ? series[1].facets[0].scale : series[0].scale;2538
2539const drawOrderMap = {2540axes: drawAxesGrid,2541series: drawSeries,2542};2543
2544const drawOrder = (opts.drawOrder || ["axes", "series"]).map(key => drawOrderMap[key]);2545
2546function initScale(scaleKey) {2547let sc = scales[scaleKey];2548
2549if (sc == null) {2550let scaleOpts = (opts.scales || EMPTY_OBJ)[scaleKey] || EMPTY_OBJ;2551
2552if (scaleOpts.from != null) {2553// ensure parent is initialized2554initScale(scaleOpts.from);2555// dependent scales inherit2556scales[scaleKey] = assign({}, scales[scaleOpts.from], scaleOpts, {key: scaleKey});2557}2558else {2559sc = scales[scaleKey] = assign({}, (scaleKey == xScaleKey ? xScaleOpts : yScaleOpts), scaleOpts);2560
2561if (mode == 2)2562sc.time = false;2563
2564sc.key = scaleKey;2565
2566let isTime = sc.time;2567
2568let rn = sc.range;2569
2570let rangeIsArr = isArr(rn);2571
2572if (scaleKey != xScaleKey || mode == 2) {2573// if range array has null limits, it should be auto2574if (rangeIsArr && (rn[0] == null || rn[1] == null)) {2575rn = {2576min: rn[0] == null ? autoRangePart : {2577mode: 1,2578hard: rn[0],2579soft: rn[0],2580},2581max: rn[1] == null ? autoRangePart : {2582mode: 1,2583hard: rn[1],2584soft: rn[1],2585},2586};2587rangeIsArr = false;2588}2589
2590if (!rangeIsArr && isObj(rn)) {2591let cfg = rn;2592// this is similar to snapNumY2593rn = (self, dataMin, dataMax) => dataMin == null ? nullNullTuple : rangeNum(dataMin, dataMax, cfg);2594}2595}2596
2597sc.range = fnOrSelf(rn || (isTime ? snapTimeX : scaleKey == xScaleKey ?2598(sc.distr == 3 ? snapLogX : sc.distr == 4 ? snapAsinhX : snapNumX) :2599(sc.distr == 3 ? snapLogY : sc.distr == 4 ? snapAsinhY : snapNumY)2600));2601
2602sc.auto = fnOrSelf(rangeIsArr ? false : sc.auto);2603
2604sc.clamp = fnOrSelf(sc.clamp || clampScale);2605
2606// caches for expensive ops like asinh() & log()2607sc._min = sc._max = null;2608}2609}2610}2611
2612initScale("x");2613initScale("y");2614
2615// TODO: init scales from facets in mode: 22616if (mode == 1) {2617series.forEach(s => {2618initScale(s.scale);2619});2620}2621
2622axes.forEach(a => {2623initScale(a.scale);2624});2625
2626for (let k in opts.scales)2627initScale(k);2628
2629const scaleX = scales[xScaleKey];2630
2631const xScaleDistr = scaleX.distr;2632
2633let valToPosX, valToPosY;2634
2635if (scaleX.ori == 0) {2636addClass(root, ORI_HZ);2637valToPosX = getHPos;2638valToPosY = getVPos;2639/*2640updOriDims = () => {
2641xDimCan = plotWid;
2642xOffCan = plotLft;
2643yDimCan = plotHgt;
2644yOffCan = plotTop;
2645
2646xDimCss = plotWidCss;
2647xOffCss = plotLftCss;
2648yDimCss = plotHgtCss;
2649yOffCss = plotTopCss;
2650};
2651*/
2652}2653else {2654addClass(root, ORI_VT);2655valToPosX = getVPos;2656valToPosY = getHPos;2657/*2658updOriDims = () => {
2659xDimCan = plotHgt;
2660xOffCan = plotTop;
2661yDimCan = plotWid;
2662yOffCan = plotLft;
2663
2664xDimCss = plotHgtCss;
2665xOffCss = plotTopCss;
2666yDimCss = plotWidCss;
2667yOffCss = plotLftCss;
2668};
2669*/
2670}2671
2672const pendScales = {};2673
2674// explicitly-set initial scales2675for (let k in scales) {2676let sc = scales[k];2677
2678if (sc.min != null || sc.max != null) {2679pendScales[k] = {min: sc.min, max: sc.max};2680sc.min = sc.max = null;2681}2682}2683
2684// self.tz = opts.tz || Intl.DateTimeFormat().resolvedOptions().timeZone;2685const _tzDate = (opts.tzDate || (ts => new Date(round(ts / ms))));2686const _fmtDate = (opts.fmtDate || fmtDate);2687
2688const _timeAxisSplits = (ms == 1 ? timeAxisSplitsMs(_tzDate) : timeAxisSplitsS(_tzDate));2689const _timeAxisVals = timeAxisVals(_tzDate, timeAxisStamps((ms == 1 ? _timeAxisStampsMs : _timeAxisStampsS), _fmtDate));2690const _timeSeriesVal = timeSeriesVal(_tzDate, timeSeriesStamp(_timeSeriesStamp, _fmtDate));2691
2692const activeIdxs = [];2693
2694const legend = (self.legend = assign({}, legendOpts, opts.legend));2695const showLegend = legend.show;2696const markers = legend.markers;2697
2698{2699legend.idxs = activeIdxs;2700
2701markers.width = fnOrSelf(markers.width);2702markers.dash = fnOrSelf(markers.dash);2703markers.stroke = fnOrSelf(markers.stroke);2704markers.fill = fnOrSelf(markers.fill);2705}2706
2707let legendEl;2708let legendRows = [];2709let legendCells = [];2710let legendCols;2711let multiValLegend = false;2712let NULL_LEGEND_VALUES = {};2713
2714if (legend.live) {2715const getMultiVals = series[1] ? series[1].values : null;2716multiValLegend = getMultiVals != null;2717legendCols = multiValLegend ? getMultiVals(self, 1, 0) : {_: 0};2718
2719for (let k in legendCols)2720NULL_LEGEND_VALUES[k] = "--";2721}2722
2723if (showLegend) {2724legendEl = placeTag("table", LEGEND, root);2725
2726if (multiValLegend) {2727let head = placeTag("tr", LEGEND_THEAD, legendEl);2728placeTag("th", null, head);2729
2730for (var key in legendCols)2731placeTag("th", LEGEND_LABEL, head).textContent = key;2732}2733else {2734addClass(legendEl, LEGEND_INLINE);2735legend.live && addClass(legendEl, LEGEND_LIVE);2736}2737}2738
2739const son = {show: true};2740const soff = {show: false};2741
2742function initLegendRow(s, i) {2743if (i == 0 && (multiValLegend || !legend.live || mode == 2))2744return nullNullTuple;2745
2746let cells = [];2747
2748let row = placeTag("tr", LEGEND_SERIES, legendEl, legendEl.childNodes[i]);2749
2750addClass(row, s.class);2751
2752if (!s.show)2753addClass(row, OFF);2754
2755let label = placeTag("th", null, row);2756
2757if (markers.show) {2758let indic = placeDiv(LEGEND_MARKER, label);2759
2760if (i > 0) {2761let width = markers.width(self, i);2762
2763if (width)2764indic.style.border = width + "px " + markers.dash(self, i) + " " + markers.stroke(self, i);2765
2766indic.style.background = markers.fill(self, i);2767}2768}2769
2770let text = placeDiv(LEGEND_LABEL, label);2771text.textContent = s.label;2772
2773if (i > 0) {2774if (!markers.show)2775text.style.color = s.width > 0 ? markers.stroke(self, i) : markers.fill(self, i);2776
2777onMouse("click", label, e => {2778if (cursor._lock)2779return;2780
2781let seriesIdx = series.indexOf(s);2782
2783if ((e.ctrlKey || e.metaKey) != legend.isolate) {2784// if any other series is shown, isolate this one. else show all2785let isolate = series.some((s, i) => i > 0 && i != seriesIdx && s.show);2786
2787series.forEach((s, i) => {2788i > 0 && setSeries(i, isolate ? (i == seriesIdx ? son : soff) : son, true, syncOpts.setSeries);2789});2790}2791else2792setSeries(seriesIdx, {show: !s.show}, true, syncOpts.setSeries);2793});2794
2795if (cursorFocus) {2796onMouse(mouseenter, label, e => {2797if (cursor._lock)2798return;2799
2800setSeries(series.indexOf(s), FOCUS_TRUE, true, syncOpts.setSeries);2801});2802}2803}2804
2805for (var key in legendCols) {2806let v = placeTag("td", LEGEND_VALUE, row);2807v.textContent = "--";2808cells.push(v);2809}2810
2811return [row, cells];2812}2813
2814const mouseListeners = new Map();2815
2816function onMouse(ev, targ, fn) {2817const targListeners = mouseListeners.get(targ) || {};2818const listener = cursor.bind[ev](self, targ, fn);2819
2820if (listener) {2821on(ev, targ, targListeners[ev] = listener);2822mouseListeners.set(targ, targListeners);2823}2824}2825
2826function offMouse(ev, targ, fn) {2827const targListeners = mouseListeners.get(targ) || {};2828
2829for (let k in targListeners) {2830if (ev == null || k == ev) {2831off(k, targ, targListeners[k]);2832delete targListeners[k];2833}2834}2835
2836if (ev == null)2837mouseListeners.delete(targ);2838}2839
2840let fullWidCss = 0;2841let fullHgtCss = 0;2842
2843let plotWidCss = 0;2844let plotHgtCss = 0;2845
2846// plot margins to account for axes2847let plotLftCss = 0;2848let plotTopCss = 0;2849
2850let plotLft = 0;2851let plotTop = 0;2852let plotWid = 0;2853let plotHgt = 0;2854
2855self.bbox = {};2856
2857let shouldSetScales = false;2858let shouldSetSize = false;2859let shouldConvergeSize = false;2860let shouldSetCursor = false;2861let shouldSetLegend = false;2862
2863function _setSize(width, height, force) {2864if (force || (width != self.width || height != self.height))2865calcSize(width, height);2866
2867resetYSeries(false);2868
2869shouldConvergeSize = true;2870shouldSetSize = true;2871shouldSetCursor = shouldSetLegend = cursor.left >= 0;2872commit();2873}2874
2875function calcSize(width, height) {2876// log("calcSize()", arguments);2877
2878self.width = fullWidCss = plotWidCss = width;2879self.height = fullHgtCss = plotHgtCss = height;2880plotLftCss = plotTopCss = 0;2881
2882calcPlotRect();2883calcAxesRects();2884
2885let bb = self.bbox;2886
2887plotLft = bb.left = incrRound(plotLftCss * pxRatio, 0.5);2888plotTop = bb.top = incrRound(plotTopCss * pxRatio, 0.5);2889plotWid = bb.width = incrRound(plotWidCss * pxRatio, 0.5);2890plotHgt = bb.height = incrRound(plotHgtCss * pxRatio, 0.5);2891
2892// updOriDims();2893}2894
2895// ensures size calc convergence2896const CYCLE_LIMIT = 3;2897
2898function convergeSize() {2899let converged = false;2900
2901let cycleNum = 0;2902
2903while (!converged) {2904cycleNum++;2905
2906let axesConverged = axesCalc(cycleNum);2907let paddingConverged = paddingCalc(cycleNum);2908
2909converged = cycleNum == CYCLE_LIMIT || (axesConverged && paddingConverged);2910
2911if (!converged) {2912calcSize(self.width, self.height);2913shouldSetSize = true;2914}2915}2916}2917
2918function setSize({width, height}) {2919_setSize(width, height);2920}2921
2922self.setSize = setSize;2923
2924// accumulate axis offsets, reduce canvas width2925function calcPlotRect() {2926// easements for edge labels2927let hasTopAxis = false;2928let hasBtmAxis = false;2929let hasRgtAxis = false;2930let hasLftAxis = false;2931
2932axes.forEach((axis, i) => {2933if (axis.show && axis._show) {2934let {side, _size} = axis;2935let isVt = side % 2;2936let labelSize = axis.label != null ? axis.labelSize : 0;2937
2938let fullSize = _size + labelSize;2939
2940if (fullSize > 0) {2941if (isVt) {2942plotWidCss -= fullSize;2943
2944if (side == 3) {2945plotLftCss += fullSize;2946hasLftAxis = true;2947}2948else2949hasRgtAxis = true;2950}2951else {2952plotHgtCss -= fullSize;2953
2954if (side == 0) {2955plotTopCss += fullSize;2956hasTopAxis = true;2957}2958else2959hasBtmAxis = true;2960}2961}2962}2963});2964
2965sidesWithAxes[0] = hasTopAxis;2966sidesWithAxes[1] = hasRgtAxis;2967sidesWithAxes[2] = hasBtmAxis;2968sidesWithAxes[3] = hasLftAxis;2969
2970// hz padding2971plotWidCss -= _padding[1] + _padding[3];2972plotLftCss += _padding[3];2973
2974// vt padding2975plotHgtCss -= _padding[2] + _padding[0];2976plotTopCss += _padding[0];2977}2978
2979function calcAxesRects() {2980// will accum +2981let off1 = plotLftCss + plotWidCss;2982let off2 = plotTopCss + plotHgtCss;2983// will accum -2984let off3 = plotLftCss;2985let off0 = plotTopCss;2986
2987function incrOffset(side, size) {2988switch (side) {2989case 1: off1 += size; return off1 - size;2990case 2: off2 += size; return off2 - size;2991case 3: off3 -= size; return off3 + size;2992case 0: off0 -= size; return off0 + size;2993}2994}2995
2996axes.forEach((axis, i) => {2997if (axis.show && axis._show) {2998let side = axis.side;2999
3000axis._pos = incrOffset(side, axis._size);3001
3002if (axis.label != null)3003axis._lpos = incrOffset(side, axis.labelSize);3004}3005});3006}3007
3008const cursor = (self.cursor = assign({}, cursorOpts, {drag: {y: mode == 2}}, opts.cursor));3009
3010{3011cursor.idxs = activeIdxs;3012
3013cursor._lock = false;3014
3015let points = cursor.points;3016
3017points.show = fnOrSelf(points.show);3018points.size = fnOrSelf(points.size);3019points.stroke = fnOrSelf(points.stroke);3020points.width = fnOrSelf(points.width);3021points.fill = fnOrSelf(points.fill);3022}3023
3024const focus = self.focus = assign({}, opts.focus || {alpha: 0.3}, cursor.focus);3025const cursorFocus = focus.prox >= 0;3026
3027// series-intersection markers3028let cursorPts = [null];3029
3030function initCursorPt(s, si) {3031if (si > 0) {3032let pt = cursor.points.show(self, si);3033
3034if (pt) {3035addClass(pt, CURSOR_PT);3036addClass(pt, s.class);3037elTrans(pt, -10, -10, plotWidCss, plotHgtCss);3038over.insertBefore(pt, cursorPts[si]);3039
3040return pt;3041}3042}3043}3044
3045function initSeries(s, i) {3046if (mode == 1 || i > 0) {3047let isTime = mode == 1 && scales[s.scale].time;3048
3049let sv = s.value;3050s.value = isTime ? (isStr(sv) ? timeSeriesVal(_tzDate, timeSeriesStamp(sv, _fmtDate)) : sv || _timeSeriesVal) : sv || numSeriesVal;3051s.label = s.label || (isTime ? timeSeriesLabel : numSeriesLabel);3052}3053
3054if (i > 0) {3055s.width = s.width == null ? 1 : s.width;3056s.paths = s.paths || linearPath || retNull;3057s.fillTo = fnOrSelf(s.fillTo || seriesFillTo);3058s.pxAlign = +ifNull(s.pxAlign, pxAlign);3059s.pxRound = pxRoundGen(s.pxAlign);3060
3061s.stroke = fnOrSelf(s.stroke || null);3062s.fill = fnOrSelf(s.fill || null);3063s._stroke = s._fill = s._paths = s._focus = null;3064
3065let _ptDia = ptDia(s.width, 1);3066let points = s.points = assign({}, {3067size: _ptDia,3068width: max(1, _ptDia * .2),3069stroke: s.stroke,3070space: _ptDia * 2,3071paths: pointsPath,3072_stroke: null,3073_fill: null,3074}, s.points);3075points.show = fnOrSelf(points.show);3076points.filter = fnOrSelf(points.filter);3077points.fill = fnOrSelf(points.fill);3078points.stroke = fnOrSelf(points.stroke);3079points.paths = fnOrSelf(points.paths);3080points.pxAlign = s.pxAlign;3081}3082
3083if (showLegend) {3084let rowCells = initLegendRow(s, i);3085legendRows.splice(i, 0, rowCells[0]);3086legendCells.splice(i, 0, rowCells[1]);3087legend.values.push(null); // NULL_LEGEND_VALS not yet avil here :(3088}3089
3090if (cursor.show) {3091activeIdxs.splice(i, 0, null);3092
3093let pt = initCursorPt(s, i);3094pt && cursorPts.splice(i, 0, pt);3095}3096}3097
3098function addSeries(opts, si) {3099si = si == null ? series.length : si;3100
3101opts = setDefault(opts, si, xSeriesOpts, ySeriesOpts);3102series.splice(si, 0, opts);3103initSeries(series[si], si);3104}3105
3106self.addSeries = addSeries;3107
3108function delSeries(i) {3109series.splice(i, 1);3110
3111if (showLegend) {3112legend.values.splice(i, 1);3113
3114legendCells.splice(i, 1);3115let tr = legendRows.splice(i, 1)[0];3116offMouse(null, tr.firstChild);3117tr.remove();3118}3119
3120if (cursor.show) {3121activeIdxs.splice(i, 1);3122
3123cursorPts.length > 1 && cursorPts.splice(i, 1)[0].remove();3124}3125
3126// TODO: de-init no-longer-needed scales?3127}3128
3129self.delSeries = delSeries;3130
3131const sidesWithAxes = [false, false, false, false];3132
3133function initAxis(axis, i) {3134axis._show = axis.show;3135
3136if (axis.show) {3137let isVt = axis.side % 2;3138
3139let sc = scales[axis.scale];3140
3141// this can occur if all series specify non-default scales3142if (sc == null) {3143axis.scale = isVt ? series[1].scale : xScaleKey;3144sc = scales[axis.scale];3145}3146
3147// also set defaults for incrs & values based on axis distr3148let isTime = sc.time;3149
3150axis.size = fnOrSelf(axis.size);3151axis.space = fnOrSelf(axis.space);3152axis.rotate = fnOrSelf(axis.rotate);3153axis.incrs = fnOrSelf(axis.incrs || ( sc.distr == 2 ? wholeIncrs : (isTime ? (ms == 1 ? timeIncrsMs : timeIncrsS) : numIncrs)));3154axis.splits = fnOrSelf(axis.splits || (isTime && sc.distr == 1 ? _timeAxisSplits : sc.distr == 3 ? logAxisSplits : sc.distr == 4 ? asinhAxisSplits : numAxisSplits));3155
3156axis.stroke = fnOrSelf(axis.stroke);3157axis.grid.stroke = fnOrSelf(axis.grid.stroke);3158axis.ticks.stroke = fnOrSelf(axis.ticks.stroke);3159
3160let av = axis.values;3161
3162axis.values = (3163// static array of tick values3164isArr(av) && !isArr(av[0]) ? fnOrSelf(av) :3165// temporal3166isTime ? (3167// config array of fmtDate string tpls3168isArr(av) ?3169timeAxisVals(_tzDate, timeAxisStamps(av, _fmtDate)) :3170// fmtDate string tpl3171isStr(av) ?3172timeAxisVal(_tzDate, av) :3173av || _timeAxisVals3174) : av || numAxisVals3175);3176
3177axis.filter = fnOrSelf(axis.filter || ( sc.distr >= 3 ? logAxisValsFilt : retArg1));3178
3179axis.font = pxRatioFont(axis.font);3180axis.labelFont = pxRatioFont(axis.labelFont);3181
3182axis._size = axis.size(self, null, i, 0);3183
3184axis._space =3185axis._rotate =3186axis._incrs =3187axis._found = // foundIncrSpace3188axis._splits =3189axis._values = null;3190
3191if (axis._size > 0)3192sidesWithAxes[i] = true;3193
3194axis._el = placeDiv(AXIS, wrap);3195
3196// debug3197// axis._el.style.background = "#" + Math.floor(Math.random()*16777215).toString(16) + '80';3198}3199}3200
3201function autoPadSide(self, side, sidesWithAxes, cycleNum) {3202let [hasTopAxis, hasRgtAxis, hasBtmAxis, hasLftAxis] = sidesWithAxes;3203
3204let ori = side % 2;3205let size = 0;3206
3207if (ori == 0 && (hasLftAxis || hasRgtAxis))3208size = (side == 0 && !hasTopAxis || side == 2 && !hasBtmAxis ? round(xAxisOpts.size / 3) : 0);3209if (ori == 1 && (hasTopAxis || hasBtmAxis))3210size = (side == 1 && !hasRgtAxis || side == 3 && !hasLftAxis ? round(yAxisOpts.size / 2) : 0);3211
3212return size;3213}3214
3215const padding = self.padding = (opts.padding || [autoPadSide,autoPadSide,autoPadSide,autoPadSide]).map(p => fnOrSelf(ifNull(p, autoPadSide)));3216const _padding = self._padding = padding.map((p, i) => p(self, i, sidesWithAxes, 0));3217
3218let dataLen;3219
3220// rendered data window3221let i0 = null;3222let i1 = null;3223const idxs = mode == 1 ? series[0].idxs : null;3224
3225let data0 = null;3226
3227let viaAutoScaleX = false;3228
3229function setData(_data, _resetScales) {3230if (mode == 2) {3231dataLen = 0;3232for (let i = 1; i < series.length; i++)3233dataLen += data[i][0].length;3234self.data = data = _data;3235}3236else {3237data = (_data || []).slice();3238data[0] = data[0] || [];3239
3240self.data = data.slice();3241data0 = data[0];3242dataLen = data0.length;3243
3244if (xScaleDistr == 2)3245data[0] = data0.map((v, i) => i);3246}3247
3248self._data = data;3249
3250resetYSeries(true);3251
3252fire("setData");3253
3254if (_resetScales !== false) {3255let xsc = scaleX;3256
3257if (xsc.auto(self, viaAutoScaleX))3258autoScaleX();3259else3260_setScale(xScaleKey, xsc.min, xsc.max);3261
3262shouldSetCursor = cursor.left >= 0;3263shouldSetLegend = true;3264commit();3265}3266}3267
3268self.setData = setData;3269
3270function autoScaleX() {3271viaAutoScaleX = true;3272
3273let _min, _max;3274
3275if (mode == 1) {3276if (dataLen > 0) {3277i0 = idxs[0] = 0;3278i1 = idxs[1] = dataLen - 1;3279
3280_min = data[0][i0];3281_max = data[0][i1];3282
3283if (xScaleDistr == 2) {3284_min = i0;3285_max = i1;3286}3287else if (dataLen == 1) {3288if (xScaleDistr == 3)3289[_min, _max] = rangeLog(_min, _min, scaleX.log, false);3290else if (xScaleDistr == 4)3291[_min, _max] = rangeAsinh(_min, _min, scaleX.log, false);3292else if (scaleX.time)3293_max = _min + round(86400 / ms);3294else3295[_min, _max] = rangeNum(_min, _max, rangePad, true);3296}3297}3298else {3299i0 = idxs[0] = _min = null;3300i1 = idxs[1] = _max = null;3301}3302}3303
3304_setScale(xScaleKey, _min, _max);3305}3306
3307let ctxStroke, ctxFill, ctxWidth, ctxDash, ctxJoin, ctxCap, ctxFont, ctxAlign, ctxBaseline;3308let ctxAlpha;3309
3310function setCtxStyle(stroke = transparent, width, dash = EMPTY_ARR, cap = "butt", fill = transparent, join = "round") {3311if (stroke != ctxStroke)3312ctx.strokeStyle = ctxStroke = stroke;3313if (fill != ctxFill)3314ctx.fillStyle = ctxFill = fill;3315if (width != ctxWidth)3316ctx.lineWidth = ctxWidth = width;3317if (join != ctxJoin)3318ctx.lineJoin = ctxJoin = join;3319if (cap != ctxCap)3320ctx.lineCap = ctxCap = cap; // (‿|‿)3321if (dash != ctxDash)3322ctx.setLineDash(ctxDash = dash);3323}3324
3325function setFontStyle(font, fill, align, baseline) {3326if (fill != ctxFill)3327ctx.fillStyle = ctxFill = fill;3328if (font != ctxFont)3329ctx.font = ctxFont = font;3330if (align != ctxAlign)3331ctx.textAlign = ctxAlign = align;3332if (baseline != ctxBaseline)3333ctx.textBaseline = ctxBaseline = baseline;3334}3335
3336function accScale(wsc, psc, facet, data) {3337if (wsc.auto(self, viaAutoScaleX) && (psc == null || psc.min == null)) {3338let _i0 = ifNull(i0, 0);3339let _i1 = ifNull(i1, data.length - 1);3340
3341// only run getMinMax() for invalidated series data, else reuse3342let minMax = facet.min == null ? (wsc.distr == 3 ? getMinMaxLog(data, _i0, _i1) : getMinMax(data, _i0, _i1)) : [facet.min, facet.max];3343
3344// initial min/max3345wsc.min = min(wsc.min, facet.min = minMax[0]);3346wsc.max = max(wsc.max, facet.max = minMax[1]);3347}3348}3349
3350function setScales() {3351// log("setScales()", arguments);3352
3353// wip scales3354let wipScales = copy(scales, fastIsObj);3355
3356for (let k in wipScales) {3357let wsc = wipScales[k];3358let psc = pendScales[k];3359
3360if (psc != null && psc.min != null) {3361assign(wsc, psc);3362
3363// explicitly setting the x-scale invalidates everything (acts as redraw)3364if (k == xScaleKey)3365resetYSeries(true);3366}3367else if (k != xScaleKey || mode == 2) {3368if (dataLen == 0 && wsc.from == null) {3369let minMax = wsc.range(self, null, null, k);3370wsc.min = minMax[0];3371wsc.max = minMax[1];3372}3373else {3374wsc.min = inf;3375wsc.max = -inf;3376}3377}3378}3379
3380if (dataLen > 0) {3381// pre-range y-scales from y series' data values3382series.forEach((s, i) => {3383if (mode == 1) {3384let k = s.scale;3385let wsc = wipScales[k];3386let psc = pendScales[k];3387
3388if (i == 0) {3389let minMax = wsc.range(self, wsc.min, wsc.max, k);3390
3391wsc.min = minMax[0];3392wsc.max = minMax[1];3393
3394i0 = closestIdx(wsc.min, data[0]);3395i1 = closestIdx(wsc.max, data[0]);3396
3397// closest indices can be outside of view3398if (data[0][i0] < wsc.min)3399i0++;3400if (data[0][i1] > wsc.max)3401i1--;3402
3403s.min = data0[i0];3404s.max = data0[i1];3405}3406else if (s.show && s.auto)3407accScale(wsc, psc, s, data[i]);3408
3409s.idxs[0] = i0;3410s.idxs[1] = i1;3411}3412else {3413if (i > 0) {3414if (s.show && s.auto) {3415// TODO: only handles, assumes and requires facets[0] / 'x' scale, and facets[1] / 'y' scale3416let [ xFacet, yFacet ] = s.facets;3417let xScaleKey = xFacet.scale;3418let yScaleKey = yFacet.scale;3419let [ xData, yData ] = data[i];3420
3421accScale(wipScales[xScaleKey], pendScales[xScaleKey], xFacet, xData);3422accScale(wipScales[yScaleKey], pendScales[yScaleKey], yFacet, yData);3423
3424// temp3425s.min = yFacet.min;3426s.max = yFacet.max;3427}3428}3429}3430});3431
3432// range independent scales3433for (let k in wipScales) {3434let wsc = wipScales[k];3435let psc = pendScales[k];3436
3437if (wsc.from == null && (psc == null || psc.min == null)) {3438let minMax = wsc.range(3439self,3440wsc.min == inf ? null : wsc.min,3441wsc.max == -inf ? null : wsc.max,3442k
3443);3444wsc.min = minMax[0];3445wsc.max = minMax[1];3446}3447}3448}3449
3450// range dependent scales3451for (let k in wipScales) {3452let wsc = wipScales[k];3453
3454if (wsc.from != null) {3455let base = wipScales[wsc.from];3456
3457if (base.min == null)3458wsc.min = wsc.max = null;3459else {3460let minMax = wsc.range(self, base.min, base.max, k);3461wsc.min = minMax[0];3462wsc.max = minMax[1];3463}3464}3465}3466
3467let changed = {};3468let anyChanged = false;3469
3470for (let k in wipScales) {3471let wsc = wipScales[k];3472let sc = scales[k];3473
3474if (sc.min != wsc.min || sc.max != wsc.max) {3475sc.min = wsc.min;3476sc.max = wsc.max;3477
3478let distr = sc.distr;3479
3480sc._min = distr == 3 ? log10(sc.min) : distr == 4 ? asinh(sc.min, sc.asinh) : sc.min;3481sc._max = distr == 3 ? log10(sc.max) : distr == 4 ? asinh(sc.max, sc.asinh) : sc.max;3482
3483changed[k] = anyChanged = true;3484}3485}3486
3487if (anyChanged) {3488// invalidate paths of all series on changed scales3489series.forEach((s, i) => {3490if (mode == 2) {3491if (i > 0 && changed.y)3492s._paths = null;3493}3494else {3495if (changed[s.scale])3496s._paths = null;3497}3498});3499
3500for (let k in changed) {3501shouldConvergeSize = true;3502fire("setScale", k);3503}3504
3505if (cursor.show)3506shouldSetCursor = shouldSetLegend = cursor.left >= 0;3507}3508
3509for (let k in pendScales)3510pendScales[k] = null;3511}3512
3513// grabs the nearest indices with y data outside of x-scale limits3514function getOuterIdxs(ydata) {3515let _i0 = clamp(i0 - 1, 0, dataLen - 1);3516let _i1 = clamp(i1 + 1, 0, dataLen - 1);3517
3518while (ydata[_i0] == null && _i0 > 0)3519_i0--;3520
3521while (ydata[_i1] == null && _i1 < dataLen - 1)3522_i1++;3523
3524return [_i0, _i1];3525}3526
3527function drawSeries() {3528if (dataLen > 0) {3529series.forEach((s, i) => {3530if (i > 0 && s.show && s._paths == null) {3531let _idxs = getOuterIdxs(data[i]);3532s._paths = s.paths(self, i, _idxs[0], _idxs[1]);3533}3534});3535
3536series.forEach((s, i) => {3537if (i > 0 && s.show) {3538if (ctxAlpha != s.alpha)3539ctx.globalAlpha = ctxAlpha = s.alpha;3540
3541{3542cacheStrokeFill(i, false);3543s._paths && drawPath(i, false);3544}3545
3546{3547cacheStrokeFill(i, true);3548
3549let show = s.points.show(self, i, i0, i1);3550let idxs = s.points.filter(self, i, show, s._paths ? s._paths.gaps : null);3551
3552if (show || idxs) {3553s.points._paths = s.points.paths(self, i, i0, i1, idxs);3554drawPath(i, true);3555}3556}3557
3558if (ctxAlpha != 1)3559ctx.globalAlpha = ctxAlpha = 1;3560
3561fire("drawSeries", i);3562}3563});3564}3565}3566
3567function cacheStrokeFill(si, _points) {3568let s = _points ? series[si].points : series[si];3569
3570s._stroke = s.stroke(self, si);3571s._fill = s.fill(self, si);3572}3573
3574function drawPath(si, _points) {3575let s = _points ? series[si].points : series[si];3576
3577let strokeStyle = s._stroke;3578let fillStyle = s._fill;3579
3580let { stroke, fill, clip: gapsClip, flags } = s._paths;3581let boundsClip = null;3582let width = roundDec(s.width * pxRatio, 3);3583let offset = (width % 2) / 2;3584
3585if (_points && fillStyle == null)3586fillStyle = width > 0 ? "#fff" : strokeStyle;3587
3588let _pxAlign = s.pxAlign == 1;3589
3590_pxAlign && ctx.translate(offset, offset);3591
3592if (!_points) {3593let lft = plotLft,3594top = plotTop,3595wid = plotWid,3596hgt = plotHgt;3597
3598let halfWid = width * pxRatio / 2;3599
3600if (s.min == 0)3601hgt += halfWid;3602
3603if (s.max == 0) {3604top -= halfWid;3605hgt += halfWid;3606}3607
3608boundsClip = new Path2D();3609boundsClip.rect(lft, top, wid, hgt);3610}3611
3612// the points pathbuilder's gapsClip is its boundsClip, since points dont need gaps clipping, and bounds depend on point size3613if (_points)3614strokeFill(strokeStyle, width, s.dash, s.cap, fillStyle, stroke, fill, flags, gapsClip);3615else3616fillStroke(si, strokeStyle, width, s.dash, s.cap, fillStyle, stroke, fill, flags, boundsClip, gapsClip);3617
3618_pxAlign && ctx.translate(-offset, -offset);3619}3620
3621function fillStroke(si, strokeStyle, lineWidth, lineDash, lineCap, fillStyle, strokePath, fillPath, flags, boundsClip, gapsClip) {3622let didStrokeFill = false;3623
3624// for all bands where this series is the top edge, create upwards clips using the bottom edges3625// and apply clips + fill with band fill or dfltFill3626bands.forEach((b, bi) => {3627// isUpperEdge?3628if (b.series[0] == si) {3629let lowerEdge = series[b.series[1]];3630let lowerData = data[b.series[1]];3631
3632let bandClip = (lowerEdge._paths || EMPTY_OBJ).band;3633let gapsClip2;3634
3635let _fillStyle = null;3636
3637// hasLowerEdge?3638if (lowerEdge.show && bandClip && hasData(lowerData, i0, i1)) {3639_fillStyle = b.fill(self, bi) || fillStyle;3640gapsClip2 = lowerEdge._paths.clip;3641}3642else3643bandClip = null;3644
3645strokeFill(strokeStyle, lineWidth, lineDash, lineCap, _fillStyle, strokePath, fillPath, flags, boundsClip, gapsClip, gapsClip2, bandClip);3646
3647didStrokeFill = true;3648}3649});3650
3651if (!didStrokeFill)3652strokeFill(strokeStyle, lineWidth, lineDash, lineCap, fillStyle, strokePath, fillPath, flags, boundsClip, gapsClip);3653}3654
3655const CLIP_FILL_STROKE = BAND_CLIP_FILL | BAND_CLIP_STROKE;3656
3657function strokeFill(strokeStyle, lineWidth, lineDash, lineCap, fillStyle, strokePath, fillPath, flags, boundsClip, gapsClip, gapsClip2, bandClip) {3658setCtxStyle(strokeStyle, lineWidth, lineDash, lineCap, fillStyle);3659
3660if (boundsClip || gapsClip || bandClip) {3661ctx.save();3662boundsClip && ctx.clip(boundsClip);3663gapsClip && ctx.clip(gapsClip);3664}3665
3666if (bandClip) {3667if ((flags & CLIP_FILL_STROKE) == CLIP_FILL_STROKE) {3668ctx.clip(bandClip);3669gapsClip2 && ctx.clip(gapsClip2);3670doFill(fillStyle, fillPath);3671doStroke(strokeStyle, strokePath, lineWidth);3672}3673else if (flags & BAND_CLIP_STROKE) {3674doFill(fillStyle, fillPath);3675ctx.clip(bandClip);3676doStroke(strokeStyle, strokePath, lineWidth);3677}3678else if (flags & BAND_CLIP_FILL) {3679ctx.save();3680ctx.clip(bandClip);3681gapsClip2 && ctx.clip(gapsClip2);3682doFill(fillStyle, fillPath);3683ctx.restore();3684doStroke(strokeStyle, strokePath, lineWidth);3685}3686}3687else {3688doFill(fillStyle, fillPath);3689doStroke(strokeStyle, strokePath, lineWidth);3690}3691
3692if (boundsClip || gapsClip || bandClip)3693ctx.restore();3694}3695
3696function doStroke(strokeStyle, strokePath, lineWidth) {3697if (lineWidth > 0) {3698if (strokePath instanceof Map) {3699strokePath.forEach((strokePath, strokeStyle) => {3700ctx.strokeStyle = ctxStroke = strokeStyle;3701ctx.stroke(strokePath);3702});3703}3704else3705strokePath != null && strokeStyle && ctx.stroke(strokePath);3706}3707}3708
3709function doFill(fillStyle, fillPath) {3710if (fillPath instanceof Map) {3711fillPath.forEach((fillPath, fillStyle) => {3712ctx.fillStyle = ctxFill = fillStyle;3713ctx.fill(fillPath);3714});3715}3716else3717fillPath != null && fillStyle && ctx.fill(fillPath);3718}3719
3720function getIncrSpace(axisIdx, min, max, fullDim) {3721let axis = axes[axisIdx];3722
3723let incrSpace;3724
3725if (fullDim <= 0)3726incrSpace = [0, 0];3727else {3728let minSpace = axis._space = axis.space(self, axisIdx, min, max, fullDim);3729let incrs = axis._incrs = axis.incrs(self, axisIdx, min, max, fullDim, minSpace);3730incrSpace = findIncr(min, max, incrs, fullDim, minSpace);3731}3732
3733return (axis._found = incrSpace);3734}3735
3736function drawOrthoLines(offs, filts, ori, side, pos0, len, width, stroke, dash, cap) {3737let offset = (width % 2) / 2;3738
3739pxAlign == 1 && ctx.translate(offset, offset);3740
3741setCtxStyle(stroke, width, dash, cap, stroke);3742
3743ctx.beginPath();3744
3745let x0, y0, x1, y1, pos1 = pos0 + (side == 0 || side == 3 ? -len : len);3746
3747if (ori == 0) {3748y0 = pos0;3749y1 = pos1;3750}3751else {3752x0 = pos0;3753x1 = pos1;3754}3755
3756for (let i = 0; i < offs.length; i++) {3757if (filts[i] != null) {3758if (ori == 0)3759x0 = x1 = offs[i];3760else3761y0 = y1 = offs[i];3762
3763ctx.moveTo(x0, y0);3764ctx.lineTo(x1, y1);3765}3766}3767
3768ctx.stroke();3769
3770pxAlign == 1 && ctx.translate(-offset, -offset);3771}3772
3773function axesCalc(cycleNum) {3774// log("axesCalc()", arguments);3775
3776let converged = true;3777
3778axes.forEach((axis, i) => {3779if (!axis.show)3780return;3781
3782let scale = scales[axis.scale];3783
3784if (scale.min == null) {3785if (axis._show) {3786converged = false;3787axis._show = false;3788resetYSeries(false);3789}3790return;3791}3792else {3793if (!axis._show) {3794converged = false;3795axis._show = true;3796resetYSeries(false);3797}3798}3799
3800let side = axis.side;3801let ori = side % 2;3802
3803let {min, max} = scale; // // should this toggle them ._show = false3804
3805let [_incr, _space] = getIncrSpace(i, min, max, ori == 0 ? plotWidCss : plotHgtCss);3806
3807if (_space == 0)3808return;3809
3810// if we're using index positions, force first tick to match passed index3811let forceMin = scale.distr == 2;3812
3813let _splits = axis._splits = axis.splits(self, i, min, max, _incr, _space, forceMin);3814
3815// tick labels3816// BOO this assumes a specific data/series3817let splits = scale.distr == 2 ? _splits.map(i => data0[i]) : _splits;3818let incr = scale.distr == 2 ? data0[_splits[1]] - data0[_splits[0]] : _incr;3819
3820let values = axis._values = axis.values(self, axis.filter(self, splits, i, _space, incr), i, _space, incr);3821
3822// rotating of labels only supported on bottom x axis3823axis._rotate = side == 2 ? axis.rotate(self, values, i, _space) : 0;3824
3825let oldSize = axis._size;3826
3827axis._size = ceil(axis.size(self, values, i, cycleNum));3828
3829if (oldSize != null && axis._size != oldSize) // ready && ?3830converged = false;3831});3832
3833return converged;3834}3835
3836function paddingCalc(cycleNum) {3837let converged = true;3838
3839padding.forEach((p, i) => {3840let _p = p(self, i, sidesWithAxes, cycleNum);3841
3842if (_p != _padding[i])3843converged = false;3844
3845_padding[i] = _p;3846});3847
3848return converged;3849}3850
3851function drawAxesGrid() {3852for (let i = 0; i < axes.length; i++) {3853let axis = axes[i];3854
3855if (!axis.show || !axis._show)3856continue;3857
3858let side = axis.side;3859let ori = side % 2;3860
3861let x, y;3862
3863let fillStyle = axis.stroke(self, i);3864
3865let shiftDir = side == 0 || side == 3 ? -1 : 1;3866
3867// axis label3868if (axis.label) {3869let shiftAmt = axis.labelGap * shiftDir;3870let baseLpos = round((axis._lpos + shiftAmt) * pxRatio);3871
3872setFontStyle(axis.labelFont[0], fillStyle, "center", side == 2 ? TOP : BOTTOM);3873
3874ctx.save();3875
3876if (ori == 1) {3877x = y = 0;3878
3879ctx.translate(3880baseLpos,3881round(plotTop + plotHgt / 2),3882);3883ctx.rotate((side == 3 ? -PI : PI) / 2);3884
3885}3886else {3887x = round(plotLft + plotWid / 2);3888y = baseLpos;3889}3890
3891ctx.fillText(axis.label, x, y);3892
3893ctx.restore();3894}3895
3896let [_incr, _space] = axis._found;3897
3898if (_space == 0)3899continue;3900
3901let scale = scales[axis.scale];3902
3903let plotDim = ori == 0 ? plotWid : plotHgt;3904let plotOff = ori == 0 ? plotLft : plotTop;3905
3906let axisGap = round(axis.gap * pxRatio);3907
3908let _splits = axis._splits;3909
3910// tick labels3911// BOO this assumes a specific data/series3912let splits = scale.distr == 2 ? _splits.map(i => data0[i]) : _splits;3913let incr = scale.distr == 2 ? data0[_splits[1]] - data0[_splits[0]] : _incr;3914
3915let ticks = axis.ticks;3916let tickSize = ticks.show ? round(ticks.size * pxRatio) : 0;3917
3918// rotating of labels only supported on bottom x axis3919let angle = axis._rotate * -PI/180;3920
3921let basePos = pxRound(axis._pos * pxRatio);3922let shiftAmt = (tickSize + axisGap) * shiftDir;3923let finalPos = basePos + shiftAmt;3924y = ori == 0 ? finalPos : 0;3925x = ori == 1 ? finalPos : 0;3926
3927let font = axis.font[0];3928let textAlign = axis.align == 1 ? LEFT :3929axis.align == 2 ? RIGHT :3930angle > 0 ? LEFT :3931angle < 0 ? RIGHT :3932ori == 0 ? "center" : side == 3 ? RIGHT : LEFT;3933let textBaseline = angle ||3934ori == 1 ? "middle" : side == 2 ? TOP : BOTTOM;3935
3936setFontStyle(font, fillStyle, textAlign, textBaseline);3937
3938let lineHeight = axis.font[1] * lineMult;3939
3940let canOffs = _splits.map(val => pxRound(getPos(val, scale, plotDim, plotOff)));3941
3942let _values = axis._values;3943
3944for (let i = 0; i < _values.length; i++) {3945let val = _values[i];3946
3947if (val != null) {3948if (ori == 0)3949x = canOffs[i];3950else3951y = canOffs[i];3952
3953val = "" + val;3954
3955let _parts = val.indexOf("\n") == -1 ? [val] : val.split(/\n/gm);3956
3957for (let j = 0; j < _parts.length; j++) {3958let text = _parts[j];3959
3960if (angle) {3961ctx.save();3962ctx.translate(x, y + j * lineHeight); // can this be replaced with position math?3963ctx.rotate(angle); // can this be done once?3964ctx.fillText(text, 0, 0);3965ctx.restore();3966}3967else3968ctx.fillText(text, x, y + j * lineHeight);3969}3970}3971}3972
3973// ticks3974if (ticks.show) {3975drawOrthoLines(3976canOffs,3977ticks.filter(self, splits, i, _space, incr),3978ori,3979side,3980basePos,3981tickSize,3982roundDec(ticks.width * pxRatio, 3),3983ticks.stroke(self, i),3984ticks.dash,3985ticks.cap,3986);3987}3988
3989// grid3990let grid = axis.grid;3991
3992if (grid.show) {3993drawOrthoLines(3994canOffs,3995grid.filter(self, splits, i, _space, incr),3996ori,3997ori == 0 ? 2 : 1,3998ori == 0 ? plotTop : plotLft,3999ori == 0 ? plotHgt : plotWid,4000roundDec(grid.width * pxRatio, 3),4001grid.stroke(self, i),4002grid.dash,4003grid.cap,4004);4005}4006}4007
4008fire("drawAxes");4009}4010
4011function resetYSeries(minMax) {4012// log("resetYSeries()", arguments);4013
4014series.forEach((s, i) => {4015if (i > 0) {4016s._paths = null;4017
4018if (minMax) {4019if (mode == 1) {4020s.min = null;4021s.max = null;4022}4023else {4024s.facets.forEach(f => {4025f.min = null;4026f.max = null;4027});4028}4029}4030}4031});4032}4033
4034let queuedCommit = false;4035
4036function commit() {4037if (!queuedCommit) {4038microTask(_commit);4039queuedCommit = true;4040}4041}4042
4043function _commit() {4044// log("_commit()", arguments);4045
4046if (shouldSetScales) {4047setScales();4048shouldSetScales = false;4049}4050
4051if (shouldConvergeSize) {4052convergeSize();4053shouldConvergeSize = false;4054}4055
4056if (shouldSetSize) {4057setStylePx(under, LEFT, plotLftCss);4058setStylePx(under, TOP, plotTopCss);4059setStylePx(under, WIDTH, plotWidCss);4060setStylePx(under, HEIGHT, plotHgtCss);4061
4062setStylePx(over, LEFT, plotLftCss);4063setStylePx(over, TOP, plotTopCss);4064setStylePx(over, WIDTH, plotWidCss);4065setStylePx(over, HEIGHT, plotHgtCss);4066
4067setStylePx(wrap, WIDTH, fullWidCss);4068setStylePx(wrap, HEIGHT, fullHgtCss);4069
4070// NOTE: mutating this during print preview in Chrome forces transparent4071// canvas pixels to white, even when followed up with clearRect() below4072can.width = round(fullWidCss * pxRatio);4073can.height = round(fullHgtCss * pxRatio);4074
4075
4076axes.forEach(a => {4077let { _show, _el, _size, _pos, side } = a;4078
4079if (_show) {4080let posOffset = (side === 3 || side === 0 ? _size : 0);4081let isVt = side % 2 == 1;4082
4083setStylePx(_el, isVt ? "left" : "top", _pos - posOffset);4084setStylePx(_el, isVt ? "width" : "height", _size);4085setStylePx(_el, isVt ? "top" : "left", isVt ? plotTopCss : plotLftCss);4086setStylePx(_el, isVt ? "height" : "width", isVt ? plotHgtCss : plotWidCss);4087
4088_el && remClass(_el, OFF);4089}4090else4091_el && addClass(_el, OFF);4092});4093
4094// invalidate ctx style cache4095ctxStroke = ctxFill = ctxWidth = ctxJoin = ctxCap = ctxFont = ctxAlign = ctxBaseline = ctxDash = null;4096ctxAlpha = 1;4097
4098syncRect(false);4099
4100fire("setSize");4101
4102shouldSetSize = false;4103}4104
4105if (fullWidCss > 0 && fullHgtCss > 0) {4106ctx.clearRect(0, 0, can.width, can.height);4107fire("drawClear");4108drawOrder.forEach(fn => fn());4109fire("draw");4110}4111
4112// if (shouldSetSelect) {4113// TODO: update .u-select metrics (if visible)4114// setStylePx(selectDiv, TOP, select.top = 0);4115// setStylePx(selectDiv, LEFT, select.left = 0);4116// setStylePx(selectDiv, WIDTH, select.width = 0);4117// setStylePx(selectDiv, HEIGHT, select.height = 0);4118// shouldSetSelect = false;4119// }4120
4121if (cursor.show && shouldSetCursor) {4122updateCursor(null, true, false);4123shouldSetCursor = false;4124}4125
4126// if (FEAT_LEGEND && legend.show && legend.live && shouldSetLegend) {}4127
4128if (!ready) {4129ready = true;4130self.status = 1;4131
4132fire("ready");4133}4134
4135viaAutoScaleX = false;4136
4137queuedCommit = false;4138}4139
4140self.redraw = (rebuildPaths, recalcAxes) => {4141shouldConvergeSize = recalcAxes || false;4142
4143if (rebuildPaths !== false)4144_setScale(xScaleKey, scaleX.min, scaleX.max);4145else4146commit();4147};4148
4149// redraw() => setScale('x', scales.x.min, scales.x.max);4150
4151// explicit, never re-ranged (is this actually true? for x and y)4152function setScale(key, opts) {4153let sc = scales[key];4154
4155if (sc.from == null) {4156if (dataLen == 0) {4157let minMax = sc.range(self, opts.min, opts.max, key);4158opts.min = minMax[0];4159opts.max = minMax[1];4160}4161
4162if (opts.min > opts.max) {4163let _min = opts.min;4164opts.min = opts.max;4165opts.max = _min;4166}4167
4168if (dataLen > 1 && opts.min != null && opts.max != null && opts.max - opts.min < 1e-16)4169return;4170
4171if (key == xScaleKey) {4172if (sc.distr == 2 && dataLen > 0) {4173opts.min = closestIdx(opts.min, data[0]);4174opts.max = closestIdx(opts.max, data[0]);4175
4176if (opts.min == opts.max)4177opts.max++;4178}4179}4180
4181// log("setScale()", arguments);4182
4183pendScales[key] = opts;4184
4185shouldSetScales = true;4186commit();4187}4188}4189
4190self.setScale = setScale;4191
4192// INTERACTION4193
4194let xCursor;4195let yCursor;4196let vCursor;4197let hCursor;4198
4199// starting position before cursor.move4200let rawMouseLeft0;4201let rawMouseTop0;4202
4203// starting position4204let mouseLeft0;4205let mouseTop0;4206
4207// current position before cursor.move4208let rawMouseLeft1;4209let rawMouseTop1;4210
4211// current position4212let mouseLeft1;4213let mouseTop1;4214
4215let dragging = false;4216
4217const drag = cursor.drag;4218
4219let dragX = drag.x;4220let dragY = drag.y;4221
4222if (cursor.show) {4223if (cursor.x)4224xCursor = placeDiv(CURSOR_X, over);4225if (cursor.y)4226yCursor = placeDiv(CURSOR_Y, over);4227
4228if (scaleX.ori == 0) {4229vCursor = xCursor;4230hCursor = yCursor;4231}4232else {4233vCursor = yCursor;4234hCursor = xCursor;4235}4236
4237mouseLeft1 = cursor.left;4238mouseTop1 = cursor.top;4239}4240
4241const select = self.select = assign({4242show: true,4243over: true,4244left: 0,4245width: 0,4246top: 0,4247height: 0,4248}, opts.select);4249
4250const selectDiv = select.show ? placeDiv(SELECT, select.over ? over : under) : null;4251
4252function setSelect(opts, _fire) {4253if (select.show) {4254for (let prop in opts)4255setStylePx(selectDiv, prop, select[prop] = opts[prop]);4256
4257_fire !== false && fire("setSelect");4258}4259}4260
4261self.setSelect = setSelect;4262
4263function toggleDOM(i, onOff) {4264let s = series[i];4265let label = showLegend ? legendRows[i] : null;4266
4267if (s.show)4268label && remClass(label, OFF);4269else {4270label && addClass(label, OFF);4271cursorPts.length > 1 && elTrans(cursorPts[i], -10, -10, plotWidCss, plotHgtCss);4272}4273}4274
4275function _setScale(key, min, max) {4276setScale(key, {min, max});4277}4278
4279function setSeries(i, opts, _fire, _pub) {4280// log("setSeries()", arguments);4281
4282let s = series[i];4283
4284if (opts.focus != null)4285setFocus(i);4286
4287if (opts.show != null) {4288s.show = opts.show;4289toggleDOM(i, opts.show);4290
4291_setScale(mode == 2 ? s.facets[1].scale : s.scale, null, null);4292commit();4293}4294
4295_fire !== false && fire("setSeries", i, opts);4296
4297_pub && pubSync("setSeries", self, i, opts);4298}4299
4300self.setSeries = setSeries;4301
4302function setBand(bi, opts) {4303assign(bands[bi], opts);4304}4305
4306function addBand(opts, bi) {4307opts.fill = fnOrSelf(opts.fill || null);4308bi = bi == null ? bands.length : bi;4309bands.splice(bi, 0, opts);4310}4311
4312function delBand(bi) {4313if (bi == null)4314bands.length = 0;4315else4316bands.splice(bi, 1);4317}4318
4319self.addBand = addBand;4320self.setBand = setBand;4321self.delBand = delBand;4322
4323function setAlpha(i, value) {4324series[i].alpha = value;4325
4326if (cursor.show && cursorPts[i])4327cursorPts[i].style.opacity = value;4328
4329if (showLegend && legendRows[i])4330legendRows[i].style.opacity = value;4331}4332
4333// y-distance4334let closestDist;4335let closestSeries;4336let focusedSeries;4337const FOCUS_TRUE = {focus: true};4338const FOCUS_FALSE = {focus: false};4339
4340function setFocus(i) {4341if (i != focusedSeries) {4342// log("setFocus()", arguments);4343
4344let allFocused = i == null;4345
4346let _setAlpha = focus.alpha != 1;4347
4348series.forEach((s, i2) => {4349let isFocused = allFocused || i2 == 0 || i2 == i;4350s._focus = allFocused ? null : isFocused;4351_setAlpha && setAlpha(i2, isFocused ? 1 : focus.alpha);4352});4353
4354focusedSeries = i;4355_setAlpha && commit();4356}4357}4358
4359if (showLegend && cursorFocus) {4360on(mouseleave, legendEl, e => {4361if (cursor._lock)4362return;4363setSeries(null, FOCUS_FALSE, true, syncOpts.setSeries);4364updateCursor(null, true, false);4365});4366}4367
4368function posToVal(pos, scale, can) {4369let sc = scales[scale];4370
4371if (can)4372pos = pos / pxRatio - (sc.ori == 1 ? plotTopCss : plotLftCss);4373
4374let dim = plotWidCss;4375
4376if (sc.ori == 1) {4377dim = plotHgtCss;4378pos = dim - pos;4379}4380
4381if (sc.dir == -1)4382pos = dim - pos;4383
4384let _min = sc._min,4385_max = sc._max,4386pct = pos / dim;4387
4388let sv = _min + (_max - _min) * pct;4389
4390let distr = sc.distr;4391
4392return (4393distr == 3 ? pow(10, sv) :4394distr == 4 ? sinh(sv, sc.asinh) :4395sv
4396);4397}4398
4399function closestIdxFromXpos(pos, can) {4400let v = posToVal(pos, xScaleKey, can);4401return closestIdx(v, data[0], i0, i1);4402}4403
4404self.valToIdx = val => closestIdx(val, data[0]);4405self.posToIdx = closestIdxFromXpos;4406self.posToVal = posToVal;4407self.valToPos = (val, scale, can) => (4408scales[scale].ori == 0 ?4409getHPos(val, scales[scale],4410can ? plotWid : plotWidCss,4411can ? plotLft : 0,4412) :4413getVPos(val, scales[scale],4414can ? plotHgt : plotHgtCss,4415can ? plotTop : 0,4416)4417);4418
4419// defers calling expensive functions4420function batch(fn) {4421fn(self);4422commit();4423}4424
4425self.batch = batch;4426
4427(self.setCursor = (opts, _fire, _pub) => {4428mouseLeft1 = opts.left;4429mouseTop1 = opts.top;4430// assign(cursor, opts);4431updateCursor(null, _fire, _pub);4432});4433
4434function setSelH(off, dim) {4435setStylePx(selectDiv, LEFT, select.left = off);4436setStylePx(selectDiv, WIDTH, select.width = dim);4437}4438
4439function setSelV(off, dim) {4440setStylePx(selectDiv, TOP, select.top = off);4441setStylePx(selectDiv, HEIGHT, select.height = dim);4442}4443
4444let setSelX = scaleX.ori == 0 ? setSelH : setSelV;4445let setSelY = scaleX.ori == 1 ? setSelH : setSelV;4446
4447function syncLegend() {4448if (showLegend && legend.live) {4449for (let i = mode == 2 ? 1 : 0; i < series.length; i++) {4450if (i == 0 && multiValLegend)4451continue;4452
4453let vals = legend.values[i];4454
4455let j = 0;4456
4457for (let k in vals)4458legendCells[i][j++].firstChild.nodeValue = vals[k];4459}4460}4461}4462
4463function setLegend(opts, _fire) {4464if (opts != null) {4465let idx = opts.idx;4466
4467legend.idx = idx;4468series.forEach((s, sidx) => {4469(sidx > 0 || !multiValLegend) && setLegendValues(sidx, idx);4470});4471}4472
4473if (showLegend && legend.live)4474syncLegend();4475
4476shouldSetLegend = false;4477
4478_fire !== false && fire("setLegend");4479}4480
4481self.setLegend = setLegend;4482
4483function setLegendValues(sidx, idx) {4484let val;4485
4486if (idx == null)4487val = NULL_LEGEND_VALUES;4488else {4489let s = series[sidx];4490let src = sidx == 0 && xScaleDistr == 2 ? data0 : data[sidx];4491val = multiValLegend ? s.values(self, sidx, idx) : {_: s.value(self, src[idx], sidx, idx)};4492}4493
4494legend.values[sidx] = val;4495}4496
4497function updateCursor(src, _fire, _pub) {4498// ts == null && log("updateCursor()", arguments);4499
4500rawMouseLeft1 = mouseLeft1;4501rawMouseTop1 = mouseTop1;4502
4503[mouseLeft1, mouseTop1] = cursor.move(self, mouseLeft1, mouseTop1);4504
4505if (cursor.show) {4506vCursor && elTrans(vCursor, round(mouseLeft1), 0, plotWidCss, plotHgtCss);4507hCursor && elTrans(hCursor, 0, round(mouseTop1), plotWidCss, plotHgtCss);4508}4509
4510let idx;4511
4512// when zooming to an x scale range between datapoints the binary search4513// for nearest min/max indices results in this condition. cheap hack :D4514let noDataInRange = i0 > i1; // works for mode 1 only4515
4516closestDist = inf;4517
4518// TODO: extract4519let xDim = scaleX.ori == 0 ? plotWidCss : plotHgtCss;4520let yDim = scaleX.ori == 1 ? plotWidCss : plotHgtCss;4521
4522// if cursor hidden, hide points & clear legend vals4523if (mouseLeft1 < 0 || dataLen == 0 || noDataInRange) {4524idx = null;4525
4526for (let i = 0; i < series.length; i++) {4527if (i > 0) {4528cursorPts.length > 1 && elTrans(cursorPts[i], -10, -10, plotWidCss, plotHgtCss);4529}4530}4531
4532if (cursorFocus)4533setSeries(null, FOCUS_TRUE, true, src == null && syncOpts.setSeries);4534
4535if (legend.live) {4536activeIdxs.fill(null);4537shouldSetLegend = true;4538
4539for (let i = 0; i < series.length; i++)4540legend.values[i] = NULL_LEGEND_VALUES;4541}4542}4543else {4544// let pctY = 1 - (y / rect.height);4545
4546let mouseXPos, valAtPosX, xPos;4547
4548if (mode == 1) {4549mouseXPos = scaleX.ori == 0 ? mouseLeft1 : mouseTop1;4550valAtPosX = posToVal(mouseXPos, xScaleKey);4551idx = closestIdx(valAtPosX, data[0], i0, i1);4552xPos = incrRoundUp(valToPosX(data[0][idx], scaleX, xDim, 0), 0.5);4553}4554
4555for (let i = mode == 2 ? 1 : 0; i < series.length; i++) {4556let s = series[i];4557
4558let idx1 = activeIdxs[i];4559let yVal1 = mode == 1 ? data[i][idx1] : data[i][1][idx1];4560
4561let idx2 = cursor.dataIdx(self, i, idx, valAtPosX);4562let yVal2 = mode == 1 ? data[i][idx2] : data[i][1][idx2];4563
4564shouldSetLegend = shouldSetLegend || yVal2 != yVal1 || idx2 != idx1;4565
4566activeIdxs[i] = idx2;4567
4568let xPos2 = idx2 == idx ? xPos : incrRoundUp(valToPosX(mode == 1 ? data[0][idx2] : data[i][0][idx2], scaleX, xDim, 0), 0.5);4569
4570if (i > 0 && s.show) {4571let yPos = yVal2 == null ? -10 : incrRoundUp(valToPosY(yVal2, mode == 1 ? scales[s.scale] : scales[s.facets[1].scale], yDim, 0), 0.5);4572
4573if (yPos > 0 && mode == 1) {4574let dist = abs(yPos - mouseTop1);4575
4576if (dist <= closestDist) {4577closestDist = dist;4578closestSeries = i;4579}4580}4581
4582let hPos, vPos;4583
4584if (scaleX.ori == 0) {4585hPos = xPos2;4586vPos = yPos;4587}4588else {4589hPos = yPos;4590vPos = xPos2;4591}4592
4593if (shouldSetLegend && cursorPts.length > 1) {4594elColor(cursorPts[i], cursor.points.fill(self, i), cursor.points.stroke(self, i));4595
4596let ptWid, ptHgt, ptLft, ptTop,4597centered = true,4598getBBox = cursor.points.bbox;4599
4600if (getBBox != null) {4601centered = false;4602
4603let bbox = getBBox(self, i);4604
4605ptLft = bbox.left;4606ptTop = bbox.top;4607ptWid = bbox.width;4608ptHgt = bbox.height;4609}4610else {4611ptLft = hPos;4612ptTop = vPos;4613ptWid = ptHgt = cursor.points.size(self, i);4614}4615
4616elSize(cursorPts[i], ptWid, ptHgt, centered);4617elTrans(cursorPts[i], ptLft, ptTop, plotWidCss, plotHgtCss);4618}4619}4620
4621if (legend.live) {4622if (!shouldSetLegend || i == 0 && multiValLegend)4623continue;4624
4625setLegendValues(i, idx2);4626}4627}4628}4629
4630cursor.idx = idx;4631cursor.left = mouseLeft1;4632cursor.top = mouseTop1;4633
4634if (shouldSetLegend) {4635legend.idx = idx;4636setLegend();4637}4638
4639// nit: cursor.drag.setSelect is assumed always true4640if (select.show && dragging) {4641if (src != null) {4642let [xKey, yKey] = syncOpts.scales;4643let [matchXKeys, matchYKeys] = syncOpts.match;4644let [xKeySrc, yKeySrc] = src.cursor.sync.scales;4645
4646// match the dragX/dragY implicitness/explicitness of src4647let sdrag = src.cursor.drag;4648dragX = sdrag._x;4649dragY = sdrag._y;4650
4651let { left, top, width, height } = src.select;4652
4653let sori = src.scales[xKey].ori;4654let sPosToVal = src.posToVal;4655
4656let sOff, sDim, sc, a, b;4657
4658let matchingX = xKey != null && matchXKeys(xKey, xKeySrc);4659let matchingY = yKey != null && matchYKeys(yKey, yKeySrc);4660
4661if (matchingX) {4662if (sori == 0) {4663sOff = left;4664sDim = width;4665}4666else {4667sOff = top;4668sDim = height;4669}4670
4671if (dragX) {4672sc = scales[xKey];4673
4674a = valToPosX(sPosToVal(sOff, xKeySrc), sc, xDim, 0);4675b = valToPosX(sPosToVal(sOff + sDim, xKeySrc), sc, xDim, 0);4676
4677setSelX(min(a,b), abs(b-a));4678}4679else4680setSelX(0, xDim);4681
4682if (!matchingY)4683setSelY(0, yDim);4684}4685
4686if (matchingY) {4687if (sori == 1) {4688sOff = left;4689sDim = width;4690}4691else {4692sOff = top;4693sDim = height;4694}4695
4696if (dragY) {4697sc = scales[yKey];4698
4699a = valToPosY(sPosToVal(sOff, yKeySrc), sc, yDim, 0);4700b = valToPosY(sPosToVal(sOff + sDim, yKeySrc), sc, yDim, 0);4701
4702setSelY(min(a,b), abs(b-a));4703}4704else4705setSelY(0, yDim);4706
4707if (!matchingX)4708setSelX(0, xDim);4709}4710}4711else {4712let rawDX = abs(rawMouseLeft1 - rawMouseLeft0);4713let rawDY = abs(rawMouseTop1 - rawMouseTop0);4714
4715if (scaleX.ori == 1) {4716let _rawDX = rawDX;4717rawDX = rawDY;4718rawDY = _rawDX;4719}4720
4721dragX = drag.x && rawDX >= drag.dist;4722dragY = drag.y && rawDY >= drag.dist;4723
4724let uni = drag.uni;4725
4726if (uni != null) {4727// only calc drag status if they pass the dist thresh4728if (dragX && dragY) {4729dragX = rawDX >= uni;4730dragY = rawDY >= uni;4731
4732// force unidirectionality when both are under uni limit4733if (!dragX && !dragY) {4734if (rawDY > rawDX)4735dragY = true;4736else4737dragX = true;4738}4739}4740}4741else if (drag.x && drag.y && (dragX || dragY))4742// if omni with no uni then both dragX / dragY should be true if either is true4743dragX = dragY = true;4744
4745let p0, p1;4746
4747if (dragX) {4748if (scaleX.ori == 0) {4749p0 = mouseLeft0;4750p1 = mouseLeft1;4751}4752else {4753p0 = mouseTop0;4754p1 = mouseTop1;4755}4756
4757setSelX(min(p0, p1), abs(p1 - p0));4758
4759if (!dragY)4760setSelY(0, yDim);4761}4762
4763if (dragY) {4764if (scaleX.ori == 1) {4765p0 = mouseLeft0;4766p1 = mouseLeft1;4767}4768else {4769p0 = mouseTop0;4770p1 = mouseTop1;4771}4772
4773setSelY(min(p0, p1), abs(p1 - p0));4774
4775if (!dragX)4776setSelX(0, xDim);4777}4778
4779// the drag didn't pass the dist requirement4780if (!dragX && !dragY) {4781setSelX(0, 0);4782setSelY(0, 0);4783}4784}4785}4786
4787drag._x = dragX;4788drag._y = dragY;4789
4790if (src == null) {4791if (_pub) {4792if (syncKey != null) {4793let [xSyncKey, ySyncKey] = syncOpts.scales;4794
4795syncOpts.values[0] = xSyncKey != null ? posToVal(scaleX.ori == 0 ? mouseLeft1 : mouseTop1, xSyncKey) : null;4796syncOpts.values[1] = ySyncKey != null ? posToVal(scaleX.ori == 1 ? mouseLeft1 : mouseTop1, ySyncKey) : null;4797}4798
4799pubSync(mousemove, self, mouseLeft1, mouseTop1, plotWidCss, plotHgtCss, idx);4800}4801
4802if (cursorFocus) {4803let shouldPub = _pub && syncOpts.setSeries;4804let p = focus.prox;4805
4806if (focusedSeries == null) {4807if (closestDist <= p)4808setSeries(closestSeries, FOCUS_TRUE, true, shouldPub);4809}4810else {4811if (closestDist > p)4812setSeries(null, FOCUS_TRUE, true, shouldPub);4813else if (closestSeries != focusedSeries)4814setSeries(closestSeries, FOCUS_TRUE, true, shouldPub);4815}4816}4817}4818
4819ready && _fire !== false && fire("setCursor");4820}4821
4822let rect = null;4823
4824function syncRect(defer) {4825if (defer === true)4826rect = null;4827else {4828rect = over.getBoundingClientRect();4829fire("syncRect", rect);4830}4831}4832
4833function mouseMove(e, src, _l, _t, _w, _h, _i) {4834if (cursor._lock)4835return;4836
4837cacheMouse(e, src, _l, _t, _w, _h, _i, false, e != null);4838
4839if (e != null)4840updateCursor(null, true, true);4841else4842updateCursor(src, true, false);4843}4844
4845function cacheMouse(e, src, _l, _t, _w, _h, _i, initial, snap) {4846if (rect == null)4847syncRect(false);4848
4849if (e != null) {4850_l = e.clientX - rect.left;4851_t = e.clientY - rect.top;4852}4853else {4854if (_l < 0 || _t < 0) {4855mouseLeft1 = -10;4856mouseTop1 = -10;4857return;4858}4859
4860let [xKey, yKey] = syncOpts.scales;4861
4862let syncOptsSrc = src.cursor.sync;4863let [xValSrc, yValSrc] = syncOptsSrc.values;4864let [xKeySrc, yKeySrc] = syncOptsSrc.scales;4865let [matchXKeys, matchYKeys] = syncOpts.match;4866
4867let rotSrc = src.scales[xKeySrc].ori == 1;4868
4869let xDim = scaleX.ori == 0 ? plotWidCss : plotHgtCss,4870yDim = scaleX.ori == 1 ? plotWidCss : plotHgtCss,4871_xDim = rotSrc ? _h : _w,4872_yDim = rotSrc ? _w : _h,4873_xPos = rotSrc ? _t : _l,4874_yPos = rotSrc ? _l : _t;4875
4876if (xKeySrc != null)4877_l = matchXKeys(xKey, xKeySrc) ? getPos(xValSrc, scales[xKey], xDim, 0) : -10;4878else4879_l = xDim * (_xPos/_xDim);4880
4881if (yKeySrc != null)4882_t = matchYKeys(yKey, yKeySrc) ? getPos(yValSrc, scales[yKey], yDim, 0) : -10;4883else4884_t = yDim * (_yPos/_yDim);4885
4886if (scaleX.ori == 1) {4887let __l = _l;4888_l = _t;4889_t = __l;4890}4891}4892
4893if (snap) {4894if (_l <= 1 || _l >= plotWidCss - 1)4895_l = incrRound(_l, plotWidCss);4896
4897if (_t <= 1 || _t >= plotHgtCss - 1)4898_t = incrRound(_t, plotHgtCss);4899}4900
4901if (initial) {4902rawMouseLeft0 = _l;4903rawMouseTop0 = _t;4904
4905[mouseLeft0, mouseTop0] = cursor.move(self, _l, _t);4906}4907else {4908mouseLeft1 = _l;4909mouseTop1 = _t;4910}4911}4912
4913function hideSelect() {4914setSelect({4915width: 0,4916height: 0,4917}, false);4918}4919
4920function mouseDown(e, src, _l, _t, _w, _h, _i) {4921dragging = true;4922dragX = dragY = drag._x = drag._y = false;4923
4924cacheMouse(e, src, _l, _t, _w, _h, _i, true, false);4925
4926if (e != null) {4927onMouse(mouseup, doc, mouseUp);4928pubSync(mousedown, self, mouseLeft0, mouseTop0, plotWidCss, plotHgtCss, null);4929}4930}4931
4932function mouseUp(e, src, _l, _t, _w, _h, _i) {4933dragging = drag._x = drag._y = false;4934
4935cacheMouse(e, src, _l, _t, _w, _h, _i, false, true);4936
4937let { left, top, width, height } = select;4938
4939let hasSelect = width > 0 || height > 0;4940
4941hasSelect && setSelect(select);4942
4943if (drag.setScale && hasSelect) {4944// if (syncKey != null) {4945// dragX = drag.x;4946// dragY = drag.y;4947// }4948
4949let xOff = left,4950xDim = width,4951yOff = top,4952yDim = height;4953
4954if (scaleX.ori == 1) {4955xOff = top,4956xDim = height,4957yOff = left,4958yDim = width;4959}4960
4961if (dragX) {4962_setScale(xScaleKey,4963posToVal(xOff, xScaleKey),4964posToVal(xOff + xDim, xScaleKey)4965);4966}4967
4968if (dragY) {4969for (let k in scales) {4970let sc = scales[k];4971
4972if (k != xScaleKey && sc.from == null && sc.min != inf) {4973_setScale(k,4974posToVal(yOff + yDim, k),4975posToVal(yOff, k)4976);4977}4978}4979}4980
4981hideSelect();4982}4983else if (cursor.lock) {4984cursor._lock = !cursor._lock;4985
4986if (!cursor._lock)4987updateCursor(null, true, false);4988}4989
4990if (e != null) {4991offMouse(mouseup, doc);4992pubSync(mouseup, self, mouseLeft1, mouseTop1, plotWidCss, plotHgtCss, null);4993}4994}4995
4996function mouseLeave(e, src, _l, _t, _w, _h, _i) {4997if (!cursor._lock) {4998let _dragging = dragging;4999
5000if (dragging) {5001// handle case when mousemove aren't fired all the way to edges by browser5002let snapH = true;5003let snapV = true;5004let snapProx = 10;5005
5006let dragH, dragV;5007
5008if (scaleX.ori == 0) {5009dragH = dragX;5010dragV = dragY;5011}5012else {5013dragH = dragY;5014dragV = dragX;5015}5016
5017if (dragH && dragV) {5018// maybe omni corner snap5019snapH = mouseLeft1 <= snapProx || mouseLeft1 >= plotWidCss - snapProx;5020snapV = mouseTop1 <= snapProx || mouseTop1 >= plotHgtCss - snapProx;5021}5022
5023if (dragH && snapH)5024mouseLeft1 = mouseLeft1 < mouseLeft0 ? 0 : plotWidCss;5025
5026if (dragV && snapV)5027mouseTop1 = mouseTop1 < mouseTop0 ? 0 : plotHgtCss;5028
5029updateCursor(null, true, true);5030
5031dragging = false;5032}5033
5034mouseLeft1 = -10;5035mouseTop1 = -10;5036
5037// passing a non-null timestamp to force sync/mousemove event5038updateCursor(null, true, true);5039
5040if (_dragging)5041dragging = _dragging;5042}5043}5044
5045function dblClick(e, src, _l, _t, _w, _h, _i) {5046autoScaleX();5047
5048hideSelect();5049
5050if (e != null)5051pubSync(dblclick, self, mouseLeft1, mouseTop1, plotWidCss, plotHgtCss, null);5052}5053
5054function syncPxRatio() {5055axes.forEach(syncFontSize);5056_setSize(self.width, self.height, true);5057}5058
5059on(dppxchange, win, syncPxRatio);5060
5061// internal pub/sub5062const events = {};5063
5064events.mousedown = mouseDown;5065events.mousemove = mouseMove;5066events.mouseup = mouseUp;5067events.dblclick = dblClick;5068events["setSeries"] = (e, src, idx, opts) => {5069setSeries(idx, opts, true, false);5070};5071
5072if (cursor.show) {5073onMouse(mousedown, over, mouseDown);5074onMouse(mousemove, over, mouseMove);5075onMouse(mouseenter, over, syncRect);5076onMouse(mouseleave, over, mouseLeave);5077
5078onMouse(dblclick, over, dblClick);5079
5080cursorPlots.add(self);5081
5082self.syncRect = syncRect;5083}5084
5085// external on/off5086const hooks = self.hooks = opts.hooks || {};5087
5088function fire(evName, a1, a2) {5089if (evName in hooks) {5090hooks[evName].forEach(fn => {5091fn.call(null, self, a1, a2);5092});5093}5094}5095
5096(opts.plugins || []).forEach(p => {5097for (let evName in p.hooks)5098hooks[evName] = (hooks[evName] || []).concat(p.hooks[evName]);5099});5100
5101const syncOpts = assign({5102key: null,5103setSeries: false,5104filters: {5105pub: retTrue,5106sub: retTrue,5107},5108scales: [xScaleKey, series[1] ? series[1].scale : null],5109match: [retEq, retEq],5110values: [null, null],5111}, cursor.sync);5112
5113(cursor.sync = syncOpts);5114
5115const syncKey = syncOpts.key;5116
5117const sync = _sync(syncKey);5118
5119function pubSync(type, src, x, y, w, h, i) {5120if (syncOpts.filters.pub(type, src, x, y, w, h, i))5121sync.pub(type, src, x, y, w, h, i);5122}5123
5124sync.sub(self);5125
5126function pub(type, src, x, y, w, h, i) {5127if (syncOpts.filters.sub(type, src, x, y, w, h, i))5128events[type](null, src, x, y, w, h, i);5129}5130
5131(self.pub = pub);5132
5133function destroy() {5134sync.unsub(self);5135cursorPlots.delete(self);5136mouseListeners.clear();5137off(dppxchange, win, syncPxRatio);5138root.remove();5139fire("destroy");5140}5141
5142self.destroy = destroy;5143
5144function _init() {5145fire("init", opts, data);5146
5147setData(data || opts.data, false);5148
5149if (pendScales[xScaleKey])5150setScale(xScaleKey, pendScales[xScaleKey]);5151else5152autoScaleX();5153
5154_setSize(opts.width, opts.height);5155
5156updateCursor(null, true, false);5157
5158setSelect(select, false);5159}5160
5161series.forEach(initSeries);5162
5163axes.forEach(initAxis);5164
5165if (then) {5166if (then instanceof HTMLElement) {5167then.appendChild(root);5168_init();5169}5170else5171then(self, _init);5172}5173else5174_init();5175
5176return self;5177}5178
5179uPlot.assign = assign;5180uPlot.fmtNum = fmtNum;5181uPlot.rangeNum = rangeNum;5182uPlot.rangeLog = rangeLog;5183uPlot.rangeAsinh = rangeAsinh;5184uPlot.orient = orient;5185
5186{5187uPlot.join = join;5188}5189
5190{5191uPlot.fmtDate = fmtDate;5192uPlot.tzDate = tzDate;5193}5194
5195{5196uPlot.sync = _sync;5197}5198
5199{5200uPlot.addGap = addGap;5201uPlot.clipGaps = clipGaps;5202
5203let paths = uPlot.paths = {5204points,5205};5206
5207(paths.linear = linear);5208(paths.stepped = stepped);5209(paths.bars = bars);5210(paths.spline = monotoneCubic);5211}5212
5213return uPlot;5214
5215})();5216