expressive-charts 0.3.0 → 0.5.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 (46) hide show
  1. package/CHANGELOG.md +73 -1
  2. package/README.md +7 -7
  3. package/dist/define-DeZLs1h7.js +95 -0
  4. package/dist/define-DeZLs1h7.js.map +1 -0
  5. package/dist/drawing-Ypmq-2h6.d.cts +214 -0
  6. package/dist/drawing-Ypmq-2h6.d.ts +214 -0
  7. package/dist/effect-C786hGyJ.d.cts +232 -0
  8. package/dist/effect-CMo-2gPf.d.ts +232 -0
  9. package/dist/expressive-charts.css +5 -2
  10. package/dist/expressive-charts.css.d.cts +1 -2
  11. package/dist/expressive-charts.css.d.ts +1 -2
  12. package/dist/expressive-charts.global.js +47 -48
  13. package/dist/expressive-charts.global.js.map +1 -1
  14. package/dist/icons/sport.cjs +211 -156
  15. package/dist/icons/sport.cjs.map +1 -1
  16. package/dist/icons/sport.d.cts +5 -7
  17. package/dist/icons/sport.d.ts +5 -7
  18. package/dist/icons/sport.js +122 -71
  19. package/dist/icons/sport.js.map +1 -1
  20. package/dist/index.cjs +13203 -9982
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +953 -871
  23. package/dist/index.d.ts +953 -871
  24. package/dist/index.js +11000 -8234
  25. package/dist/index.js.map +1 -1
  26. package/dist/path-data-DnEckjY8.js +123 -0
  27. package/dist/path-data-DnEckjY8.js.map +1 -0
  28. package/dist/testing.cjs +2047 -1255
  29. package/dist/testing.cjs.map +1 -1
  30. package/dist/testing.d.cts +135 -139
  31. package/dist/testing.d.ts +135 -139
  32. package/dist/testing.js +696 -499
  33. package/dist/testing.js.map +1 -1
  34. package/dist/transition-Bu1NsQor.js +2067 -0
  35. package/dist/transition-Bu1NsQor.js.map +1 -0
  36. package/package.json +6 -6
  37. package/dist/chunk-7A7LXXT4.js +0 -70
  38. package/dist/chunk-7A7LXXT4.js.map +0 -1
  39. package/dist/chunk-CJUQHEX6.js +0 -618
  40. package/dist/chunk-CJUQHEX6.js.map +0 -1
  41. package/dist/chunk-N2BLUETM.js +0 -1194
  42. package/dist/chunk-N2BLUETM.js.map +0 -1
  43. package/dist/drawing-CdTgixMY.d.cts +0 -206
  44. package/dist/drawing-CdTgixMY.d.ts +0 -206
  45. package/dist/effect-Bu3MHHeg.d.ts +0 -247
  46. package/dist/effect-D4vmdYP4.d.cts +0 -247
package/dist/testing.cjs CHANGED
@@ -1,1421 +1,2213 @@
1
1
  "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/testing/index.ts
21
- var testing_exports = {};
22
- __export(testing_exports, {
23
- checkEffect: () => checkEffect,
24
- checkTransition: () => checkTransition,
25
- fixturePairs: () => fixturePairs,
26
- fixtures: () => fixtures,
27
- play: () => play,
28
- testContext: () => testContext
29
- });
30
- module.exports = __toCommonJS(testing_exports);
31
-
2
+ Object.defineProperty(exports, "__esModule", { value: true });
32
3
  // src/core/registry.ts
33
4
  function isMarkEffect(value) {
34
- if (typeof value !== "object" || value === null) return false;
35
- const effect = value;
36
- return (effect.kind === "geometry" || effect.kind === "data") && typeof effect.run === "function" && typeof effect.end === "function" && typeof effect.clear === "function";
5
+ if (typeof value !== "object" || value === null) return false;
6
+ const effect = value;
7
+ return (effect.kind === "geometry" || effect.kind === "data") && typeof effect.run === "function" && typeof effect.end === "function" && typeof effect.clear === "function";
37
8
  }
38
9
  function describeValue(value) {
39
- if (typeof value !== "object" || value === null) return value === null ? "null" : typeof value;
40
- const kind = value.kind;
41
- if (kind === "transition") return "a transition effect, which runs between two charts rather than on one mark";
42
- if (kind === "geometry" || kind === "data") return `a ${kind} effect without run(), end() and clear()`;
43
- return kind === void 0 ? "an object with no kind" : `an effect of kind ${JSON.stringify(kind)}`;
10
+ if (typeof value !== "object" || value === null) return value === null ? "null" : typeof value;
11
+ const kind = value.kind;
12
+ if (kind === "transition") return "a transition effect, which runs between two charts rather than on one mark";
13
+ if (kind === "geometry" || kind === "data") return `a ${kind} effect without run(), end() and clear()`;
14
+ return kind === void 0 ? "an object with no kind" : `an effect of kind ${JSON.stringify(kind)}`;
44
15
  }
45
-
46
16
  // src/core/report.ts
47
17
  function report(error) {
48
- const platform = globalThis.reportError;
49
- if (typeof platform === "function") platform(error);
50
- else console.error(error);
18
+ const platform = globalThis.reportError;
19
+ if (typeof platform === "function") platform(error);
20
+ else console.error(error);
51
21
  }
52
-
53
22
  // src/core/clock.ts
54
23
  function createClock(source = browserFrames()) {
55
- const callbacks = /* @__PURE__ */ new Set();
56
- let cancelFrame;
57
- const schedule = () => {
58
- if (!cancelFrame && callbacks.size > 0) cancelFrame = source.request(tick);
59
- };
60
- const tick = (now) => {
61
- cancelFrame = void 0;
62
- for (const callback of [...callbacks]) {
63
- if (!callbacks.has(callback)) continue;
64
- try {
65
- callback(now);
66
- } catch (error) {
67
- report(error);
68
- }
69
- }
70
- schedule();
71
- };
72
- return {
73
- now: () => source.now(),
74
- onFrame(callback) {
75
- const entry = (now) => callback(now);
76
- callbacks.add(entry);
77
- schedule();
78
- return () => {
79
- if (!callbacks.delete(entry)) return;
80
- if (callbacks.size === 0 && cancelFrame) {
81
- cancelFrame();
82
- cancelFrame = void 0;
83
- }
84
- };
85
- }
86
- };
24
+ const callbacks = /* @__PURE__ */ new Set();
25
+ let cancelFrame;
26
+ const schedule = () => {
27
+ if (!cancelFrame && callbacks.size > 0) cancelFrame = source.request(tick);
28
+ };
29
+ const tick = (now) => {
30
+ cancelFrame = void 0;
31
+ for (const callback of [...callbacks]) {
32
+ if (!callbacks.has(callback)) continue;
33
+ try {
34
+ callback(now);
35
+ } catch (error) {
36
+ report(error);
37
+ }
38
+ }
39
+ schedule();
40
+ };
41
+ return {
42
+ now: () => source.now(),
43
+ onFrame(callback) {
44
+ const entry = (now) => callback(now);
45
+ callbacks.add(entry);
46
+ schedule();
47
+ return () => {
48
+ if (!callbacks.delete(entry)) return;
49
+ if (callbacks.size === 0 && cancelFrame) {
50
+ cancelFrame();
51
+ cancelFrame = void 0;
52
+ }
53
+ };
54
+ }
55
+ };
87
56
  }
88
57
  function manualClock(start = 0) {
89
- let time = start;
90
- let pending;
91
- const clock = createClock({
92
- now: () => time,
93
- request(callback) {
94
- pending = callback;
95
- return () => {
96
- if (pending === callback) pending = void 0;
97
- };
98
- }
99
- });
100
- return {
101
- now: clock.now,
102
- onFrame: clock.onFrame,
103
- get idle() {
104
- return pending === void 0;
105
- },
106
- advance(ms) {
107
- if (!(ms >= 0)) throw new RangeError(`manualClock.advance needs a non-negative number of ms, got ${ms}`);
108
- time += ms;
109
- const callback = pending;
110
- pending = void 0;
111
- callback?.(time);
112
- }
113
- };
58
+ let time = start;
59
+ let pending;
60
+ const clock = createClock({
61
+ now: () => time,
62
+ request(callback) {
63
+ pending = callback;
64
+ return () => {
65
+ if (pending === callback) pending = void 0;
66
+ };
67
+ }
68
+ });
69
+ return {
70
+ now: clock.now,
71
+ onFrame: clock.onFrame,
72
+ get idle() {
73
+ return pending === void 0;
74
+ },
75
+ advance(ms) {
76
+ if (!(ms >= 0)) throw new RangeError(`manualClock.advance needs a non-negative number of ms, got ${ms}`);
77
+ time += ms;
78
+ const callback = pending;
79
+ pending = void 0;
80
+ callback?.(time);
81
+ }
82
+ };
114
83
  }
115
84
  function browserFrames() {
116
- const now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
117
- return {
118
- now,
119
- request(callback) {
120
- if (typeof requestAnimationFrame === "function") {
121
- const id2 = requestAnimationFrame(callback);
122
- return () => cancelAnimationFrame(id2);
123
- }
124
- const id = setTimeout(() => callback(now()), 16);
125
- return () => clearTimeout(id);
126
- }
127
- };
128
- }
129
- var defaultClock = /* @__PURE__ */ createClock();
130
-
85
+ const now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
86
+ return {
87
+ now,
88
+ request(callback) {
89
+ if (typeof requestAnimationFrame === "function") {
90
+ const id = requestAnimationFrame(callback);
91
+ return () => cancelAnimationFrame(id);
92
+ }
93
+ const id = setTimeout(() => callback(now()), 16);
94
+ return () => clearTimeout(id);
95
+ }
96
+ };
97
+ }
98
+ const defaultClock = /* @__PURE__ */ createClock();
131
99
  // src/core/motion.ts
132
- var defaultScaling = {
133
- presentation: {
134
- feedback: { factor: 1 },
135
- transition: { factor: 1 },
136
- effect: { factor: 1 },
137
- playback: { factor: 1 },
138
- stagger: { factor: 1 }
139
- },
140
- analysis: {
141
- feedback: { factor: 1 },
142
- transition: { factor: 0.35, max: 200 },
143
- effect: { factor: 0.35, min: 140, max: 300 },
144
- playback: { factor: 0.3 },
145
- // Analysis has no staging, so marks don't wait for each other.
146
- stagger: { factor: 0 }
147
- }
100
+ const defaultScaling = {
101
+ presentation: {
102
+ feedback: { factor: 1 },
103
+ transition: { factor: 1 },
104
+ effect: { factor: 1 },
105
+ playback: { factor: 1 },
106
+ stagger: { factor: 1 }
107
+ },
108
+ analysis: {
109
+ feedback: { factor: 1 },
110
+ transition: {
111
+ factor: .35,
112
+ max: 200
113
+ },
114
+ effect: {
115
+ factor: .35,
116
+ min: 140,
117
+ max: 300
118
+ },
119
+ playback: { factor: .3 },
120
+ stagger: { factor: 0 }
121
+ }
148
122
  };
149
- var MODES = ["presentation", "analysis", "off"];
150
- var TIMINGS = ["feedback", "transition", "effect", "playback", "stagger"];
123
+ const MODES = [
124
+ "presentation",
125
+ "analysis",
126
+ "off"
127
+ ];
128
+ const TIMINGS = [
129
+ "feedback",
130
+ "transition",
131
+ "effect",
132
+ "playback",
133
+ "stagger"
134
+ ];
151
135
  function createMotion(options = {}) {
152
- let requested = checkMode(options.mode ?? "presentation");
153
- let viewerChoice;
154
- const scaling = mergeScaling(options.scaling);
155
- const reduced = options.reducedMotion ?? mediaReducedMotion();
156
- const listeners = /* @__PURE__ */ new Set();
157
- let stopWatching;
158
- const effective = () => viewerChoice ?? (reduced.matches ? "off" : requested);
159
- const notify = () => {
160
- for (const listener of [...listeners]) {
161
- if (!listeners.has(listener)) continue;
162
- try {
163
- listener();
164
- } catch (error) {
165
- report(error);
166
- }
167
- }
168
- };
169
- return {
170
- get mode() {
171
- return effective();
172
- },
173
- get staged() {
174
- return effective() === "presentation";
175
- },
176
- get requested() {
177
- return requested;
178
- },
179
- get viewerChoice() {
180
- return viewerChoice;
181
- },
182
- get prefersReduced() {
183
- return reduced.matches;
184
- },
185
- duration(base, timing = "transition") {
186
- const mode = effective();
187
- return mode === "off" ? 0 : scaleDuration(base, scaling[mode][timing]);
188
- },
189
- setMode(mode) {
190
- checkMode(mode);
191
- if (mode === requested) return;
192
- requested = mode;
193
- notify();
194
- },
195
- chooseMode(mode) {
196
- checkMode(mode);
197
- if (mode === viewerChoice) return;
198
- viewerChoice = mode;
199
- notify();
200
- },
201
- clearChoice() {
202
- if (viewerChoice === void 0) return;
203
- viewerChoice = void 0;
204
- notify();
205
- },
206
- subscribe(listener) {
207
- const entry = () => listener();
208
- listeners.add(entry);
209
- stopWatching ?? (stopWatching = reduced.subscribe(notify));
210
- return () => {
211
- if (!listeners.delete(entry) || listeners.size > 0) return;
212
- stopWatching?.();
213
- stopWatching = void 0;
214
- };
215
- }
216
- };
136
+ let requested = checkMode(options.mode ?? "presentation");
137
+ let viewerChoice;
138
+ const scaling = mergeScaling(options.scaling);
139
+ const reduced = options.reducedMotion ?? mediaReducedMotion();
140
+ const listeners = /* @__PURE__ */ new Set();
141
+ let stopWatching;
142
+ const effective = () => viewerChoice ?? (reduced.matches ? "off" : requested);
143
+ const notify = () => {
144
+ for (const listener of [...listeners]) {
145
+ if (!listeners.has(listener)) continue;
146
+ try {
147
+ listener();
148
+ } catch (error) {
149
+ report(error);
150
+ }
151
+ }
152
+ };
153
+ return {
154
+ get mode() {
155
+ return effective();
156
+ },
157
+ get staged() {
158
+ return effective() === "presentation";
159
+ },
160
+ get requested() {
161
+ return requested;
162
+ },
163
+ get viewerChoice() {
164
+ return viewerChoice;
165
+ },
166
+ get prefersReduced() {
167
+ return reduced.matches;
168
+ },
169
+ duration(base, timing = "transition") {
170
+ const mode = effective();
171
+ return mode === "off" ? 0 : scaleDuration(base, scaling[mode][timing]);
172
+ },
173
+ setMode(mode) {
174
+ checkMode(mode);
175
+ if (mode === requested) return;
176
+ requested = mode;
177
+ notify();
178
+ },
179
+ chooseMode(mode) {
180
+ checkMode(mode);
181
+ if (mode === viewerChoice) return;
182
+ viewerChoice = mode;
183
+ notify();
184
+ },
185
+ clearChoice() {
186
+ if (viewerChoice === void 0) return;
187
+ viewerChoice = void 0;
188
+ notify();
189
+ },
190
+ subscribe(listener) {
191
+ const entry = () => listener();
192
+ listeners.add(entry);
193
+ stopWatching ?? (stopWatching = reduced.subscribe(notify));
194
+ return () => {
195
+ if (!listeners.delete(entry) || listeners.size > 0) return;
196
+ stopWatching?.();
197
+ stopWatching = void 0;
198
+ };
199
+ }
200
+ };
217
201
  }
218
202
  function scaleDuration(base, rule) {
219
- if (!(base > 0)) return 0;
220
- const floor = Math.min(base, rule.min ?? 0);
221
- const ceiling = rule.max ?? Infinity;
222
- return Math.min(Math.max(base * rule.factor, floor), ceiling);
203
+ if (!(base > 0)) return 0;
204
+ const floor = Math.min(base, rule.min ?? 0);
205
+ const ceiling = rule.max ?? Infinity;
206
+ return Math.min(Math.max(base * rule.factor, floor), ceiling);
223
207
  }
224
208
  function mediaReducedMotion(query = "(prefers-reduced-motion: reduce)") {
225
- let list2;
226
- const lookup = () => {
227
- if (list2 === void 0) {
228
- try {
229
- list2 = typeof matchMedia === "function" ? matchMedia(query) : null;
230
- } catch {
231
- list2 = null;
232
- }
233
- }
234
- return list2;
235
- };
236
- return {
237
- get matches() {
238
- return lookup()?.matches ?? false;
239
- },
240
- subscribe(listener) {
241
- const media = lookup();
242
- if (!media) return () => {
243
- };
244
- const onChange = () => listener();
245
- if (typeof media.addEventListener === "function") {
246
- media.addEventListener("change", onChange);
247
- return () => media.removeEventListener("change", onChange);
248
- }
249
- media.addListener(onChange);
250
- return () => media.removeListener(onChange);
251
- }
252
- };
209
+ let list;
210
+ const lookup = () => {
211
+ if (list === void 0) try {
212
+ list = typeof matchMedia === "function" ? matchMedia(query) : null;
213
+ } catch {
214
+ list = null;
215
+ }
216
+ return list;
217
+ };
218
+ return {
219
+ get matches() {
220
+ return lookup()?.matches ?? false;
221
+ },
222
+ subscribe(listener) {
223
+ const media = lookup();
224
+ if (!media) return () => {};
225
+ const onChange = () => listener();
226
+ if (typeof media.addEventListener === "function") {
227
+ media.addEventListener("change", onChange);
228
+ return () => media.removeEventListener("change", onChange);
229
+ }
230
+ media.addListener(onChange);
231
+ return () => media.removeListener(onChange);
232
+ }
233
+ };
253
234
  }
254
235
  function checkMode(mode) {
255
- if (!MODES.includes(mode)) {
256
- throw new TypeError(`Unknown motion mode "${String(mode)}". Use one of: ${MODES.join(", ")}.`);
257
- }
258
- return mode;
236
+ if (!MODES.includes(mode)) throw new TypeError(`Unknown motion mode "${String(mode)}". Use one of: ${MODES.join(", ")}.`);
237
+ return mode;
259
238
  }
260
239
  function mergeScaling(overrides = {}) {
261
- const merge = (mode) => {
262
- const table = { ...defaultScaling[mode] };
263
- for (const timing of TIMINGS) {
264
- const rule = overrides[mode]?.[timing];
265
- if (rule) table[timing] = rule;
266
- }
267
- return table;
268
- };
269
- return { presentation: merge("presentation"), analysis: merge("analysis") };
270
- }
271
- var motion = /* @__PURE__ */ createMotion();
272
-
240
+ const merge = (mode) => {
241
+ const table = { ...defaultScaling[mode] };
242
+ for (const timing of TIMINGS) {
243
+ const rule = overrides[mode]?.[timing];
244
+ if (rule) table[timing] = rule;
245
+ }
246
+ return table;
247
+ };
248
+ return {
249
+ presentation: merge("presentation"),
250
+ analysis: merge("analysis")
251
+ };
252
+ }
253
+ const motion = /* @__PURE__ */ createMotion();
273
254
  // src/core/merge.ts
