energy-visualization-sankey 1.0.26 → 1.1.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 +91 -0
- package/babel.config.cjs +18 -21
- package/dist/.tsbuildinfo +1 -0
- package/dist/sankey.esm.js +285 -123
- package/dist/sankey.esm.js.map +1 -1
- package/dist/sankey.umd.js +285 -123
- 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 +1 -0
- 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 +11 -0
- package/dist/types/types/index.d.ts.map +1 -1
- package/jest.config.cjs +22 -7
- package/package.json +3 -2
- package/src/core/Sankey.ts +282 -21
- package/src/core/types/public-events.ts +189 -0
- package/src/index.ts +21 -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 +16 -0
- package/tests/event-bus.test.ts +137 -0
- package/tests/sankey-events.test.ts +289 -0
- package/tests/setup.js +13 -48
package/src/core/Sankey.ts
CHANGED
|
@@ -2,7 +2,14 @@ import * as d3 from 'd3';
|
|
|
2
2
|
|
|
3
3
|
// Core event system
|
|
4
4
|
import {EventBus} from '@/core/events/EventBus';
|
|
5
|
-
import type {EventSubscription,} from '@/core/types/events';
|
|
5
|
+
import type {EventHandler, EventSubscription,} from '@/core/types/events';
|
|
6
|
+
import type {
|
|
7
|
+
SankeyEventListener,
|
|
8
|
+
SankeyPublicEvent,
|
|
9
|
+
SankeyPublicEventType,
|
|
10
|
+
SankeyReadyEventData,
|
|
11
|
+
SankeyUnsubscribe
|
|
12
|
+
} from '@/core/types/public-events';
|
|
6
13
|
|
|
7
14
|
// Import shared type definitions
|
|
8
15
|
import type {D3DivSelection, D3SVGSelection, EnergyDataPoint, GraphData, SankeyOptions} from '@/types';
|
|
@@ -64,6 +71,19 @@ import {InteractionService} from "@/services/InteractionService";
|
|
|
64
71
|
* sankey.play().setSpeed(100).setYear(2020);
|
|
65
72
|
* ```
|
|
66
73
|
*/
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* One public subscription.
|
|
77
|
+
*
|
|
78
|
+
* `identity` is the handler the caller passed, which is what off() matches on.
|
|
79
|
+
* The event bus holds a distinct wrapper closure instead - see addListener().
|
|
80
|
+
*/
|
|
81
|
+
interface PublicListenerRecord {
|
|
82
|
+
readonly type: SankeyPublicEventType;
|
|
83
|
+
readonly identity: SankeyEventListener<any>;
|
|
84
|
+
readonly subscription: EventSubscription;
|
|
85
|
+
}
|
|
86
|
+
|
|
67
87
|
export default class Sankey {
|
|
68
88
|
// CORE EVENT SYSTEM: Central nervous system for all service communication
|
|
69
89
|
// Type-safe event bus enables loose coupling and async communication patterns
|
|
@@ -118,6 +138,17 @@ export default class Sankey {
|
|
|
118
138
|
// Each subscription must be explicitly unsubscribed during destroy()
|
|
119
139
|
private subscriptions: EventSubscription[] = [];
|
|
120
140
|
|
|
141
|
+
// PUBLIC SUBSCRIPTION REGISTRY: consumer-facing on()/once() registrations.
|
|
142
|
+
// Kept separate from `subscriptions` (internal service wiring) so that off()
|
|
143
|
+
// and destroy() can reason about the two independently.
|
|
144
|
+
private publicListeners: PublicListenerRecord[] = [];
|
|
145
|
+
|
|
146
|
+
// READINESS LATCH: lets callers observe successful initialization even when
|
|
147
|
+
// they attach after 'system.ready' was emitted and dropped by the event bus.
|
|
148
|
+
private readonly readyPromise: Promise<SankeyPublicEvent<'system.ready'>>;
|
|
149
|
+
private resolveReady!: (event: SankeyPublicEvent<'system.ready'>) => void;
|
|
150
|
+
private rejectReady!: (error: Error) => void;
|
|
151
|
+
|
|
121
152
|
constructor(containerId: string | HTMLElement, options: SankeyOptions) {
|
|
122
153
|
this.logger = new Logger(options)
|
|
123
154
|
// Initialize core system components
|
|
@@ -134,10 +165,26 @@ export default class Sankey {
|
|
|
134
165
|
// 4. Create core event bus
|
|
135
166
|
this.eventBus = new EventBus(this.logger);
|
|
136
167
|
|
|
137
|
-
// 5.
|
|
168
|
+
// 5. Arm the readiness latch before any asynchronous work starts.
|
|
169
|
+
// The no-op catch is REQUIRED: without it, a failed initialization
|
|
170
|
+
// produces a fresh unhandled rejection for every caller that never
|
|
171
|
+
// uses whenReady(), which would be a behaviour change.
|
|
172
|
+
this.readyPromise = new Promise<SankeyPublicEvent<'system.ready'>>((resolve, reject) => {
|
|
173
|
+
this.resolveReady = resolve;
|
|
174
|
+
this.rejectReady = reject;
|
|
175
|
+
});
|
|
176
|
+
this.readyPromise.catch(() => { /* observed only through whenReady() */
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// 6. Setup system event listeners
|
|
138
180
|
this.setupSystemEventListeners();
|
|
139
181
|
|
|
140
|
-
//
|
|
182
|
+
// 7. Register handlers supplied through the `events` option. MUST happen
|
|
183
|
+
// before initialize(): the event bus drops events that have no
|
|
184
|
+
// subscriber at emit time and there is no replay.
|
|
185
|
+
this.registerConfiguredEventHandlers();
|
|
186
|
+
|
|
187
|
+
// 8. Initialize services and visualization
|
|
141
188
|
this.initialize();
|
|
142
189
|
}
|
|
143
190
|
|
|
@@ -215,36 +262,59 @@ export default class Sankey {
|
|
|
215
262
|
// Must be created first as other services depend on configuration constants
|
|
216
263
|
this.logger.log('SankeyVisualization: Creating infrastructure services...');
|
|
217
264
|
await this.createConfigurationService();
|
|
265
|
+
// CANCELLATION CHECK: destroy() empties the service container, so a
|
|
266
|
+
// destroy() issued while initialization is still in flight would
|
|
267
|
+
// otherwise leave the remaining layers reading undefined services and
|
|
268
|
+
// throwing asynchronously, where nothing can catch it. Each await is
|
|
269
|
+
// a suspension point at which that can happen.
|
|
270
|
+
if (this.destroyed) {
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
218
273
|
|
|
219
|
-
// LAYER 2: DATA PROCESSING SERVICES
|
|
274
|
+
// LAYER 2: DATA PROCESSING SERVICES
|
|
220
275
|
// Handle input validation, data access, and transformation pipelines
|
|
221
276
|
// Depend on configuration service for validation rules and constants
|
|
222
277
|
this.logger.log('SankeyVisualization: Creating data processing services...');
|
|
223
278
|
await this.createDataServices();
|
|
279
|
+
if (this.destroyed) {
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
224
282
|
|
|
225
283
|
// LAYER 3: MATHEMATICAL CALCULATION SERVICES
|
|
226
|
-
// Perform complex energy flow calculations with performance optimizations
|
|
284
|
+
// Perform complex energy flow calculations with performance optimizations
|
|
227
285
|
// Depend on data services for input and configuration for mathematical constants
|
|
228
286
|
this.logger.log('SankeyVisualization: Creating calculation services...');
|
|
229
287
|
await this.createCalculationServices();
|
|
288
|
+
if (this.destroyed) {
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
230
291
|
|
|
231
292
|
// LAYER 4: VISUAL RENDERING SERVICES
|
|
232
293
|
// Generate SVG elements and manage visual output
|
|
233
294
|
// Depend on calculation services for positioning data and configuration for styling
|
|
234
295
|
this.logger.log('SankeyVisualization: Creating rendering services...');
|
|
235
296
|
await this.createRenderingServices();
|
|
297
|
+
if (this.destroyed) {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
236
300
|
|
|
237
301
|
// LAYER 5: ANIMATION CONTROL SERVICES
|
|
238
302
|
// Manage timeline navigation and smooth transitions between years
|
|
239
303
|
// Depend on rendering services for visual updates and calculation services for data
|
|
240
304
|
this.logger.log('SankeyVisualization: Creating animation services...');
|
|
241
305
|
await this.createAnimationService();
|
|
306
|
+
if (this.destroyed) {
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
242
309
|
|
|
243
310
|
// LAYER 6: USER INTERACTION SERVICES
|
|
244
311
|
// Handle mouse, keyboard, and touch events with accessibility support
|
|
245
312
|
// Depend on animation services for playback control and rendering for visual feedback
|
|
246
313
|
this.logger.log('SankeyVisualization: Creating interaction services...');
|
|
247
314
|
await this.createInteractionServices();
|
|
315
|
+
if (this.destroyed) {
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
248
318
|
|
|
249
319
|
// DOM INITIALIZATION: Create visualization structure in browser
|
|
250
320
|
// Must happen after all services are created as services may reference DOM elements
|
|
@@ -255,28 +325,39 @@ export default class Sankey {
|
|
|
255
325
|
// Triggers the complete data → calculation → render pipeline for the first time
|
|
256
326
|
this.logger.log('SankeyVisualization: Performing initial render...');
|
|
257
327
|
await this.performInitialRender();
|
|
328
|
+
if (this.destroyed) {
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
258
331
|
|
|
259
332
|
const totalInitializationTime = performance.now() - initializationStartTime;
|
|
260
333
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
334
|
+
const readyData: SankeyReadyEventData = {
|
|
335
|
+
totalInitTime: totalInitializationTime,
|
|
336
|
+
dataPointCount: this.options.data.length,
|
|
337
|
+
yearRange: [
|
|
338
|
+
Math.min(...this.options.data.map(d => d.year)),
|
|
339
|
+
Math.max(...this.options.data.map(d => d.year))
|
|
340
|
+
]
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
const readyEvent: SankeyPublicEvent<'system.ready'> = {
|
|
264
344
|
type: 'system.ready',
|
|
265
345
|
timestamp: Date.now(),
|
|
266
346
|
source: 'SankeyVisualization',
|
|
267
|
-
data:
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
]
|
|
274
|
-
}
|
|
275
|
-
});
|
|
347
|
+
data: readyData
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
// LIFECYCLE EVENT: Signal system fully ready for use
|
|
351
|
+
// Public API methods are safe to call after this event
|
|
352
|
+
this.eventBus.emit(readyEvent);
|
|
276
353
|
|
|
277
354
|
// SYSTEM STATE: Mark initialization complete
|
|
278
355
|
this.initialized = true;
|
|
279
356
|
|
|
357
|
+
// Latch readiness so callers that subscribe after this point can
|
|
358
|
+
// still observe it through whenReady().
|
|
359
|
+
this.resolveReady(readyEvent);
|
|
360
|
+
|
|
280
361
|
// PERFORMANCE LOGGING: Track initialization time for regression detection
|
|
281
362
|
this.logger.log(`SankeyVisualization: Complete initialization in ${totalInitializationTime.toFixed(2)}ms`);
|
|
282
363
|
|
|
@@ -517,7 +598,7 @@ export default class Sankey {
|
|
|
517
598
|
const lastYear = this.services.dataService!.lastYear!;
|
|
518
599
|
|
|
519
600
|
let html = `
|
|
520
|
-
<div class="evs-sankey evs-title-container"
|
|
601
|
+
<div class="evs-sankey evs-title-container">
|
|
521
602
|
<div class="evs-header-content">
|
|
522
603
|
<div class="evs-header-logo">
|
|
523
604
|
<a href="https://www.rdcep.org/" target="_blank">
|
|
@@ -767,24 +848,114 @@ export default class Sankey {
|
|
|
767
848
|
this.subscriptions.push(errorSubscription, yearChangeSubscription);
|
|
768
849
|
}
|
|
769
850
|
|
|
851
|
+
/**
|
|
852
|
+
* Register handlers supplied through the `events` constructor option.
|
|
853
|
+
* Runs before initialize() so that no lifecycle event is dropped.
|
|
854
|
+
*/
|
|
855
|
+
private registerConfiguredEventHandlers(): void {
|
|
856
|
+
const configured = this.options.events;
|
|
857
|
+
if (!configured) {
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
(Object.keys(configured) as SankeyPublicEventType[]).forEach(type => {
|
|
862
|
+
const handler = configured[type] as SankeyEventListener<any> | undefined;
|
|
863
|
+
if (typeof handler === 'function') {
|
|
864
|
+
this.addListener(type, handler, handler);
|
|
865
|
+
}
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* Shared registration path for on(), once() and the `events` option.
|
|
871
|
+
*
|
|
872
|
+
* @param identity what off() matches on - the handler the caller passed
|
|
873
|
+
* @param invoke what actually runs, which differs from identity for once()
|
|
874
|
+
*/
|
|
875
|
+
private addListener(
|
|
876
|
+
type: SankeyPublicEventType,
|
|
877
|
+
identity: SankeyEventListener<any>,
|
|
878
|
+
invoke: SankeyEventListener<any>
|
|
879
|
+
): SankeyUnsubscribe {
|
|
880
|
+
if (typeof identity !== 'function' || typeof invoke !== 'function') {
|
|
881
|
+
throw new SankeyError(`SankeyVisualization: event handler for '${type}' must be a function`);
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
if (this.destroyed) {
|
|
885
|
+
console.warn(`SankeyVisualization: cannot subscribe to '${type}' - instance has been destroyed`);
|
|
886
|
+
return () => { /* no-op */
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// HANDLER IDENTITY ISOLATION - do not remove.
|
|
891
|
+
// EventBus stores handlers in a Set keyed by function identity. Passing
|
|
892
|
+
// the same function object twice collapses into a single Set entry, and
|
|
893
|
+
// unsubscribing either subscription would then silently remove BOTH.
|
|
894
|
+
// Allocating a fresh closure per registration keeps every registration
|
|
895
|
+
// independently removable. Covered by tests/event-bus.test.ts.
|
|
896
|
+
const wrapped: EventHandler<any> = (event) => invoke(event as SankeyPublicEvent<any>);
|
|
897
|
+
|
|
898
|
+
const record: PublicListenerRecord = {
|
|
899
|
+
type,
|
|
900
|
+
identity,
|
|
901
|
+
subscription: this.eventBus.subscribe<any>(type, wrapped)
|
|
902
|
+
};
|
|
903
|
+
this.publicListeners.push(record);
|
|
904
|
+
|
|
905
|
+
let alreadyRemoved = false;
|
|
906
|
+
return () => {
|
|
907
|
+
if (alreadyRemoved) {
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
alreadyRemoved = true;
|
|
911
|
+
this.removeListener(record);
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* Remove a single public subscription and its bus registration
|
|
917
|
+
*/
|
|
918
|
+
private removeListener(record: PublicListenerRecord): void {
|
|
919
|
+
const index = this.publicListeners.indexOf(record);
|
|
920
|
+
if (index === -1) {
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
this.publicListeners.splice(index, 1);
|
|
924
|
+
|
|
925
|
+
// After destroy() the bus has already been cleared; unsubscribing again
|
|
926
|
+
// would only log a spurious "non-existent subscription" warning.
|
|
927
|
+
if (!this.destroyed) {
|
|
928
|
+
this.eventBus.unsubscribe(record.subscription);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
|
|
770
932
|
/**
|
|
771
933
|
* Handle initialization errors
|
|
772
934
|
*/
|
|
773
935
|
private handleInitializationError(error: any): void {
|
|
774
|
-
|
|
936
|
+
const normalizedError = error instanceof Error ? error : new Error(String(error));
|
|
937
|
+
|
|
938
|
+
console.error('SankeyVisualization: Initialization failed:', normalizedError);
|
|
775
939
|
|
|
776
940
|
this.eventBus.emit({
|
|
777
941
|
type: 'system.error',
|
|
778
942
|
timestamp: Date.now(),
|
|
779
943
|
source: 'SankeyVisualization',
|
|
780
944
|
data: {
|
|
781
|
-
error:
|
|
945
|
+
error: normalizedError,
|
|
782
946
|
context: 'initialization',
|
|
783
947
|
recoverable: false
|
|
784
948
|
},
|
|
785
949
|
});
|
|
786
950
|
|
|
787
|
-
//
|
|
951
|
+
// Settle whenReady() with the real cause BEFORE destroy(), which would
|
|
952
|
+
// otherwise reject first with a generic "destroyed" error and lose it.
|
|
953
|
+
this.rejectReady(normalizedError);
|
|
954
|
+
|
|
955
|
+
// Clean up any partially initialized state.
|
|
956
|
+
// NOTE: the emit above is already in flight and still delivers. emit()
|
|
957
|
+
// captures its handler Set synchronously and clear() empties the Map
|
|
958
|
+
// rather than the captured Sets, so 'system.error' handlers still run.
|
|
788
959
|
this.destroy();
|
|
789
960
|
|
|
790
961
|
throw error;
|
|
@@ -899,6 +1070,86 @@ export default class Sankey {
|
|
|
899
1070
|
return this.initialized;
|
|
900
1071
|
}
|
|
901
1072
|
|
|
1073
|
+
// ==================== PUBLIC EVENT API ====================
|
|
1074
|
+
|
|
1075
|
+
/**
|
|
1076
|
+
* Subscribe to a visualization event
|
|
1077
|
+
*
|
|
1078
|
+
* Handlers run asynchronously, one microtask after the event is produced,
|
|
1079
|
+
* and are error-isolated: a throwing handler cannot break the visualization
|
|
1080
|
+
* or prevent other handlers from running.
|
|
1081
|
+
*
|
|
1082
|
+
* LIFECYCLE TIMING: `system.ready` and `system.error` are produced during the
|
|
1083
|
+
* asynchronous initialization the constructor starts. Subscribing in the same
|
|
1084
|
+
* synchronous tick as `new Sankey(...)` is soon enough; subscribing later (for
|
|
1085
|
+
* example after `await nextTick()`) is not. For those, use the `events`
|
|
1086
|
+
* constructor option or {@link whenReady}.
|
|
1087
|
+
*
|
|
1088
|
+
* Registering the same function twice registers it twice and it is called
|
|
1089
|
+
* twice; each call returns its own unsubscribe.
|
|
1090
|
+
*
|
|
1091
|
+
* @returns an unsubscribe function, safe to call more than once
|
|
1092
|
+
*/
|
|
1093
|
+
public on<K extends SankeyPublicEventType>(
|
|
1094
|
+
type: K,
|
|
1095
|
+
handler: SankeyEventListener<K>
|
|
1096
|
+
): SankeyUnsubscribe {
|
|
1097
|
+
const listener = handler as SankeyEventListener<any>;
|
|
1098
|
+
return this.addListener(type, listener, listener);
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
/**
|
|
1102
|
+
* Subscribe until the first delivery, then unsubscribe automatically
|
|
1103
|
+
*
|
|
1104
|
+
* Cancellable either with the returned function or with `off(type, handler)`.
|
|
1105
|
+
*/
|
|
1106
|
+
public once<K extends SankeyPublicEventType>(
|
|
1107
|
+
type: K,
|
|
1108
|
+
handler: SankeyEventListener<K>
|
|
1109
|
+
): SankeyUnsubscribe {
|
|
1110
|
+
let unsubscribe: SankeyUnsubscribe = () => { /* replaced below */
|
|
1111
|
+
};
|
|
1112
|
+
|
|
1113
|
+
const invoke: SankeyEventListener<any> = (event) => {
|
|
1114
|
+
// Remove BEFORE invoking so a throwing handler cannot fire twice.
|
|
1115
|
+
unsubscribe();
|
|
1116
|
+
return (handler as SankeyEventListener<any>)(event);
|
|
1117
|
+
};
|
|
1118
|
+
|
|
1119
|
+
// `handler` is recorded as the identity so that off(type, handler)
|
|
1120
|
+
// cancels a pending once() even though the bus holds `invoke`.
|
|
1121
|
+
unsubscribe = this.addListener(type, handler as SankeyEventListener<any>, invoke);
|
|
1122
|
+
return unsubscribe;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/**
|
|
1126
|
+
* Remove every registration of `handler` for `type`, including a pending once()
|
|
1127
|
+
*
|
|
1128
|
+
* Removes all matching registrations rather than one, so teardown code
|
|
1129
|
+
* reliably stops delivery. No-op if the handler was never registered.
|
|
1130
|
+
*/
|
|
1131
|
+
public off<K extends SankeyPublicEventType>(
|
|
1132
|
+
type: K,
|
|
1133
|
+
handler: SankeyEventListener<K>
|
|
1134
|
+
): this {
|
|
1135
|
+
// Snapshot first: removeListener() mutates this.publicListeners.
|
|
1136
|
+
this.publicListeners
|
|
1137
|
+
.filter(record => record.type === type && record.identity === handler)
|
|
1138
|
+
.forEach(record => this.removeListener(record));
|
|
1139
|
+
|
|
1140
|
+
return this;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/**
|
|
1144
|
+
* Resolve when initialization completes, or reject if it failed
|
|
1145
|
+
*
|
|
1146
|
+
* Unlike `on('system.ready', ...)` this is a latch: it resolves even when
|
|
1147
|
+
* called long after the event was emitted. Safe to call any number of times.
|
|
1148
|
+
*/
|
|
1149
|
+
public whenReady(): Promise<SankeyPublicEvent<'system.ready'>> {
|
|
1150
|
+
return this.readyPromise;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
902
1153
|
/**
|
|
903
1154
|
* Get array of available years in dataset
|
|
904
1155
|
* @returns Readonly array of years available for visualization
|
|
@@ -966,6 +1217,10 @@ export default class Sankey {
|
|
|
966
1217
|
this.subscriptions.forEach(sub => this.eventBus.unsubscribe(sub));
|
|
967
1218
|
this.subscriptions = [];
|
|
968
1219
|
|
|
1220
|
+
// Release consumer closures. eventBus.clear() below drops the underlying
|
|
1221
|
+
// handlers; this drops our bookkeeping references to them.
|
|
1222
|
+
this.publicListeners = [];
|
|
1223
|
+
|
|
969
1224
|
// Clean up event bus
|
|
970
1225
|
this.eventBus.clear();
|
|
971
1226
|
|
|
@@ -990,6 +1245,12 @@ export default class Sankey {
|
|
|
990
1245
|
this.destroyed = true;
|
|
991
1246
|
this.initialized = false;
|
|
992
1247
|
|
|
1248
|
+
// Settle whenReady() so callers awaiting an instance that never came up
|
|
1249
|
+
// are not left hanging. No-op once the promise has already settled, so
|
|
1250
|
+
// this is harmless on the happy path. The constructor's no-op catch
|
|
1251
|
+
// prevents an unhandled rejection here.
|
|
1252
|
+
this.rejectReady(new SankeyError('SankeyVisualization: destroyed before initialization completed'));
|
|
1253
|
+
|
|
993
1254
|
// Resource cleanup completed successfully
|
|
994
1255
|
}
|
|
995
1256
|
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public Event Type Definitions
|
|
3
|
+
*
|
|
4
|
+
* The curated, consumer-facing subset of the internal event system. Everything
|
|
5
|
+
* declared here is part of the published API surface and is covered by semver.
|
|
6
|
+
* The internal union in ./events.ts is NOT: it carries service-coordination
|
|
7
|
+
* channels and several declared-but-never-emitted types.
|
|
8
|
+
*
|
|
9
|
+
* Deliberately excluded from the public map:
|
|
10
|
+
* - 'system.initialized' Three unrelated payloads from three sources
|
|
11
|
+
* (Sankey, ConfigurationService, InteractionService), two
|
|
12
|
+
* of which fire synchronously inside the constructor. The
|
|
13
|
+
* Sankey payload is {services: [], initTime: 0} - both
|
|
14
|
+
* fields are permanently dead. Use 'system.ready'.
|
|
15
|
+
* - 'data.loaded' Payload embeds a full copy of the dataset. Handing that
|
|
16
|
+
* to an analytics layer invites someone serializing it.
|
|
17
|
+
* - 'data.validated' Internal; 'system.ready' carries the same metadata.
|
|
18
|
+
* - 'rendering.completed' Fires exactly once per instance, immediately before
|
|
19
|
+
* 'system.ready', which carries strictly better data.
|
|
20
|
+
* - 'calculation.completed', 'year.changing', 'timeline.updated',
|
|
21
|
+
* 'rendering.started', 'dimensions.changed'
|
|
22
|
+
* Declared in SankeyEventType but never emitted anywhere.
|
|
23
|
+
* Publishing a typed key for an event that never fires is
|
|
24
|
+
* a promise the library does not keep.
|
|
25
|
+
*
|
|
26
|
+
* Adding a key to SankeyEventMap later is purely additive, so this map starts
|
|
27
|
+
* narrow on purpose.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import type {SankeyEventType} from '@/core/types/events';
|
|
31
|
+
|
|
32
|
+
/** Classification of the SVG element under the pointer. */
|
|
33
|
+
export type SankeyElementType = 'flow' | 'box';
|
|
34
|
+
|
|
35
|
+
/** Viewport coordinates of a pointer interaction. */
|
|
36
|
+
export interface SankeyMousePosition {
|
|
37
|
+
readonly x: number;
|
|
38
|
+
readonly y: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Payload of `system.ready`. Emitted once, after the first frame is rendered. */
|
|
42
|
+
export interface SankeyReadyEventData {
|
|
43
|
+
/** Wall-clock milliseconds from construction to first rendered frame. */
|
|
44
|
+
readonly totalInitTime: number;
|
|
45
|
+
readonly dataPointCount: number;
|
|
46
|
+
/** Earliest and latest year present in the dataset. */
|
|
47
|
+
readonly yearRange: readonly [number, number];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Payload of `system.error`. */
|
|
51
|
+
export interface SankeyErrorEventData {
|
|
52
|
+
readonly error: Error;
|
|
53
|
+
readonly context: 'initialization' | 'data_validation';
|
|
54
|
+
readonly recoverable: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Payload of `year.changed`.
|
|
59
|
+
*
|
|
60
|
+
* `isAnimating` distinguishes a user scrubbing the timeline from the animation
|
|
61
|
+
* advancing on its own. A full playthrough emits one event per year in the
|
|
62
|
+
* dataset, so analytics consumers should filter on this flag rather than
|
|
63
|
+
* forwarding every occurrence.
|
|
64
|
+
*/
|
|
65
|
+
export interface SankeyYearChangedEventData {
|
|
66
|
+
readonly year: number;
|
|
67
|
+
readonly previousYear: number;
|
|
68
|
+
readonly yearIndex: number;
|
|
69
|
+
readonly isAnimating: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Payload of `animation.started` and `animation.stopped`. */
|
|
73
|
+
export interface SankeyAnimationEventData {
|
|
74
|
+
readonly isPlaying: boolean;
|
|
75
|
+
readonly currentYear: number;
|
|
76
|
+
/** Milliseconds per year. */
|
|
77
|
+
readonly speed: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Payload of `speed.changed`. */
|
|
81
|
+
export interface SankeySpeedChangedEventData {
|
|
82
|
+
readonly speed: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Payload of `interaction.hover` and `interaction.click`.
|
|
87
|
+
*
|
|
88
|
+
* `fuel` and `sector` are read from the `data-fuel` / `data-sector` attributes
|
|
89
|
+
* and are genuinely null for elements that do not carry them.
|
|
90
|
+
*/
|
|
91
|
+
export interface SankeyElementInteractionEventData {
|
|
92
|
+
readonly elementType: SankeyElementType;
|
|
93
|
+
readonly fuel: string | null;
|
|
94
|
+
readonly sector: string | null;
|
|
95
|
+
readonly mousePosition: SankeyMousePosition;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Payload of `interaction.keypress`. */
|
|
99
|
+
export interface SankeyKeypressEventData {
|
|
100
|
+
readonly key: string;
|
|
101
|
+
readonly ctrlKey: boolean;
|
|
102
|
+
readonly shiftKey: boolean;
|
|
103
|
+
readonly altKey: boolean;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Payload of `interaction.slider`. */
|
|
107
|
+
export interface SankeySliderEventData {
|
|
108
|
+
readonly year: number;
|
|
109
|
+
/** Duplicate of `year`, retained for backwards compatibility. */
|
|
110
|
+
readonly value: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Payload of `interaction.button`. Discriminated on `action`, which is a literal
|
|
115
|
+
* at both emit sites.
|
|
116
|
+
*/
|
|
117
|
+
export type SankeyButtonEventData =
|
|
118
|
+
| {
|
|
119
|
+
readonly buttonId: 'evs-play-button';
|
|
120
|
+
readonly action: 'play' | 'pause';
|
|
121
|
+
/** Never present for play/pause. Declared so `data.speed` reads without narrowing. */
|
|
122
|
+
readonly speed?: undefined;
|
|
123
|
+
}
|
|
124
|
+
| {
|
|
125
|
+
readonly buttonId: string;
|
|
126
|
+
readonly action: 'speed-change';
|
|
127
|
+
readonly speed: number;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/** Maps every public event type to its payload. */
|
|
131
|
+
export interface SankeyEventMap {
|
|
132
|
+
'system.ready': SankeyReadyEventData;
|
|
133
|
+
'system.error': SankeyErrorEventData;
|
|
134
|
+
'year.changed': SankeyYearChangedEventData;
|
|
135
|
+
'animation.started': SankeyAnimationEventData;
|
|
136
|
+
'animation.stopped': SankeyAnimationEventData;
|
|
137
|
+
'speed.changed': SankeySpeedChangedEventData;
|
|
138
|
+
/** High frequency: fires on every mouseover. Debounce or sample before forwarding. */
|
|
139
|
+
'interaction.hover': SankeyElementInteractionEventData;
|
|
140
|
+
'interaction.click': SankeyElementInteractionEventData;
|
|
141
|
+
'interaction.keypress': SankeyKeypressEventData;
|
|
142
|
+
'interaction.slider': SankeySliderEventData;
|
|
143
|
+
'interaction.button': SankeyButtonEventData;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Name of a public event. */
|
|
147
|
+
export type SankeyPublicEventType = keyof SankeyEventMap;
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Event envelope.
|
|
151
|
+
*
|
|
152
|
+
* Distributive on purpose: the defaulted `SankeyPublicEvent` is a discriminated
|
|
153
|
+
* union, so a generic forwarder can `switch (event.type)` and narrow
|
|
154
|
+
* `event.data`. A plain generic interface would collapse to
|
|
155
|
+
* `{type: <every key>, data: <union of every payload>}`, which cannot narrow.
|
|
156
|
+
*/
|
|
157
|
+
export type SankeyPublicEvent<K extends SankeyPublicEventType = SankeyPublicEventType> =
|
|
158
|
+
K extends SankeyPublicEventType
|
|
159
|
+
? {
|
|
160
|
+
readonly type: K;
|
|
161
|
+
readonly timestamp: number;
|
|
162
|
+
/** Emitting component, e.g. 'InteractionService'. Diagnostic only; not stable. */
|
|
163
|
+
readonly source: string;
|
|
164
|
+
readonly data: SankeyEventMap[K];
|
|
165
|
+
}
|
|
166
|
+
: never;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Handler for a single public event type.
|
|
170
|
+
*
|
|
171
|
+
* Handlers are error-isolated: a throw cannot break the visualization or stop
|
|
172
|
+
* other handlers. A returned promise's rejection is caught and logged.
|
|
173
|
+
*/
|
|
174
|
+
export type SankeyEventListener<K extends SankeyPublicEventType = SankeyPublicEventType> =
|
|
175
|
+
(event: SankeyPublicEvent<K>) => void | Promise<void>;
|
|
176
|
+
|
|
177
|
+
/** Returned by `on()` and `once()`. Idempotent. */
|
|
178
|
+
export type SankeyUnsubscribe = () => void;
|
|
179
|
+
|
|
180
|
+
/** Shape of the `events` constructor option. */
|
|
181
|
+
export type SankeyEventHandlers = {
|
|
182
|
+
readonly [K in SankeyPublicEventType]?: SankeyEventListener<K>;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
// Compile-time guard: every public key must be a real internal event type.
|
|
186
|
+
// Only `npm run type-check` catches a violation - rollup runs the TypeScript
|
|
187
|
+
// plugin with abortOnError: false, so the build stays green regardless.
|
|
188
|
+
type Assert<T extends true> = T;
|
|
189
|
+
type _PublicKeysAreInternal = Assert<SankeyPublicEventType extends SankeyEventType ? true : false>;
|
package/src/index.ts
CHANGED
|
@@ -31,5 +31,26 @@ export {
|
|
|
31
31
|
DataValidationError
|
|
32
32
|
} from './types/index';
|
|
33
33
|
|
|
34
|
+
// Export the public event API types
|
|
35
|
+
export type {
|
|
36
|
+
SankeyEventMap,
|
|
37
|
+
SankeyPublicEventType,
|
|
38
|
+
SankeyPublicEvent,
|
|
39
|
+
SankeyEventListener,
|
|
40
|
+
SankeyEventHandlers,
|
|
41
|
+
SankeyUnsubscribe,
|
|
42
|
+
SankeyElementType,
|
|
43
|
+
SankeyMousePosition,
|
|
44
|
+
SankeyReadyEventData,
|
|
45
|
+
SankeyErrorEventData,
|
|
46
|
+
SankeyYearChangedEventData,
|
|
47
|
+
SankeyAnimationEventData,
|
|
48
|
+
SankeySpeedChangedEventData,
|
|
49
|
+
SankeyElementInteractionEventData,
|
|
50
|
+
SankeyKeypressEventData,
|
|
51
|
+
SankeySliderEventData,
|
|
52
|
+
SankeyButtonEventData
|
|
53
|
+
} from './core/types/public-events';
|
|
54
|
+
|
|
34
55
|
// Export the main visualization class
|
|
35
56
|
export {default as default} from './core/Sankey';
|