swiftplot 0.0.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 (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +348 -3
  3. package/dist/chart.d.ts +7 -0
  4. package/dist/chart.js +1311 -0
  5. package/dist/charts/build.d.ts +52 -0
  6. package/dist/charts/build.js +63 -0
  7. package/dist/charts/candlestick.d.ts +8 -0
  8. package/dist/charts/candlestick.js +105 -0
  9. package/dist/charts/combo.d.ts +8 -0
  10. package/dist/charts/combo.js +50 -0
  11. package/dist/charts/controller.d.ts +32 -0
  12. package/dist/charts/controller.js +231 -0
  13. package/dist/charts/defaults.d.ts +20 -0
  14. package/dist/charts/defaults.js +121 -0
  15. package/dist/charts/distribution.d.ts +15 -0
  16. package/dist/charts/distribution.js +178 -0
  17. package/dist/charts/fields.d.ts +64 -0
  18. package/dist/charts/fields.js +251 -0
  19. package/dist/charts/flow.d.ts +15 -0
  20. package/dist/charts/flow.js +189 -0
  21. package/dist/charts/heatmap.d.ts +9 -0
  22. package/dist/charts/heatmap.js +104 -0
  23. package/dist/charts/index.d.ts +13 -0
  24. package/dist/charts/index.js +10 -0
  25. package/dist/charts/mount.d.ts +5 -0
  26. package/dist/charts/mount.js +21 -0
  27. package/dist/charts/parts.d.ts +23 -0
  28. package/dist/charts/parts.js +66 -0
  29. package/dist/charts/radar.d.ts +7 -0
  30. package/dist/charts/radar.js +77 -0
  31. package/dist/charts/source.d.ts +24 -0
  32. package/dist/charts/source.js +225 -0
  33. package/dist/charts/types.d.ts +643 -0
  34. package/dist/charts/types.js +1 -0
  35. package/dist/charts/xy.d.ts +46 -0
  36. package/dist/charts/xy.js +421 -0
  37. package/dist/features/animate.d.ts +20 -0
  38. package/dist/features/animate.js +118 -0
  39. package/dist/features/brush.d.ts +15 -0
  40. package/dist/features/brush.js +128 -0
  41. package/dist/features/legend.d.ts +13 -0
  42. package/dist/features/legend.js +236 -0
  43. package/dist/features/pointer.d.ts +29 -0
  44. package/dist/features/pointer.js +23 -0
  45. package/dist/features/tooltip.d.ts +22 -0
  46. package/dist/features/tooltip.js +192 -0
  47. package/dist/features/zoom.d.ts +14 -0
  48. package/dist/features/zoom.js +246 -0
  49. package/dist/gl.d.ts +5 -0
  50. package/dist/gl.js +52 -0
  51. package/dist/index.d.ts +62 -0
  52. package/dist/index.js +32 -0
  53. package/dist/marks/arcs.d.ts +31 -0
  54. package/dist/marks/arcs.js +125 -0
  55. package/dist/marks/area.d.ts +25 -0
  56. package/dist/marks/area.js +106 -0
  57. package/dist/marks/bar.d.ts +52 -0
  58. package/dist/marks/bar.js +243 -0
  59. package/dist/marks/box.d.ts +33 -0
  60. package/dist/marks/box.js +182 -0
  61. package/dist/marks/candlestick.d.ts +22 -0
  62. package/dist/marks/candlestick.js +133 -0
  63. package/dist/marks/common.d.ts +102 -0
  64. package/dist/marks/common.js +250 -0
  65. package/dist/marks/dots.d.ts +16 -0
  66. package/dist/marks/dots.js +158 -0
  67. package/dist/marks/errorBars.d.ts +24 -0
  68. package/dist/marks/errorBars.js +99 -0
  69. package/dist/marks/funnel.d.ts +30 -0
  70. package/dist/marks/funnel.js +122 -0
  71. package/dist/marks/heatmap.d.ts +20 -0
  72. package/dist/marks/heatmap.js +139 -0
  73. package/dist/marks/line.d.ts +21 -0
  74. package/dist/marks/line.js +75 -0
  75. package/dist/marks/radar.d.ts +29 -0
  76. package/dist/marks/radar.js +162 -0
  77. package/dist/marks/radialBars.d.ts +34 -0
  78. package/dist/marks/radialBars.js +111 -0
  79. package/dist/marks/rects.d.ts +43 -0
  80. package/dist/marks/rects.js +120 -0
  81. package/dist/marks/rule.d.ts +47 -0
  82. package/dist/marks/rule.js +83 -0
  83. package/dist/marks/sankey.d.ts +53 -0
  84. package/dist/marks/sankey.js +369 -0
  85. package/dist/marks/sunburst.d.ts +31 -0
  86. package/dist/marks/sunburst.js +186 -0
  87. package/dist/marks/ticks.d.ts +12 -0
  88. package/dist/marks/ticks.js +26 -0
  89. package/dist/marks/tree.d.ts +49 -0
  90. package/dist/marks/tree.js +113 -0
  91. package/dist/marks/treemap.d.ts +30 -0
  92. package/dist/marks/treemap.js +164 -0
  93. package/dist/paint.d.ts +35 -0
  94. package/dist/paint.js +71 -0
  95. package/dist/scale.d.ts +16 -0
  96. package/dist/scale.js +97 -0
  97. package/dist/scales/band.d.ts +12 -0
  98. package/dist/scales/band.js +27 -0
  99. package/dist/scales/bare.d.ts +6 -0
  100. package/dist/scales/bare.js +10 -0
  101. package/dist/scales/color.d.ts +20 -0
  102. package/dist/scales/color.js +21 -0
  103. package/dist/scales/log.d.ts +27 -0
  104. package/dist/scales/log.js +98 -0
  105. package/dist/scales/time.d.ts +37 -0
  106. package/dist/scales/time.js +183 -0
  107. package/dist/text.d.ts +8 -0
  108. package/dist/text.js +33 -0
  109. package/dist/theme.d.ts +10 -0
  110. package/dist/theme.js +8 -0
  111. package/dist/transforms.d.ts +47 -0
  112. package/dist/transforms.js +119 -0
  113. package/dist/types.d.ts +465 -0
  114. package/dist/types.js +1 -0
  115. package/package.json +31 -6
@@ -0,0 +1,128 @@
1
+ import { locate, settle, SLOP_PX, unselect } from './pointer.js';
2
+ export function brush(b = {}) {
3
+ const [bx, by] = ['x', 'y'].map(k => (b.axes ?? 'x').includes(k));
4
+ return chart => {
5
+ const { drag } = chart;
6
+ drag.brush = true;
7
+ const shade = chart.layer('div', 'display:none;opacity:0.2');
8
+ let reported = false;
9
+ let from;
10
+ let box;
11
+ let settling = 0;
12
+ let gone = false;
13
+ const clear = () => {
14
+ shade.style.display = 'none';
15
+ box = undefined;
16
+ if (!reported)
17
+ return;
18
+ reported = false;
19
+ b.onSelect?.(null);
20
+ };
21
+ const down = (e) => {
22
+ if (from ||
23
+ e.pointerType === 'touch' ||
24
+ e.button !== 0 ||
25
+ (drag.pan && (drag.pan === 'plain' || e.shiftKey)))
26
+ return;
27
+ const { px, py, over } = locate(chart, e);
28
+ if (!over)
29
+ return;
30
+ from = { id: e.pointerId, x: px, y: py };
31
+ document.addEventListener('pointermove', move, true);
32
+ document.addEventListener('pointerup', up, true);
33
+ document.addEventListener('pointercancel', cancel, true);
34
+ document.addEventListener('keydown', key, true);
35
+ document.addEventListener('selectstart', unselect, true);
36
+ clear();
37
+ };
38
+ const move = (e) => {
39
+ if (!from || from.dropped || e.pointerId !== from.id)
40
+ return;
41
+ const { width, height } = chart.size();
42
+ const m = chart.margin();
43
+ const [l, r, t, btm] = [m.left, width - m.right, m.top, height - m.bottom];
44
+ const { px, py } = locate(chart, e);
45
+ const x = Math.min(Math.max(px, l), r);
46
+ const y = Math.min(Math.max(py, t), btm);
47
+ const [dx, dy] = [bx ? x - from.x : 0, by ? y - from.y : 0];
48
+ if (!box && Math.hypot(dx, dy) < SLOP_PX)
49
+ return;
50
+ drag.active = true;
51
+ box = {
52
+ left: bx ? Math.min(from.x, x) : l,
53
+ right: bx ? Math.max(from.x, x) : r,
54
+ top: by ? Math.min(from.y, y) : t,
55
+ bottom: by ? Math.max(from.y, y) : btm,
56
+ };
57
+ Object.assign(shade.style, {
58
+ display: '',
59
+ background: chart.theme().muted,
60
+ left: `${box.left}px`,
61
+ top: `${box.top}px`,
62
+ width: `${box.right - box.left}px`,
63
+ height: `${box.bottom - box.top}px`,
64
+ });
65
+ };
66
+ const abandon = () => {
67
+ if (from)
68
+ from.dropped = true;
69
+ clear();
70
+ };
71
+ const key = (e) => {
72
+ if (e.key === 'Escape')
73
+ abandon();
74
+ };
75
+ const end = () => {
76
+ from = undefined;
77
+ document.removeEventListener('pointermove', move, true);
78
+ document.removeEventListener('pointerup', up, true);
79
+ document.removeEventListener('pointercancel', cancel, true);
80
+ document.removeEventListener('keydown', key, true);
81
+ document.removeEventListener('selectstart', unselect, true);
82
+ if (drag.active)
83
+ settling = settle(chart);
84
+ };
85
+ const cancel = (e) => {
86
+ if (e.pointerId !== from?.id)
87
+ return;
88
+ abandon();
89
+ end();
90
+ };
91
+ const up = (e) => {
92
+ if (e.pointerId !== from?.id)
93
+ return;
94
+ move(e);
95
+ const kept = !from.dropped && box;
96
+ end();
97
+ if (!kept)
98
+ return;
99
+ const asc = (p, q) => (p <= q ? [p, q] : [q, p]);
100
+ const span = (k, [p, q]) => asc(chart.real(k, p), chart.real(k, q));
101
+ const view = chart.view();
102
+ const picked = {
103
+ x: bx ? asc(chart.xValue(kept.left), chart.xValue(kept.right)) : view.x,
104
+ y: by ? asc(chart.yValue(kept.bottom), chart.yValue(kept.top)) : view.y,
105
+ };
106
+ const y2 = view.y2 && (by ? asc(chart.yValue(kept.bottom, 'y2'), chart.yValue(kept.top, 'y2')) : view.y2);
107
+ reported = !b.zoom;
108
+ b.onSelect?.({ x: span('x', picked.x), y: span('y', picked.y), ...(y2 && { y2: span('y2', y2) }) });
109
+ if (!b.zoom || gone)
110
+ return;
111
+ clear();
112
+ chart.propose({ ...(bx && { x: picked.x }), ...(by && { y: picked.y }) });
113
+ };
114
+ chart.root.addEventListener('pointerdown', down);
115
+ return {
116
+ letGo: abandon,
117
+ destroy() {
118
+ gone = true;
119
+ from = undefined;
120
+ end();
121
+ clearTimeout(settling);
122
+ drag.brush = drag.active = false;
123
+ chart.root.removeEventListener('pointerdown', down);
124
+ shade.remove();
125
+ },
126
+ };
127
+ };
128
+ }
@@ -0,0 +1,13 @@
1
+ import type { Feature } from '../types.js';
2
+ export type LegendOptions = {
3
+ /** Whether a click, Enter or Space on an entry hides or shows its series; true when left out. */
4
+ toggle?: boolean;
5
+ /** Caps the rows of entries, by default at what fits in a third of the chart's height. */
6
+ rows?: number;
7
+ };
8
+ /**
9
+ * One entry per group of labelled marks, in rows above the plot; pointing at one focuses its group,
10
+ * and with `toggle` (the default) a click or Enter or Space hides or shows it.
11
+ * A label wider than the plot ends in an ellipsis, titled once layout shows it cut.
12
+ */
13
+ export declare function legend({ toggle, rows: cap }?: LegendOptions): Feature;
@@ -0,0 +1,236 @@
1
+ import { textWidth } from '../text.js';
2
+ const ROW = 20;
3
+ const SWATCH = 16;
4
+ const GAP = 14;
5
+ /** The two ends of a domain to as few digits as tell them apart, and at least three. */
6
+ function ends(lo, hi) {
7
+ for (let digits = 3;; digits++) {
8
+ const said = [lo, hi].map(v => String(+v.toPrecision(digits)));
9
+ if (said[0] !== said[1] || lo === hi || digits > 16)
10
+ return said;
11
+ }
12
+ }
13
+ /**
14
+ * One entry per group of labelled marks, in rows above the plot; pointing at one focuses its group,
15
+ * and with `toggle` (the default) a click or Enter or Space hides or shows it.
16
+ * A label wider than the plot ends in an ellipsis, titled once layout shows it cut.
17
+ */
18
+ export function legend({ toggle = true, rows: cap } = {}) {
19
+ return chart => {
20
+ const { root } = chart;
21
+ const toggles = (e) => toggle && !e.part;
22
+ const off = (e) => e.id !== undefined && chart.hidden().includes(e.id);
23
+ const box = chart.layer('div', `color:${chart.theme().text}`);
24
+ const shown = new Map();
25
+ const cut = new ResizeObserver(seen => {
26
+ for (const { target: t } of seen) {
27
+ if (t.scrollWidth > t.clientWidth)
28
+ t.setAttribute('title', t.textContent);
29
+ else
30
+ t.removeAttribute('title');
31
+ }
32
+ });
33
+ let built = '';
34
+ let hovered;
35
+ let at;
36
+ let held = false;
37
+ let current;
38
+ chart.reserve((left, width) => {
39
+ // One pass over the marks. A mark's own entries come before its strip of colours, and a
40
+ // mark with either is not also listed by its label.
41
+ const entries = [];
42
+ const ramps = [];
43
+ const listed = new Set();
44
+ const hidden = chart.hidden();
45
+ chart.listed().forEach((k, at) => {
46
+ const id = k.group ?? k.label;
47
+ k.entries?.forEach((e, row) => entries.push({ ...e, id, part: [at, row] }));
48
+ if (k.ramp && (id === undefined || !hidden.includes(id)))
49
+ ramps.push({ label: k.label, ...k.ramp() });
50
+ if (k.entries || k.ramp || k.label === undefined || id === undefined || listed.has(id))
51
+ return;
52
+ listed.add(id);
53
+ entries.push({ label: k.label, color: k.color, id, group: k.group });
54
+ });
55
+ // By default entries and strips share one budget of rows; a strip left out goes behind "+N more",
56
+ // which needs a row of entries to sit in.
57
+ const budget = Math.max(1, Math.floor((chart.size().height / 3 - 4) / ROW) || 1);
58
+ const kept = cap === undefined
59
+ ? Math.min(ramps.length, budget - (entries.length || ramps.length > budget ? 1 : 0))
60
+ : ramps.length;
61
+ const rows = [[]];
62
+ const most = Math.max(1, Math.floor(cap ?? budget - kept) || 1);
63
+ const wide = (e) => SWATCH + textWidth(e.label);
64
+ const more = (n) => `+${n} more`;
65
+ let used = 0;
66
+ let rest = [];
67
+ for (const [i, e] of entries.entries()) {
68
+ if (used && used + GAP + wide(e) > width) {
69
+ if (rows.length === most) {
70
+ rest = entries.slice(i);
71
+ break;
72
+ }
73
+ rows.push([]);
74
+ used = 0;
75
+ }
76
+ rows.at(-1).push(e);
77
+ used += (used && GAP) + wide(e);
78
+ }
79
+ // A strip is described by a few of its colours, which is also all the page is given of them.
80
+ const strips = ramps.map(r => ({
81
+ label: r.label,
82
+ ends: ends(r.lo, r.hi),
83
+ colors: [0, 51, 102, 153, 204, 255].map(i => {
84
+ const p = r.table[i];
85
+ return `rgb(${p & 255},${(p >> 8) & 255},${(p >> 16) & 255})`;
86
+ }),
87
+ }));
88
+ const unlisted = [
89
+ ...rest.map(e => e.label),
90
+ ...strips.splice(kept).map(s => s.label ?? s.ends.join('–')),
91
+ ];
92
+ const last = rows.at(-1);
93
+ while (unlisted.length && last.length > 1 && used + GAP + textWidth(more(unlisted.length)) > width) {
94
+ const out = last.pop();
95
+ unlisted.unshift(out.label);
96
+ used -= GAP + wide(out);
97
+ }
98
+ if (!entries.length && !unlisted.length)
99
+ rows.length = 0;
100
+ box.style.left = `${left}px`;
101
+ box.style.top = '4px';
102
+ box.style.width = `${width}px`;
103
+ const key = JSON.stringify([rows, unlisted, strips]);
104
+ if (key !== built) {
105
+ built = key;
106
+ const doc = root.getRootNode();
107
+ const focused = [...shown].find(([item]) => item.contains(doc.activeElement))?.[1].id;
108
+ shown.clear();
109
+ cut.disconnect();
110
+ box.replaceChildren(...rows.map((row, r) => {
111
+ const line = document.createElement('div');
112
+ line.style.cssText = `display:flex;gap:${GAP}px;height:${ROW}px;align-items:center;white-space:nowrap;overflow:hidden`;
113
+ const capped = r === rows.length - 1 && unlisted.length > 0;
114
+ for (const e of row) {
115
+ const item = line.appendChild(document.createElement('span'));
116
+ // Only the entries take the pointer: the rest of the strip stays the chart's.
117
+ item.style.cssText = `pointer-events:auto;${capped ? 'flex:0 1 auto;min-width:0' : 'flex:none;max-width:100%'};overflow:hidden;text-overflow:ellipsis`;
118
+ const swatch = item.appendChild(document.createElement('span'));
119
+ swatch.style.cssText =
120
+ 'display:inline-block;width:10px;height:10px;margin-right:6px;border-radius:2px';
121
+ swatch.style.backgroundColor = e.color;
122
+ item.append(e.label);
123
+ cut.observe(item);
124
+ if (toggles(e)) {
125
+ item.setAttribute('role', 'button');
126
+ item.tabIndex = 0;
127
+ }
128
+ if (e.group !== undefined || e.part || toggles(e))
129
+ shown.set(item, e);
130
+ }
131
+ if (capped) {
132
+ const item = line.appendChild(document.createElement('span'));
133
+ item.style.cssText = 'pointer-events:auto;flex:none';
134
+ item.textContent = more(unlisted.length);
135
+ item.title = unlisted.join(', ');
136
+ }
137
+ return line;
138
+ }), ...strips.map(s => {
139
+ const line = document.createElement('div');
140
+ line.style.cssText = `display:flex;gap:6px;height:${ROW}px;align-items:center;white-space:nowrap;overflow:hidden`;
141
+ const strip = document.createElement('span');
142
+ strip.style.cssText = 'display:inline-block;width:120px;height:10px;border-radius:2px';
143
+ strip.style.backgroundImage = `linear-gradient(to right,${s.colors.join()})`;
144
+ line.append(...(s.label ? [s.label, ' '] : []), s.ends[0], strip, s.ends[1]);
145
+ return line;
146
+ }));
147
+ if (focused !== undefined)
148
+ [...shown].find(([, e]) => toggles(e) && e.id === focused)?.[0].focus();
149
+ }
150
+ for (const [item, e] of shown) {
151
+ item.style.opacity = off(e) ? '0.4' : '';
152
+ if (toggles(e))
153
+ item.setAttribute('aria-pressed', String(!off(e)));
154
+ }
155
+ const lines = rows.length + strips.length;
156
+ return lines ? lines * ROW + 4 : 0;
157
+ });
158
+ // The mark is looked up when pointed at: after an update that kept the entries as they were,
159
+ // the list is not rebuilt, but the mark at that place is a new one.
160
+ const point = (e) => {
161
+ const id = e && JSON.stringify([e.group, e.part]);
162
+ if (id === hovered)
163
+ return;
164
+ hovered = id;
165
+ current = e;
166
+ const mark = e?.part && chart.listed()[e.part[0]];
167
+ chart.focus(e?.group ?? null, mark && { mark, row: e.part[1] });
168
+ };
169
+ // One listener on the chart, not enter and leave on each entry: an entry rebuilt or removed
170
+ // under the pointer never gets its leave. Capturing, so a tooltip sets its own focus after.
171
+ const entryAt = (target) => {
172
+ const item = [...shown.keys()].find(i => i.contains(target));
173
+ return [item, item && shown.get(item)];
174
+ };
175
+ const over = (target) => {
176
+ const [item, e] = entryAt(target);
177
+ point(e && !off(e) ? e : undefined);
178
+ return item;
179
+ };
180
+ const move = (e) => {
181
+ held = false;
182
+ at = over(e.target) && [e.clientX, e.clientY];
183
+ };
184
+ const leave = () => {
185
+ held = false;
186
+ at = undefined;
187
+ point(undefined);
188
+ };
189
+ const lift = (e) => {
190
+ if (e.pointerType !== 'touch' || (current && toggles(current)))
191
+ leave();
192
+ else
193
+ held = true;
194
+ };
195
+ const flip = (target) => {
196
+ const [, e] = entryAt(target);
197
+ if (!e || !toggles(e))
198
+ return false;
199
+ // Let go first: hide() repaints at once, and a pointer still recorded would focus the entry again.
200
+ at = undefined;
201
+ point(undefined);
202
+ const ids = chart.hidden();
203
+ chart.hide(ids.includes(e.id) ? ids.filter(i => i !== e.id) : [...ids, e.id]);
204
+ return true;
205
+ };
206
+ box.addEventListener('click', e => flip(e.target));
207
+ box.addEventListener('keydown', e => {
208
+ if ((e.key === 'Enter' || e.key === ' ') && flip(e.target))
209
+ e.preventDefault();
210
+ });
211
+ root.addEventListener('pointerdown', move, true);
212
+ root.addEventListener('pointermove', move, true);
213
+ root.addEventListener('pointerleave', lift);
214
+ root.addEventListener('pointercancel', leave);
215
+ document.addEventListener('pointerdown', leave, true);
216
+ return {
217
+ // The entries may have moved under a pointer at rest, so what it is over is looked up again.
218
+ update() {
219
+ box.style.color = chart.theme().text;
220
+ const doc = root.isConnected && root.getRootNode();
221
+ if (at && !over(doc ? doc.elementFromPoint(...at) : null))
222
+ at = undefined;
223
+ },
224
+ letGo: () => held && leave(),
225
+ destroy() {
226
+ root.removeEventListener('pointerdown', move, true);
227
+ root.removeEventListener('pointermove', move, true);
228
+ root.removeEventListener('pointerleave', lift);
229
+ root.removeEventListener('pointercancel', leave);
230
+ document.removeEventListener('pointerdown', leave, true);
231
+ cut.disconnect();
232
+ box.remove();
233
+ },
234
+ };
235
+ };
236
+ }
@@ -0,0 +1,29 @@
1
+ import type { Internals } from '../types.js';
2
+ export declare const SLOP_PX = 4;
3
+ export declare const unselect: (e: Event) => void;
4
+ /** Clears `drag.active` after the click the browser sends for this release, which a drag must not count as one. */
5
+ export declare const settle: (chart: Internals) => number;
6
+ /** Where a point of the page is on the chart in CSS pixels, and whether it is inside the plot rectangle. */
7
+ export declare function position(chart: Internals, clientX: number, clientY: number): {
8
+ px: number;
9
+ py: number;
10
+ inside: boolean;
11
+ w: number;
12
+ h: number;
13
+ at: {
14
+ x: number;
15
+ y: number;
16
+ };
17
+ };
18
+ /** Where a pointer event is in CSS pixels, and whether it is over the plot of a chart with axes. */
19
+ export declare function locate(chart: Internals, e: MouseEvent): {
20
+ px: number;
21
+ py: number;
22
+ w: number;
23
+ h: number;
24
+ at: {
25
+ x: number;
26
+ y: number;
27
+ };
28
+ over: boolean;
29
+ };
@@ -0,0 +1,23 @@
1
+ export const SLOP_PX = 4;
2
+ export const unselect = (e) => e.preventDefault();
3
+ /** Clears `drag.active` after the click the browser sends for this release, which a drag must not count as one. */
4
+ export const settle = (chart) => setTimeout(() => {
5
+ chart.drag.active = false;
6
+ chart.sync();
7
+ }, 0);
8
+ /** Where a point of the page is on the chart in CSS pixels, and whether it is inside the plot rectangle. */
9
+ export function position(chart, clientX, clientY) {
10
+ const { width, height } = chart.size();
11
+ const m = chart.margin();
12
+ const box = chart.root.getBoundingClientRect();
13
+ const px = ((clientX - box.left) * width) / box.width;
14
+ const py = ((clientY - box.top) * height) / box.height;
15
+ const [w, h] = [width - m.left - m.right, height - m.top - m.bottom];
16
+ const inside = px >= m.left && px <= m.left + w && py >= m.top && py <= m.top + h;
17
+ return { px, py, inside, w, h, at: { x: (px - m.left) / w, y: 1 - (py - m.top) / h } };
18
+ }
19
+ /** Where a pointer event is in CSS pixels, and whether it is over the plot of a chart with axes. */
20
+ export function locate(chart, e) {
21
+ const { inside, ...where } = position(chart, e.clientX, e.clientY);
22
+ return { ...where, over: inside && chart.frame() === 'axes' && e.target === chart.root };
23
+ }
@@ -0,0 +1,22 @@
1
+ import type { Feature } from '../types.js';
2
+ /** A tooltip at the pointer: a row for each visible, labelled line or area at its x, or the text for what is nearest it. */
3
+ export type TooltipOptions =
4
+ /** A row for each labelled line or area not hidden, at the pointer's x, with a crosshair; a band gives its thickness. */
5
+ {
6
+ /** Shows each labelled line and area that is not hidden, at the pointer's x. */
7
+ mode: 'x';
8
+ /** The first line of the tooltip, for the x at the pointer. */
9
+ title: (x: number) => string;
10
+ /** A mark's value as text, after its label, for its y on the axis it is drawn against. */
11
+ value: (y: number, axis: 'y' | 'y2') => string;
12
+ /** The x to read the title and the marks at, such as the nearest row's, from the one at the pointer, both in the marks' space. */
13
+ snap?: (x: number) => number;
14
+ }
15
+ /** x and y are where the mark says it was hit, y being the row's own value where it has one; row is its row there. */
16
+ | {
17
+ /** Shows what is nearest the pointer, within 20 CSS pixels. */
18
+ mode: 'nearest';
19
+ /** The tooltip's text, from the label of the mark or part hit, its x and y, and its row. */
20
+ text: (label: string, x: number, y: number, row?: number) => string;
21
+ };
22
+ export declare function tooltip(t: TooltipOptions): Feature;
@@ -0,0 +1,192 @@
1
+ import { NEAREST_PX } from '../chart.js';
2
+ import { position } from './pointer.js';
3
+ const FOCUS_PX = 30;
4
+ export function tooltip(t) {
5
+ return chart => {
6
+ const { root } = chart;
7
+ const cross = chart.layer('div', 'display:none;border-left:1px dashed');
8
+ const tip = chart.layer('div', 'display:none;left:0;top:0;border:1px solid;padding:4px 8px;box-sizing:border-box;width:max-content;max-width:100%;max-height:100%;overflow:hidden;white-space:normal;overflow-wrap:anywhere;z-index:100');
9
+ const restyle = () => {
10
+ const { text, muted, surface, border } = chart.theme();
11
+ cross.style.borderLeftColor = muted;
12
+ Object.assign(tip.style, { color: text, background: surface, borderColor: border });
13
+ };
14
+ restyle();
15
+ let at = null;
16
+ let held = false;
17
+ // The user's pointer is on the chart, maybe over another feature's layer, so the app's is not shown.
18
+ let inside = false;
19
+ let fromApp = false;
20
+ const hide = () => {
21
+ cross.style.display = tip.style.display = 'none';
22
+ chart.focus(null);
23
+ };
24
+ const show = (x, y, rows) => {
25
+ const { width, height } = chart.size();
26
+ tip.replaceChildren(...rows.map(r => {
27
+ const e = document.createElement('div');
28
+ e.textContent = r.text;
29
+ if (r.color)
30
+ e.style.color = r.color;
31
+ return e;
32
+ }));
33
+ const fx = x > width / 2;
34
+ const fy = y > height / 2;
35
+ tip.style.display = '';
36
+ const left = fx ? `${x - 12}px - 100%` : `${x + 12}px`;
37
+ const top = fy ? `${y - 12}px - 100%` : `${y + 12}px`;
38
+ tip.style.transform = `translate(clamp(0px, ${left}, ${width}px - 100%), clamp(0px, ${top}, ${height}px - 100%))`;
39
+ };
40
+ const place = () => {
41
+ const { width, height } = chart.size();
42
+ let px;
43
+ let py;
44
+ if (at) {
45
+ fromApp = false;
46
+ ({ px, py } = position(chart, ...at));
47
+ }
48
+ else {
49
+ const p = inside ? null : chart.pointer();
50
+ if (!p) {
51
+ if (fromApp) {
52
+ fromApp = false;
53
+ hide();
54
+ }
55
+ return;
56
+ }
57
+ fromApp = true;
58
+ ({ x: px, y: py } = p);
59
+ }
60
+ if (chart.drag.active)
61
+ return hide();
62
+ if (t.mode === 'nearest') {
63
+ if (py === undefined)
64
+ return hide();
65
+ const hit = chart.hit(px, py, NEAREST_PX);
66
+ if (!hit)
67
+ return hide();
68
+ chart.focus(hit.mark.group ?? null, hit.row === undefined ? undefined : { mark: hit.mark, row: hit.row });
69
+ // A mark made of named parts, such as slices, is spoken for by the part that was hit.
70
+ const part = hit.row === undefined ? undefined : hit.mark.entries?.[hit.row];
71
+ const { label = '', color } = part ?? hit.mark;
72
+ const on = chart.yAxis(hit.mark);
73
+ const text = t.text(label, chart.real('x', hit.x), chart.real(on, hit.value ?? hit.y), hit.row);
74
+ show(chart.xPx(hit.x), chart.yPx(hit.y, on), [{ text, color: hit.color ?? color }]);
75
+ return;
76
+ }
77
+ const m = chart.margin();
78
+ const off = py !== undefined && (py < m.top || py > height - m.bottom);
79
+ if (px < m.left || px > width - m.right || off)
80
+ return hide();
81
+ const under = chart.xValue(px);
82
+ const v = t.snap?.(under) ?? under;
83
+ const rows = [{ text: t.title(chart.real('x', v)) }];
84
+ // A line within reach of the pointer is focused before the filled mark the pointer is in,
85
+ // and of several filled marks the one drawn last.
86
+ let near = FOCUS_PX;
87
+ let line;
88
+ let fill;
89
+ for (const k of chart.marks()) {
90
+ if (!k.sampleAtX)
91
+ continue;
92
+ const s = k.sampleAtX(v);
93
+ const on = chart.yAxis(k);
94
+ const value = typeof s === 'number'
95
+ ? chart.real(on, s)
96
+ : s && (s.band ? chart.real(on, s.y2) - chart.real(on, s.y1) : chart.real(on, s.value ?? s.y2));
97
+ if (k.label !== undefined) {
98
+ rows.push({
99
+ text: `${k.label}: ${value === undefined ? '–' : t.value(value, on)}`,
100
+ color: k.color,
101
+ });
102
+ }
103
+ if (s === undefined || k.group === undefined || py === undefined)
104
+ continue;
105
+ if (typeof s === 'number') {
106
+ const gap = Math.abs(chart.yPx(s, on) - py);
107
+ if (gap < near)
108
+ [near, line] = [gap, k.group];
109
+ }
110
+ else {
111
+ const a = chart.yPx(s.y1, on);
112
+ const b = chart.yPx(s.y2, on);
113
+ if (a !== b && py >= Math.min(a, b) && py <= Math.max(a, b))
114
+ fill = k.group;
115
+ }
116
+ }
117
+ const group = line ?? fill ?? null;
118
+ cross.style.display = '';
119
+ cross.style.left = `${px}px`;
120
+ cross.style.top = `${m.top}px`;
121
+ cross.style.height = `${height - m.top - m.bottom}px`;
122
+ show(px, m.top, rows);
123
+ chart.focus(group);
124
+ };
125
+ const move = (e) => {
126
+ inside = true;
127
+ if (chart.drag.active) {
128
+ at = null;
129
+ return hide();
130
+ }
131
+ // Over another feature's layer, such as a legend, the focus is that feature's to set.
132
+ if (e.target !== root) {
133
+ at = null;
134
+ held = false;
135
+ fromApp = false;
136
+ cross.style.display = tip.style.display = 'none';
137
+ return;
138
+ }
139
+ at = [e.clientX, e.clientY];
140
+ held = false;
141
+ place();
142
+ };
143
+ const leave = () => {
144
+ at = null;
145
+ held = false;
146
+ inside = false;
147
+ hide();
148
+ };
149
+ const out = () => {
150
+ leave();
151
+ place();
152
+ };
153
+ // A lifted finger leaves the chart, and a tip it tapped open is meant to stay until a tap elsewhere.
154
+ const lift = (e) => {
155
+ inside = false;
156
+ if (e.pointerType !== 'touch')
157
+ return out();
158
+ held = !!at && tip.style.display !== 'none';
159
+ if (held)
160
+ return;
161
+ at = null;
162
+ place();
163
+ };
164
+ // Capturing, so a control that stops the tap still dismisses, and a tap on the chart sets its own state after.
165
+ const away = () => {
166
+ if (at)
167
+ out();
168
+ };
169
+ root.addEventListener('pointerdown', move);
170
+ root.addEventListener('pointermove', move);
171
+ root.addEventListener('pointerleave', lift);
172
+ root.addEventListener('pointercancel', out);
173
+ document.addEventListener('pointerdown', away, true);
174
+ return {
175
+ update() {
176
+ restyle();
177
+ place();
178
+ },
179
+ // A lifted finger is no longer anywhere on the chart, so what it tapped is let go.
180
+ letGo: () => held && leave(),
181
+ destroy() {
182
+ root.removeEventListener('pointerdown', move);
183
+ root.removeEventListener('pointermove', move);
184
+ root.removeEventListener('pointerleave', lift);
185
+ root.removeEventListener('pointercancel', out);
186
+ document.removeEventListener('pointerdown', away, true);
187
+ cross.remove();
188
+ tip.remove();
189
+ },
190
+ };
191
+ };
192
+ }
@@ -0,0 +1,14 @@
1
+ import type { Feature } from '../types.js';
2
+ /** Zooms with the wheel (ctrl or cmd held, by default) or a pinch and pans with a drag, on x, y or both; a double-click on the plot shows the whole of each zoomed axis again. */
3
+ export type ZoomOptions = {
4
+ /** 'x' when left out. */
5
+ axes?: 'x' | 'y' | 'xy';
6
+ /** 'ctrl' when left out: ctrl or cmd and the wheel zoom, and a plain wheel scrolls the page. */
7
+ wheel?: 'ctrl' | 'plain' | false;
8
+ /**
9
+ * Which drag pans: a plain one, or one with shift held. Left out, a plain drag pans unless a brush
10
+ * is in use. 'pan' takes every mouse drag, so a brush() beside it gets none.
11
+ */
12
+ drag?: 'pan' | 'shift' | false;
13
+ };
14
+ export declare function zoom(z?: ZoomOptions): Feature;