274
255
  function mergeFields(current, next) {
275
- const result = { ...current };
276
- for (const [field, value] of Object.entries(next ?? {})) {
277
- if (value === void 0) delete result[field];
278
- else result[field] = value;
279
- }
280
- return result;
256
+ const result = { ...current };
257
+ for (const [field, value] of Object.entries(next ?? {})) if (value === void 0) delete result[field];
258
+ else result[field] = value;
259
+ return result;
281
260
  }
282
-
283
261
  // src/core/easing.ts
284
- var easeInOutCubic = (t) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
285
-
262
+ const easeInOutCubic = (t) => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
286
263
  // src/core/tween.ts
287
264
  function tween(options, env = {}) {
288
- const clock = env.clock ?? defaultClock;
289
- const view = env.motion ?? motion;
290
- const timing = options.timing ?? "transition";
291
- const ease = options.ease ?? easeInOutCubic;
292
- const duration = view.duration(options.duration, timing);
293
- const delay = options.delay ? view.duration(options.delay, timing) : 0;
294
- const { update, signal } = options;
295
- const start = clock.now();
296
- let state = "running";
297
- let unsubscribe;
298
- let resolve;
299
- const finished = new Promise((r) => {
300
- resolve = r;
301
- });
302
- const settle2 = (result) => {
303
- state = result;
304
- unsubscribe?.();
305
- unsubscribe = void 0;
306
- signal?.removeEventListener("abort", cancel);
307
- resolve(result);
308
- };
309
- function cancel() {
310
- if (state === "running") settle2("cancelled");
311
- }
312
- let finishing = false;
313
- function finish2() {
314
- if (state !== "running" || finishing) return;
315
- finishing = true;
316
- step(1);
317
- if (state === "running") settle2("done");
318
- }
319
- function step(progress) {
320
- try {
321
- update(ease(progress));
322
- } catch (error) {
323
- cancel();
324
- throw error;
325
- }
326
- }
327
- const onFrame = (now) => {
328
- if (view.mode === "off") {
329
- finish2();
330
- return;
331
- }
332
- const elapsed = now - start - delay;
333
- if (elapsed >= duration) finish2();
334
- else if (elapsed > 0) step(elapsed / duration);
335
- };
336
- const handle = {
337
- finished,
338
- get state() {
339
- return state;
340
- },
341
- cancel,
342
- finish: finish2
343
- };
344
- if (signal?.aborted) {
345
- settle2("cancelled");
346
- return handle;
347
- }
348
- signal?.addEventListener("abort", cancel, { once: true });
349
- if (duration <= 0 && delay <= 0) {
350
- finish2();
351
- return handle;
352
- }
353
- step(0);
354
- if (state === "running") unsubscribe = clock.onFrame(onFrame);
355
- return handle;
265
+ const clock = env.clock ?? defaultClock;
266
+ const view = env.motion ?? motion;
267
+ const timing = options.timing ?? "transition";
268
+ const ease = options.ease ?? easeInOutCubic;
269
+ const duration = view.duration(options.duration, timing);
270
+ const delay = options.delay ? view.duration(options.delay, timing) : 0;
271
+ const { update, signal } = options;
272
+ const start = clock.now();
273
+ let state = "running";
274
+ let unsubscribe;
275
+ let resolve;
276
+ const finished = new Promise((r) => {
277
+ resolve = r;
278
+ });
279
+ const settle = (result) => {
280
+ state = result;
281
+ unsubscribe?.();
282
+ unsubscribe = void 0;
283
+ signal?.removeEventListener("abort", cancel);
284
+ resolve(result);
285
+ };
286
+ function cancel() {
287
+ if (state === "running") settle("cancelled");
288
+ }
289
+ let finishing = false;
290
+ function finish() {
291
+ if (state !== "running" || finishing) return;
292
+ finishing = true;
293
+ step(1);
294
+ if (state === "running") settle("done");
295
+ }
296
+ function step(progress) {
297
+ try {
298
+ update(ease(progress));
299
+ } catch (error) {
300
+ cancel();
301
+ throw error;
302
+ }
303
+ }
304
+ const onFrame = (now) => {
305
+ if (view.mode === "off") {
306
+ finish();
307
+ return;
308
+ }
309
+ const elapsed = now - start - delay;
310
+ if (elapsed >= duration) finish();
311
+ else if (elapsed > 0) step(elapsed / duration);
312
+ };
313
+ const handle = {
314
+ finished,
315
+ get state() {
316
+ return state;
317
+ },
318
+ cancel,
319
+ finish
320
+ };
321
+ if (signal?.aborted) {
322
+ settle("cancelled");
323
+ return handle;
324
+ }
325
+ signal?.addEventListener("abort", cancel, { once: true });
326
+ if (duration <= 0 && delay <= 0) {
327
+ finish();
328
+ return handle;
329
+ }
330
+ step(0);
331
+ if (state === "running") unsubscribe = clock.onFrame(onFrame);
332
+ return handle;
356
333
  }
357
-
358
334
  // src/core/runner.ts
359
335
  function runScope(options) {
360
- const { clock, motion: motion2, layer, mark } = options;
361
- const controller = new AbortController();
362
- let listeners = [];
363
- const context = {
364
- signal: controller.signal,
365
- motion: motion2,
366
- mark,
367
- layer,
368
- icons: options.icons,
369
- batch: options.batch,
370
- ...options.previous ? { previous: options.previous } : {},
371
- tween(tweenOptions) {
372
- const own = tweenOptions.signal;
373
- const running = tween({ ...tweenOptions, signal: own ?? controller.signal }, { clock, motion: motion2 });
374
- if (own && own !== controller.signal) {
375
- if (controller.signal.aborted) running.cancel();
376
- else controller.signal.addEventListener("abort", () => running.cancel(), { once: true });
377
- }
378
- return running;
379
- },
380
- onChange(listener) {
381
- listeners.push(listener);
382
- }
383
- };
384
- return {
385
- context,
386
- abort() {
387
- controller.abort();
388
- },
389
- change(geometry, data) {
390
- for (const listener of [...listeners]) listener(geometry, data);
391
- },
392
- clear() {
393
- controller.abort();
394
- layer.clear();
395
- mark.reset();
396
- listeners = [];
397
- }
398
- };
336
+ const { clock, motion, layer, mark } = options;
337
+ const controller = new AbortController();
338
+ let listeners = [];
339
+ return {
340
+ context: {
341
+ signal: controller.signal,
342
+ motion,
343
+ mark,
344
+ layer,
345
+ icons: options.icons,
346
+ batch: options.batch,
347
+ ...options.previous ? { previous: options.previous } : {},
348
+ tween(tweenOptions) {
349
+ const own = tweenOptions.signal;
350
+ const running = tween({
351
+ ...tweenOptions,
352
+ signal: own ?? controller.signal
353
+ }, {
354
+ clock,
355
+ motion
356
+ });
357
+ if (own && own !== controller.signal) {
358
+ if (controller.signal.aborted) running.cancel();
359
+ else controller.signal.addEventListener("abort", () => running.cancel(), { once: true });
360
+ }
361
+ return running;
362
+ },
363
+ onChange(listener) {
364
+ listeners.push(listener);
365
+ }
366
+ },
367
+ abort() {
368
+ controller.abort();
369
+ },
370
+ change(geometry, data) {
371
+ for (const listener of [...listeners]) listener(geometry, data);
372
+ },
373
+ clear() {
374
+ controller.abort();
375
+ layer.clear();
376
+ mark.reset();
377
+ listeners = [];
378
+ }
379
+ };
399
380
  }
400
-
401
381
  // src/core/testing/recording.ts
402
382
  function recordingLayer() {
403
- const drawn = /* @__PURE__ */ new Map();
404
- const calls = [];
405
- let nextId = 1;
406
- const replace = (id, next) => {
407
- const current = drawn.get(id);
408
- if (current) drawn.set(id, next(current));
409
- };
410
- const remove = (id) => {
411
- calls.push({ op: "remove", id });
412
- drawn.delete(id);
413
- };
414
- return {
415
- get drawn() {
416
- return [...drawn.values()];
417
- },
418
- get calls() {
419
- return calls;
420
- },
421
- icon(icon, options) {
422
- const id = nextId++;
423
- const size2 = options?.size;
424
- calls.push({ op: "icon", id, icon: icon.name, size: size2 });
425
- drawn.set(id, { kind: "icon", id, icon, size: size2, transform: void 0 });
426
- const handle = {
427
- place(transform) {
428
- calls.push({ op: "place", id, transform });
429
- replace(id, (current) => ({ ...current, transform }));
430
- },
431
- remove: () => remove(id)
432
- };
433
- return handle;
434
- },
435
- path(d, paint) {
436
- const id = nextId++;
437
- calls.push({ op: "path", id, d, paint });
438
- drawn.set(id, { kind: "path", id, d, paint: { ...paint } });
439
- const handle = {
440
- update(nextD, nextPaint) {
441
- calls.push({ op: "update-path", id, d: nextD, paint: nextPaint });
442
- replace(id, (current) => {
443
- const path = current;
444
- return { ...path, d: nextD, paint: mergeFields(path.paint, nextPaint) };
445
- });
446
- },
447
- remove: () => remove(id)
448
- };
449
- return handle;
450
- },
451
- text(content, style) {
452
- const id = nextId++;
453
- calls.push({ op: "text", id, content, style });
454
- drawn.set(id, { kind: "text", id, content, style: { ...style } });
455
- const handle = {
456
- update(nextStyle, nextContent) {
457
- calls.push({ op: "update-text", id, style: nextStyle, content: nextContent });
458
- replace(id, (current) => {
459
- const text = current;
460
- return { ...text, style: mergeFields(text.style, nextStyle), content: nextContent ?? text.content };
461
- });
462
- },
463
- remove: () => remove(id)
464
- };
465
- return handle;
466
- },
467
- picture(decimals = 3) {
468
- const round = rounder(decimals);
469
- return [...drawn.values()].map((item) => {
470
- switch (item.kind) {
471
- case "icon":
472
- return { kind: "icon", icon: item.icon.name, size: item.size, transform: item.transform?.map(round) };
473
- case "path":
474
- return { kind: "path", d: item.d, paint: roundFields(item.paint, round) };
475
- case "text":
476
- return { kind: "text", content: item.content, style: { ...roundFields(item.style, round), at: { x: round(item.style.at.x), y: round(item.style.at.y) } } };
477
- }
478
- });
479
- },
480
- clear() {
481
- calls.push({ op: "clear" });
482
- drawn.clear();
483
- }
484
- };
383
+ const drawn = /* @__PURE__ */ new Map();
384
+ const calls = [];
385
+ let nextId = 1;
386
+ const replace = (id, next) => {
387
+ const current = drawn.get(id);
388
+ if (current) drawn.set(id, next(current));
389
+ };
390
+ const remove = (id) => {
391
+ calls.push({
392
+ op: "remove",
393
+ id
394
+ });
395
+ drawn.delete(id);
396
+ };
397
+ return {
398
+ get drawn() {
399
+ return [...drawn.values()];
400
+ },
401
+ get calls() {
402
+ return calls;
403
+ },
404
+ icon(icon, options) {
405
+ const id = nextId++;
406
+ const size = options?.size;
407
+ calls.push({
408
+ op: "icon",
409
+ id,
410
+ icon: icon.name,
411
+ size
412
+ });
413
+ drawn.set(id, {
414
+ kind: "icon",
415
+ id,
416
+ icon,
417
+ size,
418
+ transform: void 0
419
+ });
420
+ return {
421
+ place(transform) {
422
+ calls.push({
423
+ op: "place",
424
+ id,
425
+ transform
426
+ });
427
+ replace(id, (current) => ({
428
+ ...current,
429
+ transform
430
+ }));
431
+ },
432
+ remove: () => remove(id)
433
+ };
434
+ },
435
+ path(d, paint) {
436
+ const id = nextId++;
437
+ calls.push({
438
+ op: "path",
439
+ id,
440
+ d,
441
+ paint
442
+ });
443
+ drawn.set(id, {
444
+ kind: "path",
445
+ id,
446
+ d,
447
+ paint: { ...paint }
448
+ });
449
+ return {
450
+ update(nextD, nextPaint) {
451
+ calls.push({
452
+ op: "update-path",
453
+ id,
454
+ d: nextD,
455
+ paint: nextPaint
456
+ });
457
+ replace(id, (current) => {
458
+ const path = current;
459
+ return {
460
+ ...path,
461
+ d: nextD,
462
+ paint: mergeFields(path.paint, nextPaint)
463
+ };
464
+ });
465
+ },
466
+ remove: () => remove(id)
467
+ };
468
+ },
469
+ text(content, style) {
470
+ const id = nextId++;
471
+ calls.push({
472
+ op: "text",
473
+ id,
474
+ content,
475
+ style
476
+ });
477
+ drawn.set(id, {
478
+ kind: "text",
479
+ id,
480
+ content,
481
+ style: { ...style }
482
+ });
483
+ return {
484
+ update(nextStyle, nextContent) {
485
+ calls.push({
486
+ op: "update-text",
487
+ id,
488
+ style: nextStyle,
489
+ content: nextContent
490
+ });
491
+ replace(id, (current) => {
492
+ const text = current;
493
+ return {
494
+ ...text,
495
+ style: mergeFields(text.style, nextStyle),
496
+ content: nextContent ?? text.content
497
+ };
498
+ });
499
+ },
500
+ remove: () => remove(id)
501
+ };
502
+ },
503
+ picture(decimals = 3) {
504
+ const round = rounder(decimals);
505
+ return [...drawn.values()].map((item) => {
506
+ switch (item.kind) {
507
+ case "icon": return {
508
+ kind: "icon",
509
+ icon: item.icon.name,
510
+ size: item.size,
511
+ transform: item.transform?.map(round)
512
+ };
513
+ case "path": return {
514
+ kind: "path",
515
+ d: item.d,
516
+ paint: roundFields(item.paint, round)
517
+ };
518
+ case "text": return {
519
+ kind: "text",
520
+ content: item.content,
521
+ style: {
522
+ ...roundFields(item.style, round),
523
+ at: {
524
+ x: round(item.style.at.x),
525
+ y: round(item.style.at.y)
526
+ }
527
+ }
528
+ };
529
+ }
530
+ });
531
+ },
532
+ clear() {
533
+ calls.push({ op: "clear" });
534
+ drawn.clear();
535
+ }
536
+ };
485
537
  }
486
538
  function recordingMark() {
487
- let style = {};
488
- const calls = [];
489
- return {
490
- get style() {
491
- return style;
492
- },
493
- get calls() {
494
- return calls;
495
- },
496
- set(next) {
497
- calls.push({ op: "set", style: next });
498
- style = mergeFields(style, next);
499
- },
500
- reset() {
501
- calls.push({ op: "reset" });
502
- style = {};
503
- }
504
- };
539
+ let style = {};
540
+ const calls = [];
541
+ return {
542
+ get style() {
543
+ return style;
544
+ },
545
+ get calls() {
546
+ return calls;
547
+ },
548
+ set(next) {
549
+ calls.push({
550
+ op: "set",
551
+ style: next
552
+ });
553
+ style = mergeFields(style, next);
554
+ },
555
+ reset() {
556
+ calls.push({ op: "reset" });
557
+ style = {};
558
+ }
559
+ };
505
560
  }
506
561
  function rounder(decimals) {
507
- const factor = 10 ** decimals;
508
- return (value) => {
509
- const rounded2 = Math.round(value * factor) / factor;
510
- return rounded2 === 0 ? 0 : rounded2;
511
- };
562
+ const factor = 10 ** decimals;
563
+ return (value) => {
564
+ const rounded = Math.round(value * factor) / factor;
565
+ return rounded === 0 ? 0 : rounded;
566
+ };
512
567
  }
513
568
  function roundFields(fields, round) {
514
- const result = {};
515
- for (const [field, value] of Object.entries(fields)) result[field] = typeof value === "number" ? round(value) : value;
516
- return result;
569
+ const result = {};
570
+ for (const [field, value] of Object.entries(fields)) result[field] = typeof value === "number" ? round(value) : value;
571
+ return result;
517
572
  }
518
-
519
573
  // src/core/testing/context.ts
