swiftplot 0.5.1 → 0.6.0-rc.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 (45) hide show
  1. package/README.md +8 -7
  2. package/dist/chart.d.ts +2 -1
  3. package/dist/chart.js +129 -29
  4. package/dist/charts/build.d.ts +2 -2
  5. package/dist/charts/build.js +24 -1
  6. package/dist/charts/candlestick.js +3 -0
  7. package/dist/charts/controller.d.ts +1 -1
  8. package/dist/charts/controller.js +14 -3
  9. package/dist/charts/defaults.d.ts +5 -1
  10. package/dist/charts/defaults.js +56 -20
  11. package/dist/charts/distribution.js +20 -5
  12. package/dist/charts/parts.js +1 -1
  13. package/dist/charts/types.d.ts +32 -7
  14. package/dist/charts/xy.d.ts +1 -0
  15. package/dist/charts/xy.js +81 -17
  16. package/dist/color.d.ts +7 -3
  17. package/dist/color.js +11 -7
  18. package/dist/features/animate.js +7 -7
  19. package/dist/features/brush.js +19 -14
  20. package/dist/features/legend.js +14 -14
  21. package/dist/features/pointer.d.ts +14 -1
  22. package/dist/features/pointer.js +53 -2
  23. package/dist/features/tooltip.d.ts +2 -2
  24. package/dist/features/tooltip.js +58 -18
  25. package/dist/features/zoom.d.ts +4 -0
  26. package/dist/features/zoom.js +30 -22
  27. package/dist/gl.d.ts +1 -1
  28. package/dist/gl.js +3 -2
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +1 -1
  31. package/dist/marks/arcs.d.ts +5 -0
  32. package/dist/marks/arcs.js +21 -14
  33. package/dist/scale.d.ts +4 -2
  34. package/dist/scale.js +30 -9
  35. package/dist/scales/band.js +2 -0
  36. package/dist/scales/bare.d.ts +2 -1
  37. package/dist/scales/bare.js +3 -3
  38. package/dist/scales/log.js +3 -1
  39. package/dist/scales/time.js +2 -1
  40. package/dist/schema.json +1 -0
  41. package/dist/text.js +1 -0
  42. package/dist/transforms.d.ts +6 -0
  43. package/dist/transforms.js +13 -0
  44. package/dist/types.d.ts +21 -3
  45. package/package.json +4 -3
@@ -1,7 +1,8 @@
1
+ import { clamp } from '../chart.js';
1
2
  export const SLOP_PX = 4;
2
3
  export const unselect = (e) => e.preventDefault();
3
4
  /** 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
+ export const settle = (chart) => chart.win.setTimeout(() => {
5
6
  chart.drag.active = false;
6
7
  chart.sync();
7
8
  }, 0);
@@ -30,7 +31,8 @@ export const released = ({ overlay }, e) => e.pointerType !== 'touch' && !!overl
30
31
  export const strayed = ({ overlay }, e) => {
31
32
  const held = overlay && presses.get(overlay)?.held;
32
33
  // Some browsers send a click as a MouseEvent, which does not name its pointer, and so are double clicks.
33
- return !!held && (e instanceof PointerEvent ? held.has(e.pointerId) : held.size > 0);
34
+ const id = e.pointerId;
35
+ return !!held && (id === undefined ? held.size > 0 : held.has(id));
34
36
  };
35
37
  /** Whether a hover is the chart's own: on it or on the app's DOM over it, and not on a control such as a legend's. */
36
38
  export const owns = (chart, target) => target === chart.root || !!chart.overlay?.contains(target);
@@ -39,3 +41,52 @@ export function locate(chart, e) {
39
41
  const { inside, ...where } = position(chart, e.clientX, e.clientY);
40
42
  return { ...where, over: inside && chart.frame() === 'axes' && e.target === chart.root };
41
43
  }
