swiftplot 0.5.2 → 0.6.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.
package/README.md CHANGED
@@ -14,7 +14,8 @@ project stands, what it lacks and what 1.0 needs: [swiftplot.dev/status](https:/
14
14
  [Discussions](https://github.com/GusevP/swiftplot/discussions).
15
15
 
16
16
  **For AI coding assistants:** [`llms-full.txt`](https://swiftplot.dev/llms-full.txt) is a guide to writing code with
17
- swiftplot, and [`llms.txt`](https://swiftplot.dev/llms.txt) its index.
17
+ swiftplot, and [`llms.txt`](https://swiftplot.dev/llms.txt) its index. `swiftplot/schema.json` is a JSON Schema of the
18
+ easy charts' props, for a model that answers with a chart as JSON.
18
19
 
19
20
  <img src="https://raw.githubusercontent.com/GusevP/swiftplot/main/assets/pan.gif" alt="Panning and zooming a line of a million points" width="640" />
20
21
 
@@ -97,12 +98,12 @@ Gzip size of the minified bundle of each entry in `site/scripts/size/`, built fr
97
98
 
98
99
  | entry | imports | KB |
99
100
  | ------------------ | ------------------------------------------------------- | ---: |
100
- | plot-line | `plot` and `line` from `swiftplot` | 14.4 |
101
- | plot-line-features | the same with `tooltip`, `legend`, `zoom` and `animate` | 19.1 |
102
- | line-chart | `lineChart` from `swiftplot/charts` | 37.6 |
103
- | all-charts | every chart of `swiftplot/charts` | 54.7 |
104
- | react-line-chart | `LineChart` from `@swiftplot/react`, React not counted | 39.3 |
105
- | vue-line-chart | `LineChart` from `@swiftplot/vue`, Vue not counted | 39.8 |
101
+ | plot-line | `plot` and `line` from `swiftplot` | 15.4 |
102
+ | plot-line-features | the same with `tooltip`, `legend`, `zoom` and `animate` | 20.7 |
103
+ | line-chart | `lineChart` from `swiftplot/charts` | 40.2 |
104
+ | all-charts | every chart of `swiftplot/charts` | 57.6 |
105
+ | react-line-chart | `LineChart` from `@swiftplot/react`, React not counted | 42.0 |
106
+ | vue-line-chart | `LineChart` from `@swiftplot/vue`, Vue not counted | 42.5 |
106
107
 
107
108
  On chart-bench's page, which bundles `plot`, `line`, `area`, `ticks`, `dots`, `tooltip` and `animate`, swiftplot 0.5.0 adds 19.3 KB and uPlot 23.9 KB (`results/bundle.json`: the arm's page less the same page with no chart). uPlot ships more in its size: it is one module that comes whole, with its legend, cursor, selection and series types whether a page uses them or not.
108
109
 
package/dist/chart.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import type { Chart, Options } from './types.js';
1
+ import type { Chart, Options, Span } from './types.js';
2
2
  export declare const NEAREST_PX = 20;
3
+ export declare const clamp: (want: Span | undefined, [p, q]: Span) => Span | undefined;
3
4
  /**
4
5
  * Draws the marks into `el` on the axes given, with the features in `use`, and returns the chart to update or destroy.
5
6
  * @param el The element the chart fills.
package/dist/chart.js CHANGED
@@ -2,7 +2,8 @@ import { extend, resolver, windowOf } from './color.js';
2
2
  import { copied, keep, sameData } from './equal.js';
3
3
  import { owns, position, presses, released, strayed } from './features/pointer.js';
4
4
  import { upTo } from './marks/common.js';
5
- import { extent, scale } from './scale.js';
5
+ import { extent, fixed, scale } from './scale.js';
6
+ import { resolve as bareScale } from './scales/bare.js';
6
7
  import { FONT, textWidth } from './text.js';
7
8
  import { light } from './theme.js';
8
9
  export const NEAREST_PX = 20;
@@ -28,7 +29,7 @@ const same = (a, b) => {
28
29
  const resolve = (a, of, room) => {
29
30
  if (a.scale)
30
31
  return a.scale(a, of, room);
31
- const s = scale(a.domain, typeof a.domain === 'string' ? of() : a.domain, room, a);
32
+ const s = scale(a.domain, fixed(a.domain) ? a.domain : of(), room, a);
32
33
  return { ...s, ticks: s.ticks.map(value => ({ value, label: (a.format ?? String)(value) })) };
33
34
  };
34
35
  const AUTO = { domain: 'nice', label: '' };
@@ -53,7 +54,48 @@ const within = (want, [lo, hi], least = (hi - lo) * 1e-6) => {
53
54
  const step = Math.max(-lo, hi) * Number.EPSILON * 4;
54
55
  return s[0] < s[1] || least >= step ? s : within(want, [lo, hi], step);
55
56
  };
56
- const clamp = (want, [p, q]) => {
57
+ const share = ([lo, hi]) => -lo / (hi - lo);
58
+ const towards = ([lo, hi], f) => {
59
+ const r = f / (1 - f);
60
+ return -lo < r * hi ? [-r * hi, hi] : [lo, -lo / r];
61
+ };
62
+ /** Both spans widened to take in zero at one height, or undefined where that would move an end in `fixed`. */
63
+ const zeroed = (y, y2, fixed, lead = 0) => {
64
+ // A reversed span is negated, which keeps zero and its height, so the rest works on ascending spans.
65
+ const turned = [y, y2].map(([lo, hi]) => lo > hi);
66
+ const turn = (s, i) => (turned[i] ? [-s[0], -s[1]] : s);
67
+ const given = [y, y2].map(turn);
68
+ const pair = given.map(([lo, hi]) => [Math.min(lo, 0), Math.max(hi, 0)]);
69
+ const [fy, f2] = pair.map(share);
70
+ const inside = (f) => f > 0 && f < 1;
71
+ const [first, then] = lead ? [f2, fy] : [fy, f2];
72
+ const t = inside(first) ? first : inside(then) ? then : 0.5;
73
+ const out = fy === f2 ? pair : pair.map((s, i) => ((i ? f2 : fy) === t ? s : towards(s, t)));
74
+ const moved = out.some((s, i) => s.some((v, end) => v !== given[i][end] && fixed[i][end]));
75
+ return moved ? undefined : out.map(turn);
76
+ };
77
+ const ends = (domain) => typeof domain === 'string'
78
+ ? [false, false]
79
+ : [typeof domain[0] === 'number', typeof domain[1] === 'number'];
80
+ const linearOnly = (o) => {
81
+ if (o.y2?.align !== 'zero' || bare(o))
82
+ return;
83
+ for (const k of ['y', 'y2'])
84
+ if (o[k]?.scale && o[k].scale !== bareScale)
85
+ throw new Error(`y2.align 'zero' needs a linear ${k}, not log(), time() or band()`);
86
+ };
87
+ const checked = (o) => {
88
+ linearOnly(o);
89
+ if (bare(o))
90
+ return;
91
+ for (const k of ['x', 'y', 'y2']) {
92
+ const a = o[k];
93
+ // The scale itself names a domain it cannot take; asked here, update() fails before it commits anything.
94
+ if (a?.scale && a.scale !== bareScale && typeof a.domain !== 'string' && !fixed(a.domain))
95
+ a.scale(a, () => [0, 1]);
96
+ }
97
+ };
98
+ export const clamp = (want, [p, q]) => {
57
99
  if (p <= q)
58
100
  return within(want, [p, q]);
59
101
  const s = within(want && [Math.min(...want), Math.max(...want)], [q, p]);
@@ -64,6 +106,7 @@ const clamp = (want, [p, q]) => {
64
106
  * @param el The element the chart fills.
65
107
  */
66
108
  export function plot(el, options) {
109
+ checked(options);
67
110
  let o = options;
68
111
  const doc = el.ownerDocument;
69
112
  const win = windowOf(el);
@@ -383,6 +426,8 @@ export function plot(el, options) {
383
426
  // With every series hidden an axis keeps the extent it last had.
384
427
  const last = {};
385
428
  const limits = { x: [0, 1], y: [0, 1], y2: [0, 1] };
429
+ // The y spans before zero is aligned, shown whole beside a y or y2 window of its own.
430
+ let plain = { y: [0, 1], y2: [0, 1] };
386
431
  const wholes = {};
387
432
  // A proposal's scan is kept for the display of the same window that follows it.
388
433
  let scanned = {};
@@ -482,7 +527,7 @@ export function plot(el, options) {
482
527
  return lo <= hi ? [lo, hi] : undefined;
483
528
  };
484
529
  const sorted = ([a, b]) => [Math.min(a, b), Math.max(a, b)];
485
- const fitsWindow = (axis) => axis.fit === 'window' && typeof axis.domain === 'string';
530
+ const fitsWindow = (axis) => axis.fit === 'window' && !fixed(axis.domain);
486
531
  const scanOnce = (which, a, b) => {
487
532
  const key = `${a},${b}`;
488
533
  const kept = scanned[which];
@@ -494,22 +539,25 @@ export function plot(el, options) {
494
539
  f.last = scanOnce(which, a, b) ?? f.last;
495
540
  return f.last ?? whole();
496
541
  };
497
- const fitted = (which, room) => {
542
+ const extentOf = (which) => {
498
543
  // Each y axis takes its extent from its own marks.
499
544
  const mine = (k) => which === 'x' || onAxis(k) === which;
500
545
  const cols = (list) => list.flatMap(k => (which === 'x' ? k.channels.x : mine(k) ? k.channels.y : []));
501
- const of = () => axisOf(o, which).fit === 'all'
546
+ return () => axisOf(o, which).fit === 'all'
502
547
  ? (extents[`${which}All`] ??= extent(cols(every())))
503
548
  : (extents[which] ??=
504
549
  visible.some(k => !k.backdrop && mine(k)) || !marks.length
505
550
  ? (last[which] = extent(cols(visible)))
506
551
  : (last[which] ??= extent(cols(every()))));
507
- const whole = (wholes[which] = resolve(axisOf(o, which), of, room));
552
+ };
553
+ const fitted = (which, room, of = extentOf(which), whole = resolve(axisOf(o, which), of, room)) => {
554
+ wholes[which] = whole;
508
555
  limits[which] = [whole.lo, whole.hi];
509
556
  const w = bare(o) ? undefined : clamp(into(which, o.view?.[which]), limits[which]);
510
557
  const f = which === 'x' ? undefined : fits[which];
511
558
  if (f) {
512
559
  f.fitted = false;
560
+ f.given = !!w;
513
561
  f.fit = { of, room };
514
562
  }
515
563
  if (!w) {
@@ -532,6 +580,11 @@ export function plot(el, options) {
532
580
  ticks: ticks.filter(t => t.value >= Math.min(...w) && t.value <= Math.max(...w)),
533
581
  };
534
582
  };
583
+ const zeroAligned = (y, y2, room, given = []) => {
584
+ const both = zeroed(y, y2, ['y', 'y2'].map((k, i) => given[i] ? [true, true] : ends(axisOf(o, k).domain)), given[1] && !given[0] ? 1 : 0);
585
+ return (both &&
586
+ ['y', 'y2'].map((k, i) => resolve({ ...axisOf(o, k), domain: both[i] }, extentOf(k), room)));
587
+ };
535
588
  // Before the first layout the room is judged from the margins as given; after it, from the real
536
589
  // ones, which is what catches a legend or a wide label taking the room away.
537
590
  const rescale = (laidOut) => {
@@ -541,8 +594,35 @@ export function plot(el, options) {
541
594
  ? [W - m.left - m.right, H - m.top - m.bottom]
542
595
  : [W - (g.left ?? 44) - (g.right ?? (has2() ? 44 : 16)), H - (g.top ?? 12) - bottom];
543
596
  xs = fitted('x', { length: w, horizontal: true });
544
- ys = fitted('y', { length: h, horizontal: false });
545
- ys2 = has2() ? fitted('y2', { length: h, horizontal: false }) : undefined;
597
+ const room = { length: h, horizontal: false };
598
+ if (!has2() || o.y2?.align !== 'zero') {
599
+ ys = fitted('y', room);
600
+ ys2 = has2() ? fitted('y2', room) : undefined;
601
+ return;
602
+ }
603
+ const of = { y: extentOf('y'), y2: extentOf('y2') };
604
+ const align = (a, b) => zeroAligned([a.lo, a.hi], [b.lo, b.hi], room) ?? [a, b];
605
+ const raw = { y: resolve(axisOf(o, 'y'), of.y, room), y2: resolve(axisOf(o, 'y2'), of.y2, room) };
606
+ const [y, y2] = align(raw.y, raw.y2);
607
+ ys = fitted('y', room, of.y, y);
608
+ ys2 = fitted('y2', room, of.y2, y2);
609
+ plain = { y: [raw.y.lo, raw.y.hi], y2: [raw.y2.lo, raw.y2.hi] };
610
+ const own = (k, s) => !fits[k].fitted && s !== wholes[k];
611
+ if (own('y', ys) || own('y2', ys2)) {
612
+ if (!fits.y.given && ys === wholes.y)
613
+ ys = raw.y;
614
+ if (!fits.y2.given && ys2 === wholes.y2)
615
+ ys2 = raw.y2;
616
+ }
617
+ else if (ys !== wholes.y || ys2 !== wholes.y2) {
618
+ // An axis shown whole holds still, so the span onViewChange reports for it reads back unchanged.
619
+ const held = [fits.y.given || ys === wholes.y, fits.y2.given || ys2 === wholes.y2];
620
+ const [y, y2] = zeroAligned([ys.lo, ys.hi], [ys2.lo, ys2.hi], room, held) ?? [ys, ys2];
621
+ if (!held[0])
622
+ ys = y;
623
+ if (!held[1])
624
+ ys2 = y2;
625
+ }
546
626
  };
547
627
  // The theme last taken, kept from later writes in place.
548
628
  let taken = { ...(o.theme ?? light) };
@@ -1112,19 +1192,33 @@ export function plot(el, options) {
1112
1192
  return internals.view();
1113
1193
  const next = wanted(loose(linked(asked)));
1114
1194
  const x = clamp(next.x, limits.x) ?? limits.x;
1195
+ const isWhole = (s, k) => s[0] === limits[k][0] && s[1] === limits[k][1];
1115
1196
  const side = (which) => {
1116
1197
  const w = clamp(next[which], limits[which]);
1117
1198
  if (w)
1118
- return [...w];
1119
- const whole = x[0] === limits.x[0] && x[1] === limits.x[1];
1199
+ return { span: [...w], given: true, own: !isWhole(w, which) };
1120
1200
  const f = fits[which];
1121
- if (whole || !f.fit || !fitsWindow(axisOf(o, which)))
1122
- return [...limits[which]];
1201
+ if (isWhole(x, 'x') || !f.fit || !fitsWindow(axisOf(o, which)))
1202
+ return { span: [...limits[which]] };
1123
1203
  const { fit } = f;
1124
1204
  const s = resolve(axisOf(o, which), () => scanOnce(which, ...sorted(x)) ?? f.last ?? fit.of(), fit.room);
1125
- return [s.lo, s.hi];
1205
+ return { span: [s.lo, s.hi], moved: true };
1126
1206
  };
1127
- return { x: [...x], y: side('y'), ...(ys2 && { y2: side('y2') }) };
1207
+ const y = side('y');
1208
+ if (!ys2)
1209
+ return { x: [...x], y: y.span };
1210
+ const y2 = side('y2');
1211
+ if (o.y2?.align === 'zero' && (y.own || y2.own)) {
1212
+ const shown = (s, k) => (s.given || s.moved ? s.span : [...plain[k]]);
1213
+ return { x: [...x], y: shown(y, 'y'), y2: shown(y2, 'y2') };
1214
+ }
1215
+ const again = o.y2?.align === 'zero' && (y.moved || y2.moved)
1216
+ ? zeroAligned(y.span, y2.span, fits.y.fit.room, [!y.moved, !y2.moved])
1217
+ : undefined;
1218
+ if (!again)
1219
+ return { x: [...x], y: y.span, y2: y2.span };
1220
+ const [a, b] = again;
1221
+ return { x: [...x], y: y.moved ? [a.lo, a.hi] : y.span, y2: y2.moved ? [b.lo, b.hi] : y2.span };
1128
1222
  },
1129
1223
  propose(asked) {
1130
1224
  if (bare(o))
@@ -1486,10 +1580,12 @@ export function plot(el, options) {
1486
1580
  o = { ...o, ...partial };
1487
1581
  return;
1488
1582
  }
1583
+ const next = { ...o, ...partial };
1584
+ checked(next);
1489
1585
  if (!keys.length || !keys.every(k => LIGHT.has(k)))
1490
1586
  letGo();
1491
1587
  const prev = o;
1492
- o = { ...o, ...partial };
1588
+ o = next;
1493
1589
  const hid = 'hidden' in partial && !sameIds(partial.hidden, hiddenIds);
1494
1590
  if (hid)
1495
1591
  hiddenIds = [...(partial.hidden ?? [])];
@@ -22,7 +22,7 @@ export declare const linear: (a: YAxisProps | undefined, label: string) => Axis;
22
22
  export declare const dates: (a: XAxisProps | undefined, label: string, utc: boolean) => Axis;
23
23
  export declare const given: (p: object, k: string) => boolean;
24
24
  export declare function noAxes(p: object, name: string): void;
25
- type Kinds<D> = {
25
+ export type Kinds<D> = {
26
26
  line: LineProps<D>;
27
27
  area: AreaProps<D>;
28
28
  bar: BarProps<D>;
@@ -47,7 +47,7 @@ type Later<K extends keyof Kinds<never>> = Omit<EasyChart<never>, 'update'> & {
47
47
  }): void;
48
48
  };
49
49
  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]>;
50
- 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
+ export declare function easyChart<K extends keyof Kinds<never>>(drawn: Build<Supplied<K>>): (<D extends Input | undefined = undefined>(el: HTMLElement, props: Kinds<D>[K]) => ChartOf<K, D>) & {
51
51
  spec: <D extends Input | undefined = undefined>(props: Kinds<D>[K]) => Options;
52
52
  };
53
53
  export {};
@@ -27,6 +27,28 @@ export const install = (f, tip) => [
27
27
  f.zoom && zoom(f.zoom),
28
28
  f.animate && animate(f.animate),
29
29
  ].filter((x) => !!x);
30
+ const blank = (text, backdrop) => ({
31
+ type: 'empty',
32
+ ...(backdrop && { backdrop }),
33
+ key: 'empty',
34
+ color: '',
35
+ options: { text, backdrop },
36
+ points: 0,
37
+ channels: { x: [], y: [] },
38
+ prepare: ({ left, top, width, height }) => ({
39
+ labels: [{ x: left + width / 2, y: top + height / 2, text, priority: Infinity }],
40
+ paint() { },
41
+ }),
42
+ });
43
+ /** Writes `empty` in the frame while no mark but a rule or a zone is drawn. */
44
+ const withEmpty = (build) => (p, context) => {
45
+ const b = build(p, context);
46
+ const { marks } = b.options;
47
+ if (!p.empty || marks.some(m => !m.backdrop))
48
+ return b;
49
+ // Beside rules or zones it is a backdrop, so the axes hold as without it; alone they reset as with no marks.
50
+ return { ...b, options: { ...b.options, marks: [...marks, blank(p.empty, marks.length > 0)] } };
51
+ };
30
52
  export const linear = (a, label) => defined({
31
53
  domain: a?.domain ?? 'nice',
32
54
  label: a?.label ?? label,
@@ -62,7 +84,8 @@ function specOf(build, p) {
62
84
  const given = !theme && b.options.theme === light ? undefined : b.options.theme;
63
85
  return defined({ ...b.options, theme: given, ...passed, use: b.use() });
64
86
  }
65
- export function easyChart(build) {
87
+ export function easyChart(drawn) {
88
+ const build = withEmpty(drawn);
66
89
  return Object.assign((el, props) => create(el, props, build), {
67
90
  spec: (props) => specOf(build, props),
68
91
  });
@@ -1,4 +1,5 @@
1
1
  import { candlestick } from '../marks/candlestick.js';
2
+ import { closed } from '../scale.js';
2
3
  import { band } from '../scales/band.js';
3
4
  import { dates, defined, easyChart, featuresOf, given, install, linear, sizeOf } from './build.js';
4
5
  import { colorsFor, DAY, formatNumber, namesOf, spacing } from './defaults.js';
@@ -49,6 +50,8 @@ function pick(s, p, utc) {
49
50
  };
50
51
  }
51
52
  function xAxis({ kind, label, lone, categories }, a, utc) {
53
+ if (categories || kind !== 'number')
54
+ closed(a?.domain, `${NAME}: xAxis.domain`, categories ? 'categories' : 'dates');
52
55
  if (categories)
53
56
  return band({ label: a?.label ?? label, categories });
54
57
  const shown = lone && !Array.isArray(a?.domain) ? { ...a, domain: lone } : a;
@@ -1,4 +1,4 @@
1
- import type { Theme } from '../theme.js';
1
+ import { type Theme } from '../theme.js';
2
2
  import type { Chart, Feature, Options } from '../types.js';
3
3
  import { type Source } from './source.js';
4
4
  import type { Axes, Base } from './types.js';
@@ -1,5 +1,6 @@
1
1
  import { plot } from '../chart.js';
2
2
  import { equal } from '../equal.js';
3
+ import { light } from '../theme.js';
3
4
  import { themeOf } from './defaults.js';
4
5
  import { source } from './source.js';
5
6
  const STATE = ['view', 'hidden', 'selected', 'pointer'];
@@ -113,8 +114,15 @@ export function create(el, initial, build) {
113
114
  };
114
115
  let theme;
115
116
  const onTheme = (t) => {
116
- theme = t;
117
- apply(props, read);
117
+ if (destroyed)
118
+ return;
119
+ if (t !== theme) {
120
+ theme = t;
121
+ return apply(props, read);
122
+ }
123
+ // An equal copy is how the core is asked to read its CSS variables again; it repaints only if one changed.
124
+ if (live)
125
+ guarded(() => chart.update({ theme: { ...(sent.theme ?? light) } }));
118
126
  };
119
127
  let themed = themeOf(el, props.theme, onTheme);
120
128
  theme = themed.theme;
@@ -136,9 +144,12 @@ export function create(el, initial, build) {
136
144
  let live = true;
137
145
  let held = [];
138
146
  function apply(next, r) {
147
+ guarded(() => change(next, r));
148
+ }
149
+ function guarded(run) {
139
150
  applying = true;
140
151
  try {
141
- change(next, r);
152
+ run();
142
153
  }
143
154
  finally {
144
155
  applying = false;
@@ -12,7 +12,11 @@ export declare function spacing(x: Col, fallback: number): {
12
12
  lone?: Span;
13
13
  };
14
14
  export type ThemeProp = 'auto' | 'light' | 'dark' | Theme | undefined;
15
- /** 'auto' reads the element's computed color-scheme; onChange fires when a 'light dark' page flips. */
15
+ /**
16
+ * 'auto' reads the element's computed color-scheme, then a marker on the page's root, then the system
17
+ * setting. onChange fires, at most once a frame, when the root's or the body's attributes change, whatever
18
+ * the prop, and when the system setting flips.
19
+ */
16
20
  export declare function themeOf(el: Element, prop: ThemeProp, onChange: (theme: Theme) => void): {
17
21
  theme: Theme;
18
22
  dispose(): void;
@@ -92,30 +92,64 @@ export function spacing(x, fallback) {
92
92
  Number.isFinite(at[0]) && { lone: [at[0] - fallback / 2, at[0] + fallback / 2] }),
93
93
  };
94
94
  }
95
- /** 'auto' reads the element's computed color-scheme; onChange fires when a 'light dark' page flips. */
95
+ const MARKERS = ['data-theme', 'data-mantine-color-scheme', 'data-bs-theme', 'data-color-scheme'];
96
+ /** The scheme a page's switch put on its body or root: a class, or one of the attributes kits use. */
97
+ const marked = (doc) => {
98
+ for (const e of [doc.body, doc.documentElement]) {
99
+ const word = (e ? [...MARKERS.map(a => e.getAttribute(a)), ...e.classList] : []).find(w => w === 'dark' || w === 'light');
100
+ if (word)
101
+ return word === 'dark' ? dark : light;
102
+ }
103
+ return undefined;
104
+ };
105
+ /**
106
+ * 'auto' reads the element's computed color-scheme, then a marker on the page's root, then the system
107
+ * setting. onChange fires, at most once a frame, when the root's or the body's attributes change, whatever
108
+ * the prop, and when the system setting flips.
109
+ */
96
110
  export function themeOf(el, prop, onChange) {
97
- const none = () => { };
98
111
  const win = windowOf(el);
99
- if (prop === 'light')
100
- return { theme: light, dispose: none };
101
- if (prop === 'dark')
102
- return { theme: dark, dispose: none };
103
- if (prop !== undefined && prop !== 'auto')
104
- return { theme: prop, dispose: none };
105
- const fixed = () => {
106
- const words = win.getComputedStyle(el).colorScheme.split(/\s+/);
107
- if (!words.includes('dark'))
112
+ const doc = el.ownerDocument;
113
+ let mq;
114
+ const listen = () => onChange(resolve());
115
+ const resolve = () => {
116
+ if (prop === 'light')
108
117
  return light;
109
- return words.includes('light') ? undefined : dark;
118
+ if (prop === 'dark')
119
+ return dark;
120
+ if (prop !== undefined && prop !== 'auto')
121
+ return prop;
122
+ const words = win.getComputedStyle(el).colorScheme.split(/\s+/);
123
+ const [d, l] = [words.includes('dark'), words.includes('light')];
124
+ if (d !== l)
125
+ return d ? dark : light;
126
+ const found = marked(doc);
127
+ if (found || !d)
128
+ return found ?? light;
129
+ if (!mq) {
130
+ mq = win.matchMedia('(prefers-color-scheme: dark)');
131
+ mq.addEventListener('change', listen);
132
+ }
133
+ return mq.matches ? dark : light;
134
+ };
135
+ let frame = 0;
136
+ const watch = new win.MutationObserver(() => {
137
+ frame ||= win.requestAnimationFrame(() => {
138
+ frame = 0;
139
+ listen();
140
+ });
141
+ });
142
+ for (const e of [doc.documentElement, doc.body])
143
+ if (e)
144
+ watch.observe(e, { attributes: true });
145
+ return {
146
+ theme: resolve(),
147
+ dispose: () => {
148
+ watch.disconnect();
149
+ win.cancelAnimationFrame(frame);
150
+ mq?.removeEventListener('change', listen);
151
+ },
110
152
  };
111
- const theme = fixed();
112
- if (theme)
113
- return { theme, dispose: none };
114
- const mq = win.matchMedia('(prefers-color-scheme: dark)');
115
- const resolve = () => fixed() ?? (mq.matches ? dark : light);
116
- const listen = () => onChange(resolve());
117
- mq.addEventListener('change', listen);
118
- return { theme: resolve(), dispose: () => mq.removeEventListener('change', listen) };
119
153
  }
120
154
  export function colorsFor(theme, colors, n) {
121
155
  const list = colors?.length ? colors : theme === dark ? paletteDark : palette;
@@ -1,7 +1,7 @@
1
1
  import { bar } from '../marks/bar.js';
2
2
  import { box } from '../marks/box.js';
3
3
  import { band } from '../scales/band.js';
4
- import { bin, fiveNumbers } from '../transforms.js';
4
+ import { bin, cumulate, fiveNumbers } from '../transforms.js';
5
5
  import { defined, easyChart, featuresOf, given, install, linear, sizeOf } from './build.js';
6
6
  import { colorsFor, formatNumber, namesOf } from './defaults.js';
7
7
  import { reader } from './fields.js';
@@ -42,7 +42,18 @@ const buildHistogram = (p, { source: s, theme, memo }) => {
42
42
  const { bins: by } = p;
43
43
  const picked = memo('fields', [s, p.x, typeof by, ...(typeof by === 'object' ? Array.from(by) : [by])], () => count(s, p.x, by));
44
44
  const features = featuresOf(p, 1);
45
- const text = { picked, x: p.xAxis?.format ?? picked?.edge, y: p.yAxis?.format ?? formatNumber };
45
+ const share = p.cumulative === 'share';
46
+ const running = picked && p.cumulative ? memo('cumulative', [picked], () => cumulate(picked.bins.y2)) : undefined;
47
+ const total = running?.at(-1) || 1;
48
+ const heights = running && share ? memo('share', [running], () => running.map(v => v / total)) : running;
49
+ const text = {
50
+ picked,
51
+ running,
52
+ total,
53
+ share,
54
+ x: p.xAxis?.format ?? picked?.edge,
55
+ y: p.yAxis?.format ?? formatNumber,
56
+ };
46
57
  const ref = memo('tooltip', [], () => ({}));
47
58
  ref.current = text;
48
59
  return {
@@ -50,13 +61,14 @@ const buildHistogram = (p, { source: s, theme, memo }) => {
50
61
  ...sizeOf(p),
51
62
  theme,
52
63
  x: linear(p.xAxis, picked?.label ?? ''),
53
- y: linear(p.yAxis, picked ? 'count' : ''),
64
+ y: linear(p.yAxis, picked ? (running ? `cumulative ${share ? 'share' : 'count'}` : 'count') : ''),
54
65
  marks: picked
55
66
  ? [
56
67
  bar({
57
68
  key: 'histogram',
58
69
  label: 'count',
59
70
  ...picked.bins,
71
+ ...(heights && { y2: heights }),
60
72
  color: colorsFor(theme, p.colors, 1)[0],
61
73
  gap: 1,
62
74
  }),
@@ -69,9 +81,12 @@ const buildHistogram = (p, { source: s, theme, memo }) => {
69
81
  return install(features, {
70
82
  mode: 'nearest',
71
83
  text: (label, _x, v, row) => {
72
- const { picked: shown, x, y } = ref.current;
84
+ const { picked: shown, running: sums, total: all, share: shared, x, y } = ref.current;
73
85
  const { x1, x2 } = shown.bins;
74
- return `${x(x1[row])} – ${x(x2[row])} · ${label}: ${y(v)}`;
86
+ if (!sums)
87
+ return `${x(x1[row])} – ${x(x2[row])} · ${label}: ${y(v)}`;
88
+ const n = sums[row];
89
+ return `${row === x2.length - 1 ? '≤' : '<'} ${x(x2[row])} · ${label}: ${shared ? formatNumber(n) : y(n)}, ${formatNumber((n / all) * 100)}%`;
75
90
  },
76
91
  });
77
92
  },
@@ -61,6 +61,6 @@ function parts(kind, frame, draw) {
61
61
  };
62
62
  }
63
63
  const shown = (text) => (text === false ? undefined : true);
64
- export const pieChart = easyChart(parts('pie', 'polar', (part, p) => arcs(defined({ ...part, inner: p.inner, text: shown(p.text), sweep: p.sweep }))));
64
+ export const pieChart = easyChart(parts('pie', 'polar', (part, p) => arcs(defined({ ...part, inner: p.inner, text: shown(p.text), sweep: p.sweep, center: p.center }))));
65
65
  export const funnelChart = easyChart(parts('funnel', 'blank', (part, p) => funnel(defined({ ...part, text: shown(p.text), fill: p.fill }))));
66
66
  export const radialBarChart = easyChart(parts('radialBar', 'polar', (part, p) => radialBars(defined({ ...part, max: p.max, sweep: p.sweep, inner: p.inner }))));