520
574
  function testContext(options = {}) {
521
- const clock = manualClock();
522
- const motion2 = createMotion({
523
- mode: options.mode ?? "presentation",
524
- ...options.scaling ? { scaling: options.scaling } : {},
525
- reducedMotion: { matches: false, subscribe: () => () => {
526
- } }
527
- });
528
- const layer = recordingLayer();
529
- const mark = recordingMark();
530
- const icons = new Map((options.icons ?? []).map((icon) => [icon.name, icon]));
531
- const scope = runScope({
532
- clock,
533
- motion: motion2,
534
- layer,
535
- mark,
536
- icons: { get: (name) => icons.get(name) },
537
- batch: options.batch ?? { index: 0, count: 1 },
538
- previous: options.previous
539
- });
540
- return {
541
- ...scope.context,
542
- motion: motion2,
543
- clock,
544
- layer,
545
- mark,
546
- abort: scope.abort,
547
- clear: scope.clear,
548
- change: scope.change
549
- };
575
+ const clock = manualClock();
576
+ const motion = createMotion({
577
+ mode: options.mode ?? "presentation",
578
+ ...options.scaling ? { scaling: options.scaling } : {},
579
+ reducedMotion: {
580
+ matches: false,
581
+ subscribe: () => () => {}
582
+ }
583
+ });
584
+ const layer = recordingLayer();
585
+ const mark = recordingMark();
586
+ const icons = new Map((options.icons ?? []).map((icon) => [icon.name, icon]));
587
+ const scope = runScope({
588
+ clock,
589
+ motion,
590
+ layer,
591
+ mark,
592
+ icons: { get: (name) => icons.get(name) },
593
+ batch: options.batch ?? {
594
+ index: 0,
595
+ count: 1
596
+ },
597
+ previous: options.previous
598
+ });
599
+ return {
600
+ ...scope.context,
601
+ motion,
602
+ clock,
603
+ layer,
604
+ mark,
605
+ abort: scope.abort,
606
+ clear: scope.clear,
607
+ change: scope.change
608
+ };
550
609
  }
551
-
552
610
  // src/core/testing/play.ts
553
611
  async function play(clock, running, options = {}) {
554
- const frame2 = options.frame ?? 16;
555
- const limit = options.limit ?? 1e4;
556
- let settled = false;
557
- running.then(
558
- () => settled = true,
559
- () => settled = true
560
- );
561
- let elapsed = 0;
562
- await flush();
563
- while (!settled) {
564
- if (elapsed >= limit) throw new Error(`play: still running after ${limit} ms.`);
565
- clock.advance(frame2);
566
- elapsed += frame2;
567
- await flush();
568
- }
569
- return elapsed;
612
+ const frame = options.frame ?? 16;
613
+ const limit = options.limit ?? 1e4;
614
+ let settled = false;
615
+ running.then(() => settled = true, () => settled = true);
616
+ let elapsed = 0;
617
+ await flush();
618
+ while (!settled) {
619
+ if (elapsed >= limit) throw new Error(`play: still running after ${limit} ms.`);
620
+ clock.advance(frame);
621
+ elapsed += frame;
622
+ await flush();
623
+ }
624
+ return elapsed;
570
625
  }
571
626
  async function flush() {
572
- for (let i = 0; i < 20; i++) await Promise.resolve();
627
+ for (let i = 0; i < 20; i++) await Promise.resolve();
573
628
  }
574
-
575
629
  // src/core/transition.ts
576
630
  function isTransitionEffect(value) {
577
- if (typeof value !== "object" || value === null) return false;
578
- const effect = value;
579
- return effect.kind === "transition" && typeof effect.run === "function" && typeof effect.end === "function" && typeof effect.clear === "function";
631
+ if (typeof value !== "object" || value === null) return false;
632
+ const effect = value;
633
+ return effect.kind === "transition" && typeof effect.run === "function" && typeof effect.end === "function" && typeof effect.clear === "function";
580
634
  }
581
-
582
635
  // src/core/geometry/segment.ts
583
- var TAU = 2 * Math.PI;
636
+ const TAU = 2 * Math.PI;
584
637
  function line(from, to, fallbackAngle = 0) {
585
- const dx = to.x - from.x;
586
- const dy = to.y - from.y;
587
- const length = Math.hypot(dx, dy);
588
- return { kind: "line", from, to, length, angle: length > 0 ? Math.atan2(dy, dx) : normalizeAngle(fallbackAngle) };
638
+ const dx = to.x - from.x;
639
+ const dy = to.y - from.y;
640
+ const length = Math.hypot(dx, dy);
641
+ return {
642
+ kind: "line",
643
+ from,
644
+ to,
645
+ length,
646
+ angle: length > 0 ? Math.atan2(dy, dx) : normalizeAngle(fallbackAngle)
647
+ };
589
648
  }
590
649
  function arc(center, radius, start, sweep) {
591
- return { kind: "arc", center, radius, start, sweep, length: radius * Math.abs(sweep) };
650
+ return {
651
+ kind: "arc",
652
+ center,
653
+ radius,
654
+ start,
655
+ sweep,
656
+ length: radius * Math.abs(sweep)
657
+ };
592
658
  }
593
659
  function pointOn(segment, u) {
594
- if (segment.kind === "line") {
595
- const { from, to } = segment;
596
- return { x: from.x * (1 - u) + to.x * u, y: from.y * (1 - u) + to.y * u };
597
- }
598
- return polar(segment.center, segment.radius, segment.start + segment.sweep * u);
660
+ if (segment.kind === "line") {
661
+ const { from, to } = segment;
662
+ return {
663
+ x: from.x * (1 - u) + to.x * u,
664
+ y: from.y * (1 - u) + to.y * u
665
+ };
666
+ }
667
+ return polar(segment.center, segment.radius, segment.start + segment.sweep * u);
599
668
  }
600
669
  function angleOn(segment, u) {
601
- if (segment.kind === "line") return segment.angle;
602
- const quarter = segment.sweep < 0 ? -Math.PI / 2 : Math.PI / 2;
603
- return normalizeAngle(segment.start + segment.sweep * u + quarter);
670
+ if (segment.kind === "line") return segment.angle;
671
+ const quarter = segment.sweep < 0 ? -Math.PI / 2 : Math.PI / 2;
672
+ return normalizeAngle(segment.start + segment.sweep * u + quarter);
604
673
  }
605
674
  function polar(center, radius, angle) {
606
- return { x: center.x + radius * Math.cos(angle), y: center.y + radius * Math.sin(angle) };
675
+ return {
676
+ x: center.x + radius * Math.cos(angle),
677
+ y: center.y + radius * Math.sin(angle)
678
+ };
607
679
  }
608
680
  function normalizeAngle(angle) {
609
- return angle - TAU * Math.ceil((angle - Math.PI) / TAU);
681
+ return angle - TAU * Math.ceil((angle - Math.PI) / TAU);
610
682
  }
611
683
  function extremes(segment) {
612
- if (segment.kind === "line") return [segment.from, segment.to];
613
- const points = [pointOn(segment, 0), pointOn(segment, 1)];
614
- for (let k = 0; k < 4; k++) {
615
- const angle = k * Math.PI / 2;
616
- if (sweeps(segment, angle)) points.push(polar(segment.center, segment.radius, angle));
617
- }
618
- return points;
684
+ if (segment.kind === "line") return [segment.from, segment.to];
685
+ const points = [pointOn(segment, 0), pointOn(segment, 1)];
686
+ for (let k = 0; k < 4; k++) {
687
+ const angle = k * Math.PI / 2;
688
+ if (sweeps(segment, angle)) points.push(polar(segment.center, segment.radius, angle));
689
+ }
690
+ return points;
619
691
  }
620
692
  function boundsOf(points) {
621
- let minX = Infinity;
622
- let minY = Infinity;
623
- let maxX = -Infinity;
624
- let maxY = -Infinity;
625
- for (const { x, y } of points) {
626
- if (x < minX) minX = x;
627
- if (x > maxX) maxX = x;
628
- if (y < minY) minY = y;
629
- if (y > maxY) maxY = y;
630
- }
631
- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
693
+ let minX = Infinity;
694
+ let minY = Infinity;
695
+ let maxX = -Infinity;
696
+ let maxY = -Infinity;
697
+ for (const { x, y } of points) {
698
+ if (x < minX) minX = x;
699
+ if (x > maxX) maxX = x;
700
+ if (y < minY) minY = y;
701
+ if (y > maxY) maxY = y;
702
+ }
703
+ return {
704
+ x: minX,
705
+ y: minY,
706
+ width: maxX - minX,
707
+ height: maxY - minY
708
+ };
632
709
  }
633
710
  function sweeps(segment, angle) {
634
- const extent = Math.abs(segment.sweep);
635
- if (extent >= TAU) return true;
636
- const turned = segment.sweep >= 0 ? angle - segment.start : segment.start - angle;
637
- return (turned % TAU + TAU) % TAU <= extent;
711
+ const extent = Math.abs(segment.sweep);
712
+ if (extent >= TAU) return true;
713
+ return ((segment.sweep >= 0 ? angle - segment.start : segment.start - angle) % TAU + TAU) % TAU <= extent;
638
714
  }
639
-
640
715
  // src/core/geometry/path-data.ts
641
716
  function formatNumber(value) {
642
- const rounded2 = Math.round(value * 1e3) / 1e3;
643
- return rounded2 === 0 ? "0" : String(rounded2);
717
+ const rounded = Math.round(value * 1e3) / 1e3;
718
+ return rounded === 0 ? "0" : String(rounded);
644
719
  }
645
720
  function moveTo(point) {
646
- return `M${formatNumber(point.x)},${formatNumber(point.y)}`;
721
+ return `M${formatNumber(point.x)},${formatNumber(point.y)}`;
647
722
  }
648
723
  function drawTo(segment, u0 = 0, u1 = 1) {
649
- if (segment.kind === "line") {
650
- const p = u1 === 1 ? segment.to : pointOn(segment, u1);
651
- return `L${formatNumber(p.x)},${formatNumber(p.y)}`;
652
- }
653
- const from = segment.start + segment.sweep * u0;
654
- const turn = segment.sweep * (u1 - u0);
655
- const pieces = Math.max(1, Math.ceil(Math.abs(turn) / Math.PI - 1e-9));
656
- const r = formatNumber(segment.radius);
657
- const clockwise = turn >= 0 ? 1 : 0;
658
- let d = "";
659
- for (let i = 1; i <= pieces; i++) {
660
- const p = polar(segment.center, segment.radius, from + turn * i / pieces);
661
- d += `A${r},${r} 0 0 ${clockwise} ${formatNumber(p.x)},${formatNumber(p.y)}`;
662
- }
663
- return d;
724
+ if (segment.kind === "line") {
725
+ const p = u1 === 1 ? segment.to : pointOn(segment, u1);
726
+ return `L${formatNumber(p.x)},${formatNumber(p.y)}`;
727
+ }
728
+ const from = segment.start + segment.sweep * u0;
729
+ const turn = segment.sweep * (u1 - u0);
730
+ const pieces = Math.max(1, Math.ceil(Math.abs(turn) / Math.PI - 1e-9));
731
+ const r = formatNumber(segment.radius);
732
+ const clockwise = turn >= 0 ? 1 : 0;
733
+ let d = "";
734
+ for (let i = 1; i <= pieces; i++) {
735
+ const p = polar(segment.center, segment.radius, from + turn * i / pieces);
736
+ d += `A${r},${r} 0 0 ${clockwise} ${formatNumber(p.x)},${formatNumber(p.y)}`;
737
+ }
738
+ return d;
664
739
  }
665
740
  function pathData(segments, closed = false) {
666
- const first = segments[0];
667
- if (!first) return "";
668
- let count = segments.length;
669
- if (closed) {
670
- while (count > 0 && segments[count - 1].length <= 0) count--;
671
- if (count > 0 && segments[count - 1].kind === "line") count--;
672
- }
673
- let d = moveTo(pointOn(first, 0));
674
- for (let i = 0; i < count; i++) {
675
- const segment = segments[i];
676
- if (segment.length > 0) d += drawTo(segment);
677
- }
678
- return closed ? `${d}Z` : d;
741
+ const first = segments[0];
742
+ if (!first) return "";
743
+ let count = segments.length;
744
+ if (closed) {
745
+ while (count > 0 && segments[count - 1].length <= 0) count--;
746
+ if (count > 0 && segments[count - 1].kind === "line") count--;
747
+ }
748
+ let d = moveTo(pointOn(first, 0));
749
+ for (let i = 0; i < count; i++) {
750
+ const segment = segments[i];
751
+ if (segment.length > 0) d += drawTo(segment);
752
+ }
753
+ return closed ? `${d}Z` : d;
679
754
  }
680
-
681
755
  // src/core/geometry/walk.ts
682
- var clamp01 = (t) => t > 0 ? t < 1 ? t : 1 : 0;
683
- var NONE = Object.freeze([]);
756
+ const clamp01 = (t) => t > 0 ? t < 1 ? t : 1 : 0;
757
+ const NONE = /* @__PURE__ */ Object.freeze([]);
684
758
  function createWalk(segments, gaps = NONE) {
685
- const first = segments[0];
686
- const last = segments[segments.length - 1];
687
- if (!first || !last) throw new RangeError("A walk needs at least one segment.");
688
- const cumulative = [0];
689
- for (const segment of segments) cumulative.push(cumulative[cumulative.length - 1] + segment.length);
690
- const length = cumulative[segments.length];
691
- const start = pointOn(first, 0);
692
- const end = pointOn(last, 1);
693
- const locate = (d) => {
694
- if (!(length > 0)) return { index: 0, u: 0 };
695
- if (d >= length) {
696
- let index = segments.length - 1;
697
- while (index > 0 && !(segments[index].length > 0)) index--;
698
- return { index, u: 1 };
699
- }
700
- let lo = 0;
701
- let hi = segments.length - 1;
702
- while (lo < hi) {
703
- const mid = lo + hi >> 1;
704
- if (cumulative[mid + 1] > d) hi = mid;
705
- else lo = mid + 1;
706
- }
707
- return { index: lo, u: Math.min(1, (d - cumulative[lo]) / segments[lo].length) };
708
- };
709
- const point = (t) => {
710
- const at = clamp01(t);
711
- if (at === 0) return start;
712
- if (at === 1) return end;
713
- const { index, u } = locate(at * length);
714
- return pointOn(segments[index], u);
715
- };
716
- const draw = (from, to) => {
717
- let d = moveTo(point(from));
718
- const a = from * length;
719
- const b = to * length;
720
- if (!(b > a)) return d;
721
- const first2 = locate(a);
722
- for (let i = first2.index; i < segments.length && cumulative[i] < b; i++) {
723
- const segment = segments[i];
724
- if (!(segment.length > 0)) continue;
725
- const u0 = i === first2.index ? first2.u : 0;
726
- const u1 = cumulative[i + 1] > b ? Math.min(1, (b - cumulative[i]) / segment.length) : 1;
727
- if (u1 > u0) d += drawTo(segment, u0, u1);
728
- }
729
- return d;
730
- };
731
- const slice = (t0, t1) => {
732
- const from = clamp01(Math.min(t0, t1));
733
- const to = clamp01(Math.max(t0, t1));
734
- if (gaps.length === 0) return draw(from, to);
735
- let d = "";
736
- let at = from;
737
- for (const [a, b] of gaps) {
738
- if (a >= to) break;
739
- if (a > at) d += draw(at, a);
740
- if (b > at) at = b;
741
- }
742
- if (to > at) d += draw(at, to);
743
- return d === "" ? moveTo(point(from)) : d;
744
- };
745
- return {
746
- segments,
747
- length,
748
- start,
749
- end,
750
- gaps,
751
- point,
752
- angle(t) {
753
- const { index, u } = locate(clamp01(t) * length);
754
- return angleOn(segments[index], u);
755
- },
756
- slice,
757
- d: gaps.length === 0 ? pathData(segments) : slice(0, 1)
758
- };
759
+ const first = segments[0];
760
+ const last = segments[segments.length - 1];
761
+ if (!first || !last) throw new RangeError("A walk needs at least one segment.");
762
+ const cumulative = [0];
763
+ for (const segment of segments) cumulative.push(cumulative[cumulative.length - 1] + segment.length);
764
+ const length = cumulative[segments.length];
765
+ const start = pointOn(first, 0);
766
+ const end = pointOn(last, 1);
767
+ const locate = (d) => {
768
+ if (!(length > 0)) return {
769
+ index: 0,
770
+ u: 0
771
+ };
772
+ if (d >= length) {
773
+ let index = segments.length - 1;
774
+ while (index > 0 && !(segments[index].length > 0)) index--;
775
+ return {
776
+ index,
777
+ u: 1
778
+ };
779
+ }
780
+ let lo = 0;
781
+ let hi = segments.length - 1;
782
+ while (lo < hi) {
783
+ const mid = lo + hi >> 1;
784
+ if (cumulative[mid + 1] > d) hi = mid;
785
+ else lo = mid + 1;
786
+ }
787
+ return {
788
+ index: lo,
789
+ u: Math.min(1, (d - cumulative[lo]) / segments[lo].length)
790
+ };
791
+ };
792
+ const point = (t) => {
793
+ const at = clamp01(t);
794
+ if (at === 0) return start;
795
+ if (at === 1) return end;
796
+ const { index, u } = locate(at * length);
797
+ return pointOn(segments[index], u);
798
+ };
799
+ const draw = (from, to) => {
800
+ let d = moveTo(point(from));
801
+ const a = from * length;
802
+ const b = to * length;
803
+ if (!(b > a)) return d;
804
+ const first = locate(a);
805
+ for (let i = first.index; i < segments.length && cumulative[i] < b; i++) {
806
+ const segment = segments[i];
807
+ if (!(segment.length > 0)) continue;
808
+ const u0 = i === first.index ? first.u : 0;
809
+ const u1 = cumulative[i + 1] > b ? Math.min(1, (b - cumulative[i]) / segment.length) : 1;
810
+ if (u1 > u0) d += drawTo(segment, u0, u1);
811
+ }
812
+ return d;
813
+ };
814
+ const slice = (t0, t1) => {
815
+ const from = clamp01(Math.min(t0, t1));
816
+ const to = clamp01(Math.max(t0, t1));
817
+ if (gaps.length === 0) return draw(from, to);
818
+ let d = "";
819
+ let at = from;
820
+ for (const [a, b] of gaps) {
821
+ if (a >= to) break;
822
+ if (a > at) d += draw(at, a);
823
+ if (b > at) at = b;
824
+ }
825
+ if (to > at) d += draw(at, to);
826
+ return d === "" ? moveTo(point(from)) : d;
827
+ };
828
+ return {
829
+ segments,
830
+ length,
831
+ start,
832
+ end,
833
+ gaps,
834
+ point,
835
+ angle(t) {
836
+ const { index, u } = locate(clamp01(t) * length);
837
+ return angleOn(segments[index], u);
838
+ },
839
+ slice,
840
+ d: gaps.length === 0 ? pathData(segments) : slice(0, 1)
841
+ };
759
842
  }