44
+ export const widthOf = (chart, s) => Math.abs(chart.real('x', s[1]) - chart.real('x', s[0]));
45
+ /** The width in axis units of the x span s once the chart fits it inside its domain: a span pushed off a log edge narrows or widens. */
46
+ export const fittedWidth = (chart, s) => {
47
+ const { x } = chart.domain();
48
+ return widthOf(chart, clamp(s, x) ?? x);
49
+ };
50
+ /** The narrowest x span, in axis units, that zoom() lets a gesture reach on a chart; a brush's zoom keeps to it too. */
51
+ export const narrowest = new WeakMap();
52
+ /** Where between lo and hi the increasing f reaches target, trying `guess` first: it is exact on a linear axis. */
53
+ export const reach = (f, target, lo, hi, guess) => {
54
+ if (Math.abs(f(guess) - target) <= target * 1e-9)
55
+ return guess;
56
+ for (let i = 0; i < 60; i++) {
57
+ const m = (lo + hi) / 2;
58
+ if (f(m) < target)
59
+ lo = m;
60
+ else
61
+ hi = m;
62
+ }
63
+ return (lo + hi) / 2;
64
+ };
65
+ /**
66
+ * A zoom factor for the x span s about the value a, at the share `at` of the span, held so the span in axis units goes no
67
+ * further past `min` or `max` than it already is: a pinch that moves to where a log axis is wider or narrower can need
68
+ * a factor on the other side of 1.
69
+ */
70
+ export const limited = (chart, s, k, min = 0, max = Infinity, at = 0.5, a = s[0] + at * (s[1] - s[0])) => {
71
+ const d = s[1] - s[0];
72
+ const moved = a !== s[0] + at * d;
73
+ if (!min && max === Infinity)
74
+ return k;
75
+ if (!moved && (k > 1 ? max === Infinity : !min))
76
+ return k;
77
+ const w = widthOf(chart, s);
78
+ if (!w)
79
+ return k;
80
+ const f = (t) => fittedWidth(chart, [a - at * d * t, a + (1 - at) * d * t]);
81
+ const [low, high, now] = [Math.min(min, w), Math.max(max, w), f(k)];
82
+ if (now >= low && now <= high)
83
+ return k;
84
+ const target = now > high ? high : low;
85
+ const { x } = chart.domain();
86
+ let [lo, hi] = [Math.min(k, 1), Math.max(Math.min(k, Math.abs((x[1] - x[0]) / d)), 1)];
87
+ for (let i = 0; i < 60 && f(lo) > target; i++)
88
+ lo /= 2;
89
+ for (let i = 0; i < 60 && f(hi) < target; i++)
90
+ hi *= 2;
91
+ return reach(f, target, lo, hi, target / w);
92
+ };
@@ -7,8 +7,8 @@ export type TooltipOptions =
7
7
  mode: 'x';
8
8
  /** The first line of the tooltip, for the x at the pointer. */
9
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;
10
+ /** A mark's value as text, after its label, for its y on the axis it is drawn against; label is the mark's label. */
11
+ value: (y: number, axis: 'y' | 'y2', label: string) => string;
12
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
13
  snap?: (x: number) => number;
14
14
  }
@@ -1,9 +1,9 @@
1
1
  import { NEAREST_PX } from '../chart.js';
2
- import { owns, position, released } from './pointer.js';
2
+ import { owns, position, released, strayed } from './pointer.js';
3
3
  const FOCUS_PX = 30;
