swiftplot 0.1.1 → 0.3.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 (95) hide show
  1. package/README.md +71 -47
  2. package/dist/chart.d.ts +4 -0
  3. package/dist/chart.js +171 -86
  4. package/dist/charts/build.d.ts +52 -0
  5. package/dist/charts/build.js +63 -0
  6. package/dist/charts/candlestick.d.ts +8 -0
  7. package/dist/charts/candlestick.js +105 -0
  8. package/dist/charts/combo.d.ts +8 -0
  9. package/dist/charts/combo.js +50 -0
  10. package/dist/charts/controller.d.ts +2 -2
  11. package/dist/charts/controller.js +2 -2
  12. package/dist/charts/defaults.d.ts +10 -2
  13. package/dist/charts/defaults.js +67 -6
  14. package/dist/charts/distribution.d.ts +15 -0
  15. package/dist/charts/distribution.js +178 -0
  16. package/dist/charts/fields.d.ts +33 -3
  17. package/dist/charts/fields.js +150 -66
  18. package/dist/charts/flow.d.ts +15 -0
  19. package/dist/charts/flow.js +189 -0
  20. package/dist/charts/heatmap.d.ts +9 -0
  21. package/dist/charts/heatmap.js +104 -0
  22. package/dist/charts/index.d.ts +8 -1
  23. package/dist/charts/index.js +7 -0
  24. package/dist/charts/parts.d.ts +23 -0
  25. package/dist/charts/parts.js +66 -0
  26. package/dist/charts/radar.d.ts +7 -0
  27. package/dist/charts/radar.js +77 -0
  28. package/dist/charts/types.d.ts +562 -23
  29. package/dist/charts/xy.d.ts +35 -25
  30. package/dist/charts/xy.js +327 -126
  31. package/dist/features/animate.d.ts +10 -1
  32. package/dist/features/animate.js +3 -3
  33. package/dist/features/brush.d.ts +3 -1
  34. package/dist/features/brush.js +2 -1
  35. package/dist/features/legend.d.ts +1 -3
  36. package/dist/features/legend.js +4 -5
  37. package/dist/features/tooltip.d.ts +10 -2
  38. package/dist/features/tooltip.js +12 -10
  39. package/dist/features/zoom.d.ts +1 -0
  40. package/dist/features/zoom.js +22 -4
  41. package/dist/index.d.ts +2 -0
  42. package/dist/index.js +1 -0
  43. package/dist/marks/arcs.d.ts +10 -4
  44. package/dist/marks/arcs.js +2 -1
  45. package/dist/marks/area.d.ts +9 -8
  46. package/dist/marks/area.js +2 -2
  47. package/dist/marks/bar.d.ts +18 -10
  48. package/dist/marks/bar.js +5 -5
  49. package/dist/marks/box.d.ts +7 -1
  50. package/dist/marks/box.js +2 -8
  51. package/dist/marks/candlestick.d.ts +22 -0
  52. package/dist/marks/candlestick.js +133 -0
  53. package/dist/marks/common.d.ts +18 -0
  54. package/dist/marks/common.js +14 -0
  55. package/dist/marks/dots.d.ts +6 -5
  56. package/dist/marks/dots.js +3 -1
  57. package/dist/marks/errorBars.d.ts +9 -4
  58. package/dist/marks/errorBars.js +21 -1
  59. package/dist/marks/funnel.d.ts +8 -3
  60. package/dist/marks/funnel.js +2 -1
  61. package/dist/marks/heatmap.d.ts +8 -7
  62. package/dist/marks/line.d.ts +8 -6
  63. package/dist/marks/radar.d.ts +9 -2
  64. package/dist/marks/radar.js +9 -2
  65. package/dist/marks/radialBars.d.ts +12 -5
  66. package/dist/marks/rule.d.ts +19 -0
  67. package/dist/marks/rule.js +4 -1
  68. package/dist/marks/sankey.d.ts +14 -2
  69. package/dist/marks/sankey.js +4 -1
  70. package/dist/marks/sunburst.d.ts +5 -0
  71. package/dist/marks/sunburst.js +2 -1
  72. package/dist/marks/ticks.d.ts +4 -1
  73. package/dist/marks/tree.d.ts +14 -6
  74. package/dist/marks/tree.js +6 -3
  75. package/dist/marks/treemap.d.ts +5 -0
  76. package/dist/marks/treemap.js +7 -2
  77. package/dist/paint.d.ts +6 -1
  78. package/dist/paint.js +6 -1
  79. package/dist/scale.d.ts +1 -1
  80. package/dist/scale.js +4 -3
  81. package/dist/scales/band.d.ts +3 -0
  82. package/dist/scales/band.js +5 -1
  83. package/dist/scales/bare.d.ts +4 -1
  84. package/dist/scales/bare.js +4 -1
  85. package/dist/scales/color.d.ts +2 -0
  86. package/dist/scales/log.d.ts +8 -1
  87. package/dist/scales/log.js +3 -2
  88. package/dist/scales/time.d.ts +7 -0
  89. package/dist/scales/time.js +3 -1
  90. package/dist/text.d.ts +8 -0
  91. package/dist/text.js +33 -0
  92. package/dist/transforms.d.ts +11 -7
  93. package/dist/transforms.js +8 -7
  94. package/dist/types.d.ts +44 -13
  95. package/package.json +2 -2