760
-
761
843
  // src/core/geometry/outline.ts
762
844
  function closedOutline(sides) {
763
- const walks = sides.map((side) => createWalk(side));
764
- return {
765
- d: pathData(sides.flat(), true),
766
- closed: true,
767
- sample(n) {
768
- checkCount(n, 4);
769
- const perSide = n / 4;
770
- const points = [];
771
- for (const walk of walks) {
772
- for (let j = 0; j < perSide; j++) points.push(walk.point(j / perSide));
773
- }
774
- return points;
775
- }
776
- };
777
- }
845
+ const walks = sides.map((side) => createWalk(side));
846
+ return {
847
+ d: pathData(sides.flat(), true),
848
+ closed: true,
849
+ sample(n) {
850
+ checkCount(n, 4);
851
+ const perSide = n / 4;
852
+ const points = [];
853
+ for (const walk of walks) for (let j = 0; j < perSide; j++) points.push(walk.point(j / perSide));
854
+ return points;
855
+ }
856
+ };
857
+ }
858
+ function loopOutline(loops) {
859
+ const lengths = loops.map((loop) => loop.reduce((sum, segment) => sum + segment.length, 0));
860
+ let longest = 0;
861
+ lengths.forEach((length, i) => {
862
+ if (length > lengths[longest]) longest = i;
863
+ });
864
+ const turn = area(loops[longest]) < 0;
865
+ const clockwise = loops.map((loop) => turn ? reversed(loop) : loop);
866
+ const ring = fromUpperLeft(clockwise[longest]);
867
+ const walk = createWalk(ring);
868
+ return {
869
+ d: [ring, ...clockwise.filter((_, i) => i !== longest)].map((loop) => pathData(loop, true)).join(""),
870
+ closed: true,
871
+ sample(n) {
872
+ checkCount(n, 4);
873
+ const perSide = n / 4;
874
+ const points = [];
875
+ for (let side = 0; side < 4; side++) for (let j = 0; j < perSide; j++) points.push(walk.point(side / 4 + j / perSide / 4));
876
+ return points;
877
+ }
878
+ };
879
+ }
880
+ function area(loop) {
881
+ let sum = 0;
882
+ for (const segment of loop) {
883
+ if (segment.kind === "line") {
884
+ sum += segment.from.x * segment.to.y - segment.to.x * segment.from.y;
885
+ continue;
886
+ }
887
+ const { center, radius, start, sweep } = segment;
888
+ const end = start + sweep;
889
+ sum += radius * (center.x * (Math.sin(end) - Math.sin(start)) - center.y * (Math.cos(end) - Math.cos(start))) + radius * radius * sweep;
890
+ }
891
+ return sum / 2;
892
+ }
893
+ function reversed(loop) {
894
+ return loop.map((segment) => segment.kind === "line" ? line(segment.to, segment.from) : arc(segment.center, segment.radius, segment.start + segment.sweep, -segment.sweep)).reverse();
895
+ }
896
+ function fromUpperLeft(loop) {
897
+ let index = 0;
898
+ let u = 0;
899
+ let key = Infinity;
900
+ let top = Infinity;
901
+ const consider = (point, i, at) => {
902
+ const k = point.x + point.y;
903
+ if (k < key - 1e-9 || k <= key + 1e-9 && point.y < top) [index, u, key, top] = [
904
+ i,
905
+ at,
906
+ k,
907
+ point.y
908
+ ];
909
+ };
910
+ loop.forEach((segment, i) => {
911
+ consider(pointOn(segment, 0), i, 0);
912
+ if (segment.kind === "arc") {
913
+ const at = ((segment.sweep >= 0 ? UPPER_LEFT - segment.start : segment.start - UPPER_LEFT) % TAU + TAU) % TAU / Math.abs(segment.sweep);
914
+ if (at < 1) consider(pointOn(segment, at), i, at);
915
+ }
916
+ });
917
+ const [before, after] = split(loop[index], u);
918
+ return [
919
+ after,
920
+ ...loop.slice(index + 1),
921
+ ...loop.slice(0, index),
922
+ before
923
+ ].filter((segment) => segment.length > 0);
924
+ }
925
+ function split(segment, u) {
926
+ if (segment.kind === "line") {
927
+ const at = pointOn(segment, u);
928
+ return [line(segment.from, at), line(at, segment.to)];
929
+ }
930
+ const { center, radius, start, sweep } = segment;
931
+ return [arc(center, radius, start, sweep * u), arc(center, radius, start + sweep * u, sweep * (1 - u))];
932
+ }
933
+ const UPPER_LEFT = -3 * Math.PI / 4;
778
934
  function openOutline(walk) {
779
- return {
780
- d: walk.d,
781
- closed: false,
782
- sample(n) {
783
- checkCount(n, 1);
784
- if (n === 1) return [walk.start];
785
- const points = [];
786
- for (let j = 0; j < n; j++) points.push(walk.point(j / (n - 1)));
787
- return points;
788
- }
789
- };
935
+ return {
936
+ d: walk.d,
937
+ closed: false,
938
+ sample(n) {
939
+ checkCount(n, 1);
940
+ if (n === 1) return [walk.start];
941
+ const points = [];
942
+ for (let j = 0; j < n; j++) points.push(walk.point(j / (n - 1)));
943
+ return points;
944
+ }
945
+ };
790
946
  }
791
947
  function checkCount(n, multiple) {
792
- if (!Number.isInteger(n) || n < 0 || n % multiple !== 0) {
793
- const what = multiple === 1 ? "a whole number \u2265 0" : `a whole multiple of ${multiple}`;
794
- throw new RangeError(`outline.sample(n): n must be ${what}, got ${n}.`);
795
- }
948
+ if (!Number.isInteger(n) || n < 0 || n % multiple !== 0) {
949
+ const what = multiple === 1 ? "a whole number ≥ 0" : `a whole multiple of ${multiple}`;
950
+ throw new RangeError(`outline.sample(n): n must be ${what}, got ${n}.`);
951
+ }
796
952
  }
797
-
798
953
  // src/core/geometry/describe/mark.ts
799
- function assemble({ key, series, walk, thickness, outline, bounds, center, pivot, labelBounds, segments }) {
800
- return {
801
- key,
802
- ...series === void 0 ? {} : { series },
803
- start: walk.start,
804
- end: walk.end,
805
- length: walk.length,
806
- path: (t) => walk.point(t),
807
- angle: (t) => walk.angle(t),
808
- slice: (t0, t1) => walk.slice(t0, t1),
809
- ...walk.gaps.length === 0 ? {} : { gaps: walk.gaps },
810
- thickness,
811
- outline,
812
- bounds,
813
- center,
814
- pivot,
815
- ...labelBounds === void 0 ? {} : { labelBounds },
816
- ...segments === void 0 ? {} : { segments }
817
- };
954
+ function assemble({ key, series, walk, thickness, outline, bounds, center, pivot, labelBounds, nearbyLabels, segments }) {
955
+ return {
956
+ key,
957
+ ...series === void 0 ? {} : { series },
958
+ start: walk.start,
959
+ end: walk.end,
960
+ length: walk.length,
961
+ path: (t) => walk.point(t),
962
+ angle: (t) => walk.angle(t),
963
+ slice: (t0, t1) => walk.slice(t0, t1),
964
+ ...walk.gaps.length === 0 ? {} : { gaps: walk.gaps },
965
+ thickness,
966
+ outline,
967
+ bounds,
968
+ center,
969
+ pivot,
970
+ ...labelBounds === void 0 ? {} : { labelBounds },
971
+ ...nearbyLabels === void 0 ? {} : { nearbyLabels },
972
+ ...segments === void 0 ? {} : { segments }
973
+ };
818
974
  }
819
975
  function finite(builder, field, value) {
820
- if (!Number.isFinite(value)) throw new RangeError(`describe.${builder}: ${field} must be a finite number, got ${value}.`);
821
- return value;
822
- }
823
- function labelBoxes(builder, boxes) {
824
- if (!boxes) return boxes;
825
- for (let i = 0; i < boxes.length; i++) {
826
- const { x, y, width, height } = boxes[i];
827
- if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(width) && width >= 0 && Number.isFinite(height) && height >= 0) continue;
828
- finite(builder, `labelBounds[${i}].x`, x);
829
- finite(builder, `labelBounds[${i}].y`, y);
830
- size(builder, `labelBounds[${i}].width`, width);
831
- size(builder, `labelBounds[${i}].height`, height);
832
- }
833
- return boxes;
976
+ if (!Number.isFinite(value)) throw new RangeError(`describe.${builder}: ${field} must be a finite number, got ${value}.`);
977
+ return value;
978
+ }
979
+ function labelBoxes(builder, boxes, field = "labelBounds") {
980
+ if (!boxes) return boxes;
981
+ for (let i = 0; i < boxes.length; i++) {
982
+ const { x, y, width, height } = boxes[i];
983
+ if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(width) && width >= 0 && Number.isFinite(height) && height >= 0) continue;
984
+ finite(builder, `${field}[${i}].x`, x);
985
+ finite(builder, `${field}[${i}].y`, y);
986
+ size(builder, `${field}[${i}].width`, width);
987
+ size(builder, `${field}[${i}].height`, height);
988
+ }
989
+ return boxes;
834
990
  }
835
991
  function size(builder, field, value) {
836
- if (!(Number.isFinite(value) && value >= 0)) {
837
- throw new RangeError(`describe.${builder}: ${field} must be a finite number \u2265 0, got ${value}.`);
838
- }
839
- return value;
992
+ if (!(Number.isFinite(value) && value >= 0)) throw new RangeError(`describe.${builder}: ${field} must be a finite number ≥ 0, got ${value}.`);
993
+ return value;
840
994
  }
841
-
842
995
  // src/core/geometry/describe/arc.ts
843
996
  function describeArc(spec) {
844
- const { key, series } = spec;
845
- const center = { x: finite("arc", "cx", spec.cx), y: finite("arc", "cy", spec.cy) };
846
- const r0 = Math.min(size("arc", "inner", spec.inner), size("arc", "outer", spec.outer));
847
- const r1 = Math.max(spec.inner, spec.outer);
848
- finite("arc", "start", spec.start);
849
- finite("arc", "end", spec.end);
850
- const sweep = Math.max(-TAU, Math.min(TAU, spec.end - spec.start));
851
- const from = spec.start - Math.PI / 2;
852
- const to = from + sweep;
853
- const [left, right] = sweep >= 0 ? [r1, r0] : [r0, r1];
854
- const sides = [
855
- [arc(center, left, from, sweep)],
856
- [line(polar(center, left, to), polar(center, right, to), to + (left > right ? Math.PI : 0))],
857
- [arc(center, right, to, -sweep)],
858
- [line(polar(center, right, from), polar(center, left, from), from + (left > right ? 0 : Math.PI))]
859
- ];
860
- const walk = createWalk([arc(center, (r0 + r1) / 2, from, sweep)]);
861
- return assemble({
862
- key,
863
- series,
864
- walk,
865
- thickness: r1 - r0,
866
- outline: closedOutline(sides),
867
- bounds: boundsOf(sides.flat().flatMap(extremes)),
868
- center: walk.point(0.5),
869
- pivot: center,
870
- labelBounds: labelBoxes("arc", spec.labelBounds)
871
- });
997
+ const { key, series } = spec;
998
+ const center = {
999
+ x: finite("arc", "cx", spec.cx),
1000
+ y: finite("arc", "cy", spec.cy)
1001
+ };
1002
+ const r0 = Math.min(size("arc", "inner", spec.inner), size("arc", "outer", spec.outer));
1003
+ const r1 = Math.max(spec.inner, spec.outer);
1004
+ finite("arc", "start", spec.start);
1005
+ finite("arc", "end", spec.end);
1006
+ const sweep = Math.max(-TAU, Math.min(TAU, spec.end - spec.start));
1007
+ const from = spec.start - Math.PI / 2;
1008
+ const to = from + sweep;
1009
+ const [left, right] = sweep >= 0 ? [r1, r0] : [r0, r1];
1010
+ const sides = [
1011
+ [arc(center, left, from, sweep)],
1012
+ [line(polar(center, left, to), polar(center, right, to), to + (left > right ? Math.PI : 0))],
1013
+ [arc(center, right, to, -sweep)],
1014
+ [line(polar(center, right, from), polar(center, left, from), from + (left > right ? 0 : Math.PI))]
1015
+ ];
1016
+ const walk = createWalk([arc(center, (r0 + r1) / 2, from, sweep)]);
1017
+ return assemble({
1018
+ key,
1019
+ series,
1020
+ walk,
1021
+ thickness: r1 - r0,
1022
+ outline: closedOutline(sides),
1023
+ bounds: boundsOf(sides.flat().flatMap(extremes)),
1024
+ center: walk.point(.5),
1025
+ pivot: center,
1026
+ labelBounds: labelBoxes("arc", spec.labelBounds),
1027
+ nearbyLabels: labelBoxes("arc", spec.nearbyLabels, "nearbyLabels")
1028
+ });
872
1029
  }
873
-
874
1030
  // src/core/geometry/describe/bar.ts
875
- var ANGLE = { left: 0, right: Math.PI, top: Math.PI / 2, bottom: -Math.PI / 2 };
1031
+ const ANGLE = {
1032
+ left: 0,
1033
+ right: Math.PI,
1034
+ top: Math.PI / 2,
1035
+ bottom: -Math.PI / 2
1036
+ };
876
1037
  function describeBar(spec) {
877
- const { key, series, baseline, x, y, width, height } = spec;
878
- if (!Object.prototype.hasOwnProperty.call(ANGLE, baseline)) {
879
- throw new RangeError(`describe.bar: baseline must be left, right, top or bottom, got ${String(baseline)}.`);
880
- }
881
- finite("bar", "x", x);
882
- finite("bar", "y", y);
883
- size("bar", "width", width);
884
- size("bar", "height", height);
885
- const radius = size("bar", "radius", spec.radius ?? 0);
886
- const gap = size("bar", "gap", spec.gap ?? 0);
887
- const labelBounds = labelBoxes("bar", spec.labelBounds);
888
- const horizontal = baseline === "left" || baseline === "right";
889
- const length = horizontal ? width : height;
890
- const thickness = horizontal ? height : width;
891
- const T = thickness;
892
- const angle = ANGLE[baseline];
893
- const at = frame(spec);
894
- const part = (p0, p1, tip, rest) => {
895
- const rr = Math.max(0, Math.min(tip, p1 - p0, T / 2));
896
- const outline = closedOutline([
897
- [line(at(p0, 0), at(p1 - rr, 0), angle)],
898
- rr > 0 ? [
899
- arc(at(p1 - rr, rr), rr, angle - Math.PI / 2, Math.PI / 2),
900
- line(at(p1, rr), at(p1, T - rr), angle + Math.PI / 2),
901
- arc(at(p1 - rr, T - rr), rr, angle, Math.PI / 2)
902
- ] : [line(at(p1, 0), at(p1, T), angle + Math.PI / 2)],
903
- [line(at(p1 - rr, T), at(p0, T), angle + Math.PI)],
904
- [line(at(p0, T), at(p0, 0), angle - Math.PI / 2)]
905
- ]);
906
- const walk = createWalk([line(at(p0, T / 2), at(p1, T / 2), angle)]);
907
- return assemble({
908
- ...rest,
909
- walk,
910
- thickness,
911
- outline,
912
- bounds: rest.bounds ?? boundsOf([at(p0, 0), at(p1, T)]),
913
- center: at((p0 + p1) / 2, T / 2),
914
- pivot: walk.start
915
- });
916
- };
917
- const specs = spec.segments ?? [{ series, size: length }];
918
- const seen = /* @__PURE__ */ new Set();
919
- let cursor = 0;
920
- const spans = specs.map((segment, index) => {
921
- size("bar", `segments[${index}].size`, segment.size);
922
- if (segment.series !== void 0) {
923
- if (seen.has(segment.series)) throw new Error(`describe.bar: series "${segment.series}" appears twice in the segments of "${key}".`);
924
- seen.add(segment.series);
925
- }
926
- const from = Math.min(cursor, length);
927
- cursor += segment.size;
928
- const to = Math.min(cursor, length);
929
- return { segment, index, p0: Math.min(from + Math.min(gap, from), to), p1: to };
930
- });
931
- const segments = spans.map(
932
- ({ segment, index, p0, p1 }) => (
933
- // The rounding fades in as a segment nears the tip, so a growing stack never pops.
934
- part(p0, p1, radius - (length - p1), {
935
- key: segment.series === void 0 ? `${key}/${index}` : `${key}/${segment.series}`,
936
- series: segment.series
937
- })
938
- )
939
- );
940
- return part(0, length, radius, { key, series, bounds: { x, y, width, height }, labelBounds, segments });
1038
+ const { key, series, baseline, x, y, width, height } = spec;
1039
+ if (!Object.prototype.hasOwnProperty.call(ANGLE, baseline)) throw new RangeError(`describe.bar: baseline must be left, right, top or bottom, got ${String(baseline)}.`);
1040
+ finite("bar", "x", x);
1041
+ finite("bar", "y", y);
1042
+ size("bar", "width", width);
1043
+ size("bar", "height", height);
1044
+ const radius = size("bar", "radius", spec.radius ?? 0);
1045
+ const gap = size("bar", "gap", spec.gap ?? 0);
1046
+ const labelBounds = labelBoxes("bar", spec.labelBounds);
1047
+ const nearbyLabels = labelBoxes("bar", spec.nearbyLabels, "nearbyLabels");
1048
+ const horizontal = baseline === "left" || baseline === "right";
1049
+ const length = horizontal ? width : height;
1050
+ const thickness = horizontal ? height : width;
1051
+ const T = thickness;
1052
+ const angle = ANGLE[baseline];
1053
+ const at = frame(spec);
1054
+ const part = (p0, p1, tip, rest) => {
1055
+ const rr = Math.max(0, Math.min(tip, p1 - p0, T / 2));
1056
+ const outline = closedOutline([
1057
+ [line(at(p0, 0), at(p1 - rr, 0), angle)],
1058
+ rr > 0 ? [
1059
+ arc(at(p1 - rr, rr), rr, angle - Math.PI / 2, Math.PI / 2),
1060
+ line(at(p1, rr), at(p1, T - rr), angle + Math.PI / 2),
1061
+ arc(at(p1 - rr, T - rr), rr, angle, Math.PI / 2)
1062
+ ] : [line(at(p1, 0), at(p1, T), angle + Math.PI / 2)],
1063
+ [line(at(p1 - rr, T), at(p0, T), angle + Math.PI)],
1064
+ [line(at(p0, T), at(p0, 0), angle - Math.PI / 2)]
1065
+ ]);
1066
+ const walk = createWalk([line(at(p0, T / 2), at(p1, T / 2), angle)]);
1067
+ return assemble({
1068
+ ...rest,
1069
+ walk,
1070
+ thickness,
1071
+ outline,
1072
+ bounds: rest.bounds ?? boundsOf([at(p0, 0), at(p1, T)]),
1073
+ center: at((p0 + p1) / 2, T / 2),
1074
+ pivot: walk.start
1075
+ });
1076
+ };
1077
+ const specs = spec.segments ?? [{
1078
+ series,
1079
+ size: length
1080
+ }];
1081
+ const seen = /* @__PURE__ */ new Set();
1082
+ let cursor = 0;
1083
+ const segments = specs.map((segment, index) => {
1084
+ size("bar", `segments[${index}].size`, segment.size);
1085
+ if (segment.series !== void 0) {
1086
+ if (seen.has(segment.series)) throw new Error(`describe.bar: series "${segment.series}" appears twice in the segments of "${key}".`);
1087
+ seen.add(segment.series);
1088
+ }
1089
+ const from = Math.min(cursor, length);
1090
+ cursor += segment.size;
1091
+ const to = Math.min(cursor, length);
1092
+ return {
1093
+ segment,
1094
+ index,
1095
+ p0: Math.min(from + Math.min(gap, from), to),
1096
+ p1: to
1097
+ };
1098
+ }).map(({ segment, index, p0, p1 }) => part(p0, p1, radius - (length - p1), {
1099
+ key: segment.series === void 0 ? `${key}/${index}` : `${key}/${segment.series}`,
1100
+ series: segment.series
1101
+ }));
1102
+ return part(0, length, radius, {
1103
+ key,
1104
+ series,
1105
+ bounds: {
1106
+ x,
1107
+ y,
1108
+ width,
1109
+ height
1110
+ },
1111
+ labelBounds,
1112
+ nearbyLabels,
1113
+ segments
1114
+ });
941
1115
  }
