uplot-webgpu 0.1.0 → 0.2.0

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