4
4
  export function tooltip(t) {
5
5
  return chart => {
6
- const { root } = chart;
6
+ const { root, doc } = chart;
7
7
  const cross = chart.layer('div', 'display:none;border-left:1px dashed');
8
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
9
  const restyle = () => {
@@ -12,19 +12,25 @@ export function tooltip(t) {
12
12
  Object.assign(tip.style, { color: text, background: surface, borderColor: border });
13
13
  };
14
14
  restyle();
15
+ // The pointer in the page and where the chart was then: a hover follows the page, a pin keeps to the chart.
15
16
  let at = null;
16
17
  let held = false;
17
18
  // The user's pointer is on the chart, maybe over another feature's layer, so the app's is not shown.
18
19
  let inside = false;
19
20
  let fromApp = false;
20
- const hide = () => {
21
+ // On another feature's layer, such as a legend, whose focus a tip let go must leave alone.
22
+ let aside = false;
23
+ const conceal = () => {
21
24
  cross.style.display = tip.style.display = 'none';
25
+ };
26
+ const hide = () => {
27
+ conceal();
22
28
  chart.focus(null);
23
29
  };
24
30
  const show = (x, y, rows) => {
25
31
  const { width, height } = chart.size();
26
32
  tip.replaceChildren(...rows.map(r => {
27
- const e = document.createElement('div');
33
+ const e = doc.createElement('div');
28
34
  e.textContent = r.text;
29
35
  if (r.color)
30
36
  e.style.color = chart.color(r.color);
@@ -43,7 +49,9 @@ export function tooltip(t) {
43
49
  let py;
44
50
  if (at) {
45
51
  fromApp = false;
46
- ({ px, py } = position(chart, ...at));
52
+ const [x, y, left, top] = at;
53
+ const box = held ? root.getBoundingClientRect() : { left, top };
54
+ ({ px, py } = position(chart, x + box.left - left, y + box.top - top));
47
55
  }
48
56
  else {
49
57
  const p = inside ? null : chart.pointer();
@@ -97,7 +105,7 @@ export function tooltip(t) {
97
105
  : s && (s.band ? chart.real(on, s.y2) - chart.real(on, s.y1) : chart.real(on, s.value ?? s.y2));
98
106
  if (k.label !== undefined) {
99
107
  rows.push({
100
- text: `${k.label}: ${value === undefined ? '–' : t.value(value, on)}`,
108
+ text: `${k.label}: ${value === undefined ? '–' : t.value(value, on, k.label)}`,
101
109
  color: k.color,
102
110
  });
103
111
  }
@@ -127,20 +135,24 @@ export function tooltip(t) {
127
135
  };
128
136
  const move = (e) => {
129
137
  inside = true;
138
+ aside = !owns(chart, e.target);
139
+ if (held) {
140
+ if (!aside)
141
+ place();
142
+ return;
143
+ }
130
144
  if (chart.drag.active || chart.drag.child) {
131
145
  at = null;
132
146
  return hide();
133
147
  }
134
148
  // Over another feature's layer, such as a legend, the focus is that feature's to set.
135
- if (!owns(chart, e.target)) {
149
+ if (aside) {
136
150
  at = null;
137
- held = false;
138
151
  fromApp = false;
139
- cross.style.display = tip.style.display = 'none';
140
- return;
152
+ return conceal();
141
153
  }
142
- at = [e.clientX, e.clientY];
143
- held = false;
154
+ const { left, top } = root.getBoundingClientRect();
155
+ at = [e.clientX, e.clientY, left, top];
144
156
  place();
145
157
  };
146
158
  const release = (e) => {
@@ -159,7 +171,9 @@ export function tooltip(t) {
159
171
  };
160
172
  // A lifted finger leaves the chart, and a tip it tapped open is meant to stay until a tap elsewhere.
161
173
  const lift = (e) => {
162
- inside = false;
174
+ inside = aside = false;
175
+ if (held)
176
+ return;
163
177
  if (e.pointerType !== 'touch')
164
178
  return out();
165
179
  held = !!at && tip.style.display !== 'none';
@@ -173,27 +187,53 @@ export function tooltip(t) {
173
187
  if (at)
174
188
  out();
175
189
  };
190
+ const pin = (e) => {
191
+ if (e.target !== root || strayed(chart, e) || chart.drag.active)
192
+ return;
193
+ held = !!at && tip.style.display !== 'none';
194
+ };
195
+ const letGo = () => {
196
+ if (!held)
197
+ return;
198
+ held = false;
199
+ at = null;
200
+ if (aside)
201
+ conceal();
202
+ else
203
+ hide();
204
+ };
205
+ const escape = (e) => {
206
+ if (held && e.key === 'Escape') {
207
+ letGo();
208
+ place();
209
+ }
210
+ };
176
211
  root.addEventListener('pointerdown', move);
177
212
  // Capturing, so a child that stops its own events still moves the tip and brings it back.
178
213
  root.addEventListener('pointermove', move, true);
179
214
  root.addEventListener('pointerup', release, true);
180
215
  root.addEventListener('pointerleave', lift);
181
216
  root.addEventListener('pointercancel', out);
182
- document.addEventListener('pointerdown', away, true);
217
+ root.addEventListener('click', pin);
218
+ doc.addEventListener('pointerdown', away, true);
219
+ doc.addEventListener('keydown', escape);
183
220
  return {
184
221
  update() {
185
222
  restyle();
186
- place();
223
+ if (!(held && aside))
224
+ place();
187
225
  },
188
- // A lifted finger is no longer anywhere on the chart, so what it tapped is let go.
189
- letGo: () => held && leave(),
226
+ // What a tap or a click pinned is let go: the chart under it is redrawn.
227
+ letGo,
190
228
  destroy() {
191
229
  root.removeEventListener('pointerdown', move);
192
230
  root.removeEventListener('pointermove', move, true);
193
231
  root.removeEventListener('pointerup', release, true);
194
232
  root.removeEventListener('pointerleave', lift);
195
233
  root.removeEventListener('pointercancel', out);
196
- document.removeEventListener('pointerdown', away, true);
234
+ root.removeEventListener('click', pin);
235
+ doc.removeEventListener('pointerdown', away, true);
236
+ doc.removeEventListener('keydown', escape);
197
237
  cross.remove();
198
238
  tip.remove();
199
239
  },
@@ -10,5 +10,9 @@ export type ZoomOptions = {
10
10
  * is in use. 'pan' takes every mouse drag, so a brush() beside it gets none.
11
11
  */
12
12
  drag?: 'pan' | 'shift' | false;
13
+ /** The narrowest x span the wheel, a pinch and `brush({ zoom })` reach, in axis units: milliseconds on a time axis. */
14
+ min?: number;
15
+ /** The widest x span the wheel and a pinch zoom out to, in axis units. A view already wider, such as the whole domain, is left as it is. */
16
+ max?: number;
13
17
  };
14
18
  export declare function zoom(z?: ZoomOptions): Feature;
@@ -1,4 +1,4 @@
1
- import { locate as where, settle as release, SLOP_PX, strayed, unselect } from './pointer.js';
1
+ import { limited, locate as where, narrowest, settle as release, SLOP_PX, strayed, unselect, } from './pointer.js';
2
2
  // How far a drag that pans both axes must move up or down before it pans y: a hand does not move level.
3
3
  const LEVEL_PX = 8;
4
4
  const DOUBLE_TAP_MS = 300;
@@ -6,11 +6,16 @@ const DOUBLE_TAP_PX = 20;
6
6
  const TAP_MS = 500;
7
7
  export function zoom(z = {}) {
8
8
  const sides = ['x', 'y'].filter(k => (z.axes ?? 'x').includes(k));
9
+ if (z.min !== undefined && z.max !== undefined && z.min > z.max)
10
+ throw new Error(`zoom() min ${z.min} is above max ${z.max}`);
9
11
  return chart => {
10
- const { root, drag } = chart;
12
+ const { root, drag, doc, win } = chart;
11
13
  const locate = (e) => where(chart, e);
12
14
  if (z.drag !== false)
13
15
  drag.pan = z.drag === 'pan' ? 'plain' : 'shift';
16
+ if (z.min !== undefined && sides.includes('x'))
17
+ narrowest.set(chart, z.min);
18
+ const limit = (s, span, k, at, a) => s === 'x' ? limited(chart, span, k, z.min, z.max, at, a) : k;
14
19
  let pending;
15
20
  const shown = () => chart.fit(pending === undefined ? {} : pending);
16
21
  let frame = 0;
@@ -23,7 +28,7 @@ export function zoom(z = {}) {
23
28
  };
24
29
  const ask = (want) => {
25
30
  pending = want;
26
- frame ||= requestAnimationFrame(flush);
31
+ frame ||= win.requestAnimationFrame(flush);
27
32
  };
28
33
  const wheel = (e) => {
29
34
  if (z.wheel === false)
@@ -35,11 +40,12 @@ export function zoom(z = {}) {
35
40
  if (!over || !e.deltaY)
36
41
  return;
37
42
  const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? chart.size().height : 1;
38
- const k = Math.exp(e.deltaY * unit * 0.002);
43
+ const zoomed = Math.exp(e.deltaY * unit * 0.002);
39
44
  const base = shown();
40
45
  const want = { ...pending };
41
46
  for (const s of sides) {
42
47
  const [lo, hi] = base[s];
48
+ const k = limit(s, base[s], zoomed, at[s]);
43
49
  const a = lo + at[s] * (hi - lo);
44
50
  const around = (t) => [a - (a - lo) * t, a + (hi - a) * t];
45
51
  const step = around(k);
@@ -69,10 +75,10 @@ export function zoom(z = {}) {
69
75
  if (!over)
70
76
  return;
71
77
  from = { id: e.pointerId, x: px, y: py, view: shown(), w, h };
72
- document.addEventListener('pointermove', move, true);
73
- document.addEventListener('pointerup', up, true);
74
- document.addEventListener('pointercancel', up, true);
75
- document.addEventListener('selectstart', unselect, true);
78
+ doc.addEventListener('pointermove', move, true);
79
+ doc.addEventListener('pointerup', up, true);
80
+ doc.addEventListener('pointercancel', up, true);
81
+ doc.addEventListener('selectstart', unselect, true);
76
82
  };
77
83
  const move = (e) => {
78
84
  if (!from || e.pointerId !== from.id)
@@ -107,10 +113,10 @@ export function zoom(z = {}) {
107
113
  };
108
114
  const end = () => {
109
115
  from = undefined;
110
- document.removeEventListener('pointermove', move, true);
111
- document.removeEventListener('pointerup', up, true);
112
- document.removeEventListener('pointercancel', up, true);
113
- document.removeEventListener('selectstart', unselect, true);
116
+ doc.removeEventListener('pointermove', move, true);
117
+ doc.removeEventListener('pointerup', up, true);
118
+ doc.removeEventListener('pointercancel', up, true);
119
+ doc.removeEventListener('selectstart', unselect, true);
114
120
  };
115
121
  const up = (e) => {
116
122
  if (e.pointerId !== from?.id)
@@ -121,7 +127,7 @@ export function zoom(z = {}) {
121
127
  };
122
128
  const settle = () => (settling = release(chart));
123
129
  const engage = () => {
124
- clearTimeout(settling);
130
+ win.clearTimeout(settling);
125
131
  drag.active = true;
126
132
  };
127
133
  const whole = () => ask(sides.length === 2 ? null : { [sides[0]]: undefined });
@@ -145,9 +151,9 @@ export function zoom(z = {}) {
145
151
  if (!over || touches.size >= 2)
146
152
  return;
147
153
  if (!touches.size) {
148
- document.addEventListener('pointermove', touchMove, true);
149
- document.addEventListener('pointerup', touchUp, true);
150
- document.addEventListener('pointercancel', touchCancel, true);
154
+ doc.addEventListener('pointermove', touchMove, true);
155
+ doc.addEventListener('pointerup', touchUp, true);
156
+ doc.addEventListener('pointercancel', touchCancel, true);
151
157
  }
152
158
  touches.set(e.pointerId, { px, py, at });
153
159
  if (touches.size === 2) {
@@ -178,11 +184,12 @@ export function zoom(z = {}) {
178
184
  if (!pinch)
179
185
  return;
180
186
  const { mid, d } = span(touches.get(pinch.a), touches.get(pinch.b));
181
- const k = d && pinch.d ? pinch.d / d : 1;
187
+ const zoomed = d && pinch.d ? pinch.d / d : 1;
182
188
  const want = {};
183
189
  for (const s of sides) {
184
190
  const [lo, hi] = pinch.view[s];
185
191
  const under = lo + pinch.mid[s] * (hi - lo);
192
+ const k = limit(s, pinch.view[s], zoomed, mid[s], under);
186
193
  const [flo, fhi] = chart.fit({ [s]: [lo, lo + (hi - lo) * k] })[s];
187
194
  const width = fhi - flo;
188
195
  const start = under - mid[s] * width;
@@ -194,9 +201,9 @@ export function zoom(z = {}) {
194
201
  touches.clear();
195
202
  pinch = tap = undefined;
196
203
  again = false;
197
- document.removeEventListener('pointermove', touchMove, true);
198
- document.removeEventListener('pointerup', touchUp, true);
199
- document.removeEventListener('pointercancel', touchCancel, true);
204
+ doc.removeEventListener('pointermove', touchMove, true);
205
+ doc.removeEventListener('pointerup', touchUp, true);
206
+ doc.removeEventListener('pointercancel', touchCancel, true);
200
207
  if (drag.active)
201
208
  settle();
202
209
  };
@@ -234,9 +241,10 @@ export function zoom(z = {}) {
234
241
  touchEnd();
235
242
  root.style.touchAction = touchAction;
236
243
  root.removeEventListener('pointerdown', touchDown, true);
237
- cancelAnimationFrame(frame);
238
- clearTimeout(settling);
244
+ win.cancelAnimationFrame(frame);
245
+ win.clearTimeout(settling);
239
246
  drag.pan = drag.active = false;
247
+ narrowest.delete(chart);
240
248
  root.removeEventListener('wheel', wheel);
241
249
  root.removeEventListener('pointerdown', down);
242
250
  root.removeEventListener('dblclick', reset);
package/dist/gl.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { GlLayer } from './types.js';
2
2
  export declare function program(gl: WebGL2RenderingContext, vertex: string, fragment: string): WebGLProgram;
3
3
  export declare function glLayer(canvas: HTMLCanvasElement): GlLayer | null;
4
- /** A colour for addColorStop, which takes no CSS variable. */
4
+ /** A colour for addColorStop, which takes no CSS variable or `light-dark()`. */
5
5
  export declare function stop(ctx: CanvasRenderingContext2D, color: string): string;
6
6
  /** A CSS colour as red, green, blue and opacity from 0 to 1. */
7
7
  export declare function rgba(ctx: CanvasRenderingContext2D, color: string): number[];
package/dist/gl.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { placed } from './color.js';
1
2
  export function program(gl, vertex, fragment) {
2
3
  const p = gl.createProgram();
3
4
  for (const [type, src] of [
@@ -38,9 +39,9 @@ export function glLayer(canvas) {
38
39
  },
39
40
  };
40
41
  }
41
- /** A colour for addColorStop, which takes no CSS variable. */
42
+ /** A colour for addColorStop, which takes no CSS variable or `light-dark()`. */
42
43
  export function stop(ctx, color) {
43
- if (!color.includes('var('))
44
+ if (!placed(color))
44
45
  return color;
45
46
  ctx.fillStyle = color;
46
47
  return ctx.fillStyle;
package/dist/index.d.ts CHANGED
@@ -33,7 +33,7 @@ export type { LogAxis, LogOptions } from './scales/log.js';
33
33
  export { time } from './scales/time.js';
34
34
  export { dark, light } from './theme.js';
35
35
  export type { Theme } from './theme.js';
36
- export { bands, bin, fiveNumbers, stack } from './transforms.js';
36
+ export { bands, bin, cumulate, fiveNumbers, stack } from './transforms.js';
37
37
  export type { AnimateOptions } from './features/animate.js';
38
38
  export type { BrushOptions } from './features/brush.js';
39
39
  export type { LegendOptions } from './features/legend.js';
package/dist/index.js CHANGED
@@ -29,4 +29,4 @@ export { sequential } from './scales/color.js';
29
29
  export { log } from './scales/log.js';
30
30
  export { time } from './scales/time.js';
31
31
  export { dark, light } from './theme.js';
32
- export { bands, bin, fiveNumbers, stack } from './transforms.js';
32
+ export { bands, bin, cumulate, fiveNumbers, stack } from './transforms.js';
@@ -14,6 +14,11 @@ export type ArcsOptions = {
14
14
  inner?: number;
15
15
  /** Text on each slice that has room for it: true for its share as a percentage, or your own. */
16
16
  text?: true | ((row: number, share: number) => string);
17
+ /**
18
+ * Text in the middle, or a function of the total of the values drawn. It is kept over any slice
19
+ * label it would cover, and with `inner` 0 it is drawn over the slices.
20
+ */
21
+ center?: string | ((total: number) => string);
17
22
  /**
18
23
  * Each slice starts at this opacity and reaches its full colour at its end, clockwise. Where
19
24
  * the browser has no conic gradient the slices stay solid.
@@ -11,9 +11,12 @@ export function arcs(o) {
11
11
  let most = 0;
12
12
  for (let i = 0; i < n; i++)
13
13
  most = Math.max(most, worth(i));
14
- let total = 0;
15
- for (let i = 0; i < n; i++)
16
- ends[i] = total += worth(i) / (most || 1);
14
+ let [total, sum] = [0, 0];
15
+ for (let i = 0; i < n; i++) {
16
+ const w = worth(i);
17
+ ends[i] = total += w / (most || 1);
18
+ sum += w;
19
+ }
17
20
  for (let i = 0; i < n; i++)
18
21
  ends[i] /= total || 1;
19
22
  let wide = 0;
@@ -73,17 +76,21 @@ export function arcs(o) {
73
76
  };
74
77
  const said = o.text === true ? (_, share) => `${Math.round(share * 100)}%` : o.text;
75
78
  const within = (i, x, y, w, h) => inRing([cx, cy, hole, outer, ends[i - 1] ?? 0, ends[i]], x, y, w, h);
76
- const labels = !said
77
- ? undefined
78
- : Array.from(ends, (end, i) => {
79
- const share = end - (ends[i - 1] ?? 0);
80
- // A slice narrower at the rim than one character has no room, so it is not asked.
81
- const text = share * TURN * outer >= 7 * dpr ? said(i, share) : '';
82
- const [x, y] = anchor(i);
83
- if (!text || !within(i, x, y, textWidth(text) * dpr, 16 * dpr))
84
- return undefined;
85
- return { x, y, text, color: '#fff', priority: share };
86
- }).filter(l => l !== undefined);
79
+ const middle = outer ? (typeof o.center === 'function' ? o.center(sum) : o.center) : '';
80
+ const labels = [
81
+ ...(middle ? [{ x: cx, y: cy, text: middle, priority: Infinity }] : []),
82
+ ...(!said
83
+ ? []
84
+ : Array.from(ends, (end, i) => {
85
+ const share = end - (ends[i - 1] ?? 0);
86
+ // A slice narrower at the rim than one character has no room, so it is not asked.
87
+ const text = share * TURN * outer >= 7 * dpr ? said(i, share) : '';
88
+ const [x, y] = anchor(i);
89
+ if (!text || !within(i, x, y, textWidth(text) * dpr, 16 * dpr))
90
+ return undefined;
91
+ return { x, y, text, color: '#fff', priority: share };
92
+ }).filter(l => l !== undefined)),
93
+ ];
87
94
  return {
88
95
  labels,
89
96
  paint(k, row, rest = 1) {
package/dist/scale.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Axis, Col, Room } from './types.js';
1
+ import type { Axis, Col, Room, Span } from './types.js';
2
2
  /** The 1, 2 or 5 times a power of ten that cuts the span into at most `max` steps. */
3
3
  export declare function niceStep(span: number, max?: number): number;
4
4
  export declare function extent(cols: Col[]): [number, number];
@@ -8,7 +8,9 @@ export declare const fits: (count: number, widest: number, room: Room) => boolea
8
8
  export declare const thin: <T>(ticks: T[], widest: number, room?: Room) => T[];
9
9
  /** The ticks `keep` picks for the least k whose labels fit, every k-th by default; the first when it picks none. */
10
10
  export declare const spaced: <T>(ticks: T[], widest: number, room?: Room, keep?: (t: T, i: number, k: number) => boolean) => T[];
11
- /** `of` is the extent of the data, used when the domain is 'nice' or 'data'. */
11
+ export declare const fixed: (domain: Axis['domain']) => domain is Span;
12
+ export declare function closed(domain: Axis['domain'] | undefined, who: string, what: string): asserts domain is Span | 'nice' | 'data' | undefined;
13
+ /** `of` is the extent of the data, used for each end of the domain that is 'nice' or 'data'. */
12
14
  export declare function scale(domain: Axis['domain'], of: [number, number], room?: Room, { step: given, format }?: Pick<Axis, 'step' | 'format'>): {
13
15
  lo: number;
14
16
  hi: number;
package/dist/scale.js CHANGED
@@ -31,20 +31,39 @@ export const spaced = (ticks, widest, room, keep = (_, i, k) => i % k === 0) =>
31
31
  const kept = ticks.filter((t, i) => keep(t, i, k));
32
32
  return kept.length ? kept : ticks.slice(0, 1);
33
33
  };
34
- /** `of` is the extent of the data, used when the domain is 'nice' or 'data'. */
34
+ export const fixed = (domain) => typeof domain !== 'string' && typeof domain[0] === 'number' && typeof domain[1] === 'number';
35
+ export function closed(domain, who, what) {
36
+ if (Array.isArray(domain) && !fixed(domain))
37
+ throw new Error(`${who} with one open end does not apply to ${what}`);
38
+ }
39
+ /** `of` is the extent of the data, used for each end of the domain that is 'nice' or 'data'. */
35
40
  export function scale(domain, of, room, { step: given, format = String } = {}) {
36
- let [lo, hi] = typeof domain === 'string' ? of : domain;
37
- if (lo === hi) {
38
- const pad = Math.abs(lo) / 2 || 0.5;
39
- lo -= pad;
40
- hi += pad;
41
+ const [first, last] = typeof domain === 'string' ? [domain, domain] : domain;
42
+ const held = (v) => Math.max(-Number.MAX_VALUE, Math.min(Number.MAX_VALUE, v));
43
+ let lo = typeof first === 'number' ? first : of[0];
44
+ let hi = typeof last === 'number' ? last : of[1];
45
+ if (typeof first === typeof last) {
46
+ if (lo === hi) {
47
+ const pad = Math.abs(lo) / 2 || 0.5;
48
+ lo -= pad;
49
+ hi += pad;
50
+ }
51
+ }
52
+ else if (lo >= hi) {
53
+ // Data at or past the fixed end: the open end moves away from it, so the axis does not invert.
54
+ if (typeof first === 'number')
55
+ hi = held(lo + (Math.abs(lo) / 2 || 0.5));
56
+ else
57
+ lo = held(hi - (Math.abs(hi) / 2 || 0.5));
58
+ // A fixed end at ±MAX_VALUE has no room past it, so it moves inward by half instead.
59
+ if (lo === hi)
60
+ [lo, hi] = typeof first === 'number' ? [lo / 2, hi] : [lo, hi / 2];
41
61
  }
42
62
  // The bounds are rounded to this step whatever the room, so they hold still when the chart is resized.
43
63
  // A span too small to divide is its own step, and a bound rounded past the largest number stays on it.
44
64
  // A step too fine for the 1000 ticks counted below would leave ticks at the low end only.
45
65
  const fixed = Number.isFinite(given) && given > 0 && (hi - lo) / given < 990;
46
66
  const step = fixed ? given : niceStep(hi - lo) || hi - lo;
47
- const held = (v) => Math.max(-Number.MAX_VALUE, Math.min(Number.MAX_VALUE, v));
48
67
  // Cleaning to 15 digits is undone where it moves a value by more than float error, so it never merges multiples.
49
68
  const clean = (v, tick) => {
50
69
  const c = +v.toPrecision(15);
@@ -61,8 +80,10 @@ export function scale(domain, of, room, { step: given, format = String } = {}) {
61
80
  }
62
81
  return v;
63
82
  };
64
- if (domain === 'nice')
65
- [lo, hi] = [multiple(lo, -1), multiple(hi, 1)];
83
+ if (first === 'nice')
84
+ lo = multiple(lo, -1);
85
+ if (last === 'nice')
86
+ hi = multiple(hi, 1);
66
87
  const at = (tick) => {
67
88
  const digits = Math.max(0, -Math.floor(Math.log10(tick)));
68
89
  const first = Math.ceil(lo / tick - 1e-9);
@@ -1,5 +1,7 @@
1
+ import { closed } from '../scale.js';
1
2
  import { widest } from '../text.js';
2
3
  function resolve({ categories, domain }, _extent, room) {
4
+ closed(domain, 'band() domain', 'categories');
3
5
  const n = categories.length;
4
6
  const [first, last] = typeof domain === 'string'
5
7
  ? [0, n - 1]
@@ -1,4 +1,5 @@
1
- import type { Axis } from '../types.js';
1
+ import type { Axis, Resolved } from '../types.js';
2
+ export declare function resolve(axis: Axis, extent: () => [number, number]): Resolved;
2
3
  /**
3
4
  * An axis that places the marks and shows nothing itself: no ticks, no grid lines and no label.
4
5
  * @param domain 'data' (the default) fits the marks exactly, 'nice' widens that to whole steps; or [lo, hi].
@@ -1,6 +1,6 @@
1
- import { scale } from '../scale.js';
2
- function resolve(axis, extent) {
3
- const { lo, hi } = scale(axis.domain, typeof axis.domain === 'string' ? extent() : axis.domain);
1
+ import { fixed, scale } from '../scale.js';
2
+ export function resolve(axis, extent) {
3
+ const { lo, hi } = scale(axis.domain, fixed(axis.domain) ? axis.domain : extent());
4
4
  return { lo, hi, ticks: [] };
5
5
  }
6
6
  /**
@@ -1,4 +1,4 @@
1
- import { fits, scale as linear, spaced } from '../scale.js';
1
+ import { closed, fits, scale as linear, spaced } from '../scale.js';
2
2
  import { widest as widestOf } from '../text.js';
3
3
  // log10 and log2 are exact at their own powers; another base's division can land a hair off one.
4
4
  const lg = (v, base) => {
@@ -18,6 +18,7 @@ function col(values) {
18
18
  function resolve(axis, extent, room) {
19
19
  const base = baseOf(axis);
20
20
  const format = axis.format ?? String;
21
+ closed(axis.domain, 'log() domain', 'a log scale');
21
22
  let [lo, hi] = typeof axis.domain === 'string' ? extent() : axis.domain;
22
23
  if (lo === hi)
23
24
  [lo, hi] = [lo - 0.5, hi + 0.5];
@@ -80,6 +81,7 @@ function resolve(axis, extent, room) {
80
81
  export function log({ label, base = 10, domain = 'nice', format, fit }) {
81
82
  if (!(base > 0 && base !== 1 && Number.isFinite(base)))
82
83
  throw new RangeError(`log() base ${base} must be above zero and not 1`);
84
+ closed(domain, 'log() domain', 'a log scale');
83
85
  if (typeof domain !== 'string')
84
86
  for (const bound of domain)
85
87
  if (!(bound > 0 && bound < Infinity))
@@ -1,4 +1,4 @@
1
- import { niceStep, spaced, thin } from '../scale.js';
1
+ import { closed, niceStep, spaced, thin } from '../scale.js';
2
2
  import { estimated, textWidth, widest as widestOf } from '../text.js';
3
3
  const UNITS = ['year', 'month', 'day', 'hour', 'minute', 'second'];
4
4
  const MONTHS = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
@@ -71,6 +71,7 @@ function label([y, mo, d, h, mi, s], field) {
71
71
  return h || mi ? `${pad(h)}:${pad(mi)}` : day;
72
72
  }
73
73
  function resolve(axis, extent, room) {
74
+ closed(axis.domain, 'time() domain', 'dates');
74
75
  const { lo, hi, ticks, fixed, keep } = stepped(axis, typeof axis.domain === 'string' ? extent() : axis.domain, room);
75
76
  const widest = widestOf(ticks.map(t => t.label), axis.format ? textWidth : estimated);
76
77
  return {