942
1116
  function frame({ x, y, width: w, height: h, baseline }) {
943
- switch (baseline) {
944
- case "left":
945
- return (p, s) => ({ x: x + p, y: y + s });
946
- case "right":
947
- return (p, s) => ({ x: x + w - p, y: y + h - s });
948
- case "top":
949
- return (p, s) => ({ x: x + w - s, y: y + p });
950
- case "bottom":
951
- return (p, s) => ({ x: x + s, y: y + h - p });
952
- }
1117
+ switch (baseline) {
1118
+ case "left": return (p, s) => ({
1119
+ x: x + p,
1120
+ y: y + s
1121
+ });
1122
+ case "right": return (p, s) => ({
1123
+ x: x + w - p,
1124
+ y: y + h - s
1125
+ });
1126
+ case "top": return (p, s) => ({
1127
+ x: x + w - s,
1128
+ y: y + p
1129
+ });
1130
+ case "bottom": return (p, s) => ({
1131
+ x: x + s,
1132
+ y: y + h - p
1133
+ });
1134
+ }
953
1135
  }
954
-
955
1136
  // src/core/geometry/describe/line.ts
956
1137
  function describeLine(spec) {
957
- const { key, series, points } = spec;
958
- const width = size("line", "width", spec.width ?? 1);
959
- const first = points[0];
960
- if (!first) throw new RangeError(`describe.line: "${key}" needs at least one point.`);
961
- points.forEach((p, i) => {
962
- finite("line", `points[${i}].x`, p.x);
963
- finite("line", `points[${i}].y`, p.y);
964
- });
965
- const breaks = checkBreaks(spec.breaks, points.length);
966
- const segments = [];
967
- for (let i = 1; i < points.length; i++) {
968
- segments.push(line(points[i - 1], points[i], segments[segments.length - 1]?.angle ?? 0));
969
- }
970
- if (segments.length === 0) segments.push(line(first, first));
971
- const walk = createWalk(segments, gapsAt(breaks, segments));
972
- const box = boundsOf(points);
973
- const pad = width / 2;
974
- return assemble({
975
- key,
976
- series,
977
- walk,
978
- thickness: width,
979
- outline: openOutline(walk),
980
- bounds: { x: box.x - pad, y: box.y - pad, width: box.width + width, height: box.height + width },
981
- center: walk.point(0.5),
982
- pivot: first,
983
- labelBounds: labelBoxes("line", spec.labelBounds)
984
- });
1138
+ const { key, series, points } = spec;
1139
+ const width = size("line", "width", spec.width ?? 1);
1140
+ const first = points[0];
1141
+ if (!first) throw new RangeError(`describe.line: "${key}" needs at least one point.`);
1142
+ points.forEach((p, i) => {
1143
+ finite("line", `points[${i}].x`, p.x);
1144
+ finite("line", `points[${i}].y`, p.y);
1145
+ });
1146
+ const breaks = checkBreaks(spec.breaks, points.length);
1147
+ const segments = [];
1148
+ for (let i = 1; i < points.length; i++) segments.push(line(points[i - 1], points[i], segments[segments.length - 1]?.angle ?? 0));
1149
+ if (segments.length === 0) segments.push(line(first, first));
1150
+ const walk = createWalk(segments, gapsAt(breaks, segments));
1151
+ const box = boundsOf(points);
1152
+ const pad = width / 2;
1153
+ return assemble({
1154
+ key,
1155
+ series,
1156
+ walk,
1157
+ thickness: width,
1158
+ outline: openOutline(walk),
1159
+ bounds: {
1160
+ x: box.x - pad,
1161
+ y: box.y - pad,
1162
+ width: box.width + width,
1163
+ height: box.height + width
1164
+ },
1165
+ center: walk.point(.5),
1166
+ pivot: first,
1167
+ labelBounds: labelBoxes("line", spec.labelBounds),
1168
+ nearbyLabels: labelBoxes("line", spec.nearbyLabels, "nearbyLabels")
1169
+ });
985
1170
  }
986
1171
  function gapsAt(breaks, segments) {
987
- const along = [0];
988
- for (const segment of segments) along.push(along[along.length - 1] + segment.length);
989
- const length = along[along.length - 1];
990
- return breaks.filter((i) => along[i] > along[i - 1]).map((i) => [along[i - 1] / length, along[i] / length]);
1172
+ const along = [0];
1173
+ for (const segment of segments) along.push(along[along.length - 1] + segment.length);
1174
+ const length = along[along.length - 1];
1175
+ return breaks.filter((i) => along[i] > along[i - 1]).map((i) => [along[i - 1] / length, along[i] / length]);
991
1176
  }
992
1177
  function checkBreaks(breaks, count) {
993
- if (breaks === void 0) return [];
994
- if (!Array.isArray(breaks)) throw new RangeError(`describe.line: breaks must be an array of point indices, got ${show(breaks)}.`);
995
- let after = 0;
996
- breaks.forEach((index, i) => {
997
- if (!(Number.isInteger(index) && index > after && index < count)) {
998
- throw new RangeError(`describe.line: breaks[${i}] must be a whole number more than ${after} and less than ${count}, the number of points, got ${show(index)}.`);
999
- }
1000
- after = index;
1001
- });
1002
- return breaks;
1003
- }
1004
- var show = (value) => typeof value === "string" ? JSON.stringify(value) : String(value);
1005
-
1178
+ if (breaks === void 0) return [];
1179
+ if (!Array.isArray(breaks)) throw new RangeError(`describe.line: breaks must be an array of point indices, got ${show$2(breaks)}.`);
1180
+ let after = 0;
1181
+ breaks.forEach((index, i) => {
1182
+ if (!(Number.isInteger(index) && index > after && index < count)) throw new RangeError(`describe.line: breaks[${i}] must be a whole number more than ${after} and less than ${count}, the number of points, got ${show$2(index)}.`);
1183
+ after = index;
1184
+ });
1185
+ return breaks;
1186
+ }
1187
+ const show$2 = (value) => typeof value === "string" ? JSON.stringify(value) : String(value);
1006
1188
  // src/core/geometry/describe/point.ts
