energy-visualization-sankey 1.0.27 → 1.2.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 +125 -0
- package/babel.config.cjs +18 -21
- package/dist/.tsbuildinfo +1 -0
- package/dist/sankey.esm.js +490 -160
- package/dist/sankey.esm.js.map +1 -1
- package/dist/sankey.umd.js +490 -160
- package/dist/sankey.umd.js.map +1 -1
- package/dist/types/core/Sankey.d.ts +60 -46
- package/dist/types/core/Sankey.d.ts.map +1 -1
- package/dist/types/core/types/public-events.d.ts +159 -0
- package/dist/types/core/types/public-events.d.ts.map +1 -0
- package/dist/types/index.d.ts +2 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/services/AnimationService.d.ts.map +1 -1
- package/dist/types/services/InteractionService.d.ts.map +1 -1
- package/dist/types/services/data/DataValidationService.d.ts.map +1 -1
- package/dist/types/types/index.d.ts +40 -0
- package/dist/types/types/index.d.ts.map +1 -1
- package/dist/types/utils/header.d.ts +54 -0
- package/dist/types/utils/header.d.ts.map +1 -0
- package/jest.config.cjs +22 -7
- package/package.json +3 -2
- package/src/core/Sankey.ts +291 -61
- package/src/core/types/public-events.ts +189 -0
- package/src/index.ts +23 -0
- package/src/services/AnimationService.ts +34 -19
- package/src/services/InteractionService.ts +49 -31
- package/src/services/data/DataValidationService.ts +8 -5
- package/src/types/index.ts +47 -0
- package/src/utils/header.ts +238 -0
- package/tests/event-bus.test.ts +137 -0
- package/tests/header.test.ts +198 -0
- package/tests/sankey-events.test.ts +289 -0
- package/tests/setup.js +13 -48
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EventBus behaviours the public event API depends on
|
|
3
|
+
*
|
|
4
|
+
* These are not incidental implementation details: each one directly justifies a
|
|
5
|
+
* design decision in Sankey's on()/once()/off() and in the `events` constructor
|
|
6
|
+
* option. If one of these changes, the public API has to change with it.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {EventBus} from '@/core/events/EventBus';
|
|
10
|
+
import type {SankeyEvent, SankeyEventType} from '@/core/types/events';
|
|
11
|
+
import type {SankeyOptions} from '@/types';
|
|
12
|
+
import {Logger} from '@/utils/Logger';
|
|
13
|
+
|
|
14
|
+
const makeBus = (): EventBus => new EventBus(new Logger({data: [], country: 'US'} as SankeyOptions));
|
|
15
|
+
|
|
16
|
+
const evt = (type: SankeyEventType, data: any): SankeyEvent<any> => ({
|
|
17
|
+
type,
|
|
18
|
+
timestamp: Date.now(),
|
|
19
|
+
source: 'test',
|
|
20
|
+
data
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** Dispatch happens in a microtask, so one turn of the queue is enough here. */
|
|
24
|
+
const drain = (): Promise<void> => Promise.resolve();
|
|
25
|
+
|
|
26
|
+
describe('EventBus', () => {
|
|
27
|
+
describe('dispatch timing', () => {
|
|
28
|
+
it('should dispatch on a microtask rather than synchronously', async () => {
|
|
29
|
+
const bus = makeBus();
|
|
30
|
+
const seen: number[] = [];
|
|
31
|
+
bus.subscribe('year.changed', (event) => {
|
|
32
|
+
seen.push(event.data.year);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
bus.emit(evt('year.changed', {year: 1900}));
|
|
36
|
+
expect(seen).toEqual([]);
|
|
37
|
+
|
|
38
|
+
await drain();
|
|
39
|
+
expect(seen).toEqual([1900]);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('delivery guarantees', () => {
|
|
44
|
+
// This is why the `events` constructor option exists: a handler attached
|
|
45
|
+
// after initialization has already emitted 'system.ready' never sees it.
|
|
46
|
+
it('should silently drop events that have no subscriber, with no replay', async () => {
|
|
47
|
+
const bus = makeBus();
|
|
48
|
+
bus.emit(evt('system.ready', {totalInitTime: 1, dataPointCount: 1, yearRange: [1800, 2021]}));
|
|
49
|
+
|
|
50
|
+
const late = jest.fn();
|
|
51
|
+
bus.subscribe('system.ready', late);
|
|
52
|
+
await drain();
|
|
53
|
+
|
|
54
|
+
expect(late).not.toHaveBeenCalled();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('should isolate a handler that throws from the other handlers', async () => {
|
|
58
|
+
const bus = makeBus();
|
|
59
|
+
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {
|
|
60
|
+
});
|
|
61
|
+
const survivor = jest.fn();
|
|
62
|
+
|
|
63
|
+
bus.subscribe('year.changed', () => {
|
|
64
|
+
throw new Error('boom');
|
|
65
|
+
});
|
|
66
|
+
bus.subscribe('year.changed', survivor);
|
|
67
|
+
|
|
68
|
+
bus.emit(evt('year.changed', {year: 1900}));
|
|
69
|
+
await drain();
|
|
70
|
+
|
|
71
|
+
expect(survivor).toHaveBeenCalledTimes(1);
|
|
72
|
+
consoleError.mockRestore();
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
describe('handler identity deduplication', () => {
|
|
77
|
+
// REGRESSION GUARD for the wrapper closure in Sankey.addListener().
|
|
78
|
+
// The bus stores handlers in a Set keyed by function identity, so the
|
|
79
|
+
// same reference registered twice collapses to one entry and a single
|
|
80
|
+
// unsubscribe silently removes both logical subscriptions.
|
|
81
|
+
it('should collapse an identical handler reference into one Set entry', async () => {
|
|
82
|
+
const bus = makeBus();
|
|
83
|
+
const handler = jest.fn();
|
|
84
|
+
|
|
85
|
+
const first = bus.subscribe('year.changed', handler);
|
|
86
|
+
bus.subscribe('year.changed', handler);
|
|
87
|
+
|
|
88
|
+
bus.unsubscribe(first);
|
|
89
|
+
bus.emit(evt('year.changed', {year: 1900}));
|
|
90
|
+
await drain();
|
|
91
|
+
|
|
92
|
+
expect(handler).not.toHaveBeenCalled();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('should keep distinct closures independently removable', async () => {
|
|
96
|
+
const bus = makeBus();
|
|
97
|
+
const handler = jest.fn();
|
|
98
|
+
|
|
99
|
+
const first = bus.subscribe('year.changed', (event) => handler(event));
|
|
100
|
+
bus.subscribe('year.changed', (event) => handler(event));
|
|
101
|
+
|
|
102
|
+
bus.unsubscribe(first);
|
|
103
|
+
bus.emit(evt('year.changed', {year: 1900}));
|
|
104
|
+
await drain();
|
|
105
|
+
|
|
106
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
describe('clear', () => {
|
|
111
|
+
it('should stop delivery for handlers registered before the call', async () => {
|
|
112
|
+
const bus = makeBus();
|
|
113
|
+
const handler = jest.fn();
|
|
114
|
+
bus.subscribe('year.changed', handler);
|
|
115
|
+
|
|
116
|
+
bus.clear();
|
|
117
|
+
bus.emit(evt('year.changed', {year: 1900}));
|
|
118
|
+
await drain();
|
|
119
|
+
|
|
120
|
+
expect(handler).not.toHaveBeenCalled();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// Documents why 'system.error' still reaches handlers even though
|
|
124
|
+
// handleInitializationError() calls destroy() right after emitting.
|
|
125
|
+
it('should still deliver an emit that was already in flight', async () => {
|
|
126
|
+
const bus = makeBus();
|
|
127
|
+
const handler = jest.fn();
|
|
128
|
+
bus.subscribe('system.error', handler);
|
|
129
|
+
|
|
130
|
+
bus.emit(evt('system.error', {error: new Error('x'), context: 'initialization', recoverable: false}));
|
|
131
|
+
bus.clear();
|
|
132
|
+
await drain();
|
|
133
|
+
|
|
134
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
});
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configurable header
|
|
3
|
+
*
|
|
4
|
+
* Unit tests for the pure helpers in utils/header plus DOM tests against the
|
|
5
|
+
* real class in jsdom, using the same dataset as sankey-events.test.ts.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import * as fs from 'fs';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
|
|
11
|
+
import Sankey from '@/core/Sankey';
|
|
12
|
+
import {SankeyError} from '@/types';
|
|
13
|
+
import type {EnergyDataPoint, SankeyHeaderOptions, SankeyOptions} from '@/types';
|
|
14
|
+
import {DEFAULT_HEADER, escapeHtml, isHttpsUrl, resolveHeader} from '@/utils/header';
|
|
15
|
+
|
|
16
|
+
const actualData: EnergyDataPoint[] = JSON.parse(
|
|
17
|
+
fs.readFileSync(path.join(__dirname, '../examples/data/us.json'), 'utf8')
|
|
18
|
+
);
|
|
19
|
+
const firstYear = Math.min(...actualData.map(d => d.year));
|
|
20
|
+
const lastYear = Math.max(...actualData.map(d => d.year));
|
|
21
|
+
|
|
22
|
+
const flush = (): Promise<void> => new Promise(resolve => setTimeout(resolve, 0));
|
|
23
|
+
|
|
24
|
+
const baseOptions = (overrides: Partial<SankeyOptions> = {}): SankeyOptions => ({
|
|
25
|
+
data: actualData,
|
|
26
|
+
country: 'US',
|
|
27
|
+
width: 1400,
|
|
28
|
+
...overrides
|
|
29
|
+
} as SankeyOptions);
|
|
30
|
+
|
|
31
|
+
const context = {country: 'China', firstYear: 1950, lastYear: 2020};
|
|
32
|
+
|
|
33
|
+
describe('header helpers', () => {
|
|
34
|
+
it('escapeHtml escapes markup and quotes', () => {
|
|
35
|
+
expect(escapeHtml(`<a href="x" onclick='y'>&</a>`))
|
|
36
|
+
.toBe('<a href="x" onclick='y'>&</a>');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('isHttpsUrl accepts only https URLs', () => {
|
|
40
|
+
expect(isHttpsUrl('https://example.org/logo.png')).toBe(true);
|
|
41
|
+
expect(isHttpsUrl('http://example.org/logo.png')).toBe(false);
|
|
42
|
+
expect(isHttpsUrl('javascript:alert(1)')).toBe(false);
|
|
43
|
+
expect(isHttpsUrl('data:image/png;base64,AAAA')).toBe(false);
|
|
44
|
+
expect(isHttpsUrl('not a url')).toBe(false);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('resolveHeader without options gives the historical defaults', () => {
|
|
48
|
+
expect(resolveHeader(undefined, context)).toEqual({
|
|
49
|
+
title: 'China energy usage',
|
|
50
|
+
subtitle: 'Energy Transitions in China History, 1950-2020',
|
|
51
|
+
attribution: 'Suits, Matteson, and Moyer (2020)',
|
|
52
|
+
affiliation: ['Center for Robust Decision-making on', 'Climate and Energy Policy, UChicago'],
|
|
53
|
+
logo: {...DEFAULT_HEADER.logo}
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('resolveHeader substitutes placeholders in every text field', () => {
|
|
58
|
+
const resolved = resolveHeader({
|
|
59
|
+
title: '{country}',
|
|
60
|
+
subtitle: '{firstYear} to {lastYear}',
|
|
61
|
+
attribution: 'Data for {country}, {lastYear}',
|
|
62
|
+
affiliation: ['{country} team']
|
|
63
|
+
}, context);
|
|
64
|
+
|
|
65
|
+
expect(resolved.title).toBe('China');
|
|
66
|
+
expect(resolved.subtitle).toBe('1950 to 2020');
|
|
67
|
+
expect(resolved.attribution).toBe('Data for China, 2020');
|
|
68
|
+
expect(resolved.affiliation).toEqual(['China team']);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('resolveHeader hides null and blank values', () => {
|
|
72
|
+
const resolved = resolveHeader({
|
|
73
|
+
title: null,
|
|
74
|
+
subtitle: ' ',
|
|
75
|
+
attribution: null,
|
|
76
|
+
affiliation: ['', ' '],
|
|
77
|
+
logo: null
|
|
78
|
+
}, context);
|
|
79
|
+
|
|
80
|
+
expect(resolved).toEqual({
|
|
81
|
+
title: null, subtitle: null, attribution: null, affiliation: null, logo: null
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('resolveHeader uses a custom logo without falling back to the RDCEP link', () => {
|
|
86
|
+
expect(resolveHeader({logo: {src: 'https://example.org/l.png'}}, context).logo)
|
|
87
|
+
.toEqual({src: 'https://example.org/l.png', href: null, alt: ''});
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
describe('Sankey header rendering', () => {
|
|
92
|
+
let sankey: Sankey | null = null;
|
|
93
|
+
|
|
94
|
+
const text = (selector: string): string[] =>
|
|
95
|
+
Array.from(document.querySelectorAll(selector)).map(el => el.textContent ?? '');
|
|
96
|
+
|
|
97
|
+
const create = async (header?: SankeyHeaderOptions, country = 'US'): Promise<void> => {
|
|
98
|
+
sankey = new Sankey('sankey', baseOptions({header, country}));
|
|
99
|
+
await flush();
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
beforeEach(() => {
|
|
103
|
+
document.body.innerHTML = '<div id="sankey"></div>';
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
afterEach(() => {
|
|
107
|
+
sankey?.destroy();
|
|
108
|
+
sankey = null;
|
|
109
|
+
document.body.innerHTML = '';
|
|
110
|
+
jest.restoreAllMocks();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('renders the historical header when no header option is given', async () => {
|
|
114
|
+
await create();
|
|
115
|
+
|
|
116
|
+
expect(text('.evs-main-title')).toEqual(['US energy usage']);
|
|
117
|
+
expect(text('.evs-subtitle')).toEqual([`Energy Transitions in US History, ${firstYear}-${lastYear}`]);
|
|
118
|
+
expect(text('.evs-attribution')).toEqual(['Suits, Matteson, and Moyer (2020)']);
|
|
119
|
+
expect(text('.evs-affiliation-text')).toEqual([
|
|
120
|
+
'Center for Robust Decision-making on',
|
|
121
|
+
'Climate and Energy Policy, UChicago'
|
|
122
|
+
]);
|
|
123
|
+
|
|
124
|
+
const link = document.querySelector('.evs-header-logo a') as HTMLAnchorElement;
|
|
125
|
+
expect(link.getAttribute('href')).toBe('https://www.rdcep.org/');
|
|
126
|
+
const img = link.querySelector('img') as HTMLImageElement;
|
|
127
|
+
expect(img.getAttribute('src')).toBe(DEFAULT_HEADER.logo.src);
|
|
128
|
+
expect(img.getAttribute('alt')).toBe(DEFAULT_HEADER.logo.alt);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('renders overridden values', async () => {
|
|
132
|
+
await create({
|
|
133
|
+
title: 'Energy in {country}',
|
|
134
|
+
attribution: 'Author A and Author B (2024)',
|
|
135
|
+
affiliation: ['Line one'],
|
|
136
|
+
logo: {src: 'https://example.org/l.png', href: 'https://example.org/', alt: 'Example'}
|
|
137
|
+
}, 'China');
|
|
138
|
+
|
|
139
|
+
expect(text('.evs-main-title')).toEqual(['Energy in China']);
|
|
140
|
+
expect(text('.evs-attribution')).toEqual(['Author A and Author B (2024)']);
|
|
141
|
+
expect(text('.evs-affiliation-text')).toEqual(['Line one']);
|
|
142
|
+
// Not overridden, so still the default, with the new country.
|
|
143
|
+
expect(text('.evs-subtitle')).toEqual([`Energy Transitions in China History, ${firstYear}-${lastYear}`]);
|
|
144
|
+
expect(document.querySelector('.evs-header-logo a')!.getAttribute('href')).toBe('https://example.org/');
|
|
145
|
+
expect(document.querySelector('.evs-header-logo img')!.getAttribute('alt')).toBe('Example');
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it('hides elements set to null but keeps the animated overlays', async () => {
|
|
149
|
+
await create({title: null, subtitle: null, attribution: null, affiliation: null, logo: null});
|
|
150
|
+
|
|
151
|
+
expect(document.querySelector('.evs-main-title')).toBeNull();
|
|
152
|
+
expect(document.querySelector('.evs-header-info')).toBeNull();
|
|
153
|
+
expect(document.querySelector('.evs-header-affiliation')).toBeNull();
|
|
154
|
+
expect(document.querySelector('.evs-header-logo')).toBeNull();
|
|
155
|
+
|
|
156
|
+
expect(document.querySelector('.evs-energy-usage-overlay svg#evs-energy-usage-overlay')).not.toBeNull();
|
|
157
|
+
expect(document.querySelector('.evs-year-overlay svg#evs-year-overlay')).not.toBeNull();
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it('keeps the info block when only one of subtitle and attribution is hidden', async () => {
|
|
161
|
+
await create({subtitle: null});
|
|
162
|
+
|
|
163
|
+
expect(document.querySelector('.evs-subtitle')).toBeNull();
|
|
164
|
+
expect(text('.evs-attribution')).toEqual(['Suits, Matteson, and Moyer (2020)']);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it('renders markup in header text and country as plain text', async () => {
|
|
168
|
+
const payload = '<img src=x onerror="window.__xss=1"><script>window.__xss=1</script>';
|
|
169
|
+
await create({attribution: payload, affiliation: [payload]}, payload);
|
|
170
|
+
|
|
171
|
+
// Only the logo image exists; nothing was injected.
|
|
172
|
+
expect(document.querySelectorAll('.evs-title-container img')).toHaveLength(1);
|
|
173
|
+
expect(document.querySelectorAll('.evs-title-container script')).toHaveLength(0);
|
|
174
|
+
expect(text('.evs-attribution')).toEqual([payload]);
|
|
175
|
+
expect(text('.evs-affiliation-text')).toEqual([payload]);
|
|
176
|
+
expect(text('.evs-main-title')).toEqual([`${payload} energy usage`]);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
describe('validation', () => {
|
|
180
|
+
const construct = (header: unknown) => () =>
|
|
181
|
+
new Sankey('sankey', baseOptions({header: header as SankeyHeaderOptions}));
|
|
182
|
+
|
|
183
|
+
it.each([
|
|
184
|
+
['javascript: logo src', {logo: {src: 'javascript:alert(1)'}}],
|
|
185
|
+
['http logo src', {logo: {src: 'http://example.org/l.png'}}],
|
|
186
|
+
['javascript: logo href', {logo: {src: 'https://example.org/l.png', href: 'javascript:alert(1)'}}],
|
|
187
|
+
['missing logo src', {logo: {}}],
|
|
188
|
+
['unknown header key', {author: 'x'}],
|
|
189
|
+
['unknown logo key', {logo: {src: 'https://example.org/l.png', onload: 'x'}}],
|
|
190
|
+
['non-string title', {title: 42}],
|
|
191
|
+
['non-array affiliation', {affiliation: 'one line'}],
|
|
192
|
+
['non-string affiliation line', {affiliation: ['ok', 3]}],
|
|
193
|
+
['header that is not an object', 'title']
|
|
194
|
+
])('rejects %s', (_label, header) => {
|
|
195
|
+
expect(construct(header)).toThrow(SankeyError);
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
});
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public event API of the Sankey visualization
|
|
3
|
+
*
|
|
4
|
+
* Exercises the real class against the real dataset in jsdom, rather than the
|
|
5
|
+
* hand-written mocks used by numerical-validation.test.js.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import * as fs from 'fs';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
|
|
11
|
+
import Sankey from '@/core/Sankey';
|
|
12
|
+
import type {EnergyDataPoint, SankeyOptions} from '@/types';
|
|
13
|
+
|
|
14
|
+
const actualData: EnergyDataPoint[] = JSON.parse(
|
|
15
|
+
fs.readFileSync(path.join(__dirname, '../examples/data/us.json'), 'utf8')
|
|
16
|
+
);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* initialize() chains several awaits before emitting 'system.ready', so a single
|
|
20
|
+
* `await Promise.resolve()` is not enough to observe it. A macrotask turn drains
|
|
21
|
+
* the whole chain.
|
|
22
|
+
*/
|
|
23
|
+
const flush = (): Promise<void> => new Promise(resolve => setTimeout(resolve, 0));
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* An explicit width keeps assertions deterministic: getBoundingClientRect()
|
|
27
|
+
* returns 0 under jsdom, which would otherwise fall through to a default.
|
|
28
|
+
*/
|
|
29
|
+
const baseOptions = (overrides: Partial<SankeyOptions> = {}): SankeyOptions => ({
|
|
30
|
+
data: actualData,
|
|
31
|
+
country: 'US',
|
|
32
|
+
width: 1400,
|
|
33
|
+
...overrides
|
|
34
|
+
} as SankeyOptions);
|
|
35
|
+
|
|
36
|
+
describe('Sankey public event API', () => {
|
|
37
|
+
let sankey: Sankey | null = null;
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
document.body.innerHTML = '<div id="sankey"></div>';
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
afterEach(() => {
|
|
44
|
+
sankey?.destroy();
|
|
45
|
+
sankey = null;
|
|
46
|
+
document.body.innerHTML = '';
|
|
47
|
+
jest.restoreAllMocks();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe('events constructor option', () => {
|
|
51
|
+
it('should deliver system.ready, which a later subscription would miss', async () => {
|
|
52
|
+
const onReady = jest.fn();
|
|
53
|
+
sankey = new Sankey('sankey', baseOptions({events: {'system.ready': onReady}}));
|
|
54
|
+
|
|
55
|
+
await flush();
|
|
56
|
+
|
|
57
|
+
expect(onReady).toHaveBeenCalledTimes(1);
|
|
58
|
+
const event = onReady.mock.calls[0][0];
|
|
59
|
+
expect(event.type).toBe('system.ready');
|
|
60
|
+
expect(event.data.dataPointCount).toBe(actualData.length);
|
|
61
|
+
expect(event.data.yearRange).toEqual([1800, 2021]);
|
|
62
|
+
expect(typeof event.data.totalInitTime).toBe('number');
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('should ignore a non-function entry rather than throwing', async () => {
|
|
66
|
+
sankey = new Sankey('sankey', baseOptions({events: {'system.ready': undefined}}));
|
|
67
|
+
await flush();
|
|
68
|
+
|
|
69
|
+
expect(sankey.isInitialized()).toBe(true);
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
describe('whenReady', () => {
|
|
74
|
+
it('should resolve for a caller that awaits it after initialization finished', async () => {
|
|
75
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
76
|
+
|
|
77
|
+
// Deliberately let initialization complete before touching the latch.
|
|
78
|
+
await flush();
|
|
79
|
+
await flush();
|
|
80
|
+
|
|
81
|
+
const event = await sankey.whenReady();
|
|
82
|
+
expect(event.type).toBe('system.ready');
|
|
83
|
+
expect(event.data.dataPointCount).toBe(actualData.length);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('should reject when the instance is destroyed before it becomes ready', async () => {
|
|
87
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
88
|
+
const pending = sankey.whenReady();
|
|
89
|
+
|
|
90
|
+
sankey.destroy();
|
|
91
|
+
|
|
92
|
+
await expect(pending).rejects.toThrow(/destroyed before initialization/);
|
|
93
|
+
sankey = null;
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
describe('on', () => {
|
|
98
|
+
it('should deliver year.changed with isAnimating false for a programmatic change', async () => {
|
|
99
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
100
|
+
await flush();
|
|
101
|
+
|
|
102
|
+
const handler = jest.fn();
|
|
103
|
+
sankey.on('year.changed', handler);
|
|
104
|
+
|
|
105
|
+
const years = sankey.getYears();
|
|
106
|
+
sankey.setYear(years[5]);
|
|
107
|
+
await flush();
|
|
108
|
+
|
|
109
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
110
|
+
const {data} = handler.mock.calls[0][0];
|
|
111
|
+
expect(data.year).toBe(years[5]);
|
|
112
|
+
expect(data.yearIndex).toBe(5);
|
|
113
|
+
expect(data.isAnimating).toBe(false);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('should register the same handler reference twice and call it twice', async () => {
|
|
117
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
118
|
+
await flush();
|
|
119
|
+
|
|
120
|
+
const handler = jest.fn();
|
|
121
|
+
const stopFirst = sankey.on('year.changed', handler);
|
|
122
|
+
sankey.on('year.changed', handler);
|
|
123
|
+
|
|
124
|
+
const years = sankey.getYears();
|
|
125
|
+
sankey.setYear(years[1]);
|
|
126
|
+
await flush();
|
|
127
|
+
expect(handler).toHaveBeenCalledTimes(2);
|
|
128
|
+
|
|
129
|
+
// The bus dedupes by function identity, so this only works because
|
|
130
|
+
// each registration is wrapped in its own closure.
|
|
131
|
+
handler.mockClear();
|
|
132
|
+
stopFirst();
|
|
133
|
+
sankey.setYear(years[2]);
|
|
134
|
+
await flush();
|
|
135
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('should return an unsubscribe function that is safe to call twice', async () => {
|
|
139
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
140
|
+
await flush();
|
|
141
|
+
|
|
142
|
+
const handler = jest.fn();
|
|
143
|
+
const stop = sankey.on('year.changed', handler);
|
|
144
|
+
const years = sankey.getYears();
|
|
145
|
+
|
|
146
|
+
stop();
|
|
147
|
+
expect(() => stop()).not.toThrow();
|
|
148
|
+
|
|
149
|
+
sankey.setYear(years[3]);
|
|
150
|
+
await flush();
|
|
151
|
+
expect(handler).not.toHaveBeenCalled();
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('should not let a throwing handler break the visualization', async () => {
|
|
155
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
156
|
+
await flush();
|
|
157
|
+
|
|
158
|
+
jest.spyOn(console, 'error').mockImplementation(() => {
|
|
159
|
+
});
|
|
160
|
+
const survivor = jest.fn();
|
|
161
|
+
sankey.on('year.changed', () => {
|
|
162
|
+
throw new Error('handler exploded');
|
|
163
|
+
});
|
|
164
|
+
sankey.on('year.changed', survivor);
|
|
165
|
+
|
|
166
|
+
const years = sankey.getYears();
|
|
167
|
+
sankey.setYear(years[4]);
|
|
168
|
+
await flush();
|
|
169
|
+
|
|
170
|
+
expect(survivor).toHaveBeenCalledTimes(1);
|
|
171
|
+
expect(sankey.getCurrentYear()).toBe(years[4]);
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
describe('once', () => {
|
|
176
|
+
it('should fire exactly once across two year changes', async () => {
|
|
177
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
178
|
+
await flush();
|
|
179
|
+
|
|
180
|
+
const handler = jest.fn();
|
|
181
|
+
sankey.once('year.changed', handler);
|
|
182
|
+
|
|
183
|
+
const years = sankey.getYears();
|
|
184
|
+
sankey.setYear(years[1]);
|
|
185
|
+
await flush();
|
|
186
|
+
sankey.setYear(years[2]);
|
|
187
|
+
await flush();
|
|
188
|
+
|
|
189
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
describe('off', () => {
|
|
194
|
+
it('should remove every registration of a handler for that event', async () => {
|
|
195
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
196
|
+
await flush();
|
|
197
|
+
|
|
198
|
+
const handler = jest.fn();
|
|
199
|
+
sankey.on('year.changed', handler);
|
|
200
|
+
sankey.on('year.changed', handler);
|
|
201
|
+
sankey.off('year.changed', handler);
|
|
202
|
+
|
|
203
|
+
const years = sankey.getYears();
|
|
204
|
+
sankey.setYear(years[1]);
|
|
205
|
+
await flush();
|
|
206
|
+
|
|
207
|
+
expect(handler).not.toHaveBeenCalled();
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it('should cancel a pending once registration', async () => {
|
|
211
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
212
|
+
await flush();
|
|
213
|
+
|
|
214
|
+
const handler = jest.fn();
|
|
215
|
+
sankey.once('year.changed', handler);
|
|
216
|
+
sankey.off('year.changed', handler);
|
|
217
|
+
|
|
218
|
+
const years = sankey.getYears();
|
|
219
|
+
sankey.setYear(years[1]);
|
|
220
|
+
await flush();
|
|
221
|
+
|
|
222
|
+
expect(handler).not.toHaveBeenCalled();
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
it('should be a no-op for a handler that was never registered', async () => {
|
|
226
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
227
|
+
await flush();
|
|
228
|
+
|
|
229
|
+
expect(() => sankey!.off('year.changed', jest.fn())).not.toThrow();
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
describe('destroy', () => {
|
|
234
|
+
it('should stop delivering events', async () => {
|
|
235
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
236
|
+
await flush();
|
|
237
|
+
|
|
238
|
+
const handler = jest.fn();
|
|
239
|
+
sankey.on('year.changed', handler);
|
|
240
|
+
|
|
241
|
+
sankey.destroy();
|
|
242
|
+
await flush();
|
|
243
|
+
handler.mockClear();
|
|
244
|
+
|
|
245
|
+
sankey.setYear(1900);
|
|
246
|
+
await flush();
|
|
247
|
+
expect(handler).not.toHaveBeenCalled();
|
|
248
|
+
|
|
249
|
+
sankey = null;
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it('should warn and return a no-op unsubscribe when subscribing after destroy', async () => {
|
|
253
|
+
sankey = new Sankey('sankey', baseOptions());
|
|
254
|
+
await flush();
|
|
255
|
+
|
|
256
|
+
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {
|
|
257
|
+
});
|
|
258
|
+
sankey.destroy();
|
|
259
|
+
|
|
260
|
+
const stop = sankey.on('year.changed', jest.fn());
|
|
261
|
+
expect(warn).toHaveBeenCalledWith(expect.stringContaining('has been destroyed'));
|
|
262
|
+
expect(() => stop()).not.toThrow();
|
|
263
|
+
|
|
264
|
+
sankey = null;
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
describe('unhandled rejections', () => {
|
|
269
|
+
// Guards the deliberate no-op .catch() on readyPromise in the
|
|
270
|
+
// constructor. Without it, every destroyed-before-ready instance would
|
|
271
|
+
// surface a fresh unhandled rejection for callers that never awaited.
|
|
272
|
+
it('should not produce an unhandled rejection when destroyed before ready', async () => {
|
|
273
|
+
const onUnhandled = jest.fn();
|
|
274
|
+
process.on('unhandledRejection', onUnhandled);
|
|
275
|
+
|
|
276
|
+
try {
|
|
277
|
+
const instance = new Sankey('sankey', baseOptions());
|
|
278
|
+
instance.destroy();
|
|
279
|
+
|
|
280
|
+
await flush();
|
|
281
|
+
await flush();
|
|
282
|
+
|
|
283
|
+
expect(onUnhandled).not.toHaveBeenCalled();
|
|
284
|
+
} finally {
|
|
285
|
+
process.off('unhandledRejection', onUnhandled);
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
});
|
package/tests/setup.js
CHANGED
|
@@ -1,53 +1,18 @@
|
|
|
1
1
|
// Jest setup for US Energy Sankey validation tests
|
|
2
|
+
//
|
|
3
|
+
// jest-environment-jsdom already supplies document, window, HTMLElement,
|
|
4
|
+
// performance and requestAnimationFrame. This file used to build a SECOND JSDOM
|
|
5
|
+
// realm and overwrite those globals, which caused two real problems:
|
|
6
|
+
//
|
|
7
|
+
// 1. Cross-realm `instanceof` failures. Sankey.resolveContainer() checks
|
|
8
|
+
// `containerId instanceof HTMLElement`, and an element created by Jest's
|
|
9
|
+
// document is not an instance of the overwritten global.HTMLElement.
|
|
10
|
+
// 2. `resources: 'usable'` made JSDOM issue real network requests for the
|
|
11
|
+
// <img> in Sankey's injected header markup.
|
|
12
|
+
//
|
|
13
|
+
// Only the encoder polyfills are still needed.
|
|
2
14
|
|
|
3
|
-
// Polyfills for JSDOM environment
|
|
4
15
|
const {TextEncoder, TextDecoder} = require('util');
|
|
16
|
+
|
|
5
17
|
global.TextEncoder = TextEncoder;
|
|
6
18
|
global.TextDecoder = TextDecoder;
|
|
7
|
-
|
|
8
|
-
const {JSDOM} = require('jsdom');
|
|
9
|
-
|
|
10
|
-
// Setup DOM environment
|
|
11
|
-
const dom = new JSDOM('<!DOCTYPE html><html><body><div id="test-container"></div></body></html>', {
|
|
12
|
-
pretendToBeVisual: true,
|
|
13
|
-
resources: 'usable',
|
|
14
|
-
url: 'http://localhost'
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
// Make DOM available globally
|
|
18
|
-
global.document = dom.window.document;
|
|
19
|
-
global.window = dom.window;
|
|
20
|
-
global.HTMLElement = dom.window.HTMLElement;
|
|
21
|
-
global.HTMLInputElement = dom.window.HTMLInputElement;
|
|
22
|
-
global.HTMLOutputElement = dom.window.HTMLOutputElement;
|
|
23
|
-
global.SVGSVGElement = dom.window.SVGSVGElement;
|
|
24
|
-
global.SVGElement = dom.window.SVGElement;
|
|
25
|
-
|
|
26
|
-
// Mock performance API for Node.js
|
|
27
|
-
global.performance = {
|
|
28
|
-
now: () => Date.now(),
|
|
29
|
-
timing: {},
|
|
30
|
-
memory: {
|
|
31
|
-
usedJSHeapSize: 1024 * 1024 * 10, // 10MB mock
|
|
32
|
-
totalJSHeapSize: 1024 * 1024 * 50, // 50MB mock
|
|
33
|
-
jsHeapSizeLimit: 1024 * 1024 * 100 // 100MB mock
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
// Mock requestAnimationFrame
|
|
38
|
-
global.requestAnimationFrame = (callback) => {
|
|
39
|
-
return setTimeout(callback, 16); // ~60fps
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
global.cancelAnimationFrame = (id) => {
|
|
43
|
-
clearTimeout(id);
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
// Suppress console logs during tests (optional)
|
|
47
|
-
// global.console = {
|
|
48
|
-
// ...console,
|
|
49
|
-
// log: jest.fn(),
|
|
50
|
-
// debug: jest.fn(),
|
|
51
|
-
// info: jest.fn(),
|
|
52
|
-
// warn: jest.fn()
|
|
53
|
-
// };
|