chartjs-test-utils 0.4.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,233 @@
1
1
  # chartjs-test-utils
2
2
 
3
- Chart.js test utils package. For usage examples, take a look at these repositories:
3
+ Chart.js test utils for [Vitest](https://vitest.dev/) browser mode.
4
4
 
5
- - [Chart.js](https://github.com/chartjs/Chart.js)
6
- - [chartjs-plugin-annotation](https://github.com/chartjs/chartjs-plugin-annotation)
7
- - [chartjs-plugin-datalabels](https://github.com/chartjs/chartjs-plugin-datalabels)
5
+ `v1` drops Karma and Jasmine: Karma was deprecated in 2023, and the pieces of
6
+ this package that existed to work around it (the `__karma__` file scan, reading
7
+ fixture configs back over `XMLHttpRequest`, `jasmine.addMatchers`) have no
8
+ counterpart in a bundler-driven runner. The rendering rules that make chart
9
+ pixels comparable across browsers and platforms are unchanged, and so are the
10
+ reference images captured with them.
11
+
12
+ Consumers still on Karma stay on `0.5.x`.
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ npm install --save-dev chartjs-test-utils vitest @vitest/browser @vitest/browser-playwright playwright
18
+ ```
19
+
20
+ ## Setup
21
+
22
+ `Chart` is injected rather than read from a global: Karma loaded the UMD bundle
23
+ into `window`, a bundler does not.
24
+
25
+ ```js
26
+ // test/setup.js
27
+ import {Chart, registerables} from 'chart.js';
28
+ import {setup} from 'chartjs-test-utils';
29
+
30
+ Chart.register(...registerables);
31
+
32
+ // Registers the matchers, the per-spec chart cleanup and `devicePixelRatio = 1`.
33
+ setup({Chart});
34
+ ```
35
+
36
+ ```js
37
+ // vitest.browser.config.ts
38
+ import {playwright} from '@vitest/browser-playwright';
39
+ import {defineConfig} from 'vitest/config';
40
+
41
+ export default defineConfig({
42
+ test: {
43
+ browser: {
44
+ enabled: true,
45
+ headless: true,
46
+ instances: [{browser: 'chromium'}, {browser: 'firefox'}],
47
+ // Browser launch options belong to the provider. Vitest accepts a
48
+ // `launch` key on an instance and silently ignores it.
49
+ provider: playwright({
50
+ launchOptions: {
51
+ args: ['--disable-accelerated-2d-canvas'],
52
+ firefoxUserPrefs: {'gfx.canvas.accelerated': false}
53
+ }
54
+ })
55
+ },
56
+ include: ['test/specs/**/*.spec.js'],
57
+ setupFiles: ['test/setup.js']
58
+ }
59
+ });
60
+ ```
61
+
62
+ Keep the canvas on the CPU. These are the flags Karma used, and they belong to
63
+ the provider: Vitest accepts `launch` or `launchOptions` on an instance and
64
+ silently ignores both. Forcing 2d acceleration back on makes no difference to a
65
+ handful of fixtures, but in the Chart.js plugin suites it fails several of them
66
+ reproducibly.
67
+
68
+ ## Charts
69
+
70
+ ```js
71
+ import {acquireChart, releaseChart, triggerMouseEvent} from 'chartjs-test-utils';
72
+
73
+ const chart = acquireChart(config, {canvas: {height: 256, width: 256}});
74
+ await triggerMouseEvent(chart, 'mousemove', chart.getDatasetMeta(0).data[0]);
75
+ ```
76
+
77
+ Charts acquired during a spec are released after it. Options that not every
78
+ browser supports (`useShadowDOM`, `useOffscreenCanvas`) skip the spec instead of
79
+ failing it, which needs the test context — Jasmine's global `pending()` has no
80
+ equivalent in Vitest:
81
+
82
+ ```js
83
+ it('renders into a shadow root', (ctx) => {
84
+ const chart = acquireChart(config, {useShadowDOM: true}, ctx);
85
+ });
86
+ ```
87
+
88
+ ## Fixtures
89
+
90
+ A fixture is a chart config plus a reference PNG of what it should render. The
91
+ file lookup has to stay in your repo: `import.meta.glob` resolves against the
92
+ file the literal pattern is written in, so `createFixtures` takes the resolved
93
+ maps instead of globbing itself.
94
+
95
+ ```js
96
+ // test/specs/fixtures.spec.js
97
+ import {createFixtures} from 'chartjs-test-utils';
98
+
99
+ const specsFromFixtures = createFixtures({
100
+ configs: {
101
+ ...import.meta.glob('../fixtures/**/*.js', {eager: true, import: 'default'}),
102
+ ...import.meta.glob('../fixtures/**/*.json', {eager: true, import: 'default'})
103
+ },
104
+ images: import.meta.glob('../fixtures/**/*.png', {eager: true, import: 'default', query: '?url'}),
105
+ prefix: '../fixtures/'
106
+ });
107
+
108
+ describe('basic', specsFromFixtures('basic'));
109
+ ```
110
+
111
+ Text rendering differs between browsers and platforms, so a fixture that draws
112
+ text should set `spriteText: true` to blit characters from the bundled sprite
113
+ sheet.
114
+
115
+ ### Updating reference images
116
+
117
+ Reference images can only be produced by a real browser, so producing them is a
118
+ mode of the fixture suite. Register the `saveFixtureImage` command only in that
119
+ mode — its presence is what the suite detects. A flag would have to go through
120
+ `define`, which Vitest re-encodes: `JSON.stringify(false)` arrives in the
121
+ browser as the string `"false"`, which is truthy, and every fixture quietly
122
+ rewrites itself while reporting a pass.
123
+
124
+ ```ts
125
+ // vitest.browser.config.ts
126
+ import {createSaveFixtureImage} from 'chartjs-test-utils/node';
127
+
128
+ const updating = process.env.UPDATE_FIXTURES === '1';
129
+
130
+ export default defineConfig({
131
+ test: {
132
+ browser: {
133
+ commands: updating ? {saveFixtureImage: createSaveFixtureImage()} : {},
134
+ // One browser is the source of truth for the images.
135
+ instances: updating ? [{browser: 'chromium'}] : [{browser: 'chromium'}, {browser: 'firefox'}]
136
+ }
137
+ }
138
+ });
139
+ ```
140
+
141
+ Only images that actually changed are rewritten, so an update is a reviewable
142
+ diff rather than every fixture touched. Regenerating one is never routine: it
143
+ means accepting that the output changed.
144
+
145
+ ## Matchers
146
+
147
+ `setup()` registers all of them.
148
+
149
+ | Matcher | Checks |
150
+ | --- | --- |
151
+ | `toEqualImageData(expected, opts)` | rendered canvas against a reference image |
152
+ | `toEqualOptions(expected)` | resolved options, ignoring `_`-prefixed properties |
153
+ | `toBeValidChart()` | chart, canvas, context and finite size |
154
+ | `toBeChartOfSize({dh, dw, rh, rw})` | display and render size |
155
+ | `toBeCloseToPixel(expected)` | within 0.5% or 2px |
156
+ | `toBeCloseToPoint({x, y})` | rounded to two decimals |
157
+ | `toEqualOneOf([...])` | value is one of the expected |
158
+
159
+ `toEqualImageData` takes `threshold` (per-pixel color distance) and `tolerance`
160
+ (accepted ratio of differing pixels). It blends transparency against white:
161
+ pixelmatch 7.2.0 made checkerboard blending the default, which is a different
162
+ measurement rather than a stricter one, and every reference image this package
163
+ has ever compared was captured against white. `checkerboard: true` opts a
164
+ fixture in once its image has been re-validated.
165
+
166
+ ## Types
167
+
168
+ The package ships type declarations, generated from the JSDoc in `src` by
169
+ `npm run types` so they cannot drift from the implementation. Chart instances
170
+ are typed as chart.js's own `Chart`, through a type-only import — chart.js is
171
+ not a runtime dependency of this package, it is injected into `setup()`.
172
+
173
+ The matchers are declared as an augmentation of Vitest's `Matchers` interface,
174
+ so `expect(chart).toEqualImageData(...)` typechecks once the package is
175
+ imported anywhere in the project. That part is hand-written in
176
+ `types/entry.d.ts`, since a declaration emit cannot produce it; the mock
177
+ context's recorded methods are declared there too, because the mock assigns
178
+ them in a loop. A unit test compares both lists against the implementation, so
179
+ they cannot fall behind it silently.
180
+
181
+ ## Node
182
+
183
+ `createMockContext()` records the calls a chart makes to a 2d context, and works
184
+ outside the browser:
185
+
186
+ ```js
187
+ import {createMockContext} from 'chartjs-test-utils';
188
+
189
+ const ctx = createMockContext();
190
+ ctx.fillRect(1, 2, 3, 4);
191
+ ctx.getCalls(); // [{name: 'fillRect', args: [1, 2, 3, 4]}]
192
+ ```
193
+
194
+ ## Development
195
+
196
+ ```sh
197
+ npm run lint # biome check
198
+ npm run format # biome check --write
199
+ npm run typecheck # the Vitest configs, through tsconfig.tooling.json
200
+ npm run types # emit the declarations into types/generated
201
+ npm test # lint, typecheck, node specs, browser specs
202
+ npm run dev # the browser suite in watch mode
203
+ npm run fixtures:update # rewrite reference images from a Chromium render
204
+ ```
205
+
206
+ Lint and formatting are Biome's, configured in `biome.jsonc`. `src/spriting.js`
207
+ is the one file with a rule exception, explained in that config: it is a port of
208
+ the 0.5.0 sprite sheet and is kept diffable against it.
209
+
210
+ ## Releases
211
+
212
+ Releases are made by [semantic-release](https://semantic-release.gitbook.io/)
213
+ from `master`: it decides the version, writes the release notes, tags, and
214
+ publishes to npm. Nothing is released by hand, and `package.json` carries
215
+ `0.0.0-development` — the published version is set during the release.
216
+
217
+ This repository merges pull requests by squash, and the squash commit takes the
218
+ **pull request title**. The title is therefore what decides the next version:
219
+
220
+ | Pull request title | Release |
221
+ | --- | --- |
222
+ | `fix: ...`, `perf: ...` | patch |
223
+ | `feat: ...` | minor |
224
+ | `feat!: ...`, or any type with a `BREAKING CHANGE:` footer | major |
225
+ | `docs:`, `test:`, `chore:`, `refactor:`, `revert:`, `ci:`, `build:`, `style:` | none |
226
+
227
+ Note `revert:` in the last row: reverting a released change does not itself
228
+ release, so an actual rollback wants `fix:`.
229
+
230
+ A workflow checks the title against this convention on every pull request, so a
231
+ title that would not release — or would release the wrong thing — fails before
232
+ review. The scope (`fix(matchers): ...`) is free text and does not affect the
233
+ version.
package/package.json CHANGED
@@ -1,25 +1,47 @@
1
1
  {
2
2
  "name": "chartjs-test-utils",
3
- "version": "0.4.0",
4
- "description": "Chart.js test utils",
5
- "main": "dist/chartjs-test-utils.js",
6
- "module": "dist/chartjs-test-utils.js",
3
+ "version": "1.0.0",
4
+ "description": "Chart.js test utils for Vitest",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "module": "./src/index.js",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./types/entry.d.ts",
11
+ "default": "./src/index.js"
12
+ },
13
+ "./node": {
14
+ "types": "./types/generated/node.d.ts",
15
+ "default": "./src/node.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
7
19
  "scripts": {
8
- "build": "rollup -c",
9
- "lint": "eslint src/**/*.js",
10
- "test": "npm run lint && npx mocha -r esm"
20
+ "dev": "vitest --config vitest.browser.config.ts",
21
+ "fixtures:update": "node scripts/update-fixtures.mjs",
22
+ "format": "biome check --write",
23
+ "lint": "biome check",
24
+ "prepack": "npm run types",
25
+ "pretypes": "node -e \"require('node:fs').rmSync('types/generated', {recursive: true, force: true})\"",
26
+ "test": "npm run lint && npm run typecheck && npm run test:types && npm run test:unit && npm run test:browser",
27
+ "test:browser": "vitest run --config vitest.browser.config.ts",
28
+ "test:types": "npm run types && tsc --noEmit -p test/types/tsconfig.json",
29
+ "test:unit": "vitest run --config vitest.config.ts",
30
+ "typecheck": "tsc --noEmit -p tsconfig.tooling.json",
31
+ "types": "tsc -p tsconfig.types.json"
11
32
  },
12
33
  "repository": {
13
34
  "type": "git",
14
35
  "url": "git+https://github.com/chartjs/chartjs-test-utils.git"
15
36
  },
16
37
  "files": [
17
- "dist/*.js"
38
+ "src/*.js",
39
+ "types/**/*.d.ts"
18
40
  ],
19
41
  "keywords": [
20
42
  "chart.js",
21
- "karma",
22
- "jasmine",
43
+ "vitest",
44
+ "playwright",
23
45
  "fixture",
24
46
  "test",
25
47
  "utils"
@@ -30,21 +52,35 @@
30
52
  },
31
53
  "homepage": "https://github.com/chartjs/chartjs-test-utils#readme",
32
54
  "devDependencies": {
33
- "@rollup/plugin-commonjs": "^20.0.0",
34
- "@rollup/plugin-node-resolve": "^13.0.0",
35
- "eslint": "^7.20.0",
36
- "eslint-config-chartjs": "^0.3.0",
37
- "eslint-plugin-es": "^4.1.0",
38
- "esm": "^3.2.25",
39
- "mocha": "^8.3.0",
40
- "rollup": "^2.39.0"
55
+ "@biomejs/biome": "^2.5.13",
56
+ "@types/node": "^26.5.1",
57
+ "@vitest/browser": "^5.0.0",
58
+ "@vitest/browser-playwright": "^5.0.0",
59
+ "chart.js": "^4.5.0",
60
+ "conventional-changelog-conventionalcommits": "^9.3.1",
61
+ "playwright": "^1.63.0",
62
+ "semantic-release": "^25.0.9",
63
+ "typescript": "^7.0.2",
64
+ "vitest": "^5.0.0"
41
65
  },
42
66
  "dependencies": {
43
- "pixelmatch": "^5.2.1"
67
+ "pixelmatch": "^7.2.0"
44
68
  },
45
69
  "peerDependencies": {
46
- "jasmine": "^3.6.4",
47
- "karma": "^6.1.1",
48
- "karma-jasmine": "^4.0.1"
70
+ "@vitest/browser": ">=5.0.0",
71
+ "vitest": ">=5.0.0"
72
+ },
73
+ "peerDependenciesMeta": {
74
+ "@vitest/browser": {
75
+ "optional": true
76
+ }
77
+ },
78
+ "types": "./types/entry.d.ts",
79
+ "typesVersions": {
80
+ "*": {
81
+ "node": [
82
+ "./types/generated/node.d.ts"
83
+ ]
84
+ }
49
85
  }
50
86
  }
package/src/canvas.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Canvas and image helpers.
3
+ *
4
+ * The Karma file server is gone, so reference PNGs arrive as bundler asset
5
+ * URLs instead of `/base/test/...` paths, and reading one resolves a promise
6
+ * instead of taking a callback.
7
+ */
8
+
9
+ /**
10
+ * @param {number} width
11
+ * @param {number} height
12
+ * @returns {HTMLCanvasElement}
13
+ */
14
+ export function createCanvas(width, height) {
15
+ const canvas = document.createElement('canvas');
16
+ canvas.height = height;
17
+ canvas.width = width;
18
+ return canvas;
19
+ }
20
+
21
+ /**
22
+ * @param {number} width
23
+ * @param {number} height
24
+ * @returns {ImageData} blank image data of the given size
25
+ */
26
+ export function createImageData(width, height) {
27
+ return createCanvas(width, height).getContext('2d').getImageData(0, 0, width, height);
28
+ }
29
+
30
+ /**
31
+ * @param {ImageData} data
32
+ * @returns {HTMLCanvasElement} a canvas with the image data drawn on it
33
+ */
34
+ export function canvasFromImageData(data) {
35
+ const canvas = createCanvas(data.width, data.height);
36
+ canvas.getContext('2d').putImageData(data, 0, 0);
37
+ return canvas;
38
+ }
39
+
40
+ /**
41
+ * Decodes a PNG into ImageData.
42
+ * @param {string} url - image url, usually produced by the bundler
43
+ * @returns {Promise<ImageData>}
44
+ */
45
+ export function readImageData(url) {
46
+ return new Promise((resolve, reject) => {
47
+ const image = new Image();
48
+ image.onerror = () => reject(new Error(`Failed to load image ${url}`));
49
+ image.onload = () => {
50
+ const {height, width} = image;
51
+ const ctx = createCanvas(width, height).getContext('2d');
52
+ ctx.drawImage(image, 0, 0, width, height);
53
+ resolve(ctx.getImageData(0, 0, width, height));
54
+ };
55
+ image.src = url;
56
+ });
57
+ }
58
+
59
+ /**
60
+ * Appends a stylesheet to the document.
61
+ * @param {string} css
62
+ */
63
+ export function injectCSS(css) {
64
+ // https://stackoverflow.com/q/3922139
65
+ const style = document.createElement('style');
66
+ style.setAttribute('type', 'text/css');
67
+ style.appendChild(document.createTextNode(css));
68
+ document.getElementsByTagName('head')[0].appendChild(style);
69
+ }
package/src/chart.js ADDED
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Chart acquisition and event helpers.
3
+ *
4
+ * `Chart` is injected through `setup()` rather than read from a global: Karma
5
+ * loaded the UMD bundle into `window`, a bundler does not.
6
+ */
7
+ import {spritingOff, spritingOn} from './spriting.js';
8
+
9
+ /**
10
+ * The chart.js types are used type-only: the constructor itself is injected
11
+ * through `setup({Chart})`, so chart.js is not a runtime dependency here. A
12
+ * consumer of this package always has chart.js -- that is what it is for.
13
+ * @typedef {import('chart.js').Chart} ChartInstance
14
+ * @typedef {typeof import('chart.js').Chart} ChartConstructor
15
+ * @typedef {object} AcquireOptions
16
+ * @property {object} [canvas] - Canvas attributes.
17
+ * @property {object} [wrapper] - Canvas wrapper attributes.
18
+ * @property {boolean} [useOffscreenCanvas] - use an OffscreenCanvas instead of the normal HTMLCanvasElement.
19
+ * @property {boolean} [useShadowDOM] - use shadowDom.
20
+ * @property {boolean} [spriteText] - draw text from a bitmap sprite sheet.
21
+ * @property {boolean} [persistent] - If true, the chart will not be released after the spec.
22
+ * @typedef {{skip: (reason?: string) => void}} TestContext
23
+ */
24
+
25
+ // Every chart acquired by a spec, so they can all be released afterwards.
26
+ const charts = {};
27
+
28
+ let Chart;
29
+
30
+ /**
31
+ * Registers the Chart.js constructor used to build charts. Called by `setup()`.
32
+ * @param {ChartConstructor} chartConstructor - the `Chart` export of chart.js
33
+ */
34
+ export function useChart(chartConstructor) {
35
+ Chart = chartConstructor;
36
+ }
37
+
38
+ /** @returns {ChartConstructor} the registered Chart.js constructor */
39
+ export function getChart() {
40
+ return Chart;
41
+ }
42
+
43
+ /**
44
+ * Skips the running spec, or throws when no test context was given.
45
+ * Jasmine had a global `pending()`; in Vitest skipping is a method on the test
46
+ * context, so a helper can only skip when the spec passes its context in.
47
+ */
48
+ function skip(ctx, reason) {
49
+ if (ctx && typeof ctx.skip === 'function') {
50
+ return ctx.skip(reason);
51
+ }
52
+ throw new Error(
53
+ `${reason}. Pass the test context to acquireChart to skip instead: it('...', (ctx) => acquireChart(config, options, ctx))`
54
+ );
55
+ }
56
+
57
+ function applyAttributes(node, attributes) {
58
+ for (const key of Object.keys(attributes)) {
59
+ node.setAttribute(key, attributes[key]);
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Skips the spec when the browser lacks a feature the options ask for. Checked
65
+ * before anything is added to the document, so an aborted spec leaves no
66
+ * wrapper behind.
67
+ */
68
+ function checkSupport(options, ctx) {
69
+ if (options.useShadowDOM && !Element.prototype.attachShadow) {
70
+ skip(ctx, 'This browser does not support the shadow DOM');
71
+ }
72
+ if (options.useOffscreenCanvas && !HTMLCanvasElement.prototype.transferControlToOffscreen) {
73
+ skip(ctx, 'This browser does not support OffscreenCanvas');
74
+ }
75
+ }
76
+
77
+ function acquireContext(canvas, options) {
78
+ return options.useOffscreenCanvas ? canvas.transferControlToOffscreen().getContext('2d') : canvas.getContext('2d');
79
+ }
80
+
81
+ /**
82
+ * Injects a new canvas (and div wrapper) and creates the associated Chart instance
83
+ * using the given config. Additional options allow tweaking elements generation.
84
+ * @param {object} [config] - Chart config.
85
+ * @param {AcquireOptions} [options] - Chart acquisition options.
86
+ * @param {TestContext} [ctx] - Vitest test context, required by options that may be unsupported.
87
+ * @returns {ChartInstance} the chart
88
+ */
89
+ export function buildChart(config = {}, options = {}, ctx) {
90
+ if (!Chart) {
91
+ throw new Error('No Chart.js constructor registered. Call setup({Chart}) from your setup file.');
92
+ }
93
+
94
+ checkSupport(options, ctx);
95
+
96
+ const wrapper = document.createElement('div');
97
+ const canvas = document.createElement('canvas');
98
+
99
+ applyAttributes(canvas, options.canvas || {height: 512, width: 512});
100
+ applyAttributes(wrapper, options.wrapper || {class: 'chartjs-wrapper'});
101
+
102
+ // by default, remove chart animation and auto resize
103
+ config.options = config.options || {};
104
+ config.options.animation = config.options.animation === undefined ? false : config.options.animation;
105
+ config.options.responsive = config.options.responsive === undefined ? false : config.options.responsive;
106
+ config.options.locale = config.options.locale || 'en-US';
107
+
108
+ if (options.useShadowDOM) {
109
+ wrapper.attachShadow({mode: 'open'}).appendChild(canvas);
110
+ } else {
111
+ wrapper.appendChild(canvas);
112
+ }
113
+ document.body.appendChild(wrapper);
114
+
115
+ let chart;
116
+ try {
117
+ const context = acquireContext(canvas, options);
118
+ if (options.spriteText) {
119
+ spritingOn(context);
120
+ }
121
+ chart = new Chart(context, config);
122
+ } catch (e) {
123
+ document.body.removeChild(wrapper);
124
+ throw e;
125
+ }
126
+
127
+ chart.$test = {persistent: options.persistent, wrapper};
128
+ return chart;
129
+ }
130
+
131
+ /** @param {ChartInstance} chart */
132
+ export function destroyChart(chart) {
133
+ spritingOff(chart.ctx);
134
+ chart.destroy();
135
+
136
+ const wrapper = chart.$test?.wrapper;
137
+ wrapper?.parentNode?.removeChild(wrapper);
138
+ }
139
+
140
+ /**
141
+ * Builds a chart and registers it for release after the spec.
142
+ * @param {object} [config] - Chart config.
143
+ * @param {AcquireOptions} [options] - Chart acquisition options.
144
+ * @param {TestContext} [ctx] - Vitest test context, required by options that may be unsupported.
145
+ * @returns {ChartInstance} the chart
146
+ */
147
+ export function acquireChart(config, options, ctx) {
148
+ const chart = buildChart(config, options, ctx);
149
+ charts[chart.id] = chart;
150
+ return chart;
151
+ }
152
+
153
+ /**
154
+ * Destroys a chart and removes it from the registry.
155
+ * @param {ChartInstance} chart
156
+ */
157
+ export function releaseChart(chart) {
158
+ destroyChart(chart);
159
+ delete charts[chart.id];
160
+ }
161
+
162
+ /** Releases every chart acquired since the last call, except persistent ones. */
163
+ export function releaseCharts() {
164
+ for (const id of Object.keys(charts)) {
165
+ const chart = charts[id];
166
+ if (!chart.$test?.persistent) {
167
+ destroyChart(chart);
168
+ delete charts[id];
169
+ }
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Runs `callback` once the chart has handled an event of the given type.
175
+ * @param {ChartInstance} chart
176
+ * @param {string} type - event type, e.g. `mousemove`
177
+ * @param {() => void} callback
178
+ */
179
+ export function afterEvent(chart, type, callback) {
180
+ const override = chart._eventHandler;
181
+ chart._eventHandler = function (event) {
182
+ override.call(this, event);
183
+ if (event.type === type || (event.native && event.native.type === type)) {
184
+ chart._eventHandler = override;
185
+ callback();
186
+ }
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Runs `callback` after the chart's next resize.
192
+ * @param {ChartInstance} chart
193
+ * @param {() => void} callback
194
+ */
195
+ export function waitForResize(chart, callback) {
196
+ const override = chart.resize;
197
+ chart.resize = function (...args) {
198
+ chart.resize = override;
199
+ override.apply(this, args);
200
+ callback();
201
+ };
202
+ }
203
+
204
+ function resolveElementPoint(el) {
205
+ if (el) {
206
+ if (typeof el.getCenterPoint === 'function') {
207
+ return el.getCenterPoint();
208
+ }
209
+ if (el.x !== undefined && el.y !== undefined) {
210
+ return el;
211
+ }
212
+ }
213
+ return {x: 0, y: 0};
214
+ }
215
+
216
+ /**
217
+ * Dispatches a mouse event at an element's position and awaits its handling.
218
+ * @param {ChartInstance} chart
219
+ * @param {string} type - event type, e.g. `mousemove`
220
+ * @param {{x?: number, y?: number, getCenterPoint?: () => {x: number, y: number}}} [el]
221
+ * element to aim at; the chart's origin when omitted
222
+ * @returns {Promise<MouseEvent>} the dispatched event
223
+ */
224
+ export async function triggerMouseEvent(chart, type, el) {
225
+ const node = chart.canvas;
226
+ const rect = node.getBoundingClientRect();
227
+ const point = resolveElementPoint(el);
228
+ const event = new MouseEvent(type, {
229
+ bubbles: true,
230
+ cancelable: true,
231
+ clientX: rect.left + point.x,
232
+ clientY: rect.top + point.y,
233
+ view: window
234
+ });
235
+
236
+ const handled = new Promise((resolve) => afterEvent(chart, type, resolve));
237
+ node.dispatchEvent(event);
238
+ await handled;
239
+
240
+ return event;
241
+ }