1007
1189
  function describePoint(spec) {
1008
- const { key, series } = spec;
1009
- const center = { x: finite("point", "x", spec.x), y: finite("point", "y", spec.y) };
1010
- const r = size("point", "r", spec.r);
1011
- const quarter = Math.PI / 2;
1012
- return assemble({
1013
- key,
1014
- series,
1015
- walk: createWalk([line(center, center)]),
1016
- thickness: 2 * r,
1017
- outline: closedOutline([
1018
- [arc(center, r, -3 * quarter / 2, quarter)],
1019
- [arc(center, r, -quarter / 2, quarter)],
1020
- [arc(center, r, quarter / 2, quarter)],
1021
- [arc(center, r, 3 * quarter / 2, quarter)]
1022
- ]),
1023
- bounds: { x: center.x - r, y: center.y - r, width: 2 * r, height: 2 * r },
1024
- center,
1025
- pivot: center,
1026
- labelBounds: labelBoxes("point", spec.labelBounds)
1027
- });
1190
+ const { key, series } = spec;
1191
+ const center = {
1192
+ x: finite("point", "x", spec.x),
1193
+ y: finite("point", "y", spec.y)
1194
+ };
1195
+ const r = size("point", "r", spec.r);
1196
+ const quarter = Math.PI / 2;
1197
+ return assemble({
1198
+ key,
1199
+ series,
1200
+ walk: createWalk([line(center, center)]),
1201
+ thickness: 2 * r,
1202
+ outline: closedOutline([
1203
+ [arc(center, r, -3 * quarter / 2, quarter)],
1204
+ [arc(center, r, -quarter / 2, quarter)],
1205
+ [arc(center, r, quarter / 2, quarter)],
1206
+ [arc(center, r, 3 * quarter / 2, quarter)]
1207
+ ]),
1208
+ bounds: {
1209
+ x: center.x - r,
1210
+ y: center.y - r,
1211
+ width: 2 * r,
1212
+ height: 2 * r
1213
+ },
1214
+ center,
1215
+ pivot: center,
1216
+ labelBounds: labelBoxes("point", spec.labelBounds),
1217
+ nearbyLabels: labelBoxes("point", spec.nearbyLabels, "nearbyLabels")
1218
+ });
1219
+ }
1220
+ // src/core/geometry/flatten.ts
1221
+ const FLAT = .1;
1222
+ const MAX_PIECES = 1e4;
1223
+ function flattenPath(commands) {
1224
+ const subpaths = [];
1225
+ let start;
1226
+ let pen = {
1227
+ x: 0,
1228
+ y: 0
1229
+ };
1230
+ let segments = [];
1231
+ let open = false;
1232
+ const finish = (closed) => {
1233
+ if (open) subpaths.push({
1234
+ start,
1235
+ end: pen,
1236
+ segments,
1237
+ closed
1238
+ });
1239
+ segments = [];
1240
+ open = false;
1241
+ };
1242
+ const to = (point) => {
1243
+ if (!open) {
1244
+ start = pen;
1245
+ open = true;
1246
+ }
1247
+ pen = point;
1248
+ };
1249
+ const push = (segment) => {
1250
+ if (segment.length !== 0) segments.push(segment);
1251
+ };
1252
+ const straight = (a, b) => push(line(a, b));
1253
+ const through = (points) => {
1254
+ for (let k = 1; k < points.length; k++) straight(points[k - 1], points[k]);
1255
+ };
1256
+ for (let i = 0; i < commands.length; i++) {
1257
+ const command = commands[i];
1258
+ const from = pen;
1259
+ switch (command.op) {
1260
+ case "M":
1261
+ finish(false);
1262
+ pen = command.to;
1263
+ if (commands[i + 1] && commands[i + 1].op !== "M") {
1264
+ start = pen;
1265
+ open = true;
1266
+ }
1267
+ break;
1268
+ case "Z":
1269
+ to(start ?? pen);
1270
+ straight(from, pen);
1271
+ finish(true);
1272
+ break;
1273
+ case "L":
1274
+ to(command.to);
1275
+ straight(from, pen);
1276
+ break;
1277
+ case "C":
1278
+ to(command.to);
1279
+ through(bezier(from, command.c1, command.c2, command.to));
1280
+ break;
1281
+ case "Q":
1282
+ to(command.to);
1283
+ through(bezier(from, command.c, command.to));
1284
+ break;
1285
+ case "A":
1286
+ to(command.to);
1287
+ for (const segment of arcSegments(from, command)) push(segment);
1288
+ }
1289
+ }
1290
+ finish(false);
1291
+ return subpaths;
1292
+ }
1293
+ function bezier(...p) {
1294
+ const cubic = p.length === 4;
1295
+ const n = cubic ? cubicPieces(p[0], p[1], p[2], p[3]) : pieces(1, 2 * bend(p[0], p[1], p[2]));
1296
+ const points = [p[0]];
1297
+ for (let k = 1; k < n; k++) {
1298
+ const t = k / n;
1299
+ const s = 1 - t;
1300
+ const [a, b, c, d] = cubic ? [
1301
+ s * s * s,
1302
+ 3 * s * s * t,
1303
+ 3 * s * t * t,
1304
+ t * t * t
1305
+ ] : [
1306
+ s * s,
1307
+ 2 * s * t,
1308
+ t * t,
1309
+ 0
1310
+ ];
1311
+ points.push({
1312
+ x: a * p[0].x + b * p[1].x + c * p[2].x + (cubic ? d * p[3].x : 0),
1313
+ y: a * p[0].y + b * p[1].y + c * p[2].y + (cubic ? d * p[3].y : 0)
1314
+ });
1315
+ }
1316
+ points.push(p[p.length - 1]);
1317
+ return points;
1318
+ }
1319
+ function cubicPieces(p0, p1, p2, p3) {
1320
+ return pieces(1, 6 * Math.max(bend(p0, p1, p2), bend(p1, p2, p3)));
1321
+ }
1322
+ function bend(a, b, c) {
1323
+ return Math.hypot(a.x - 2 * b.x + c.x, a.y - 2 * b.y + c.y);
1324
+ }
1325
+ function pieces(span, second) {
1326
+ const n = Math.ceil(span * Math.sqrt(second / (8 * FLAT)));
1327
+ return Number.isFinite(n) ? Math.min(MAX_PIECES, Math.max(1, n)) : MAX_PIECES;
1328
+ }
1329
+ const ROUND = 1e-9;
1330
+ function arcSegments(from, command) {
1331
+ const { to, large, sweep } = command;
1332
+ if (from.x === to.x && from.y === to.y) return [];
1333
+ let { rx, ry } = command;
1334
+ if (!(rx > 0 && ry > 0)) return [line(from, to)];
1335
+ const circle = Math.abs(rx - ry) <= ROUND * Math.max(rx, ry);
1336
+ const phi = circle ? 0 : command.rotation * Math.PI / 180;
1337
+ const cos = Math.cos(phi);
1338
+ const sin = Math.sin(phi);
1339
+ const hx = (from.x - to.x) / 2;
1340
+ const hy = (from.y - to.y) / 2;
1341
+ const x1 = cos * hx + sin * hy;
1342
+ const y1 = -sin * hx + cos * hy;
1343
+ const reach = x1 * x1 / (rx * rx) + y1 * y1 / (ry * ry);
1344
+ if (reach > 1) {
1345
+ rx *= Math.sqrt(reach);
1346
+ ry *= Math.sqrt(reach);
1347
+ }
1348
+ const rx2 = rx * rx;
1349
+ const ry2 = ry * ry;
1350
+ const spread = rx2 * y1 * y1 + ry2 * x1 * x1;
1351
+ const k = (large !== sweep ? 1 : -1) * Math.sqrt(Math.max(0, (rx2 * ry2 - spread) / spread));
1352
+ const cx1 = k * rx * y1 / ry;
1353
+ const cy1 = -k * ry * x1 / rx;
1354
+ const center = {
1355
+ x: cos * cx1 - sin * cy1 + (from.x + to.x) / 2,
1356
+ y: sin * cx1 + cos * cy1 + (from.y + to.y) / 2
1357
+ };
1358
+ const theta = Math.atan2((y1 - cy1) / ry, (x1 - cx1) / rx);
1359
+ let turn = Math.atan2((-y1 - cy1) / ry, (-x1 - cx1) / rx) - theta;
1360
+ if (sweep && turn < 0) turn += TAU;
1361
+ else if (!sweep && turn > 0) turn -= TAU;
1362
+ if (circle) return [arc(center, rx, theta, turn)];
1363
+ const n = pieces(Math.abs(turn), Math.max(rx, ry));
1364
+ const at = (angle) => {
1365
+ const ex = rx * Math.cos(angle);
1366
+ const ey = ry * Math.sin(angle);
1367
+ return {
1368
+ x: center.x + cos * ex - sin * ey,
1369
+ y: center.y + sin * ex + cos * ey
1370
+ };
1371
+ };
1372
+ const segments = [];
1373
+ let previous = from;
1374
+ for (let j = 1; j <= n; j++) {
1375
+ const next = j === n ? to : at(theta + turn * j / n);
1376
+ segments.push(line(previous, next));
1377
+ previous = next;
1378
+ }
1379
+ return segments;
1380
+ }
1381
+ // src/core/geometry/path.ts
1382
+ const ARITY = {
1383
+ M: 2,
1384
+ L: 2,
1385
+ H: 1,
1386
+ V: 1,
1387
+ C: 6,
1388
+ S: 4,
1389
+ Q: 4,
1390
+ T: 2,
1391
+ A: 7
1392
+ };
1393
+ const TOKEN = /[\s,]*([A-Za-z]|[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)/y;
1394
+ const LETTER = /^[A-Za-z]$/;
1395
+ function parsePath(d) {
1396
+ const tokens = [];
1397
+ TOKEN.lastIndex = 0;
1398
+ for (let match = TOKEN.exec(d); match; match = TOKEN.exec(d)) tokens.push(match[1]);
1399
+ const out = [];
1400
+ let pen = {
1401
+ x: 0,
1402
+ y: 0
1403
+ };
1404
+ let start = pen;
1405
+ let control;
1406
+ let command = "";
1407
+ let i = 0;
1408
+ while (i < tokens.length) {
1409
+ if (LETTER.test(tokens[i])) command = tokens[i++];
1410
+ else if (command === "" || command === "Z" || command === "z") break;
1411
+ const upper = command.toUpperCase();
1412
+ if (upper === "Z") {
1413
+ out.push({
1414
+ op: "Z",
1415
+ to: start
1416
+ });
1417
+ pen = start;
1418
+ control = void 0;
1419
+ continue;
1420
+ }
1421
+ const arity = ARITY[upper];
1422
+ if (arity === void 0) break;
1423
+ const args = [];
1424
+ let flagError = false;
1425
+ while (args.length < arity && i < tokens.length && !LETTER.test(tokens[i])) {
1426
+ const token = tokens[i];
1427
+ if (upper === "A" && (args.length === 3 || args.length === 4)) {
1428
+ const flag = token[0];
1429
+ if (flag !== "0" && flag !== "1") {
1430
+ flagError = true;
1431
+ break;
1432
+ }
1433
+ args.push(Number(flag));
1434
+ if (token.length > 1) tokens[i] = token.slice(1);
1435
+ else i++;
1436
+ continue;
1437
+ }
1438
+ args.push(Number(token));
1439
+ i++;
1440
+ }
1441
+ if (flagError || args.length < arity || !args.every(Number.isFinite)) break;
1442
+ const relative = command !== upper;
1443
+ const at = (x, y) => relative ? {
1444
+ x: pen.x + x,
1445
+ y: pen.y + y
1446
+ } : {
1447
+ x,
1448
+ y
1449
+ };
1450
+ const [a = 0, b = 0, c = 0, e = 0, f = 0, g = 0, h = 0] = args;
1451
+ let next;
1452
+ switch (upper) {
1453
+ case "M":
1454
+ pen = start = at(a, b);
1455
+ out.push({
1456
+ op: "M",
1457
+ to: pen
1458
+ });
1459
+ command = relative ? "l" : "L";
1460
+ break;
1461
+ case "L":
1462
+ out.push({
1463
+ op: "L",
1464
+ to: pen = at(a, b)
1465
+ });
1466
+ break;
1467
+ case "H":
1468
+ out.push({
1469
+ op: "L",
1470
+ to: pen = {
1471
+ x: relative ? pen.x + a : a,
1472
+ y: pen.y
1473
+ }
1474
+ });
1475
+ break;
1476
+ case "V":
1477
+ out.push({
1478
+ op: "L",
1479
+ to: pen = {
1480
+ x: pen.x,
1481
+ y: relative ? pen.y + a : a
1482
+ }
1483
+ });
1484
+ break;
1485
+ case "C":
1486
+ case "S": {
1487
+ const smooth = upper === "S";
1488
+ const c1 = smooth ? control && lastIs(out, "C") ? reflect(control, pen) : pen : at(a, b);
1489
+ next = smooth ? at(a, b) : at(c, e);
1490
+ out.push({
1491
+ op: "C",
1492
+ c1,
1493
+ c2: next,
1494
+ to: pen = smooth ? at(c, e) : at(f, g)
1495
+ });
1496
+ break;
1497
+ }
1498
+ case "Q":
1499
+ case "T": {
1500
+ const smooth = upper === "T";
1501
+ next = smooth ? control && lastIs(out, "Q") ? reflect(control, pen) : pen : at(a, b);
1502
+ out.push({
1503
+ op: "Q",
1504
+ c: next,
1505
+ to: pen = smooth ? at(a, b) : at(c, e)
1506
+ });
1507
+ break;
1508
+ }
1509
+ case "A": out.push({
1510
+ op: "A",
1511
+ rx: Math.abs(a),
1512
+ ry: Math.abs(b),
1513
+ rotation: c,
1514
+ large: e !== 0,
1515
+ sweep: f !== 0,
1516
+ to: pen = at(g, h)
1517
+ });
1518
+ }
1519
+ control = next;
1520
+ }
1521
+ return out;
1522
+ }
1523
+ const lastIs = (commands, op) => commands[commands.length - 1]?.op === op;
1524
+ const reflect = (control, about) => ({
1525
+ x: 2 * about.x - control.x,
1526
+ y: 2 * about.y - control.y
1527
+ });
1528
+ function transformPath(commands, m) {
1529
+ const p = (point) => ({
1530
+ x: m[0] * point.x + m[2] * point.y + m[4],
1531
+ y: m[1] * point.x + m[3] * point.y + m[5]
1532
+ });
1533
+ const mirrored = m[0] * m[3] - m[1] * m[2] < 0;
1534
+ return commands.map((command) => {
1535
+ switch (command.op) {
1536
+ case "M":
1537
+ case "L":
1538
+ case "Z": return {
1539
+ op: command.op,
1540
+ to: p(command.to)
1541
+ };
1542
+ case "C": return {
1543
+ op: "C",
1544
+ c1: p(command.c1),
1545
+ c2: p(command.c2),
1546
+ to: p(command.to)
1547
+ };
1548
+ case "Q": return {
1549
+ op: "Q",
1550
+ c: p(command.c),
1551
+ to: p(command.to)
1552
+ };
1553
+ case "A": return {
1554
+ ...command,
1555
+ ...transformEllipse(command, m),
1556
+ sweep: mirrored !== command.sweep,
1557
+ to: p(command.to)
1558
+ };
1559
+ }
1560
+ });
1561
+ }
1562
+ function transformEllipse({ rx, ry, rotation }, m) {
1563
+ const r = rotation * Math.PI / 180;
1564
+ const cos = Math.cos(r);
1565
+ const sin = Math.sin(r);
1566
+ const e11 = (m[0] * cos + m[2] * sin) * rx;
1567
+ const e12 = (m[2] * cos - m[0] * sin) * ry;
1568
+ const e21 = (m[1] * cos + m[3] * sin) * rx;
1569
+ const e22 = (m[3] * cos - m[1] * sin) * ry;
1570
+ const a = e11 * e11 + e12 * e12;
1571
+ const b = e11 * e21 + e12 * e22;
1572
+ const c = e21 * e21 + e22 * e22;
1573
+ const mean = (a + c) / 2;
1574
+ const spread = Math.hypot((a - c) / 2, b);
1575
+ const major = mean + spread;
1576
+ const angle = Math.abs(b) < 1e-12 ? a >= c ? 0 : Math.PI / 2 : Math.atan2(major - a, b);
1577
+ return {
1578
+ rx: Math.sqrt(major),
1579
+ ry: Math.sqrt(Math.max(0, mean - spread)),
1580
+ rotation: angle * 180 / Math.PI
1581
+ };
1582
+ }
1583
+ // src/core/geometry/describe/shape.ts
1584
+ function describeShape(spec) {
1585
+ const { key, series, d } = spec;
1586
+ const width = spec.width ?? 1;
1587
+ if (!(Number.isFinite(width) && width > 0)) throw new RangeError(`describe.shape: width must be a finite number more than 0, got ${width}.`);
1588
+ const m = checkMatrix(spec.matrix);
1589
+ if (typeof d !== "string") throw new RangeError(`describe.shape: d must be path data, a string, got ${show$1(d)}.`);
1590
+ const commands = parsePath(d);
1591
+ const subpaths = commands[0]?.op === "M" ? flattenPath(m ? transformPath(commands, m) : commands) : [];
1592
+ if (subpaths.length === 0) throw new RangeError(`describe.shape: d must start with a move and draw something after it, got ${show$1(d)}.`);
1593
+ const points = [];
1594
+ let length = 0;
1595
+ for (const subpath of subpaths) {
1596
+ points.push(subpath.start);
1597
+ for (const segment of subpath.segments) {
1598
+ for (const point of extremes(segment)) points.push(point);
1599
+ length += segment.length;
1600
+ }
1601
+ }
1602
+ const box = boundsOf(points);
1603
+ if (![
1604
+ box.x,
1605
+ box.y,
1606
+ box.width,
1607
+ box.height,
1608
+ length
1609
+ ].every(Number.isFinite)) throw new RangeError(`describe.shape: d must stay finite${m ? " once moved by matrix" : ""}, got ${show$1(d)}.`);
1610
+ const labelBounds = labelBoxes("shape", spec.labelBounds);
1611
+ const nearbyLabels = labelBoxes("shape", spec.nearbyLabels, "nearbyLabels");
1612
+ if (subpaths.every(closes) && length > 0) {
1613
+ const center = {
1614
+ x: box.x + box.width / 2,
1615
+ y: box.y + box.height / 2
1616
+ };
1617
+ return assemble({
1618
+ key,
1619
+ series,
1620
+ walk: createWalk([line(center, center)]),
1621
+ thickness: Math.min(box.width, box.height),
1622
+ outline: loopOutline(subpaths.map((subpath) => subpath.segments).filter((segments) => segments.length > 0)),
1623
+ bounds: box,
1624
+ center,
1625
+ pivot: center,
1626
+ labelBounds,
1627
+ nearbyLabels
1628
+ });
1629
+ }
1630
+ const { segments, gaps } = joined(subpaths);
1631
+ const walk = createWalk(segments, gaps);
1632
+ const pad = width / 2;
1633
+ return assemble({
1634
+ key,
1635
+ series,
1636
+ walk,
1637
+ thickness: width,
1638
+ outline: openOutline(walk),
1639
+ bounds: {
1640
+ x: box.x - pad,
1641
+ y: box.y - pad,
1642
+ width: box.width + width,
1643
+ height: box.height + width
1644
+ },
1645
+ center: walk.point(.5),
1646
+ pivot: walk.start,
1647
+ labelBounds,
1648
+ nearbyLabels
1649
+ });
1650
+ }
1651
+ const closes = ({ closed, start, end }) => closed || start.x === end.x && start.y === end.y;
1652
+ function joined(subpaths) {
1653
+ const segments = [];
1654
+ const across = [];
1655
+ let pen;
1656
+ for (const subpath of subpaths) {
1657
+ if (pen && (pen.x !== subpath.start.x || pen.y !== subpath.start.y)) {
1658
+ across.push(segments.length);
1659
+ segments.push(line(pen, subpath.start));
1660
+ }
1661
+ for (const segment of subpath.segments) segments.push(segment);
1662
+ pen = subpath.end;
1663
+ }
1664
+ if (segments.length === 0) segments.push(line(subpaths[0].start, subpaths[0].start));
1665
+ const along = [0];
1666
+ for (const segment of segments) along.push(along[along.length - 1] + segment.length);
1667
+ const length = along[along.length - 1];
1668
+ return {
1669
+ segments,
1670
+ gaps: across.map((i) => [along[i] / length, along[i + 1] / length])
1671
+ };
1672
+ }
1673
+ function checkMatrix(m) {
1674
+ if (m === void 0) return m;
1675
+ if (!(Array.isArray(m) && m.length === 6 && m.every(Number.isFinite))) throw new RangeError(`describe.shape: matrix must be six finite numbers [a, b, c, d, e, f], got ${show$1(m)}.`);
1676
+ return m;
1677
+ }
1678
+ function show$1(value) {
1679
+ if (Array.isArray(value)) return `[${value.map(show$1).join(", ")}]`;
1680
+ if (typeof value !== "string") return String(value);
1681
+ return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value);
1028
1682
  }
1029
-
1030
1683
  // src/core/geometry/describe/index.ts
