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