package/dist/chart.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { locate, position } from './features/pointer.js';
2
2
  import { upTo } from './marks/common.js';
3
3
  import { extent, scale } from './scale.js';
4
+ import { FONT, textWidth } from './text.js';
4
5
  import { light } from './theme.js';
5
6
  export const NEAREST_PX = 20;
6
7
  // What an update of these alone leaves alone: a tip held by a tap stays.
@@ -46,22 +47,15 @@ const clamp = (want, [p, q]) => {
46
47
  const s = within(want && [Math.min(...want), Math.max(...want)], [q, p]);
47
48
  return s && [s[1], s[0]];
48
49
  };
50
+ /**
51
+ * Draws the marks into `el` on the axes given, with the features in `use`, and returns the chart to update or destroy.
52
+ * @param el The element the chart fills.
53
+ */
49
54
  export function plot(el, options) {
50
55
  let o = options;
51
56
  let dpr = devicePixelRatio;
52
57
  const root = document.createElement('div');
53
- const font = '12px system-ui,sans-serif';
54
- root.style.cssText = `position:relative;font:${font};pointer-events:auto`;
55
- const widths = new Map();
56
- let pen;
57
- const textWidth = (s) => {
58
- let w = widths.get(s);
59
- if (w === undefined) {
60
- pen ??= Object.assign(document.createElement('canvas').getContext('2d'), { font });
61
- widths.set(s, (w = pen.measureText(s).width));
62
- }
63
- return w;
64
- };
58
+ root.style.cssText = `position:relative;font:${FONT};pointer-events:auto`;
65
59
  const layer = (tag, css = '') => {
66
60
  const e = document.createElement(tag);
67
61
  e.style.cssText = `position:absolute;pointer-events:none;${css}`;
@@ -155,12 +149,19 @@ export function plot(el, options) {
155
149
  const relaid = showing();
156
150
  delete extents.x;
157
151
  delete extents.y;
158
- scanned = undefined;
152
+ delete extents.y2;
153
+ scanned = {};
159
154
  return relaid;
160
155
  };
161
156
  let xs;
162
157
  let ys;
158
+ let ys2;
163
159
  let view;
160
+ // What a mark on y2 is given: the same plot with the second scale as its y.
161
+ let view2;
162
+ const has2 = () => !!o.y2 && !bare(o);
163
+ const onAxis = (k) => (k.yAxis === 'y2' && has2() ? 'y2' : 'y');
164
+ const keys = () => (has2() ? ['x', 'y', 'y2'] : ['x', 'y']);
164
165
  let viewKey = '';
165
166
  let axesKey = '';
166
167
  let cache = new Map();
@@ -275,7 +276,7 @@ export function plot(el, options) {
275
276
  const wanted = [...new Set(visible)].flatMap(k => cache.get(k)?.p.labels ?? []);
276
277
  const kept = [];
277
278
  for (const label of wanted.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))) {
278
- const [x, y, w] = [label.x / dpr, label.y / dpr, label.text.length * 7];
279
+ const [x, y, w] = [label.x / dpr, label.y / dpr, textWidth(label.text)];
279
280
  const l = label.align === 'start' ? x : label.align === 'end' ? x - w : x - w / 2;
280
281
  const box = { l, t: y - 8, r: l + w, b: y + 8, text: label.text, color: label.color };
281
282
  if (box.l < 0 || box.t < 0 || box.r > W || box.b > H)
@@ -362,17 +363,19 @@ export function plot(el, options) {
362
363
  let extents = {};
363
364
  // With every series hidden an axis keeps the extent it last had.
364
365
  const last = {};
365
- const limits = { x: [0, 1], y: [0, 1] };
366
+ const limits = { x: [0, 1], y: [0, 1], y2: [0, 1] };
366
367
  const wholes = {};
367
368
  // A proposal's scan is kept for the display of the same window that follows it.
368
- let scanned;
369
- let lastWindowFit;
370
- let yFitted = false;
371
- let yFit;
372
- // The y extent of the shown marks between a and b on x, if any shows there. A connected mark's x
369
+ let scanned = {};
370
+ // Per y axis: whether it is fitted to the x window, what it fits when it is, and the last fit that found a mark.
371
+ const fits = {
372
+ y: { fitted: false },
373
+ y2: { fitted: false },
374
+ };
375
+ // The extent on one y axis of its shown marks between a and b on x, if any shows there. A connected mark's x
373
376
  // is ascending, so its rows are found by binary search, and its values at the two edges count too.
374
377
  // A row counts only where every value of it is a number, as a mark draws nothing of it otherwise.
375
- const scan = (a, b) => {
378
+ const scan = (which, a, b) => {
376
379
  let lo = Infinity;
377
380
  let hi = -Infinity;
378
381
  let seen = false;
@@ -386,6 +389,8 @@ export function plot(el, options) {
386
389
  hi = v;
387
390
  };
388
391
  for (const k of visible) {
392
+ if (onAxis(k) !== which)
393
+ continue;
389
394
  const n = k.points;
390
395
  const { x: X, y: Y } = k.channels;
391
396
  const rows = Y.filter(c => c.length === n);
@@ -459,39 +464,43 @@ export function plot(el, options) {
459
464
  };
460
465
  const sorted = ([a, b]) => [Math.min(a, b), Math.max(a, b)];
461
466
  const fitsWindow = (axis) => axis.fit === 'window' && typeof axis.domain === 'string';
462
- const scanOnce = (a, b) => {
467
+ const scanOnce = (which, a, b) => {
463
468
  const key = `${a},${b}`;
464
- if (scanned?.key !== key)
465
- scanned = { key, span: scan(a, b) };
466
- return scanned.span;
469
+ const kept = scanned[which];
470
+ return kept?.key === key ? kept.span : (scanned[which] = { key, span: scan(which, a, b) }).span;
467
471
  };
468
- const windowExtent = (whole) => {
472
+ const windowExtent = (which, whole) => {
469
473
  const [a, b] = sorted([xs.lo, xs.hi]);
470
- lastWindowFit = scanOnce(a, b) ?? lastWindowFit;
471
- return lastWindowFit ?? whole();
474
+ const f = fits[which];
475
+ f.last = scanOnce(which, a, b) ?? f.last;
476
+ return f.last ?? whole();
472
477
  };
473
478
  const fitted = (which, room) => {
479
+ // Each y axis takes its extent from its own marks.
480
+ const mine = (k) => which === 'x' || onAxis(k) === which;
481
+ const cols = (list) => list.flatMap(k => (which === 'x' ? k.channels.x : mine(k) ? k.channels.y : []));
474
482
  const of = () => axisOf(o, which).fit === 'all'
475
- ? (extents[`${which}All`] ??= extent(every().flatMap(k => k.channels[which])))
483
+ ? (extents[`${which}All`] ??= extent(cols(every())))
476
484
  : (extents[which] ??=
477
- visible.some(k => !k.backdrop) || !marks.length
478
- ? (last[which] = extent(visible.flatMap(k => k.channels[which])))
479
- : (last[which] ??= extent(every().flatMap(k => k.channels[which]))));
485
+ visible.some(k => !k.backdrop && mine(k)) || !marks.length
486
+ ? (last[which] = extent(cols(visible)))
487
+ : (last[which] ??= extent(cols(every()))));
480
488
  const whole = (wholes[which] = resolve(axisOf(o, which), of, room));
481
489
  limits[which] = [whole.lo, whole.hi];
482
490
  const w = bare(o) ? undefined : clamp(into(which, o.view?.[which]), limits[which]);
483
- if (which === 'y') {
484
- yFitted = false;
485
- yFit = { of, room };
491
+ const f = which === 'x' ? undefined : fits[which];
492
+ if (f) {
493
+ f.fitted = false;
494
+ f.fit = { of, room };
486
495
  }
487
496
  if (!w) {
488
497
  const axis = axisOf(o, which);
489
- if (which === 'x' || !fitsWindow(axis))
498
+ if (which === 'x' || !f || !fitsWindow(axis))
490
499
  return whole;
491
- yFitted = true;
500
+ f.fitted = true;
492
501
  if (xs !== wholes.x)
493
- return resolve(axis, () => windowExtent(of), room);
494
- lastWindowFit = of();
502
+ return resolve(axis, () => windowExtent(which, of), room);
503
+ f.last = of();
495
504
  return whole;
496
505
  }
497
506
  if (w[0] === whole.lo && w[1] === whole.hi)
@@ -511,9 +520,10 @@ export function plot(el, options) {
511
520
  const bottom = g.bottom ?? (axisOf(o, 'x').label ? 44 : 26);
512
521
  const [w, h] = laidOut
513
522
  ? [W - m.left - m.right, H - m.top - m.bottom]
514
- : [W - (g.left ?? 44) - (g.right ?? 16), H - (g.top ?? 12) - bottom];
523
+ : [W - (g.left ?? 44) - (g.right ?? (has2() ? 44 : 16)), H - (g.top ?? 12) - bottom];
515
524
  xs = fitted('x', { length: w, horizontal: true });
516
525
  ys = fitted('y', { length: h, horizontal: false });
526
+ ys2 = has2() ? fitted('y2', { length: h, horizontal: false }) : undefined;
517
527
  };
518
528
  const theme = () => o.theme ?? light;
519
529
  const real = (k, v) => {
@@ -543,23 +553,29 @@ export function plot(el, options) {
543
553
  return r;
544
554
  };
545
555
  const xPx = (v) => (view.ox + v * view.kx) / dpr;
546
- const yPx = (v) => (view.oy - v * view.ky) / dpr;
556
+ const yPx = (v, axis) => {
557
+ const s = axis === 'y2' ? view2 : view;
558
+ return (s.oy - v * s.ky) / dpr;
559
+ };
547
560
  const layout = () => {
548
- // ponytail: tick labels are taken as 7 px a character, not measured, because measuring text
549
- // forces a layout before the first paint. Set the margin when labels are wider than that.
550
561
  const [xLabel, yLabel] = [axisOf(o, 'x').label, axisOf(o, 'y').label];
562
+ const y2Label = ys2 ? axisOf(o, 'y2').label : '';
551
563
  const given = o.margin ?? {};
552
564
  let widest = 0;
553
565
  if (given.left === undefined)
554
566
  for (const t of [...ys.ticks, ...wholes.y.ticks])
555
- widest = Math.max(widest, t.label.length);
567
+ widest = Math.max(widest, textWidth(t.label));
568
+ let widest2 = 0;
569
+ if (ys2 && given.right === undefined)
570
+ for (const t of [...ys2.ticks, ...wholes.y2.ticks])
571
+ widest2 = Math.max(widest2, textWidth(t.label));
556
572
  m = bare(o)
557
573
  ? { top: given.top ?? 8, right: given.right ?? 8, bottom: given.bottom ?? 8, left: given.left ?? 8 }
558
574
  : {
559
575
  top: given.top ?? 12,
560
- right: given.right ?? 16,
576
+ right: given.right ?? (ys2 ? 14 + Math.ceil(widest2) + (y2Label ? 20 : 0) : 16),
561
577
  bottom: given.bottom ?? (xLabel ? 44 : 26),
562
- left: given.left ?? 14 + widest * 7 + (yLabel ? 20 : 0),
578
+ left: given.left ?? 14 + Math.ceil(widest) + (yLabel ? 20 : 0),
563
579
  };
564
580
  // x tick labels are centred on their ticks, so the first and the last may reach past the chart.
565
581
  // A tick at fraction u of the axis sits at (1 - u) * left + u * (W - right). Each side is first
@@ -604,11 +620,13 @@ export function plot(el, options) {
604
620
  ctx,
605
621
  theme: theme(),
606
622
  };
623
+ const ky2 = ys2 ? height / (ys2.hi - ys2.lo) : ky;
624
+ view2 = ys2 ? { ...view, ky: ky2, oy: top + height + ys2.lo * ky2 } : view;
607
625
  axes.style.color = theme().text;
608
626
  if (notes)
609
627
  notes.style.color = theme().text;
610
628
  uncover();
611
- const key = JSON.stringify([W, H, m, xs, ys, xLabel, yLabel, xs !== wx]);
629
+ const key = JSON.stringify([W, H, m, xs, ys, ys2, xLabel, yLabel, y2Label, xs !== wx]);
612
630
  if (key !== axesKey) {
613
631
  axesKey = key;
614
632
  // Axis text is DOM, not fillText: the first text drawn on a canvas cost ~20 ms at 4x CPU slowdown.
@@ -627,17 +645,22 @@ export function plot(el, options) {
627
645
  }
628
646
  for (const t of ys.ticks)
629
647
  text(t.label, m.left - 8, yPx(t.value), 'translate(-100%,-50%)');
648
+ for (const t of ys2?.ticks ?? [])
649
+ text(t.label, W - m.right + 8, yPx(t.value, 'y2'), 'translate(0,-50%)');
630
650
  text(xLabel, m.left + width / dpr / 2, H - 2, 'translate(-50%,-100%)');
631
651
  text(yLabel, 10, m.top + height / dpr / 2, 'translate(-50%,-50%) rotate(-90deg)');
652
+ if (y2Label)
653
+ text(y2Label, W - 10, m.top + height / dpr / 2, 'translate(-50%,-50%) rotate(90deg)');
632
654
  axes.replaceChildren(labels);
633
655
  }
634
656
  const described = () => {
635
657
  const names = [...new Set(marks.flatMap(k => k.label ?? []))].join(', ');
636
- const axesNamed = yLabel && xLabel ? `${yLabel} by ${xLabel}` : yLabel || xLabel;
658
+ const yNamed = [yLabel, y2Label].filter(Boolean).join(' and ');
659
+ const axesNamed = yNamed && xLabel ? `${yNamed} by ${xLabel}` : yNamed || xLabel;
637
660
  return [axesNamed, names].filter(Boolean).join(': ') || 'Chart';
638
661
  };
639
662
  canvas.ariaLabel = o.description ?? described();
640
- viewKey = [kx, view.ox, ky, view.oy, left, top, width, height].join();
663
+ viewKey = [kx, view.ox, ky, view.oy, view2.ky, view2.oy, left, top, width, height].join();
641
664
  };
642
665
  // The browser takes a context away when too many are open, so a lost layer gives its marks back to the canvas.
643
666
  const dropLost = () => {
@@ -674,10 +697,13 @@ export function plot(el, options) {
674
697
  const onLayer = (k) => layered.get(k);
675
698
  // ponytail: WebGL positions are 32-bit, a pixel off past ~4096x, so deeper zoom draws on the
676
699
  // canvas; 64-bit positions in the shader (a high and a low float) would lift this ceiling.
677
- const deep = [xs, ys].some((s, i) => {
678
- const whole = i ? wholes.y : wholes.x;
679
- return (whole.hi - whole.lo) / (s.hi - s.lo) > 4096;
680
- });
700
+ const scales = [
701
+ [xs, wholes.x],
702
+ [ys, wholes.y],
703
+ ];
704
+ if (ys2)
705
+ scales.push([ys2, wholes.y2]);
706
+ const deep = scales.some(([s, whole]) => (whole.hi - whole.lo) / (s.hi - s.lo) > 4096);
681
707
  // Each mark fills its own share of the threshold, so a mark may ask for the layer sooner or later.
682
708
  let useGl = !deep &&
683
709
  visible.reduce((sum, k) => sum + (onLayer(k) ? k.points / (k.gl.from ?? GL_FROM) : 0), 0) >= 1;
@@ -708,7 +734,8 @@ export function plot(el, options) {
708
734
  let e = old.get(k);
709
735
  const changed = !e;
710
736
  if (!e || viewChanged || e.gl !== g) {
711
- e = { p: g ? k.gl.prepare(view, gl) : k.prepare(view, replaced.get(k)), gl: g };
737
+ const v = onAxis(k) === 'y2' ? view2 : view;
738
+ e = { p: g ? k.gl.prepare(v, gl) : k.prepare(v, replaced.get(k)), gl: g };
712
739
  if (g)
713
740
  placed.add(k);
714
741
  }
@@ -841,15 +868,15 @@ export function plot(el, options) {
841
868
  const paint = (why) => (painter ? painter(render, why) : render());
842
869
  const refresh = (data, also, restyled = false, asked = false) => {
843
870
  const before = viewKey;
844
- const shown = () => [xs.lo, xs.hi, ys.lo, ys.hi].join();
871
+ const shown = () => [xs.lo, xs.hi, ys.lo, ys.hi, ys2?.lo, ys2?.hi].join();
845
872
  const was = asked && shown();
846
873
  rescale(false);
847
874
  layout();
848
875
  // The scales were resolved for a guessed room; resolved again for the real one, their ticks or
849
876
  // bounds may differ, and then so may the margins. Once more is enough to be right in all but contrived cases.
850
- const guessed = JSON.stringify([xs, ys, wholes]);
877
+ const guessed = JSON.stringify([xs, ys, ys2, wholes]);
851
878
  rescale(true);
852
- if (JSON.stringify([xs, ys, wholes]) !== guessed)
879
+ if (JSON.stringify([xs, ys, ys2, wholes]) !== guessed)
853
880
  layout();
854
881
  if (asked && shown() !== was)
855
882
  also = 'size';
@@ -896,7 +923,7 @@ export function plot(el, options) {
896
923
  // In the marks' space, or with `stored` as o.view keeps it: in real values, a side not proposed as the app gave it.
897
924
  const wanted = (want, stored = false) => {
898
925
  const next = {};
899
- for (const k of ['x', 'y']) {
926
+ for (const k of keys()) {
900
927
  if (!want)
901
928
  continue;
902
929
  const given = o.view?.[k];
@@ -906,6 +933,38 @@ export function plot(el, options) {
906
933
  }
907
934
  return next;
908
935
  };
936
+ // A y window takes y2 with it: the same pixels through the second scale, and the whole of it with the whole of y.
937
+ const linked = (want) => {
938
+ if (!want || !ys2 || !('y' in want) || 'y2' in want)
939
+ return want;
940
+ const y = clamp(want.y, limits.y);
941
+ // A y proposed as it is shown, as a pan along x does, leaves y2 its own window.
942
+ if (y && y[0] === ys.lo && y[1] === ys.hi)
943
+ return want;
944
+ if (!y || (y[0] === limits.y[0] && y[1] === limits.y[1]))
945
+ return { ...want, y2: undefined };
946
+ const { lo, hi } = ys2;
947
+ const through = (v) => lo + ((v - ys.lo) / (ys.hi - ys.lo)) * (hi - lo);
948
+ return { ...want, y2: [through(y[0]), through(y[1])] };
949
+ };
950
+ // A side proposed just as it is shown, with no window of its own, gets none: an axis that follows its
951
+ // marks goes on following them. update({ view }) is how an app holds a span that is already shown.
952
+ const loose = (want) => {
953
+ if (!want)
954
+ return want;
955
+ const next = { ...want };
956
+ const now = internals.view();
957
+ for (const k of keys()) {
958
+ if (next[k] === undefined || clamp(into(k, o.view?.[k]), limits[k]))
959
+ continue;
960
+ const [w, shown] = [clamp(next[k], limits[k]), now[k]];
961
+ // Clamped at an edge, a span comes back a float step off the one shown.
962
+ const slack = Math.abs(shown[1] - shown[0]) * 1e-9;
963
+ if (w && Math.abs(w[0] - shown[0]) <= slack && Math.abs(w[1] - shown[1]) <= slack)
964
+ delete next[k];
965
+ }
966
+ return next;
967
+ };
909
968
  const internals = {
910
969
  root,
911
970
  canvas,
@@ -943,37 +1002,50 @@ export function plot(el, options) {
943
1002
  xPx,
944
1003
  yPx,
945
1004
  xValue: px => (px * dpr - view.ox) / view.kx,
946
- yValue: px => (view.oy - px * dpr) / view.ky,
947
- view: () => ({ x: [xs.lo, xs.hi], y: [ys.lo, ys.hi] }),
948
- domain: () => ({ ...limits }),
949
- fit(want) {
1005
+ yValue(px, axis) {
1006
+ const s = axis === 'y2' ? view2 : view;
1007
+ return (s.oy - px * dpr) / s.ky;
1008
+ },
1009
+ yAxis: onAxis,
1010
+ view: () => ({ x: [xs.lo, xs.hi], y: [ys.lo, ys.hi], ...(ys2 && { y2: [ys2.lo, ys2.hi] }) }),
1011
+ domain: () => ({ x: limits.x, y: limits.y, ...(ys2 && { y2: limits.y2 }) }),
1012
+ fit(asked) {
950
1013
  if (bare(o))
951
1014
  return internals.view();
952
- const next = wanted(want);
1015
+ const next = wanted(loose(linked(asked)));
953
1016
  const x = clamp(next.x, limits.x) ?? limits.x;
954
- const derived = () => {
1017
+ const side = (which) => {
1018
+ const w = clamp(next[which], limits[which]);
1019
+ if (w)
1020
+ return [...w];
955
1021
  const whole = x[0] === limits.x[0] && x[1] === limits.x[1];
956
- if (whole || !yFit || !fitsWindow(axisOf(o, 'y')))
957
- return limits.y;
958
- const fit = resolve(axisOf(o, 'y'), () => scanOnce(...sorted(x)) ?? lastWindowFit ?? yFit.of(), yFit.room);
959
- return [fit.lo, fit.hi];
1022
+ const f = fits[which];
1023
+ if (whole || !f.fit || !fitsWindow(axisOf(o, which)))
1024
+ return [...limits[which]];
1025
+ const { fit } = f;
1026
+ const s = resolve(axisOf(o, which), () => scanOnce(which, ...sorted(x)) ?? f.last ?? fit.of(), fit.room);
1027
+ return [s.lo, s.hi];
960
1028
  };
961
- const y = clamp(next.y, limits.y) ?? derived();
962
- return { x: [...x], y: [...y] };
1029
+ return { x: [...x], y: side('y'), ...(ys2 && { y2: side('y2') }) };
963
1030
  },
964
- propose(want) {
1031
+ propose(asked) {
965
1032
  if (bare(o))
966
1033
  return false;
1034
+ const want = loose(linked(asked));
967
1035
  const [shown, will] = [internals.view(), internals.fit(want)];
968
- if (['x', 'y'].every(k => String(will[k]) === String(shown[k])))
1036
+ if (keys().every(k => String(will[k]) === String(shown[k])))
969
1037
  return false;
970
1038
  letGo();
971
- o = { ...o, view: want ? wanted(want, true) : undefined };
1039
+ // A y2 window given while the chart has no second axis is kept for when it has one, unless y is shown whole again.
1040
+ const whole = !want || ('y' in want && want.y === undefined);
1041
+ const held = !has2() && !whole && o.view?.y2;
1042
+ o = { ...o, view: want ? { ...(held && { y2: held }), ...wanted(want, true) } : undefined };
972
1043
  if (refresh(false, 'size'))
973
1044
  sync();
974
1045
  o.onViewChange?.({
975
1046
  x: [real('x', xs.lo), real('x', xs.hi)],
976
- ...(!yFitted && { y: [real('y', ys.lo), real('y', ys.hi)] }),
1047
+ ...(!fits.y.fitted && { y: [real('y', ys.lo), real('y', ys.hi)] }),
1048
+ ...(ys2 && !fits.y2.fitted && { y2: [real('y2', ys2.lo), real('y2', ys2.hi)] }),
977
1049
  });
978
1050
  return true;
979
1051
  },
@@ -1006,9 +1078,11 @@ export function plot(el, options) {
1006
1078
  const x = xPx(inward('x', p.x));
1007
1079
  if (!(x >= m.left && x <= W - m.right))
1008
1080
  return null;
1009
- if (p.y === undefined)
1081
+ const on = p.y2 !== undefined && ys2 ? 'y2' : 'y';
1082
+ const v = p[on];
1083
+ if (v === undefined)
1010
1084
  return { x };
1011
- const y = yPx(inward('y', p.y));
1085
+ const y = yPx(inward(on, v), on);
1012
1086
  return !(y >= m.top && y <= H - m.bottom) ? { x } : { x, y };
1013
1087
  },
1014
1088
  focus,
@@ -1030,8 +1104,13 @@ export function plot(el, options) {
1030
1104
  if (internals.drag.active)
1031
1105
  return tell(null);
1032
1106
  const { px, py, over } = locate(internals, e);
1033
- tell(over ? { x: real('x', internals.xValue(px)), y: real('y', internals.yValue(py)) } : null);
1107
+ tell(over ? valuesAt(px, py) : null);
1034
1108
  };
1109
+ const valuesAt = (px, py) => ({
1110
+ x: real('x', internals.xValue(px)),
1111
+ y: real('y', internals.yValue(py)),
1112
+ ...(ys2 && { y2: real('y2', internals.yValue(py, 'y2')) }),
1113
+ });
1035
1114
  const unpoint = () => {
1036
1115
  at = undefined;
1037
1116
  root.style.cursor = '';
@@ -1054,16 +1133,14 @@ export function plot(el, options) {
1054
1133
  if (!c)
1055
1134
  return;
1056
1135
  const { px, py, hit } = c;
1136
+ const on = hit ? onAxis(hit.mark) : 'y';
1057
1137
  o.onClick(hit && {
1058
1138
  ...hit,
1059
1139
  mark: declared.get(hit.mark) ?? hit.mark,
1060
1140
  x: real('x', hit.x),
1061
- y: real('y', hit.y),
1062
- ...(hit.value !== undefined && { value: real('y', hit.value) }),
1063
- }, {
1064
- x: real('x', internals.xValue(px)),
1065
- y: real('y', internals.yValue(py)),
1066
- });
1141
+ y: real(on, hit.y),
1142
+ ...(hit.value !== undefined && { value: real(on, hit.value) }),
1143
+ }, valuesAt(px, py));
1067
1144
  });
1068
1145
  showing();
1069
1146
  const features = [];
@@ -1158,7 +1235,15 @@ export function plot(el, options) {
1158
1235
  const hid = 'hidden' in partial && !sameIds(partial.hidden, hiddenIds);
1159
1236
  if (hid)
1160
1237
  hiddenIds = [...(partial.hidden ?? [])];
1161
- let data = !sameAxis(axisOf(o, 'x'), axisOf(prev, 'x')) || !sameAxis(axisOf(o, 'y'), axisOf(prev, 'y'));
1238
+ let data = !o.y2 !== !prev.y2 || ['x', 'y', 'y2'].some(k => !sameAxis(axisOf(o, k), axisOf(prev, k)));
1239
+ // A second axis that comes or goes moves marks from one axis to the other, so no extent scanned before holds.
1240
+ if (!o.y2 !== !prev.y2) {
1241
+ extents = {};
1242
+ scanned = {};
1243
+ delete last.y;
1244
+ delete last.y2;
1245
+ fits.y.last = fits.y2.last = undefined;
1246
+ }
1162
1247
  replaced = new Map();
1163
1248
  paired = true;
1164
1249
  let relaid = false;
@@ -1179,7 +1264,7 @@ export function plot(el, options) {
1179
1264
  data = true;
1180
1265
  extents = {};
1181
1266
  everyLaid = undefined;
1182
- lastWindowFit = undefined;
1267
+ fits.y.last = fits.y2.last = undefined;
1183
1268
  relaid = reshow();
1184
1269
  reshown = true;
1185
1270
  }
@@ -1211,7 +1296,7 @@ export function plot(el, options) {
1211
1296
  const resized = measure();
1212
1297
  const restyled = theme() !== (prev.theme ?? light);
1213
1298
  // Ticks are DOM and change at once, so a new window must not cross-fade with new marks.
1214
- const moved = ['x', 'y'].some(k => String(o.view?.[k]) !== String(prev.view?.[k]));
1299
+ const moved = ['x', 'y', 'y2'].some(k => String(o.view?.[k]) !== String(prev.view?.[k]));
1215
1300
  if (refresh(data, resized || restyled || (hid && !relaid)
1216
1301
  ? 'size'
1217
1302
  : lost || o.dim !== prev.dim || o.selected !== prev.selected
@@ -0,0 +1,52 @@
1
+ import { type TooltipOptions } from '../features/tooltip.js';
2
+ import type { Axis, Feature, Options } from '../types.js';
3
+ import { type Build, type EasyChart } from './controller.js';
4
+ import type { AreaProps, Axes, BarProps, Base, BoxPlotProps, CandlestickProps, ComboProps, FunnelProps, HeatmapProps, HistogramProps, Input, LineProps, PieProps, RadarProps, RadialBarProps, SankeyProps, ScatterProps, SunburstProps, TreemapProps, XAxisProps, YAxisProps } from './types.js';
5
+ export declare const defined: <T extends object>(o: T) => T;
6
+ export declare const on: <T extends object>(v: boolean | T | undefined) => T | false;
7
+ export declare const sizeOf: (p: Base) => {
8
+ width: number | undefined;
9
+ height: number | undefined;
10
+ margin: Partial<import("../types.js").Margin> | undefined;
11
+ description: string | undefined;
12
+ };
13
+ export declare const featuresOf: (p: Base & Pick<Axes, 'zoom'>, listed: number) => {
14
+ tooltip: boolean;
15
+ legend: false | import("../index.js").LegendOptions;
16
+ zoom: false | import("../index.js").ZoomOptions;
17
+ animate: false | import("../index.js").AnimateOptions;
18
+ };
19
+ export declare const install: (f: ReturnType<typeof featuresOf>, tip: TooltipOptions) => Feature[];
20
+ export declare const linear: (a: YAxisProps | undefined, label: string) => Axis;
21
+ export declare const dates: (a: XAxisProps | undefined, label: string, utc: boolean) => Axis;
22
+ export declare const given: (p: object, k: string) => boolean;
23
+ export declare function noAxes(p: object, name: string): void;
24
+ type Kinds<D> = {
25
+ line: LineProps<D>;
26
+ area: AreaProps<D>;
27
+ bar: BarProps<D>;
28
+ scatter: ScatterProps<D>;
29
+ pie: PieProps<D>;
30
+ funnel: FunnelProps<D>;
31
+ radialBar: RadialBarProps<D>;
32
+ radar: RadarProps<D>;
33
+ heatmap: HeatmapProps<D>;
34
+ histogram: HistogramProps<D>;
35
+ boxPlot: BoxPlotProps<D>;
36
+ candlestick: CandlestickProps<D>;
37
+ combo: ComboProps<D>;
38
+ sankey: SankeyProps<D>;
39
+ treemap: TreemapProps;
40
+ sunburst: SunburstProps;
41
+ };
42
+ type Supplied<K extends keyof Kinds<never>, D = Input | undefined> = D extends unknown ? Kinds<D>[K] : never;
43
+ type Later<K extends keyof Kinds<never>> = Omit<EasyChart<never>, 'update'> & {
44
+ update<D extends Input | undefined = undefined>(props: Partial<Kinds<D>[K]> & {
45
+ data?: D | null;
46
+ }): void;
47
+ };
48
+ type ChartOf<K extends keyof Kinds<never>, D> = [D] extends [undefined | readonly never[]] ? K extends 'treemap' | 'sunburst' ? EasyChart<Kinds<D>[K]> : Later<K> : EasyChart<Kinds<D>[K]>;
49
+ export declare function easyChart<K extends keyof Kinds<never>>(build: Build<Supplied<K>>): (<D extends Input | undefined = undefined>(el: HTMLElement, props: Kinds<D>[K]) => ChartOf<K, D>) & {
50
+ spec: <D extends Input | undefined = undefined>(props: Kinds<D>[K]) => Options;
51
+ };
52
+ export {};
@@ -0,0 +1,63 @@
1
+ import { animate } from '../features/animate.js';
2
+ import { legend } from '../features/legend.js';
3
+ import { tooltip } from '../features/tooltip.js';
4
+ import { zoom } from '../features/zoom.js';
5
+ import { time } from '../scales/time.js';
6
+ import { dark, light } from '../theme.js';
7
+ import { create, PASSED, } from './controller.js';
8
+ import { source } from './source.js';
9
+ export const defined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
10
+ export const on = (v) => v === true ? {} : v || false;
11
+ export const sizeOf = (p) => defined({ width: p.width, height: p.height, margin: p.margin, description: p.description });
12
+ export const featuresOf = (p, listed) => ({
13
+ tooltip: p.tooltip !== false,
14
+ legend: p.legend !== false && listed >= 2 && (typeof p.legend === 'object' ? p.legend : {}),
15
+ zoom: on(p.zoom),
16
+ animate: on(p.animate),
17
+ });
18
+ export const install = (f, tip) => [
19
+ f.tooltip && tooltip(tip),
20
+ f.legend && legend(f.legend),
21
+ f.zoom && zoom(f.zoom),
22
+ f.animate && animate(f.animate),
23
+ ].filter((x) => !!x);
24
+ export const linear = (a, label) => defined({
25
+ domain: a?.domain ?? 'nice',
26
+ label: a?.label ?? label,
27
+ step: a?.step,
28
+ format: a?.format,
29
+ fit: a?.fit,
30
+ });
31
+ export const dates = (a, label, utc) => time({
32
+ label: a?.label ?? label,
33
+ utc,
34
+ format: a?.format,
35
+ fit: a?.fit,
36
+ ...(Array.isArray(a?.domain) && { domain: a.domain }),
37
+ ...(a?.unit && { unit: a.unit, every: a.every }),
38
+ });
39
+ export const given = (p, k) => p[k] !== undefined;
40
+ export function noAxes(p, name) {
41
+ for (const k of ['xAxis', 'yAxis', 'zoom'])
42
+ if (given(p, k))
43
+ throw new Error(`${name}: ${k} does not apply, as there are no axes`);
44
+ }
45
+ const themeFor = (t) => t === 'light' ? light : t === 'dark' ? dark : t === 'auto' ? undefined : t;
46
+ /** The options plot() would get, without an element: a theme of 'auto' builds with the light theme and leaves it out. */
47
+ function specOf(build, p) {
48
+ const theme = themeFor(p.theme);
49
+ const context = {
50
+ source: source(p.data),
51
+ theme: theme ?? light,
52
+ memo: (_name, _deps, make) => make(),
53
+ };
54
+ const b = build(p, context);
55
+ const passed = Object.fromEntries([...PASSED].filter(k => p[k] !== undefined).map(k => [k, p[k]]));
56
+ const given = !theme && b.options.theme === light ? undefined : b.options.theme;
57
+ return defined({ ...b.options, theme: given, ...passed, use: b.use() });
58
+ }
59
+ export function easyChart(build) {
60
+ return Object.assign((el, props) => create(el, props, build), {
61
+ spec: (props) => specOf(build, props),
62
+ });
63
+ }
@@ -0,0 +1,8 @@
1
+ import type { CandlestickProps } from './types.js';
2
+ export declare const candlestickChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: CandlestickProps<D>) => [D] extends [readonly never[] | undefined] ? Omit<import("./controller.js").EasyChart<never>, "update"> & {
3
+ update<D_1 extends import("./types.js").Input | undefined = undefined>(props: Partial<CandlestickProps<D_1>> & {
4
+ data?: D_1 | null | undefined;
5
+ }): void;
6
+ } : import("./controller.js").EasyChart<CandlestickProps<D>>) & {
7
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: CandlestickProps<D>) => import("../types.js").Options;
8
+ };