1031
- var describe = {
1032
- bar: describeBar,
1033
- arc: describeArc,
1034
- line: describeLine,
1035
- point: describePoint
1684
+ const describe = {
1685
+ bar: describeBar,
1686
+ arc: describeArc,
1687
+ line: describeLine,
1688
+ point: describePoint,
1689
+ shape: describeShape
1036
1690
  };
1037
-
1038
1691
  // src/testing/fixtures.ts
1039
- var fixtures = /* @__PURE__ */ makeFixtures(false);
1040
- var movedFixtures = /* @__PURE__ */ makeFixtures(true);
1041
- var fixturePairs = /* @__PURE__ */ Object.freeze({
1042
- "slice and column": [fixtures.slice, fixtures.column],
1043
- "bar and column": [fixtures.bar, fixtures.column],
1044
- "two slices": [fixtures.slice, movedFixtures.slice],
1045
- "two lines": [fixtures.line, movedFixtures.line],
1046
- "two points": [fixtures.point, movedFixtures.point]
1692
+ const fixtures = /* @__PURE__ */ makeFixtures(false);
1693
+ const movedFixtures = /* @__PURE__ */ makeFixtures(true);
1694
+ const fixturePairs = /* @__PURE__ */ Object.freeze({
1695
+ "slice and column": [fixtures.slice, fixtures.column],
1696
+ "bar and column": [fixtures.bar, fixtures.column],
1697
+ "two slices": [fixtures.slice, movedFixtures.slice],
1698
+ "two lines": [fixtures.line, movedFixtures.line],
1699
+ "two points": [fixtures.point, movedFixtures.point]
1047
1700
  });
1048
1701
  function makeFixtures(moved) {
1049
- const y = moved ? 30 : 0;
1050
- const bar = (width, more = {}) => describe.bar({ key: "Okafor", series: "goals", x: 0, y, width, height: 20, baseline: "left", ...more });
1051
- const [goals, assists] = moved ? [120, 82] : [160, 62];
1052
- const points = moved ? [{ x: 0, y: 90 }, { x: 64, y: 58 }, { x: 128, y: 82 }, { x: 192, y: 26 }, { x: 256, y: 40 }] : [{ x: 0, y: 100 }, { x: 80, y: 60 }, { x: 160, y: 90 }, { x: 240, y: 20 }];
1053
- return Object.freeze({
1054
- bar: bar(moved ? 160 : 200, { radius: 4 }),
1055
- "negative bar": describe.bar({ key: "n", series: "goals", x: moved ? 30 : 0, y, width: moved ? 90 : 120, height: 20, baseline: "right" }),
1056
- column: describe.bar({ key: "c", series: "goals", x: moved ? 30 : 0, y: moved ? 40 : 0, width: 20, height: moved ? 110 : 150, baseline: "bottom" }),
1057
- stacked: bar(goals + assists, { series: void 0, gap: 2, segments: [{ series: "goals", size: goals }, { series: "assists", size: assists }] }),
1058
- "short bar": bar(moved ? 4 : 6),
1059
- slice: moved ? describe.arc({ key: "Saved", cx: 140, cy: 130, inner: 60, outer: 100, start: 0.5, end: 2 }) : describe.arc({ key: "Saved", cx: 150, cy: 150, inner: 70, outer: 116, start: 0.3, end: 2.4 }),
1060
- line: describe.line({ key: "goals", series: "goals", points, width: 2 }),
1061
- // The line broken after its second point: a run, a gap, and a run.
1062
- "gapped line": describe.line({ key: "goals", series: "goals", points, breaks: [2], width: 2 }),
1063
- point: describe.point({ key: "p", x: moved ? 40 : 10, y: moved ? 25 : 10, r: 3 })
1064
- });
1702
+ const y = moved ? 30 : 0;
1703
+ const bar = (width, more = {}) => describe.bar({
1704
+ key: "Okafor",
1705
+ series: "goals",
1706
+ x: 0,
1707
+ y,
1708
+ width,
1709
+ height: 20,
1710
+ baseline: "left",
1711
+ ...more
1712
+ });
1713
+ const [goals, assists] = moved ? [120, 82] : [160, 62];
1714
+ const points = moved ? [
1715
+ {
1716
+ x: 0,
1717
+ y: 90
1718
+ },
1719
+ {
1720
+ x: 64,
1721
+ y: 58
1722
+ },
1723
+ {
1724
+ x: 128,
1725
+ y: 82
1726
+ },
1727
+ {
1728
+ x: 192,
1729
+ y: 26
1730
+ },
1731
+ {
1732
+ x: 256,
1733
+ y: 40
1734
+ }
1735
+ ] : [
1736
+ {
1737
+ x: 0,
1738
+ y: 100
1739
+ },
1740
+ {
1741
+ x: 80,
1742
+ y: 60
1743
+ },
1744
+ {
1745
+ x: 160,
1746
+ y: 90
1747
+ },
1748
+ {
1749
+ x: 240,
1750
+ y: 20
1751
+ }
1752
+ ];
1753
+ return Object.freeze({
1754
+ bar: bar(moved ? 160 : 200, { radius: 4 }),
1755
+ "negative bar": describe.bar({
1756
+ key: "n",
1757
+ series: "goals",
1758
+ x: moved ? 30 : 0,
1759
+ y,
1760
+ width: moved ? 90 : 120,
1761
+ height: 20,
1762
+ baseline: "right"
1763
+ }),
1764
+ column: describe.bar({
1765
+ key: "c",
1766
+ series: "goals",
1767
+ x: moved ? 30 : 0,
1768
+ y: moved ? 40 : 0,
1769
+ width: 20,
1770
+ height: moved ? 110 : 150,
1771
+ baseline: "bottom"
1772
+ }),
1773
+ stacked: bar(goals + assists, {
1774
+ series: void 0,
1775
+ gap: 2,
1776
+ segments: [{
1777
+ series: "goals",
1778
+ size: goals
1779
+ }, {
1780
+ series: "assists",
1781
+ size: assists
1782
+ }]
1783
+ }),
1784
+ "short bar": bar(moved ? 4 : 6),
1785
+ slice: moved ? describe.arc({
1786
+ key: "Saved",
1787
+ cx: 140,
1788
+ cy: 130,
1789
+ inner: 60,
1790
+ outer: 100,
1791
+ start: .5,
1792
+ end: 2
1793
+ }) : describe.arc({
1794
+ key: "Saved",
1795
+ cx: 150,
1796
+ cy: 150,
1797
+ inner: 70,
1798
+ outer: 116,
1799
+ start: .3,
1800
+ end: 2.4
1801
+ }),
1802
+ line: describe.line({
1803
+ key: "goals",
1804
+ series: "goals",
1805
+ points,
1806
+ width: 2
1807
+ }),
1808
+ "gapped line": describe.line({
1809
+ key: "goals",
1810
+ series: "goals",
1811
+ points,
1812
+ breaks: [2],
1813
+ width: 2
1814
+ }),
1815
+ point: describe.point({
1816
+ key: "p",
1817
+ x: moved ? 40 : 10,
1818
+ y: moved ? 25 : 10,
1819
+ r: 3
1820
+ })
1821
+ });
1065
1822
  }
1066
-
1067
1823
  // src/testing/check.ts
1068
1824
  async function checkEffect(effect, options = {}) {
1069
- if (!isMarkEffect(effect)) {
1070
- const hint = isTransitionEffect(effect) ? "; check it with checkTransition" : "";
1071
- throw new TypeError(`checkEffect needs a mark effect (kind "geometry" or "data"), got ${describeValue(effect)}${hint}.`);
1072
- }
1073
- const name = options.name ?? "the effect";
1074
- const related = effect.kind === "data" ? effect.needs?.related ?? [] : [];
1075
- if (related.length > 0 && !options.data) {
1076
- throw new TypeError(
1077
- `checkEffect: ${name} needs the related series ${related.map((s) => `"${s}"`).join(", ")}, so pass data(mark) with them: the default data has no related series.`
1078
- );
1079
- }
1080
- const marks = named(options.marks ?? fixtures);
1081
- if (marks.length === 0) throw new TypeError("checkEffect: there are no marks to check on.");
1082
- const dataOf = (mark) => effect.kind === "data" ? (options.data ?? defaultData)(mark) : void 0;
1083
- const failures = [];
1084
- for (const [markName, mark] of marks) {
1085
- let data;
1086
- try {
1087
- data = dataOf(mark);
1088
- } catch (error) {
1089
- failures.push(`on ${markName}: data(mark) threw ${describeError(error)}`);
1090
- continue;
1091
- }
1092
- let moved;
1093
- try {
1094
- moved = movedSubject(effect, (options.moved ?? movedFixture)(mark), dataOf);
1095
- } catch (error) {
1096
- failures.push(`on ${markName}: the moved mark, or its data, threw ${describeError(error)}`);
1097
- }
1098
- const subject = {
1099
- context: (more = {}) => testContext({ icons: options.icons, batch: options.batch, ...more }),
1100
- run: (ctx) => promised(effect.kind === "data" ? effect.run(mark, data, ctx) : effect.run(mark, ctx)),
1101
- end: (ctx) => effect.kind === "data" ? effect.end(mark, data, ctx) : effect.end(mark, ctx),
1102
- clear: (ctx) => effect.clear(ctx),
1103
- moved
1104
- };
1105
- for (const check of CHECKS) {
1106
- const problem = await attempt(check, subject);
1107
- if (problem) failures.push(`on ${markName}, ${check.title}: ${problem}`);
1108
- }
1109
- }
1110
- if (failures.length > 0) throw new Error(`checkEffect found ${problems(failures)} with ${name}:
1111
- ${list(failures)}`);
1112
- }
1113
- var RETRACE_AT = [0.25, 0.5, 0.75];
1825
+ if (!isMarkEffect(effect)) {
1826
+ const hint = isTransitionEffect(effect) ? "; check it with checkTransition" : "";
1827
+ throw new TypeError(`checkEffect needs a mark effect (kind "geometry" or "data"), got ${describeValue(effect)}${hint}.`);
1828
+ }
1829
+ const name = options.name ?? "the effect";
1830
+ const related = effect.kind === "data" ? effect.needs?.related ?? [] : [];
1831
+ if (related.length > 0 && !options.data) throw new TypeError(`checkEffect: ${name} needs the related series ${related.map((s) => `"${s}"`).join(", ")}, so pass data(mark) with them: the default data has no related series.`);
1832
+ const marks = named(options.marks ?? fixtures);
1833
+ if (marks.length === 0) throw new TypeError("checkEffect: there are no marks to check on.");
1834
+ const dataOf = (mark) => effect.kind === "data" ? (options.data ?? defaultData)(mark) : void 0;
1835
+ const failures = [];
1836
+ for (const [markName, mark] of marks) {
1837
+ let data;
1838
+ try {
1839
+ data = dataOf(mark);
1840
+ } catch (error) {
1841
+ failures.push(`on ${markName}: data(mark) threw ${describeError(error)}`);
1842
+ continue;
1843
+ }
1844
+ let moved;
1845
+ try {
1846
+ moved = movedSubject(effect, (options.moved ?? movedFixture)(mark), dataOf);
1847
+ } catch (error) {
1848
+ failures.push(`on ${markName}: the moved mark, or its data, threw ${describeError(error)}`);
1849
+ }
1850
+ const subject = {
1851
+ context: (more = {}) => testContext({
1852
+ icons: options.icons,
1853
+ batch: options.batch,
1854
+ ...more
1855
+ }),
1856
+ run: (ctx) => promised(effect.kind === "data" ? effect.run(mark, data, ctx) : effect.run(mark, ctx)),
1857
+ end: (ctx) => effect.kind === "data" ? effect.end(mark, data, ctx) : effect.end(mark, ctx),
1858
+ clear: (ctx) => effect.clear(ctx),
1859
+ moved
1860
+ };
1861
+ for (const check of CHECKS) {
1862
+ const problem = await attempt(check, subject);
1863
+ if (problem) failures.push(`on ${markName}, ${check.title}: ${problem}`);
1864
+ }
1865
+ }
1866
+ if (failures.length > 0) throw new Error(`checkEffect found ${problems(failures)} with ${name}:\n${list(failures)}`);
1867
+ }
1868
+ const RETRACE_AT = [
1869
+ .25,
1870
+ .5,
1871
+ .75
1872
+ ];
1114
1873
  async function checkTransition(effect, options = {}) {
1115
- if (!isTransitionEffect(effect)) {
1116
- const hint = isMarkEffect(effect) ? "; check it with checkEffect" : "";
1117
- throw new TypeError(`checkTransition needs a transition effect (kind "transition" with run, end and clear), got ${describeTransition(effect)}${hint}.`);
1118
- }
1119
- const name = options.name ?? "the effect";
1120
- const pairs = namedPairs(options.pairs ?? fixturePairs);
1121
- if (pairs.length === 0) throw new TypeError("checkTransition: there are no pairs to check on.");
1122
- const failures = [];
1123
- for (const [pairName, [a, b]] of pairs) {
1124
- for (const [way, from, to] of [["a to b", a, b], ["b to a", b, a]]) {
1125
- for (const check of COMMON) {
1126
- const problem3 = await attempt(check, transitionSubject(effect, from, to, 0, options.icons));
1127
- if (problem3) failures.push(`on ${pairName}, ${way}, ${check.title}: ${problem3}`);
1128
- }
1129
- const problem2 = await attempt(FULL_RUN, transitionSubject(effect, from, to, 0.5, options.icons));
1130
- if (problem2) failures.push(`on ${pairName}, ${way}, a run from start: 0.5 should end with the same picture as end(): ${problem2}`);
1131
- }
1132
- let problem;
1133
- try {
1134
- problem = await retraces(effect, a, b, options.icons);
1135
- } catch (error) {
1136
- problem = `it threw ${describeError(error)}`;
1137
- }
1138
- if (problem) failures.push(`on ${pairName}, a run back should retrace the run forward: ${problem}`);
1139
- }
1140
- if (failures.length > 0) throw new Error(`checkTransition found ${problems(failures)} with ${name}:
1141
- ${list(failures)}`);
1874
+ if (!isTransitionEffect(effect)) {
1875
+ const hint = isMarkEffect(effect) ? "; check it with checkEffect" : "";
1876
+ throw new TypeError(`checkTransition needs a transition effect (kind "transition" with run, end and clear), got ${describeTransition(effect)}${hint}.`);
1877
+ }
1878
+ const name = options.name ?? "the effect";
1879
+ const pairs = namedPairs(options.pairs ?? fixturePairs);
1880
+ if (pairs.length === 0) throw new TypeError("checkTransition: there are no pairs to check on.");
1881
+ const failures = [];
1882
+ for (const [pairName, [a, b]] of pairs) {
1883
+ for (const [way, from, to] of [[
1884
+ "a to b",
1885
+ a,
1886
+ b
1887
+ ], [
1888
+ "b to a",
1889
+ b,
1890
+ a
1891
+ ]]) {
1892
+ for (const check of COMMON) {
1893
+ const problem = await attempt(check, transitionSubject(effect, from, to, 0, options.icons));
1894
+ if (problem) failures.push(`on ${pairName}, ${way}, ${check.title}: ${problem}`);
1895
+ }
1896
+ const problem = await attempt(FULL_RUN, transitionSubject(effect, from, to, .5, options.icons));
1897
+ if (problem) failures.push(`on ${pairName}, ${way}, a run from start: 0.5 should end with the same picture as end(): ${problem}`);
1898
+ }
1899
+ let problem;
1900
+ try {
1901
+ problem = await retraces(effect, a, b, options.icons);
1902
+ } catch (error) {
1903
+ problem = `it threw ${describeError(error)}`;
1904
+ }
1905
+ if (problem) failures.push(`on ${pairName}, a run back should retrace the run forward: ${problem}`);
1906
+ }
1907
+ if (failures.length > 0) throw new Error(`checkTransition found ${problems(failures)} with ${name}:\n${list(failures)}`);
1142
1908
  }
1143
1909
  function transitionContext(start, options) {
1144
- return { ...testContext(options), start };
1910
+ return {
1911
+ ...testContext(options),
1912
+ start
1913
+ };
1145
1914
  }
1146
1915
  function transitionSubject(effect, from, to, start, icons) {
1147
- return {
1148
- context: (more = {}) => transitionContext(start, { icons, ...more }),
1149
- run: (ctx) => promised(effect.run(from, to, ctx)),
1150
- end: (ctx) => effect.end(from, to, ctx),
1151
- clear: (ctx) => effect.clear(ctx),
1152
- moved: void 0
1153
- };
1916
+ return {
1917
+ context: (more = {}) => transitionContext(start, {
1918
+ icons,
1919
+ ...more
1920
+ }),
1921
+ run: (ctx) => promised(effect.run(from, to, ctx)),
1922
+ end: (ctx) => effect.end(from, to, ctx),
1923
+ clear: (ctx) => effect.clear(ctx),
1924
+ moved: void 0
1925
+ };
1154
1926
  }
1155
1927
  async function opening(effect, from, to, start, icons) {
1156
- const ctx = transitionContext(start, { icons });
1157
- const run = track(promised(effect.run(from, to, ctx)));
1158
- await flush();
1159
- const picture = ctx.layer.picture();
1160
- ctx.abort();
1161
- await settle(run);
1162
- effect.clear(ctx);
1163
- ctx.clear();
1164
- if (run.failed) throw run.error;
1165
- return picture;
1928
+ const ctx = transitionContext(start, { icons });
1929
+ const run = track(promised(effect.run(from, to, ctx)));
1930
+ await flush();
1931
+ const picture = ctx.layer.picture();
1932
+ ctx.abort();
1933
+ await settle(run);
1934
+ effect.clear(ctx);
1935
+ ctx.clear();
1936
+ if (run.failed) throw run.error;
1937
+ return picture;
1166
1938
  }
1167
1939
  async function retraces(effect, a, b, icons) {
1168
- for (const p of RETRACE_AT) {
1169
- const forward = await opening(effect, a, b, p, icons);
1170
- const back = await opening(effect, b, a, 1 - p, icons);
1171
- if (same(back, forward)) continue;
1172
- const index = back.findIndex((item, i) => !same(item, forward[i]));
1173
- const what = back.length !== forward.length ? `${back.length} ${back.length === 1 ? "item" : "items"} (${show2(back)}) where the run from a to b from start: ${p} begins with ${forward.length} (${show2(forward)})` : `item ${index + 1} unlike the run from a to b from start: ${p}: ${difference(back[index], forward[index])}`;
1174
- return `the run from b to a from start: ${1 - p} begins with ${what}`;
1175
- }
1176
- return void 0;
1940
+ for (const p of RETRACE_AT) {
1941
+ const forward = await opening(effect, a, b, p, icons);
1942
+ const back = await opening(effect, b, a, 1 - p, icons);
1943
+ if (same(back, forward)) continue;
1944
+ const index = back.findIndex((item, i) => !same(item, forward[i]));
1945
+ const what = back.length !== forward.length ? `${back.length} ${back.length === 1 ? "item" : "items"} (${show(back)}) where the run from a to b from start: ${p} begins with ${forward.length} (${show(forward)})` : `item ${index + 1} unlike the run from a to b from start: ${p}: ${difference(back[index], forward[index])}`;
1946
+ return `the run from b to a from start: ${1 - p} begins with ${what}`;
1947
+ }
1177
1948
  }
1178
1949
  function difference(actual, expected) {
1179
- if (typeof actual !== "object" || typeof expected !== "object" || actual === null || expected === null) return `${show2(actual)}, not ${show2(expected)}`;
1180
- const a = actual;
1181
- const b = expected;
1182
- for (const field of /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])) {
1183
- const x = a[field];
1184
- const y = b[field];
1185
- if (same(x, y)) continue;
1186
- if (typeof x !== "string" || typeof y !== "string") return `its ${field} is ${show2(x)}, not ${show2(y)}`;
1187
- let at = 0;
1188
- while (at < x.length && x[at] === y[at]) at++;
1189
- const from = Math.max(0, at - 24);
1190
- const part = (text) => `${from > 0 ? "\u2026" : ""}${text.slice(from, at + 24)}${at + 24 < text.length ? "\u2026" : ""}`;
1191
- return `its ${field} parts at character ${at + 1}: ${JSON.stringify(part(x))}, not ${JSON.stringify(part(y))}`;
1192
- }
1193
- return `${show2(actual)}, not ${show2(expected)}`;
1950
+ if (typeof actual !== "object" || typeof expected !== "object" || actual === null || expected === null) return `${show(actual)}, not ${show(expected)}`;
1951
+ const a = actual;
1952
+ const b = expected;
1953
+ for (const field of /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])) {
1954
+ const x = a[field];
1955
+ const y = b[field];
1956
+ if (same(x, y)) continue;
1957
+ if (typeof x !== "string" || typeof y !== "string") return `its ${field} is ${show(x)}, not ${show(y)}`;
1958
+ let at = 0;
1959
+ while (at < x.length && x[at] === y[at]) at++;
1960
+ const from = Math.max(0, at - 24);
1961
+ const part = (text) => `${from > 0 ? "…" : ""}${text.slice(from, at + 24)}${at + 24 < text.length ? "…" : ""}`;
1962
+ return `its ${field} parts at character ${at + 1}: ${JSON.stringify(part(x))}, not ${JSON.stringify(part(y))}`;
1963
+ }
1964
+ return `${show(actual)}, not ${show(expected)}`;
1194
1965
  }
1195
1966
  function namedPairs(pairs) {
1196
- if (!Array.isArray(pairs)) return Object.entries(pairs).map(([name, pair]) => [`the ${name}`, pair]);
1197
- return pairs.map((pair, i) => {
1198
- const [a, b] = pair;
1199
- const keys = a?.key === b?.key ? `"${String(a?.key)}"` : `"${String(a?.key)}" and "${String(b?.key)}"`;
1200
- return [`pair ${i + 1} (${keys})`, pair];
1201
- });
1967
+ if (!Array.isArray(pairs)) return Object.entries(pairs).map(([name, pair]) => [`the ${name}`, pair]);
1968
+ return pairs.map((pair, i) => {
1969
+ const [a, b] = pair;
1970
+ const keys = a?.key === b?.key ? `"${String(a?.key)}"` : `"${String(a?.key)}" and "${String(b?.key)}"`;
1971
+ return [`pair ${i + 1} (${keys})`, pair];
1972
+ });
1202
1973
  }
1203
1974
  function describeTransition(value) {
1204
- if (typeof value !== "object" || value === null) return value === null ? "null" : typeof value;
1205
- const kind = value.kind;
1206
- if (kind === "geometry" || kind === "data") return `a ${kind} effect, which plays on one mark`;
1207
- if (kind === "transition") return "a transition effect without run(), end() and clear()";
1208
- return kind === void 0 ? "an object with no kind" : `an effect of kind ${JSON.stringify(kind)}`;
1975
+ if (typeof value !== "object" || value === null) return value === null ? "null" : typeof value;
1976
+ const kind = value.kind;
1977
+ if (kind === "geometry" || kind === "data") return `a ${kind} effect, which plays on one mark`;
1978
+ if (kind === "transition") return "a transition effect without run(), end() and clear()";
1979
+ return kind === void 0 ? "an object with no kind" : `an effect of kind ${JSON.stringify(kind)}`;
1209
1980
  }
1210
1981
  async function attempt(check, subject) {
1211
- try {
1212
- return await check.test(subject);
1213
- } catch (error) {
1214
- return `it threw ${describeError(error)}`;
1215
- }
1982
+ try {
1983
+ return await check.test(subject);
1984
+ } catch (error) {
1985
+ return `it threw ${describeError(error)}`;
1986
+ }
1216
1987
  }
1217
1988
  function promised(running) {
1218
- if (typeof running?.then !== "function") throw new TypeError(`run() must return a promise, got ${describeValue(running)}.`);
1219
- return running;
1989
+ if (typeof running?.then !== "function") throw new TypeError(`run() must return a promise, got ${describeValue(running)}.`);
1990
+ return running;
1220
1991
  }
1221
- var problems = (failures) => failures.length === 1 ? "1 problem" : `${failures.length} problems`;
1222
- var list = (failures) => failures.map((failure) => `- ${failure}`).join("\n");
1992
+ const problems = (failures) => failures.length === 1 ? "1 problem" : `${failures.length} problems`;
1993
+ const list = (failures) => failures.map((failure) => `- ${failure}`).join("\n");
1223
1994
  function movedFixture(mark) {
1224
- const name = Object.keys(fixtures).find((fixture) => fixtures[fixture] === mark);
1225
- return name === void 0 ? void 0 : movedFixtures[name];
1995
+ const name = Object.keys(fixtures).find((fixture) => fixtures[fixture] === mark);
1996
+ return name === void 0 ? void 0 : movedFixtures[name];
1226
1997
  }
