uplot
Version:
A small, fast chart for time series, lines, areas, ohlc & bars
2,123 lines (1,684 loc) • 129 kB
JavaScript
/**
* Copyright (c) 2022, Leon Sorokin
* All rights reserved. (MIT Licensed)
*
* uPlot.js (μPlot)
* A small, fast chart for time series, lines, areas, ohlc & bars
* https://github.com/leeoniya/uPlot (v1.6.20)
*/
var uPlot = (function () {
'use strict';
const FEAT_TIME = true;
const pre = "u-";
const UPLOT = "uplot";
const ORI_HZ = pre + "hz";
const ORI_VT = pre + "vt";
const TITLE = pre + "title";
const WRAP = pre + "wrap";
const UNDER = pre + "under";
const OVER = pre + "over";
const AXIS = pre + "axis";
const OFF = pre + "off";
const SELECT = pre + "select";
const CURSOR_X = pre + "cursor-x";
const CURSOR_Y = pre + "cursor-y";
const CURSOR_PT = pre + "cursor-pt";
const LEGEND = pre + "legend";
const LEGEND_LIVE = pre + "live";
const LEGEND_INLINE = pre + "inline";
const LEGEND_THEAD = pre + "thead";
const LEGEND_SERIES = pre + "series";
const LEGEND_MARKER = pre + "marker";
const LEGEND_LABEL = pre + "label";
const LEGEND_VALUE = pre + "value";
const WIDTH = "width";
const HEIGHT = "height";
const TOP = "top";
const BOTTOM = "bottom";
const LEFT = "left";
const RIGHT = "right";
const hexBlack = "#000";
const transparent = hexBlack + "0";
const mousemove = "mousemove";
const mousedown = "mousedown";
const mouseup = "mouseup";
const mouseenter = "mouseenter";
const mouseleave = "mouseleave";
const dblclick = "dblclick";
const resize = "resize";
const scroll = "scroll";
const change = "change";
const dppxchange = "dppxchange";
const domEnv = typeof window != 'undefined';
const doc = domEnv ? document : null;
const win = domEnv ? window : null;
const nav = domEnv ? navigator : null;
let pxRatio;
let query;
function setPxRatio() {
let _pxRatio = devicePixelRatio;
// during print preview, Chrome fires off these dppx queries even without changes
if (pxRatio != _pxRatio) {
pxRatio = _pxRatio;
query && off(change, query, setPxRatio);
query = matchMedia(`(min-resolution: ${pxRatio - 0.001}dppx) and (max-resolution: ${pxRatio + 0.001}dppx)`);
on(change, query, setPxRatio);
win.dispatchEvent(new CustomEvent(dppxchange));
}
}
function addClass(el, c) {
if (c != null) {
let cl = el.classList;
!cl.contains(c) && cl.add(c);
}
}
function remClass(el, c) {
let cl = el.classList;
cl.contains(c) && cl.remove(c);
}
function setStylePx(el, name, value) {
el.style[name] = value + "px";
}
function placeTag(tag, cls, targ, refEl) {
let el = doc.createElement(tag);
if (cls != null)
addClass(el, cls);
if (targ != null)
targ.insertBefore(el, refEl);
return el;
}
function placeDiv(cls, targ) {
return placeTag("div", cls, targ);
}
const xformCache = new WeakMap();
function elTrans(el, xPos, yPos, xMax, yMax) {
let xform = "translate(" + xPos + "px," + yPos + "px)";
let xformOld = xformCache.get(el);
if (xform != xformOld) {
el.style.transform = xform;
xformCache.set(el, xform);
if (xPos < 0 || yPos < 0 || xPos > xMax || yPos > yMax)
addClass(el, OFF);
else
remClass(el, OFF);
}
}
const colorCache = new WeakMap();
function elColor(el, background, borderColor) {
let newColor = background + borderColor;
let oldColor = colorCache.get(el);
if (newColor != oldColor) {
colorCache.set(el, newColor);
el.style.background = background;
el.style.borderColor = borderColor;
}
}
const sizeCache = new WeakMap();
function elSize(el, newWid, newHgt, centered) {
let newSize = newWid + "" + newHgt;
let oldSize = sizeCache.get(el);
if (newSize != oldSize) {
sizeCache.set(el, newSize);
el.style.height = newHgt + "px";
el.style.width = newWid + "px";
el.style.marginLeft = centered ? -newWid/2 + "px" : 0;
el.style.marginTop = centered ? -newHgt/2 + "px" : 0;
}
}
const evOpts = {passive: true};
const evOpts2 = {...evOpts, capture: true};
function on(ev, el, cb, capt) {
el.addEventListener(ev, cb, capt ? evOpts2 : evOpts);
}
function off(ev, el, cb, capt) {
el.removeEventListener(ev, cb, capt ? evOpts2 : evOpts);
}
domEnv && setPxRatio();
// binary search for index of closest value
function closestIdx(num, arr, lo, hi) {
let mid;
lo = lo || 0;
hi = hi || arr.length - 1;
let bitwise = hi <= 2147483647;
while (hi - lo > 1) {
mid = bitwise ? (lo + hi) >> 1 : floor((lo + hi) / 2);
if (arr[mid] < num)
lo = mid;
else
hi = mid;
}
if (num - arr[lo] <= arr[hi] - num)
return lo;
return hi;
}
function nonNullIdx(data, _i0, _i1, dir) {
for (let i = dir == 1 ? _i0 : _i1; i >= _i0 && i <= _i1; i += dir) {
if (data[i] != null)
return i;
}
return -1;
}
function getMinMax(data, _i0, _i1, sorted) {
// console.log("getMinMax()");
let _min = inf;
let _max = -inf;
if (sorted == 1) {
_min = data[_i0];
_max = data[_i1];
}
else if (sorted == -1) {
_min = data[_i1];
_max = data[_i0];
}
else {
for (let i = _i0; i <= _i1; i++) {
if (data[i] != null) {
_min = min(_min, data[i]);
_max = max(_max, data[i]);
}
}
}
return [_min, _max];
}
function getMinMaxLog(data, _i0, _i1) {
// console.log("getMinMax()");
let _min = inf;
let _max = -inf;
for (let i = _i0; i <= _i1; i++) {
if (data[i] > 0) {
_min = min(_min, data[i]);
_max = max(_max, data[i]);
}
}
return [
_min == inf ? 1 : _min,
_max == -inf ? 10 : _max,
];
}
const _fixedTuple = [0, 0];
function fixIncr(minIncr, maxIncr, minExp, maxExp) {
_fixedTuple[0] = minExp < 0 ? roundDec(minIncr, -minExp) : minIncr;
_fixedTuple[1] = maxExp < 0 ? roundDec(maxIncr, -maxExp) : maxIncr;
return _fixedTuple;
}
function rangeLog(min, max, base, fullMags) {
let minSign = sign(min);
let logFn = base == 10 ? log10 : log2;
if (min == max) {
if (minSign == -1) {
min *= base;
max /= base;
}
else {
min /= base;
max *= base;
}
}
let minExp, maxExp, minMaxIncrs;
if (fullMags) {
minExp = floor(logFn(min));
maxExp = ceil(logFn(max));
minMaxIncrs = fixIncr(pow(base, minExp), pow(base, maxExp), minExp, maxExp);
min = minMaxIncrs[0];
max = minMaxIncrs[1];
}
else {
minExp = floor(logFn(abs(min)));
maxExp = floor(logFn(abs(max)));
minMaxIncrs = fixIncr(pow(base, minExp), pow(base, maxExp), minExp, maxExp);
min = incrRoundDn(min, minMaxIncrs[0]);
max = incrRoundUp(max, minMaxIncrs[1]);
}
return [min, max];
}
function rangeAsinh(min, max, base, fullMags) {
let minMax = rangeLog(min, max, base, fullMags);
if (min == 0)
minMax[0] = 0;
if (max == 0)
minMax[1] = 0;
return minMax;
}
const rangePad = 0.1;
const autoRangePart = {
mode: 3,
pad: rangePad,
};
const _eqRangePart = {
pad: 0,
soft: null,
mode: 0,
};
const _eqRange = {
min: _eqRangePart,
max: _eqRangePart,
};
// this ensures that non-temporal/numeric y-axes get multiple-snapped padding added above/below
// TODO: also account for incrs when snapping to ensure top of axis gets a tick & value
function rangeNum(_min, _max, mult, extra) {
if (isObj(mult))
return _rangeNum(_min, _max, mult);
_eqRangePart.pad = mult;
_eqRangePart.soft = extra ? 0 : null;
_eqRangePart.mode = extra ? 3 : 0;
return _rangeNum(_min, _max, _eqRange);
}
// nullish coalesce
function ifNull(lh, rh) {
return lh == null ? rh : lh;
}
// checks if given index range in an array contains a non-null value
// aka a range-bounded Array.some()
function hasData(data, idx0, idx1) {
idx0 = ifNull(idx0, 0);
idx1 = ifNull(idx1, data.length - 1);
while (idx0 <= idx1) {
if (data[idx0] != null)
return true;
idx0++;
}
return false;
}
function _rangeNum(_min, _max, cfg) {
let cmin = cfg.min;
let cmax = cfg.max;
let padMin = ifNull(cmin.pad, 0);
let padMax = ifNull(cmax.pad, 0);
let hardMin = ifNull(cmin.hard, -inf);
let hardMax = ifNull(cmax.hard, inf);
let softMin = ifNull(cmin.soft, inf);
let softMax = ifNull(cmax.soft, -inf);
let softMinMode = ifNull(cmin.mode, 0);
let softMaxMode = ifNull(cmax.mode, 0);
let delta = _max - _min;
// this handles situations like 89.7, 89.69999999999999
// by assuming 0.001x deltas are precision errors
// if (delta > 0 && delta < abs(_max) / 1e3)
// delta = 0;
// treat data as flat if delta is less than 1 billionth
if (delta < 1e-9) {
delta = 0;
// if soft mode is 2 and all vals are flat at 0, avoid the 0.1 * 1e3 fallback
// this prevents 0,0,0 from ranging to -100,100 when softMin/softMax are -1,1
if (_min == 0 || _max == 0) {
delta = 1e-9;
if (softMinMode == 2 && softMin != inf)
padMin = 0;
if (softMaxMode == 2 && softMax != -inf)
padMax = 0;
}
}
let nonZeroDelta = delta || abs(_max) || 1e3;
let mag = log10(nonZeroDelta);
let base = pow(10, floor(mag));
let _padMin = nonZeroDelta * (delta == 0 ? (_min == 0 ? .1 : 1) : padMin);
let _newMin = roundDec(incrRoundDn(_min - _padMin, base/10), 9);
let _softMin = _min >= softMin && (softMinMode == 1 || softMinMode == 3 && _newMin <= softMin || softMinMode == 2 && _newMin >= softMin) ? softMin : inf;
let minLim = max(hardMin, _newMin < _softMin && _min >= _softMin ? _softMin : min(_softMin, _newMin));
let _padMax = nonZeroDelta * (delta == 0 ? (_max == 0 ? .1 : 1) : padMax);
let _newMax = roundDec(incrRoundUp(_max + _padMax, base/10), 9);
let _softMax = _max <= softMax && (softMaxMode == 1 || softMaxMode == 3 && _newMax >= softMax || softMaxMode == 2 && _newMax <= softMax) ? softMax : -inf;
let maxLim = min(hardMax, _newMax > _softMax && _max <= _softMax ? _softMax : max(_softMax, _newMax));
if (minLim == maxLim && minLim == 0)
maxLim = 100;
return [minLim, maxLim];
}
// alternative: https://stackoverflow.com/a/2254896
const numFormatter = new Intl.NumberFormat(domEnv ? nav.language : 'en-US');
const fmtNum = val => numFormatter.format(val);
const M = Math;
const PI = M.PI;
const abs = M.abs;
const floor = M.floor;
const round = M.round;
const ceil = M.ceil;
const min = M.min;
const max = M.max;
const pow = M.pow;
const sign = M.sign;
const log10 = M.log10;
const log2 = M.log2;
// TODO: seems like this needs to match asinh impl if the passed v is tweaked?
const sinh = (v, linthresh = 1) => M.sinh(v) * linthresh;
const asinh = (v, linthresh = 1) => M.asinh(v / linthresh);
const inf = Infinity;
function numIntDigits(x) {
return (log10((x ^ (x >> 31)) - (x >> 31)) | 0) + 1;
}
function incrRound(num, incr) {
return round(num/incr)*incr;
}
function clamp(num, _min, _max) {
return min(max(num, _min), _max);
}
function fnOrSelf(v) {
return typeof v == "function" ? v : () => v;
}
const retArg0 = _0 => _0;
const retArg1 = (_0, _1) => _1;
const retNull = _ => null;
const retTrue = _ => true;
const retEq = (a, b) => a == b;
function incrRoundUp(num, incr) {
return ceil(num/incr)*incr;
}
function incrRoundDn(num, incr) {
return floor(num/incr)*incr;
}
function roundDec(val, dec) {
return round(val * (dec = 10**dec)) / dec;
}
const fixedDec = new Map();
function guessDec(num) {
return ((""+num).split(".")[1] || "").length;
}
function genIncrs(base, minExp, maxExp, mults) {
let incrs = [];
let multDec = mults.map(guessDec);
for (let exp = minExp; exp < maxExp; exp++) {
let expa = abs(exp);
let mag = roundDec(pow(base, exp), expa);
for (let i = 0; i < mults.length; i++) {
let _incr = mults[i] * mag;
let dec = (_incr >= 0 && exp >= 0 ? 0 : expa) + (exp >= multDec[i] ? 0 : multDec[i]);
let incr = roundDec(_incr, dec);
incrs.push(incr);
fixedDec.set(incr, dec);
}
}
return incrs;
}
//export const assign = Object.assign;
const EMPTY_OBJ = {};
const EMPTY_ARR = [];
const nullNullTuple = [null, null];
const isArr = Array.isArray;
function isStr(v) {
return typeof v == 'string';
}
function isObj(v) {
let is = false;
if (v != null) {
let c = v.constructor;
is = c == null || c == Object;
}
return is;
}
function fastIsObj(v) {
return v != null && typeof v == 'object';
}
function copy(o, _isObj = isObj) {
let out;
if (isArr(o)) {
let val = o.find(v => v != null);
if (isArr(val) || _isObj(val)) {
out = Array(o.length);
for (let i = 0; i < o.length; i++)
out[i] = copy(o[i], _isObj);
}
else
out = o.slice();
}
else if (_isObj(o)) {
out = {};
for (let k in o)
out[k] = copy(o[k], _isObj);
}
else
out = o;
return out;
}
function assign(targ) {
let args = arguments;
for (let i = 1; i < args.length; i++) {
let src = args[i];
for (let key in src) {
if (isObj(targ[key]))
assign(targ[key], copy(src[key]));
else
targ[key] = copy(src[key]);
}
}
return targ;
}
// nullModes
const NULL_REMOVE = 0; // nulls are converted to undefined (e.g. for spanGaps: true)
const NULL_RETAIN = 1; // nulls are retained, with alignment artifacts set to undefined (default)
const NULL_EXPAND = 2; // nulls are expanded to include any adjacent alignment artifacts
// sets undefined values to nulls when adjacent to existing nulls (minesweeper)
function nullExpand(yVals, nullIdxs, alignedLen) {
for (let i = 0, xi, lastNullIdx = -1; i < nullIdxs.length; i++) {
let nullIdx = nullIdxs[i];
if (nullIdx > lastNullIdx) {
xi = nullIdx - 1;
while (xi >= 0 && yVals[xi] == null)
yVals[xi--] = null;
xi = nullIdx + 1;
while (xi < alignedLen && yVals[xi] == null)
yVals[lastNullIdx = xi++] = null;
}
}
}
// nullModes is a tables-matched array indicating how to treat nulls in each series
// output is sorted ASC on the joined field (table[0]) and duplicate join values are collapsed
function join(tables, nullModes) {
let xVals = new Set();
for (let ti = 0; ti < tables.length; ti++) {
let t = tables[ti];
let xs = t[0];
let len = xs.length;
for (let i = 0; i < len; i++)
xVals.add(xs[i]);
}
let data = [Array.from(xVals).sort((a, b) => a - b)];
let alignedLen = data[0].length;
let xIdxs = new Map();
for (let i = 0; i < alignedLen; i++)
xIdxs.set(data[0][i], i);
for (let ti = 0; ti < tables.length; ti++) {
let t = tables[ti];
let xs = t[0];
for (let si = 1; si < t.length; si++) {
let ys = t[si];
let yVals = Array(alignedLen).fill(undefined);
let nullMode = nullModes ? nullModes[ti][si] : NULL_RETAIN;
let nullIdxs = [];
for (let i = 0; i < ys.length; i++) {
let yVal = ys[i];
let alignedIdx = xIdxs.get(xs[i]);
if (yVal === null) {
if (nullMode != NULL_REMOVE) {
yVals[alignedIdx] = yVal;
if (nullMode == NULL_EXPAND)
nullIdxs.push(alignedIdx);
}
}
else
yVals[alignedIdx] = yVal;
}
nullExpand(yVals, nullIdxs, alignedLen);
data.push(yVals);
}
}
return data;
}
const microTask = typeof queueMicrotask == "undefined" ? fn => Promise.resolve().then(fn) : queueMicrotask;
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
function slice3(str) {
return str.slice(0, 3);
}
const days3 = days.map(slice3);
const months3 = months.map(slice3);
const engNames = {
MMMM: months,
MMM: months3,
WWWW: days,
WWW: days3,
};
function zeroPad2(int) {
return (int < 10 ? '0' : '') + int;
}
function zeroPad3(int) {
return (int < 10 ? '00' : int < 100 ? '0' : '') + int;
}
/*
function suffix(int) {
let mod10 = int % 10;
return int + (
mod10 == 1 && int != 11 ? "st" :
mod10 == 2 && int != 12 ? "nd" :
mod10 == 3 && int != 13 ? "rd" : "th"
);
}
*/
const subs = {
// 2019
YYYY: d => d.getFullYear(),
// 19
YY: d => (d.getFullYear()+'').slice(2),
// July
MMMM: (d, names) => names.MMMM[d.getMonth()],
// Jul
MMM: (d, names) => names.MMM[d.getMonth()],
// 07
MM: d => zeroPad2(d.getMonth()+1),
// 7
M: d => d.getMonth()+1,
// 09
DD: d => zeroPad2(d.getDate()),
// 9
D: d => d.getDate(),
// Monday
WWWW: (d, names) => names.WWWW[d.getDay()],
// Mon
WWW: (d, names) => names.WWW[d.getDay()],
// 03
HH: d => zeroPad2(d.getHours()),
// 3
H: d => d.getHours(),
// 9 (12hr, unpadded)
h: d => {let h = d.getHours(); return h == 0 ? 12 : h > 12 ? h - 12 : h;},
// AM
AA: d => d.getHours() >= 12 ? 'PM' : 'AM',
// am
aa: d => d.getHours() >= 12 ? 'pm' : 'am',
// a
a: d => d.getHours() >= 12 ? 'p' : 'a',
// 09
mm: d => zeroPad2(d.getMinutes()),
// 9
m: d => d.getMinutes(),
// 09
ss: d => zeroPad2(d.getSeconds()),
// 9
s: d => d.getSeconds(),
// 374
fff: d => zeroPad3(d.getMilliseconds()),
};
function fmtDate(tpl, names) {
names = names || engNames;
let parts = [];
let R = /\{([a-z]+)\}|[^{]+/gi, m;
while (m = R.exec(tpl))
parts.push(m[0][0] == '{' ? subs[m[1]] : m[0]);
return d => {
let out = '';
for (let i = 0; i < parts.length; i++)
out += typeof parts[i] == "string" ? parts[i] : parts[i](d, names);
return out;
}
}
const localTz = new Intl.DateTimeFormat().resolvedOptions().timeZone;
// https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone/53652131#53652131
function tzDate(date, tz) {
let date2;
// perf optimization
if (tz == 'UTC' || tz == 'Etc/UTC')
date2 = new Date(+date + date.getTimezoneOffset() * 6e4);
else if (tz == localTz)
date2 = date;
else {
date2 = new Date(date.toLocaleString('en-US', {timeZone: tz}));
date2.setMilliseconds(date.getMilliseconds());
}
return date2;
}
//export const series = [];
// default formatters:
const onlyWhole = v => v % 1 == 0;
const allMults = [1,2,2.5,5];
// ...0.01, 0.02, 0.025, 0.05, 0.1, 0.2, 0.25, 0.5
const decIncrs = genIncrs(10, -16, 0, allMults);
// 1, 2, 2.5, 5, 10, 20, 25, 50...
const oneIncrs = genIncrs(10, 0, 16, allMults);
// 1, 2, 5, 10, 20, 25, 50...
const wholeIncrs = oneIncrs.filter(onlyWhole);
const numIncrs = decIncrs.concat(oneIncrs);
const NL = "\n";
const yyyy = "{YYYY}";
const NLyyyy = NL + yyyy;
const md = "{M}/{D}";
const NLmd = NL + md;
const NLmdyy = NLmd + "/{YY}";
const aa = "{aa}";
const hmm = "{h}:{mm}";
const hmmaa = hmm + aa;
const NLhmmaa = NL + hmmaa;
const ss = ":{ss}";
const _ = null;
function genTimeStuffs(ms) {
let s = ms * 1e3,
m = s * 60,
h = m * 60,
d = h * 24,
mo = d * 30,
y = d * 365;
// min of 1e-3 prevents setting a temporal x ticks too small since Date objects cannot advance ticks smaller than 1ms
let subSecIncrs = ms == 1 ? genIncrs(10, 0, 3, allMults).filter(onlyWhole) : genIncrs(10, -3, 0, allMults);
let timeIncrs = subSecIncrs.concat([
// minute divisors (# of secs)
s,
s * 5,
s * 10,
s * 15,
s * 30,
// hour divisors (# of mins)
m,
m * 5,
m * 10,
m * 15,
m * 30,
// day divisors (# of hrs)
h,
h * 2,
h * 3,
h * 4,
h * 6,
h * 8,
h * 12,
// month divisors TODO: need more?
d,
d * 2,
d * 3,
d * 4,
d * 5,
d * 6,
d * 7,
d * 8,
d * 9,
d * 10,
d * 15,
// year divisors (# months, approx)
mo,
mo * 2,
mo * 3,
mo * 4,
mo * 6,
// century divisors
y,
y * 2,
y * 5,
y * 10,
y * 25,
y * 50,
y * 100,
]);
// [0]: minimum num secs in the tick incr
// [1]: default tick format
// [2-7]: rollover tick formats
// [8]: mode: 0: replace [1] -> [2-7], 1: concat [1] + [2-7]
const _timeAxisStamps = [
// tick incr default year month day hour min sec mode
[y, yyyy, _, _, _, _, _, _, 1],
[d * 28, "{MMM}", NLyyyy, _, _, _, _, _, 1],
[d, md, NLyyyy, _, _, _, _, _, 1],
[h, "{h}" + aa, NLmdyy, _, NLmd, _, _, _, 1],
[m, hmmaa, NLmdyy, _, NLmd, _, _, _, 1],
[s, ss, NLmdyy + " " + hmmaa, _, NLmd + " " + hmmaa, _, NLhmmaa, _, 1],
[ms, ss + ".{fff}", NLmdyy + " " + hmmaa, _, NLmd + " " + hmmaa, _, NLhmmaa, _, 1],
];
// the ensures that axis ticks, values & grid are aligned to logical temporal breakpoints and not an arbitrary timestamp
// https://www.timeanddate.com/time/dst/
// https://www.timeanddate.com/time/dst/2019.html
// https://www.epochconverter.com/timezones
function timeAxisSplits(tzDate) {
return (self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace) => {
let splits = [];
let isYr = foundIncr >= y;
let isMo = foundIncr >= mo && foundIncr < y;
// get the timezone-adjusted date
let minDate = tzDate(scaleMin);
let minDateTs = roundDec(minDate * ms, 3);
// get ts of 12am (this lands us at or before the original scaleMin)
let minMin = mkDate(minDate.getFullYear(), isYr ? 0 : minDate.getMonth(), isMo || isYr ? 1 : minDate.getDate());
let minMinTs = roundDec(minMin * ms, 3);
if (isMo || isYr) {
let moIncr = isMo ? foundIncr / mo : 0;
let yrIncr = isYr ? foundIncr / y : 0;
// let tzOffset = scaleMin - minDateTs; // needed?
let split = minDateTs == minMinTs ? minDateTs : roundDec(mkDate(minMin.getFullYear() + yrIncr, minMin.getMonth() + moIncr, 1) * ms, 3);
let splitDate = new Date(round(split / ms));
let baseYear = splitDate.getFullYear();
let baseMonth = splitDate.getMonth();
for (let i = 0; split <= scaleMax; i++) {
let next = mkDate(baseYear + yrIncr * i, baseMonth + moIncr * i, 1);
let offs = next - tzDate(roundDec(next * ms, 3));
split = roundDec((+next + offs) * ms, 3);
if (split <= scaleMax)
splits.push(split);
}
}
else {
let incr0 = foundIncr >= d ? d : foundIncr;
let tzOffset = floor(scaleMin) - floor(minDateTs);
let split = minMinTs + tzOffset + incrRoundUp(minDateTs - minMinTs, incr0);
splits.push(split);
let date0 = tzDate(split);
let prevHour = date0.getHours() + (date0.getMinutes() / m) + (date0.getSeconds() / h);
let incrHours = foundIncr / h;
let minSpace = self.axes[axisIdx]._space;
let pctSpace = foundSpace / minSpace;
while (1) {
split = roundDec(split + foundIncr, ms == 1 ? 0 : 3);
if (split > scaleMax)
break;
if (incrHours > 1) {
let expectedHour = floor(roundDec(prevHour + incrHours, 6)) % 24;
let splitDate = tzDate(split);
let actualHour = splitDate.getHours();
let dstShift = actualHour - expectedHour;
if (dstShift > 1)
dstShift = -1;
split -= dstShift * h;
prevHour = (prevHour + incrHours) % 24;
// add a tick only if it's further than 70% of the min allowed label spacing
let prevSplit = splits[splits.length - 1];
let pctIncr = roundDec((split - prevSplit) / foundIncr, 3);
if (pctIncr * pctSpace >= .7)
splits.push(split);
}
else
splits.push(split);
}
}
return splits;
}
}
return [
timeIncrs,
_timeAxisStamps,
timeAxisSplits,
];
}
const [ timeIncrsMs, _timeAxisStampsMs, timeAxisSplitsMs ] = genTimeStuffs(1);
const [ timeIncrsS, _timeAxisStampsS, timeAxisSplitsS ] = genTimeStuffs(1e-3);
// base 2
genIncrs(2, -53, 53, [1]);
/*
console.log({
decIncrs,
oneIncrs,
wholeIncrs,
numIncrs,
timeIncrs,
fixedDec,
});
*/
function timeAxisStamps(stampCfg, fmtDate) {
return stampCfg.map(s => s.map((v, i) =>
i == 0 || i == 8 || v == null ? v : fmtDate(i == 1 || s[8] == 0 ? v : s[1] + v)
));
}
// TODO: will need to accept spaces[] and pull incr into the loop when grid will be non-uniform, eg for log scales.
// currently we ignore this for months since they're *nearly* uniform and the added complexity is not worth it
function timeAxisVals(tzDate, stamps) {
return (self, splits, axisIdx, foundSpace, foundIncr) => {
let s = stamps.find(s => foundIncr >= s[0]) || stamps[stamps.length - 1];
// these track boundaries when a full label is needed again
let prevYear;
let prevMnth;
let prevDate;
let prevHour;
let prevMins;
let prevSecs;
return splits.map(split => {
let date = tzDate(split);
let newYear = date.getFullYear();
let newMnth = date.getMonth();
let newDate = date.getDate();
let newHour = date.getHours();
let newMins = date.getMinutes();
let newSecs = date.getSeconds();
let stamp = (
newYear != prevYear && s[2] ||
newMnth != prevMnth && s[3] ||
newDate != prevDate && s[4] ||
newHour != prevHour && s[5] ||
newMins != prevMins && s[6] ||
newSecs != prevSecs && s[7] ||
s[1]
);
prevYear = newYear;
prevMnth = newMnth;
prevDate = newDate;
prevHour = newHour;
prevMins = newMins;
prevSecs = newSecs;
return stamp(date);
});
}
}
// for when axis.values is defined as a static fmtDate template string
function timeAxisVal(tzDate, dateTpl) {
let stamp = fmtDate(dateTpl);
return (self, splits, axisIdx, foundSpace, foundIncr) => splits.map(split => stamp(tzDate(split)));
}
function mkDate(y, m, d) {
return new Date(y, m, d);
}
function timeSeriesStamp(stampCfg, fmtDate) {
return fmtDate(stampCfg);
}
const _timeSeriesStamp = '{YYYY}-{MM}-{DD} {h}:{mm}{aa}';
function timeSeriesVal(tzDate, stamp) {
return (self, val) => stamp(tzDate(val));
}
function legendStroke(self, seriesIdx) {
let s = self.series[seriesIdx];
return s.width ? s.stroke(self, seriesIdx) : s.points.width ? s.points.stroke(self, seriesIdx) : null;
}
function legendFill(self, seriesIdx) {
return self.series[seriesIdx].fill(self, seriesIdx);
}
const legendOpts = {
show: true,
live: true,
isolate: false,
markers: {
show: true,
width: 2,
stroke: legendStroke,
fill: legendFill,
dash: "solid",
},
idx: null,
idxs: null,
values: [],
};
function cursorPointShow(self, si) {
let o = self.cursor.points;
let pt = placeDiv();
let size = o.size(self, si);
setStylePx(pt, WIDTH, size);
setStylePx(pt, HEIGHT, size);
let mar = size / -2;
setStylePx(pt, "marginLeft", mar);
setStylePx(pt, "marginTop", mar);
let width = o.width(self, si, size);
width && setStylePx(pt, "borderWidth", width);
return pt;
}
function cursorPointFill(self, si) {
let sp = self.series[si].points;
return sp._fill || sp._stroke;
}
function cursorPointStroke(self, si) {
let sp = self.series[si].points;
return sp._stroke || sp._fill;
}
function cursorPointSize(self, si) {
let sp = self.series[si].points;
return ptDia(sp.width, 1);
}
function dataIdx(self, seriesIdx, cursorIdx) {
return cursorIdx;
}
const moveTuple = [0,0];
function cursorMove(self, mouseLeft1, mouseTop1) {
moveTuple[0] = mouseLeft1;
moveTuple[1] = mouseTop1;
return moveTuple;
}
function filtBtn0(self, targ, handle) {
return e => {
e.button == 0 && handle(e);
};
}
function passThru(self, targ, handle) {
return handle;
}
const cursorOpts = {
show: true,
x: true,
y: true,
lock: false,
move: cursorMove,
points: {
show: cursorPointShow,
size: cursorPointSize,
width: 0,
stroke: cursorPointStroke,
fill: cursorPointFill,
},
bind: {
mousedown: filtBtn0,
mouseup: filtBtn0,
click: filtBtn0,
dblclick: filtBtn0,
mousemove: passThru,
mouseleave: passThru,
mouseenter: passThru,
},
drag: {
setScale: true,
x: true,
y: false,
dist: 0,
uni: null,
_x: false,
_y: false,
},
focus: {
prox: -1,
},
left: -10,
top: -10,
idx: null,
dataIdx,
idxs: null,
};
const axisLines = {
show: true,
stroke: "rgba(0,0,0,0.07)",
width: 2,
// dash: [],
};
const grid = assign({}, axisLines, {
filter: retArg1,
});
const ticks = assign({}, grid, {
size: 10,
});
const border = assign({}, axisLines, {
show: false,
});
const font = '12px system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"';
const labelFont = "bold " + font;
const lineMult = 1.5; // font-size multiplier
const xAxisOpts = {
show: true,
scale: "x",
stroke: hexBlack,
space: 50,
gap: 5,
size: 50,
labelGap: 0,
labelSize: 30,
labelFont,
side: 2,
// class: "x-vals",
// incrs: timeIncrs,
// values: timeVals,
// filter: retArg1,
grid,
ticks,
border,
font,
rotate: 0,
};
const numSeriesLabel = "Value";
const timeSeriesLabel = "Time";
const xSeriesOpts = {
show: true,
scale: "x",
auto: false,
sorted: 1,
// label: "Time",
// value: v => stamp(new Date(v * 1e3)),
// internal caches
min: inf,
max: -inf,
idxs: [],
};
function numAxisVals(self, splits, axisIdx, foundSpace, foundIncr) {
return splits.map(v => v == null ? "" : fmtNum(v));
}
function numAxisSplits(self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace, forceMin) {
let splits = [];
let numDec = fixedDec.get(foundIncr) || 0;
scaleMin = forceMin ? scaleMin : roundDec(incrRoundUp(scaleMin, foundIncr), numDec);
for (let val = scaleMin; val <= scaleMax; val = roundDec(val + foundIncr, numDec))
splits.push(Object.is(val, -0) ? 0 : val); // coalesces -0
return splits;
}
// this doesnt work for sin, which needs to come off from 0 independently in pos and neg dirs
function logAxisSplits(self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace, forceMin) {
const splits = [];
const logBase = self.scales[self.axes[axisIdx].scale].log;
const logFn = logBase == 10 ? log10 : log2;
const exp = floor(logFn(scaleMin));
foundIncr = pow(logBase, exp);
if (exp < 0)
foundIncr = roundDec(foundIncr, -exp);
let split = scaleMin;
do {
splits.push(split);
split = roundDec(split + foundIncr, fixedDec.get(foundIncr));
if (split >= foundIncr * logBase)
foundIncr = split;
} while (split <= scaleMax);
return splits;
}
function asinhAxisSplits(self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace, forceMin) {
let sc = self.scales[self.axes[axisIdx].scale];
let linthresh = sc.asinh;
let posSplits = scaleMax > linthresh ? logAxisSplits(self, axisIdx, max(linthresh, scaleMin), scaleMax, foundIncr) : [linthresh];
let zero = scaleMax >= 0 && scaleMin <= 0 ? [0] : [];
let negSplits = scaleMin < -linthresh ? logAxisSplits(self, axisIdx, max(linthresh, -scaleMax), -scaleMin, foundIncr): [linthresh];
return negSplits.reverse().map(v => -v).concat(zero, posSplits);
}
const RE_ALL = /./;
const RE_12357 = /[12357]/;
const RE_125 = /[125]/;
const RE_1 = /1/;
function logAxisValsFilt(self, splits, axisIdx, foundSpace, foundIncr) {
let axis = self.axes[axisIdx];
let scaleKey = axis.scale;
let sc = self.scales[scaleKey];
if (sc.distr == 3 && sc.log == 2)
return splits;
let valToPos = self.valToPos;
let minSpace = axis._space;
let _10 = valToPos(10, scaleKey);
let re = (
valToPos(9, scaleKey) - _10 >= minSpace ? RE_ALL :
valToPos(7, scaleKey) - _10 >= minSpace ? RE_12357 :
valToPos(5, scaleKey) - _10 >= minSpace ? RE_125 :
RE_1
);
return splits.map(v => ((sc.distr == 4 && v == 0) || re.test(v)) ? v : null);
}
function numSeriesVal(self, val) {
return val == null ? "" : fmtNum(val);
}
const yAxisOpts = {
show: true,
scale: "y",
stroke: hexBlack,
space: 30,
gap: 5,
size: 50,
labelGap: 0,
labelSize: 30,
labelFont,
side: 3,
// class: "y-vals",
// incrs: numIncrs,
// values: (vals, space) => vals,
// filter: retArg1,
grid,
ticks,
border,
font,
rotate: 0,
};
// takes stroke width
function ptDia(width, mult) {
let dia = 3 + (width || 1) * 2;
return roundDec(dia * mult, 3);
}
function seriesPointsShow(self, si) {
let { scale, idxs } = self.series[0];
let xData = self._data[0];
let p0 = self.valToPos(xData[idxs[0]], scale, true);
let p1 = self.valToPos(xData[idxs[1]], scale, true);
let dim = abs(p1 - p0);
let s = self.series[si];
// const dia = ptDia(s.width, pxRatio);
let maxPts = dim / (s.points.space * pxRatio);
return idxs[1] - idxs[0] <= maxPts;
}
const facet = {
scale: null,
auto: true,
sorted: 0,
// internal caches
min: inf,
max: -inf,
};
const xySeriesOpts = {
show: true,
auto: true,
sorted: 0,
alpha: 1,
facets: [
assign({}, facet, {scale: 'x'}),
assign({}, facet, {scale: 'y'}),
],
};
const ySeriesOpts = {
scale: "y",
auto: true,
sorted: 0,
show: true,
spanGaps: false,
gaps: (self, seriesIdx, idx0, idx1, nullGaps) => nullGaps,
alpha: 1,
points: {
show: seriesPointsShow,
filter: null,
// paths:
// stroke: "#000",
// fill: "#fff",
// width: 1,
// size: 10,
},
// label: "Value",
// value: v => v,
values: null,
// internal caches
min: inf,
max: -inf,
idxs: [],
path: null,
clip: null,
};
function clampScale(self, val, scaleMin, scaleMax, scaleKey) {
/*
if (val < 0) {
let cssHgt = self.bbox.height / pxRatio;
let absPos = self.valToPos(abs(val), scaleKey);
let fromBtm = cssHgt - absPos;
return self.posToVal(cssHgt + fromBtm, scaleKey);
}
*/
return scaleMin / 10;
}
const xScaleOpts = {
time: FEAT_TIME,
auto: true,
distr: 1,
log: 10,
asinh: 1,
min: null,
max: null,
dir: 1,
ori: 0,
};
const yScaleOpts = assign({}, xScaleOpts, {
time: false,
ori: 1,
});
const syncs = {};
function _sync(key, opts) {
let s = syncs[key];
if (!s) {
s = {
key,
plots: [],
sub(plot) {
s.plots.push(plot);
},
unsub(plot) {
s.plots = s.plots.filter(c => c != plot);
},
pub(type, self, x, y, w, h, i) {
for (let j = 0; j < s.plots.length; j++)
s.plots[j] != self && s.plots[j].pub(type, self, x, y, w, h, i);
},
};
if (key != null)
syncs[key] = s;
}
return s;
}
const BAND_CLIP_FILL = 1 << 0;
const BAND_CLIP_STROKE = 1 << 1;
function orient(u, seriesIdx, cb) {
const series = u.series[seriesIdx];
const scales = u.scales;
const bbox = u.bbox;
const scaleX = u.mode == 2 ? scales[series.facets[0].scale] : scales[u.series[0].scale];
let dx = u._data[0],
dy = u._data[seriesIdx],
sx = scaleX,
sy = u.mode == 2 ? scales[series.facets[1].scale] : scales[series.scale],
l = bbox.left,
t = bbox.top,
w = bbox.width,
h = bbox.height,
H = u.valToPosH,
V = u.valToPosV;
return (sx.ori == 0
? cb(
series,
dx,
dy,
sx,
sy,
H,
V,
l,
t,
w,
h,
moveToH,
lineToH,
rectH,
arcH,
bezierCurveToH,
)
: cb(
series,
dx,
dy,
sx,
sy,
V,
H,
t,
l,
h,
w,
moveToV,
lineToV,
rectV,
arcV,
bezierCurveToV,
)
);
}
function bandFillClipDirs(self, seriesIdx) {
let fillDir = 0;
// 2 bits, -1 | 1
let clipDirs = 0;
let bands = ifNull(self.bands, EMPTY_ARR);
for (let i = 0; i < bands.length; i++) {
let b = bands[i];
// is a "from" band edge
if (b.series[0] == seriesIdx)
fillDir = b.dir;
// is a "to" band edge
else if (b.series[1] == seriesIdx) {
if (b.dir == 1)
clipDirs |= 1;
else
clipDirs |= 2;
}
}
return [
fillDir,
(
clipDirs == 1 ? -1 : // neg only
clipDirs == 2 ? 1 : // pos only
clipDirs == 3 ? 2 : // both
0 // neither
)
];
}
function seriesFillTo(self, seriesIdx, dataMin, dataMax, bandFillDir) {
let scale = self.scales[self.series[seriesIdx].scale];
return (
bandFillDir == -1 ? scale.min :
bandFillDir == 1 ? scale.max :
scale.distr == 3 ? (
scale.dir == 1 ? scale.min :
scale.max
) : 0
);
}
// creates inverted band clip path (from stroke path -> yMax || yMin)
// clipDir is always inverse of fillDir
// default clip dir is upwards (1), since default band fill is downwards/fillBelowTo (-1) (highIdx -> lowIdx)
function clipBandLine(self, seriesIdx, idx0, idx1, strokePath, clipDir) {
return orient(self, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {
let pxRound = series.pxRound;
const dir = scaleX.dir * (scaleX.ori == 0 ? 1 : -1);
const lineTo = scaleX.ori == 0 ? lineToH : lineToV;
let frIdx, toIdx;
if (dir == 1) {
frIdx = idx0;
toIdx = idx1;
}
else {
frIdx = idx1;
toIdx = idx0;
}
// path start
let x0 = pxRound(valToPosX(dataX[frIdx], scaleX, xDim, xOff));
let y0 = pxRound(valToPosY(dataY[frIdx], scaleY, yDim, yOff));
// path end x
let x1 = pxRound(valToPosX(dataX[toIdx], scaleX, xDim, xOff));
// upper or lower y limit
let yLimit = pxRound(valToPosY(clipDir == 1 ? scaleY.max : scaleY.min, scaleY, yDim, yOff));
let clip = new Path2D(strokePath);
lineTo(clip, x1, yLimit);
lineTo(clip, x0, yLimit);
lineTo(clip, x0, y0);
return clip;
});
}
function clipGaps(gaps, ori, plotLft, plotTop, plotWid, plotHgt) {
let clip = null;
// create clip path (invert gaps and non-gaps)
if (gaps.length > 0) {
clip = new Path2D();
const rect = ori == 0 ? rectH : rectV;
let prevGapEnd = plotLft;
for (let i = 0; i < gaps.length; i++) {
let g = gaps[i];
if (g[1] > g[0]) {
let w = g[0] - prevGapEnd;
w > 0 && rect(clip, prevGapEnd, plotTop, w, plotTop + plotHgt);
prevGapEnd = g[1];
}
}
let w = plotLft + plotWid - prevGapEnd;
w > 0 && rect(clip, prevGapEnd, plotTop, w, plotTop + plotHgt);
}
return clip;
}
function addGap(gaps, fromX, toX) {
let prevGap = gaps[gaps.length - 1];
if (prevGap && prevGap[0] == fromX) // TODO: gaps must be encoded at stroke widths?
prevGap[1] = toX;
else
gaps.push([fromX, toX]);
}
function findGaps(xs, ys, idx0, idx1, dir, pixelForX) {
let gaps = [];
for (let i = dir == 1 ? idx0 : idx1; i >= idx0 && i <= idx1; i += dir) {
let yVal = ys[i];
if (yVal === null) {
let fr = i, to = i;
if (dir == 1) {
while (++i <= idx1 && ys[i] === null)
to = i;
}
else {
while (--i >= idx0 && ys[i] === null)
to = i;
}
let frPx = pixelForX(xs[fr]);
let toPx = to == fr ? frPx : pixelForX(xs[to]);
// if value adjacent to edge null is same pixel, then it's partially
// filled and gap should start at next pixel
let frPx2 = pixelForX(xs[fr-dir]);
// if (frPx2 == frPx)
// frPx++;
// else
frPx = frPx2;
let toPx2 = pixelForX(xs[to+dir]);
// if (toPx2 == toPx)
// toPx--;
// else
toPx = toPx2;
if (toPx >= frPx)
gaps.push([frPx, toPx]); // addGap
}
}
return gaps;
}
function pxRoundGen(pxAlign) {
return pxAlign == 0 ? retArg0 : pxAlign == 1 ? round : v => incrRound(v, pxAlign);
}
function rect(ori) {
let moveTo = ori == 0 ?
moveToH :
moveToV;
let arcTo = ori == 0 ?
(p, x1, y1, x2, y2, r) => { p.arcTo(x1, y1, x2, y2, r); } :
(p, y1, x1, y2, x2, r) => { p.arcTo(x1, y1, x2, y2, r); };
let rect = ori == 0 ?
(p, x, y, w, h) => { p.rect(x, y, w, h); } :
(p, y, x, h, w) => { p.rect(x, y, w, h); };
return (p, x, y, w, h, r = 0) => {
if (r == 0)
rect(p, x, y, w, h);
else {
r = min(r, w / 2, h / 2);
// adapted from https://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-using-html-canvas/7838871#7838871
moveTo(p, x + r, y);
arcTo(p, x + w, y, x + w, y + h, r);
arcTo(p, x + w, y + h, x, y + h, r);
arcTo(p, x, y + h, x, y, r);
arcTo(p, x, y, x + w, y, r);
p.closePath();
}
};
}
// orientation-inverting canvas functions
const moveToH = (p, x, y) => { p.moveTo(x, y); };
const moveToV = (p, y, x) => { p.moveTo(x, y); };
const lineToH = (p, x, y) => { p.lineTo(x, y); };
const lineToV = (p, y, x) => { p.lineTo(x, y); };
const rectH = rect(0);
const rectV = rect(1);
const arcH = (p, x, y, r, startAngle, endAngle) => { p.arc(x, y, r, startAngle, endAngle); };
const arcV = (p, y, x, r, startAngle, endAngle) => { p.arc(x, y, r, startAngle, endAngle); };
const bezierCurveToH = (p, bp1x, bp1y, bp2x, bp2y, p2x, p2y) => { p.bezierCurveTo(bp1x, bp1y, bp2x, bp2y, p2x, p2y); };
const bezierCurveToV = (p, bp1y, bp1x, bp2y, bp2x, p2y, p2x) => { p.bezierCurveTo(bp1x, bp1y, bp2x, bp2y, p2x, p2y); };
// TODO: drawWrap(seriesIdx, drawPoints) (save, restore, translate, clip)
function points(opts) {
return (u, seriesIdx, idx0, idx1, filtIdxs) => {
// log("drawPoints()", arguments);
return orient(u, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {
let { pxRound, points } = series;
let moveTo, arc;
if (scaleX.ori == 0) {
moveTo = moveToH;
arc = arcH;
}
else {
moveTo = moveToV;
arc = arcV;
}
const width = roundDec(points.width * pxRatio, 3);
let rad = (points.size - points.width) / 2 * pxRatio;
let dia = roundDec(rad * 2, 3);
let fill = new Path2D();
let clip = new Path2D();
let { left: lft, top: top, width: wid, height: hgt } = u.bbox;
rectH(clip,
lft - dia,
top - dia,
wid + dia * 2,
hgt + dia * 2,
);
const drawPoint = pi => {
if (dataY[pi] != null) {
let x = pxRound(valToPosX(dataX[pi], scaleX, xDim, xOff));
let y = pxRound(valToPosY(dataY[pi], scaleY, yDim, yOff));
moveTo(fill, x + rad, y);
arc(fill, x, y, rad, 0, PI * 2);
}
};
if (filtIdxs)
filtIdxs.forEach(drawPoint);
else {
for (let pi = idx0; pi <= idx1; pi++)
drawPoint(pi);
}
return {
stroke: width > 0 ? fill : null,
fill,
clip,
flags: BAND_CLIP_FILL | BAND_CLIP_STROKE,
};
});
};
}
function _drawAcc(lineTo) {
return (stroke, accX, minY, maxY, inY, outY) => {
if (minY != maxY) {
if (inY != minY && outY != minY)
lineTo(stroke, accX, minY);
if (inY != maxY && outY != maxY)
lineTo(stroke, accX, maxY);
lineTo(stroke, accX, outY);
}
};
}
const drawAccH = _drawAcc(lineToH);
const drawAccV = _drawAcc(lineToV);
function linear() {
return (u, seriesIdx, idx0, idx1) => {
return orient(u, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {
let pxRound = series.pxRound;
let pixelForX = val => pxRound(valToPosX(val, scaleX, xDim, xOff));
let pixelForY = val => pxRound(valToPosY(val, scaleY, yDim, yOff));
let lineTo, drawAcc;
if (scaleX.ori == 0) {
lineTo = lineToH;
drawAcc = drawAccH;
}
else {
lineTo = lineToV;
drawAcc = drawAccV;
}
const dir = scaleX.dir * (scaleX.ori == 0 ? 1 : -1);
const _paths = {stroke: new Path2D(), fill: null, clip: null, band: null, gaps: null, flags: BAND_CLIP_FILL};
const stroke = _paths.stroke;
let minY = inf,
maxY = -inf,
inY, outY, drawnAtX;
let accX = pixelForX(dataX[dir == 1 ? idx0 : idx1]);
// data edges
let lftIdx = nonNullIdx(dataY, idx0, idx1, 1 * dir);
let rgtIdx = nonNullIdx(dataY, idx0, idx1, -1 * dir);
let lftX = pixelForX(dataX[lftIdx]);
let rgtX = pixelForX(dataX[rgtIdx]);
for (let i = dir == 1 ? idx0 : idx1; i >= idx0 && i <= idx1; i += dir) {
let x = pixelForX(dataX[i]);
if (x == accX) {
if (dataY[i] != null) {
outY = pixelForY(dataY[i]);
if (minY == inf) {
lineTo(stroke, x, outY);
inY = outY;
}
minY = min(outY, minY);
maxY = max(outY, maxY);
}
}
else {
if (minY != inf) {
drawAcc(stroke, accX, minY, maxY, inY, outY);
drawnAtX = accX;
}
if (dataY[i] != null) {
outY = pixelForY(dataY[i]);
lineTo(stroke, x, outY);
minY = maxY = inY = outY;
}
else {
minY = inf;
maxY = -inf;
}
accX = x;
}
}
if (minY != inf && minY != maxY && drawnAtX != accX)
drawAcc(stroke, accX, minY, maxY, inY, outY);
let [ bandFillDir, bandClipDir ] = bandFillClipDirs(u, seriesIdx);
if (series.fill != null || bandFillDir != 0) {
let fill = _paths.fill = new Path2D(stroke);
let fillToVal = series.fillTo(u, seriesIdx, series.min, series.max, bandFillDir);
let fillToY = pixelForY(fillToVal);
lineTo(fill, rgtX, fillToY);
lineTo(fill, lftX, fillToY);
}
if (!series.spanGaps) {
// console.time('gaps');
let gaps = [];
if (lftX > xOff)
gaps.push([xOff, lftX]);
gaps.push(...findGaps(dataX, dataY, idx0, idx1, dir, pixelForX));
if (rgtX < xOff + xDim)
gaps.push([rgtX, xOff + xDim]);
// console.timeEnd('gaps');
// console.log('gaps', JSON.stringify(gaps));
_paths.gaps = gaps = series.gaps(u, seriesIdx, idx0, idx1, gaps);
_paths.clip = clipGaps(gaps, scaleX.ori, xOff, yOff, xDim, yDim);
}
if (bandClipDir != 0) {
_paths.band = bandClipDir == 2 ? [
clipBandLine(u, seriesIdx, idx0, idx1, stroke, -1),
clipBandLine(u, seriesIdx, idx0, idx1, stroke, 1),
] : clipBandLine(u, seriesIdx, idx0, idx1, stroke, bandClipDir);
}
return _paths;
});
};
}
function stepped(opts) {
const align = ifNull(opts.align, 1);
// whether to draw ascenders/descenders at null/gap bondaries
const ascDesc = ifNull(opts.ascDesc, false);
return (u, seriesIdx, idx0, idx1) => {
return orient(u, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {
let pxRound = series.pxRound;
let lineTo = scaleX.ori == 0 ? lineToH : lineToV;
const _paths = {stroke: new Path2D(), fill: null, clip: null, band: null, gaps: null, flags: BAND_CLIP_FILL};
const stroke = _paths.stroke;
const _dir = 1 * scaleX.dir * (scaleX.ori == 0 ? 1 : -1);
idx0 = nonNullIdx(dataY, idx0, idx1, 1);
idx1 = nonNullIdx(dataY, idx0, idx1, -1);
let gaps = [];
let inGap = false;
let prevYPos = pxRound(valToPosY(dataY[_dir == 1 ? idx0 : idx1], scaleY, yDim, yOff));
let firstXPos = pxRound(valToPosX(dataX[_dir == 1 ? idx0 : idx1], scaleX, xDim, xOff));
let prevXPos = firstXPos;
lineTo(stroke, firstXPos, prevYPos);
for (let i = _dir == 1 ? idx0 : idx1; i >= idx0 && i <= idx1; i += _dir) {
let yVal1 = dataY[i];
let x1 = pxRound(valToPosX(dataX[i], scaleX, xDim, xOff));
if (yVal1 == null) {
if (yVal1 === null) {
addGap(gaps, prevXPos, x1);
inGap = true;
}
continue;
}
let y1 = pxRound(valToPosY(yVal1, scaleY, yDim, yOff));
if (inGap) {
addGap(gaps, prevXPos, x1);
inGap = false;
}
if (align == 1)
lineTo(stroke, x1, prevYPos);
else
lineTo(stroke, prevXPos, y1);
lineTo(stroke, x1, y1);
prevYPos = y1;
prevXPos = x1;
}
let [ bandFillDir, bandClipDir ] = bandFillClipDirs(u, seriesIdx);
if (series.fill != null || bandFillDir != 0) {
let fill = _paths.fill = new Path2D(stroke);
let fillTo = series.fillTo(u, seriesIdx, series.min, series.max, bandFillDir);
let fillToY = pxRound(valToPosY(fillTo, scaleY, yDim, yOff));
lineTo(fill, prevXPos, fillToY);
lineTo(fill, firstXPos, fillToY);
}
_paths.gaps = gaps = series.gaps(u, seriesIdx, idx0, idx1, gaps);
// expand/contract clips for ascenders/descenders
let halfStroke = (series.width * pxRatio) / 2;
let startsOffset = (ascDesc || align == 1) ? halfStroke : -halfStroke;
let endsOffset = (ascDesc || align == -1) ? -halfStroke : halfStroke;
gaps.forEach(g => {
g[0] += startsOffset;
g[1] += endsOffset;
});
if (!series.spanGaps)
_paths.clip = clipGaps(gaps, scaleX.ori, xOff, yOff, xDim, yDim);
if (bandClipDir != 0) {
_paths.band = bandClipDir == 2 ? [
clipBandLine(u, seriesIdx, idx0, idx1, stroke, -1),
clipBandLine(u, seriesIdx, idx0, idx1, stroke, 1),
] : clipBandLine(u, seriesIdx, idx0, idx1, stroke, bandClipDir);
}
return _paths;
});
};
}
function bars(opts) {
opts = opts || EMPTY_OBJ;
const size = ifNull(opts.size, [0.6, inf, 1]);
const align = opts.align || 0;
const extraGap = (opts.gap || 0) * pxRatio;
const radius = ifNull(opts.radius, 0);
const gapFactor = 1 - size[0];
const maxWidth = ifNull(size[1], inf) * pxRatio;
const minWidth = ifNull(size[2], 1) * pxRatio;
const disp = ifNull(opts.disp, EMPTY_OBJ);
const _each = ifNull(opts.each, _ => {});
const { fill: dispFills, stroke: dispStrokes } = disp;
return (u, seriesIdx, idx0, idx1) => {
return orient(u, seriesIdx, (series, dataX, dataY, scaleX, scaleY, valToPosX, valToPosY, xOff, yOff, xDim, yDim) => {
let pxRound = series.pxRound;
const _dirX = scaleX.dir * (scaleX.ori == 0 ? 1 : -1);
const _dirY = scaleY.dir * (scaleY.ori == 1 ? 1 : -1);
let rect = scaleX.ori == 0