1227
1998
  function movedSubject(effect, mark, dataOf) {
1228
- if (mark === void 0) return void 0;
1229
- const data = dataOf(mark);
1230
- return {
1231
- change: (ctx) => ctx.change(mark, data),
1232
- end: (ctx) => effect.kind === "data" ? effect.end(mark, data, ctx) : effect.end(mark, ctx)
1233
- };
1234
- }
1235
- var FULL_RUN = {
1236
- title: "a full run should end with the same picture and mark style as end()",
1237
- async test(subject) {
1238
- const ran = subject.context();
1239
- const run = track(subject.run(ran));
1240
- await play(ran.clock, run.done);
1241
- if (run.failed) return `run() rejected with ${describeError(run.error)}`;
1242
- const ended = subject.context();
1243
- subject.end(ended);
1244
- return compare(ran, ended, "after the run");
1245
- }
1999
+ if (mark === void 0) return void 0;
2000
+ const data = dataOf(mark);
2001
+ return {
2002
+ change: (ctx) => ctx.change(mark, data),
2003
+ end: (ctx) => effect.kind === "data" ? effect.end(mark, data, ctx) : effect.end(mark, ctx)
2004
+ };
2005
+ }
2006
+ const FULL_RUN = {
2007
+ title: "a full run should end with the same picture and mark style as end()",
2008
+ async test(subject) {
2009
+ const ran = subject.context();
2010
+ const run = track(subject.run(ran));
2011
+ await play(ran.clock, run.done);
2012
+ if (run.failed) return `run() rejected with ${describeError(run.error)}`;
2013
+ const ended = subject.context();
2014
+ subject.end(ended);
2015
+ return compare(ran, ended, "after the run");
2016
+ }
1246
2017
  };
1247
- var COMMON = [
1248
- FULL_RUN,
1249
- {
1250
- title: "clearing should leave nothing behind",
1251
- async test(subject) {
1252
- const ctx = subject.context();
1253
- const run = track(subject.run(ctx));
1254
- await play(ctx.clock, run.done);
1255
- subject.clear(ctx);
1256
- ctx.clear();
1257
- ctx.clock.advance(48);
1258
- await flush();
1259
- return leftovers(ctx);
1260
- }
1261
- },
1262
- {
1263
- title: "an abort mid-run should settle the run and clear to nothing",
1264
- async test(subject) {
1265
- const ctx = subject.context();
1266
- const run = track(subject.run(ctx));
1267
- ctx.clock.advance(16);
1268
- ctx.clock.advance(16);
1269
- ctx.abort();
1270
- await settle(run);
1271
- if (!run.settled) return "run() was still running after the abort; it should resolve once ctx.signal aborts, without more frames";
1272
- if (run.failed) return `run() rejected with ${describeError(run.error)} (it should resolve, aborted or not)`;
1273
- subject.clear(ctx);
1274
- ctx.clear();
1275
- return leftovers(ctx);
1276
- }
1277
- },
1278
- {
1279
- title: "with motion off, no frames should run and the end state should be drawn",
1280
- async test(subject) {
1281
- const ctx = subject.context({ mode: "off" });
1282
- const run = track(subject.run(ctx));
1283
- const framesAtStart = !ctx.clock.idle;
1284
- await settle(run);
1285
- if (!run.settled) return "run() didn't finish; with motion off ctx.tween() ends at once, so wait only through it, never on a timer";
1286
- if (run.failed) return `run() rejected with ${describeError(run.error)}`;
1287
- if (framesAtStart || !ctx.clock.idle) return "it asked for animation frames";
1288
- const ended = subject.context({ mode: "off" });
1289
- subject.end(ended);
1290
- return compare(ctx, ended, "after the run with motion off");
1291
- }
1292
- }
1293
- ];
1294
- var CHECKS = [
1295
- ...COMMON,
1296
- {
1297
- title: "a change() to the moved mark should leave what end() draws on it",
1298
- async test(subject) {
1299
- const { moved } = subject;
1300
- if (!moved) return void 0;
1301
- const problems2 = [];
1302
- const ran = subject.context();
1303
- const run = track(subject.run(ran));
1304
- await play(ran.clock, run.done);
1305
- if (run.failed) return `run() rejected with ${describeError(run.error)}`;
1306
- moved.change(ran);
1307
- if (!await finish(ran)) return "it was still animating 10 s after the change()";
1308
- const ended = subject.context();
1309
- moved.end(ended);
1310
- const afterRun = compare(ran, ended, "after a full run and a change()");
1311
- if (afterRun) problems2.push(afterRun);
1312
- const still = subject.context({ mode: "off" });
1313
- subject.end(still);
1314
- moved.change(still);
1315
- await flush();
1316
- const endedOff = subject.context({ mode: "off" });
1317
- moved.end(endedOff);
1318
- const afterEnd = compare(still, endedOff, "after end() and a change()");
1319
- if (afterEnd) problems2.push(afterEnd);
1320
- return problems2.length > 0 ? problems2.join("; ") : void 0;
1321
- }
1322
- }
2018
+ const COMMON = [
2019
+ FULL_RUN,
2020
+ {
2021
+ title: "clearing should leave nothing behind",
2022
+ async test(subject) {
2023
+ const ctx = subject.context();
2024
+ const run = track(subject.run(ctx));
2025
+ await play(ctx.clock, run.done);
2026
+ subject.clear(ctx);
2027
+ ctx.clear();
2028
+ ctx.clock.advance(48);
2029
+ await flush();
2030
+ return leftovers(ctx);
2031
+ }
2032
+ },
2033
+ {
2034
+ title: "an abort mid-run should settle the run and clear to nothing",
2035
+ async test(subject) {
2036
+ const ctx = subject.context();
2037
+ const run = track(subject.run(ctx));
2038
+ ctx.clock.advance(16);
2039
+ ctx.clock.advance(16);
2040
+ ctx.abort();
2041
+ await settle(run);
2042
+ if (!run.settled) return "run() was still running after the abort; it should resolve once ctx.signal aborts, without more frames";
2043
+ if (run.failed) return `run() rejected with ${describeError(run.error)} (it should resolve, aborted or not)`;
2044
+ subject.clear(ctx);
2045
+ ctx.clear();
2046
+ return leftovers(ctx);
2047
+ }
2048
+ },
2049
+ {
2050
+ title: "with motion off, no frames should run and the end state should be drawn",
2051
+ async test(subject) {
2052
+ const ctx = subject.context({ mode: "off" });
2053
+ const run = track(subject.run(ctx));
2054
+ const framesAtStart = !ctx.clock.idle;
2055
+ await settle(run);
2056
+ if (!run.settled) return "run() didn't finish; with motion off ctx.tween() ends at once, so wait only through it, never on a timer";
2057
+ if (run.failed) return `run() rejected with ${describeError(run.error)}`;
2058
+ if (framesAtStart || !ctx.clock.idle) return "it asked for animation frames";
2059
+ const ended = subject.context({ mode: "off" });
2060
+ subject.end(ended);
2061
+ return compare(ctx, ended, "after the run with motion off");
2062
+ }
2063
+ }
1323
2064
  ];
2065
+ const CHECKS = [...COMMON, {
2066
+ title: "a change() to the moved mark should leave what end() draws on it",
2067
+ async test(subject) {
2068
+ const { moved } = subject;
2069
+ if (!moved) return void 0;
2070
+ const problems = [];
2071
+ const ran = subject.context();
2072
+ const run = track(subject.run(ran));
2073
+ await play(ran.clock, run.done);
2074
+ if (run.failed) return `run() rejected with ${describeError(run.error)}`;
2075
+ moved.change(ran);
2076
+ if (!await finish(ran)) return "it was still animating 10 s after the change()";
2077
+ const ended = subject.context();
2078
+ moved.end(ended);
2079
+ const afterRun = compare(ran, ended, "after a full run and a change()");
2080
+ if (afterRun) problems.push(afterRun);
2081
+ const still = subject.context({ mode: "off" });
2082
+ subject.end(still);
2083
+ moved.change(still);
2084
+ await flush();
2085
+ const endedOff = subject.context({ mode: "off" });
2086
+ moved.end(endedOff);
2087
+ const afterEnd = compare(still, endedOff, "after end() and a change()");
2088
+ if (afterEnd) problems.push(afterEnd);
2089
+ return problems.length > 0 ? problems.join("; ") : void 0;
2090
+ }
2091
+ }];
1324
2092
  async function finish(ctx) {
1325
- await flush();
1326
- for (let elapsed = 0; !ctx.clock.idle; elapsed += 16) {
1327
- if (elapsed >= 1e4) return false;
1328
- ctx.clock.advance(16);
1329
- await flush();
1330
- }
1331
- return true;
1332
- }
1333
- var defaultData = () => ({
1334
- datum: void 0,
1335
- samples: [
1336
- { t: 0, value: 0 },
1337
- { t: 1, value: 1 }
1338
- ],
1339
- related: () => void 0
1340
- });
2093
+ await flush();
2094
+ for (let elapsed = 0; !ctx.clock.idle; elapsed += 16) {
2095
+ if (elapsed >= 1e4) return false;
2096
+ ctx.clock.advance(16);
2097
+ await flush();
2098
+ }
2099
+ return true;
2100
+ }
2101
+ const defaultData = (mark) => {
2102
+ const samples = [{
2103
+ t: 0,
2104
+ value: 0
2105
+ }];
2106
+ const add = (t, gapBefore) => {
2107
+ const last = samples[samples.length - 1];
2108
+ if (t === last.t) samples[samples.length - 1] = gapBefore ? {
2109
+ ...last,
2110
+ gapBefore
2111
+ } : last;
2112
+ else samples.push(gapBefore ? {
2113
+ t,
2114
+ value: t,
2115
+ gapBefore
2116
+ } : {
2117
+ t,
2118
+ value: t
2119
+ });
2120
+ };
2121
+ for (const [from, to] of mark.gaps ?? []) {
2122
+ add(from, false);
2123
+ add(to, true);
2124
+ }
2125
+ add(1, false);
2126
+ return {
2127
+ datum: void 0,
2128
+ samples,
2129
+ related: () => void 0
2130
+ };
2131
+ };
1341
2132
  function named(marks) {
1342
- if (!Array.isArray(marks)) return Object.entries(marks).map(([name, mark]) => [`the ${name}`, mark]);
1343
- const seen = /* @__PURE__ */ new Map();
1344
- return marks.map((mark) => {
1345
- const count = (seen.get(mark.key) ?? 0) + 1;
1346
- seen.set(mark.key, count);
1347
- return [`mark "${mark.key}"${count > 1 ? ` (${count})` : ""}`, mark];
1348
- });
2133
+ if (!Array.isArray(marks)) return Object.entries(marks).map(([name, mark]) => [`the ${name}`, mark]);
2134
+ const seen = /* @__PURE__ */ new Map();
2135
+ return marks.map((mark) => {
2136
+ const count = (seen.get(mark.key) ?? 0) + 1;
2137
+ seen.set(mark.key, count);
2138
+ return [`mark "${mark.key}"${count > 1 ? ` (${count})` : ""}`, mark];
2139
+ });
1349
2140
  }
1350
2141
  function track(running) {
1351
- const state = { settled: false, failed: false, error: void 0 };
1352
- const done = running.then(
1353
- () => {
1354
- state.settled = true;
1355
- },
1356
- (error) => {
1357
- Object.assign(state, { settled: true, failed: true, error });
1358
- }
1359
- );
1360
- return Object.assign(state, { done });
2142
+ const state = {
2143
+ settled: false,
2144
+ failed: false,
2145
+ error: void 0
2146
+ };
2147
+ const done = running.then(() => {
2148
+ state.settled = true;
2149
+ }, (error) => {
2150
+ Object.assign(state, {
2151
+ settled: true,
2152
+ failed: true,
2153
+ error
2154
+ });
2155
+ });
2156
+ return Object.assign(state, { done });
1361
2157
  }
1362
2158
  async function settle(run) {
1363
- for (let i = 0; i < 10 && !run.settled; i++) await flush();
2159
+ for (let i = 0; i < 10 && !run.settled; i++) await flush();
1364
2160
  }
1365
2161
  function compare(actual, expected, when) {
1366
- const problems2 = [];
1367
- const drawn = actual.layer.picture();
1368
- const wanted = expected.layer.picture();
1369
- if (!same(drawn, wanted)) {
1370
- const index = drawn.findIndex((item, i) => !same(item, wanted[i]));
1371
- problems2.push(
1372
- drawn.length !== wanted.length ? `${drawn.length} ${drawn.length === 1 ? "item is" : "items are"} drawn ${when} but end() draws ${wanted.length} (${show2(drawn)} vs ${show2(wanted)})` : `item ${index + 1} drawn ${when} is ${show2(drawn[index])} but end() draws ${show2(wanted[index])}`
1373
- );
1374
- }
1375
- const style = rounded(actual.mark.style);
1376
- const wantedStyle = rounded(expected.mark.style);
1377
- if (!same(style, wantedStyle)) problems2.push(`the mark's style ${when} is ${show2(style)} but end() leaves ${show2(wantedStyle)}`);
1378
- return problems2.length > 0 ? problems2.join("; ") : void 0;
2162
+ const problems = [];
2163
+ const drawn = actual.layer.picture();
2164
+ const wanted = expected.layer.picture();
2165
+ if (!same(drawn, wanted)) {
2166
+ const index = drawn.findIndex((item, i) => !same(item, wanted[i]));
2167
+ problems.push(drawn.length !== wanted.length ? `${drawn.length} ${drawn.length === 1 ? "item is" : "items are"} drawn ${when} but end() draws ${wanted.length} (${show(drawn)} vs ${show(wanted)})` : `item ${index + 1} drawn ${when} is ${show(drawn[index])} but end() draws ${show(wanted[index])}`);
2168
+ }
2169
+ const style = rounded(actual.mark.style);
2170
+ const wantedStyle = rounded(expected.mark.style);
2171
+ if (!same(style, wantedStyle)) problems.push(`the mark's style ${when} is ${show(style)} but end() leaves ${show(wantedStyle)}`);
2172
+ return problems.length > 0 ? problems.join("; ") : void 0;
1379
2173
  }
1380
2174
  function leftovers(ctx) {
1381
- const problems2 = [];
1382
- if (ctx.layer.drawn.length > 0) problems2.push(`${show2(ctx.layer.picture())} is still drawn`);
1383
- if (Object.keys(ctx.mark.style).length > 0) problems2.push(`the mark's style is still ${show2(ctx.mark.style)}`);
1384
- if (!ctx.clock.idle) problems2.push("animation frames are still running");
1385
- return problems2.length > 0 ? problems2.join("; ") : void 0;
2175
+ const problems = [];
2176
+ if (ctx.layer.drawn.length > 0) problems.push(`${show(ctx.layer.picture())} is still drawn`);
2177
+ if (Object.keys(ctx.mark.style).length > 0) problems.push(`the mark's style is still ${show(ctx.mark.style)}`);
2178
+ if (!ctx.clock.idle) problems.push("animation frames are still running");
2179
+ return problems.length > 0 ? problems.join("; ") : void 0;
1386
2180
  }
1387
2181
  function same(a, b) {
1388
- if (a === b || Number.isNaN(a) && Number.isNaN(b)) return true;
1389
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
1390
- if (Array.isArray(a) !== Array.isArray(b)) return false;
1391
- const keysA = Object.keys(a).filter((key) => a[key] !== void 0);
1392
- const keysB = Object.keys(b).filter((key) => b[key] !== void 0);
1393
- return keysA.length === keysB.length && keysA.every((key) => same(a[key], b[key]));
2182
+ if (a === b || Number.isNaN(a) && Number.isNaN(b)) return true;
2183
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
2184
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
2185
+ const keysA = Object.keys(a).filter((key) => a[key] !== void 0);
2186
+ const keysB = Object.keys(b).filter((key) => b[key] !== void 0);
2187
+ return keysA.length === keysB.length && keysA.every((key) => same(a[key], b[key]));
1394
2188
  }
1395
2189
  function rounded(value) {
1396
- if (typeof value === "number") {
1397
- const round = Math.round(value * 1e3) / 1e3;
1398
- return round === 0 ? 0 : round;
1399
- }
1400
- if (Array.isArray(value)) return value.map(rounded);
1401
- if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, field]) => [key, rounded(field)]));
1402
- return value;
1403
- }
1404
- var LONGEST = 240;
1405
- function show2(value) {
1406
- const text = JSON.stringify(value) ?? String(value);
1407
- return text.length > LONGEST ? `${text.slice(0, LONGEST - 1)}\u2026` : text;
2190
+ if (typeof value === "number") {
2191
+ const round = Math.round(value * 1e3) / 1e3;
2192
+ return round === 0 ? 0 : round;
2193
+ }
2194
+ if (Array.isArray(value)) return value.map(rounded);
2195
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, field]) => [key, rounded(field)]));
2196
+ return value;
2197
+ }
2198
+ const LONGEST = 240;
2199
+ function show(value) {
2200
+ const text = JSON.stringify(value) ?? String(value);
2201
+ return text.length > LONGEST ? `${text.slice(0, 239)}…` : text;
1408
2202
  }
1409
2203
  function describeError(error) {
1410
- return error instanceof Error ? `${error.name}: ${error.message}` : show2(error);
1411
- }
1412
- // Annotate the CommonJS export names for ESM import in node:
1413
- 0 && (module.exports = {
1414
- checkEffect,
1415
- checkTransition,
1416
- fixturePairs,
1417
- fixtures,
1418
- play,
1419
- testContext
1420
- });
2204
+ return error instanceof Error ? `${error.name}: ${error.message}` : show(error);
2205
+ }
2206
+ exports.checkEffect = checkEffect;
2207
+ exports.checkTransition = checkTransition;
2208
+ exports.fixturePairs = fixturePairs;
2209
+ exports.fixtures = fixtures;
2210
+ exports.play = play;
2211
+ exports.testContext = testContext;
2212
+
1421
2213
  //# sourceMappingURL=testing.cjs.map