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.
@@ -2,13 +2,21 @@ 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';
9
16
  // Import validation errors
10
17
  import {DataValidationError, SankeyError} from '@/types';
11
18
  import {Logger} from "@/utils/Logger";
19
+ import {renderHeaderHtml, resolveHeader, validateHeaderOptions} from "@/utils/header";
12
20
  import {ConfigurationService} from "@/services/ConfigurationService";
13
21
  import {DataValidationService} from "@/services/data/DataValidationService";
14
22
  import {DataService} from "@/services/data/DataService";
@@ -64,6 +72,19 @@ import {InteractionService} from "@/services/InteractionService";
64
72
  * sankey.play().setSpeed(100).setYear(2020);
65
73
  * ```
66
74
  */
75
+
76
+ /**
77
+ * One public subscription.
78
+ *
79
+ * `identity` is the handler the caller passed, which is what off() matches on.
80
+ * The event bus holds a distinct wrapper closure instead - see addListener().
81
+ */
82
+ interface PublicListenerRecord {
83
+ readonly type: SankeyPublicEventType;
84
+ readonly identity: SankeyEventListener<any>;
85
+ readonly subscription: EventSubscription;
86
+ }
87
+
67
88
  export default class Sankey {
68
89
  // CORE EVENT SYSTEM: Central nervous system for all service communication
69
90
  // Type-safe event bus enables loose coupling and async communication patterns
@@ -118,6 +139,17 @@ export default class Sankey {
118
139
  // Each subscription must be explicitly unsubscribed during destroy()
119
140
  private subscriptions: EventSubscription[] = [];
120
141
 
142
+ // PUBLIC SUBSCRIPTION REGISTRY: consumer-facing on()/once() registrations.
143
+ // Kept separate from `subscriptions` (internal service wiring) so that off()
144
+ // and destroy() can reason about the two independently.
145
+ private publicListeners: PublicListenerRecord[] = [];
146
+
147
+ // READINESS LATCH: lets callers observe successful initialization even when
148
+ // they attach after 'system.ready' was emitted and dropped by the event bus.
149
+ private readonly readyPromise: Promise<SankeyPublicEvent<'system.ready'>>;
150
+ private resolveReady!: (event: SankeyPublicEvent<'system.ready'>) => void;
151
+ private rejectReady!: (error: Error) => void;
152
+
121
153
  constructor(containerId: string | HTMLElement, options: SankeyOptions) {
122
154
  this.logger = new Logger(options)
123
155
  // Initialize core system components
@@ -134,10 +166,26 @@ export default class Sankey {
134
166
  // 4. Create core event bus
135
167
  this.eventBus = new EventBus(this.logger);
136
168
 
137
- // 5. Setup system event listeners
169
+ // 5. Arm the readiness latch before any asynchronous work starts.
170
+ // The no-op catch is REQUIRED: without it, a failed initialization
171
+ // produces a fresh unhandled rejection for every caller that never
172
+ // uses whenReady(), which would be a behaviour change.
173
+ this.readyPromise = new Promise<SankeyPublicEvent<'system.ready'>>((resolve, reject) => {
174
+ this.resolveReady = resolve;
175
+ this.rejectReady = reject;
176
+ });
177
+ this.readyPromise.catch(() => { /* observed only through whenReady() */
178
+ });
179
+
180
+ // 6. Setup system event listeners
138
181
  this.setupSystemEventListeners();
139
182
 
140
- // 6. Initialize services and visualization
183
+ // 7. Register handlers supplied through the `events` option. MUST happen
184
+ // before initialize(): the event bus drops events that have no
185
+ // subscriber at emit time and there is no replay.
186
+ this.registerConfiguredEventHandlers();
187
+
188
+ // 8. Initialize services and visualization
141
189
  this.initialize();
142
190
  }
143
191
 
@@ -215,36 +263,59 @@ export default class Sankey {
215
263
  // Must be created first as other services depend on configuration constants
216
264
  this.logger.log('SankeyVisualization: Creating infrastructure services...');
217
265
  await this.createConfigurationService();
266
+ // CANCELLATION CHECK: destroy() empties the service container, so a
267
+ // destroy() issued while initialization is still in flight would
268
+ // otherwise leave the remaining layers reading undefined services and
269
+ // throwing asynchronously, where nothing can catch it. Each await is
270
+ // a suspension point at which that can happen.
271
+ if (this.destroyed) {
272
+ return;
273
+ }
218
274
 
219
- // LAYER 2: DATA PROCESSING SERVICES
275
+ // LAYER 2: DATA PROCESSING SERVICES
220
276
  // Handle input validation, data access, and transformation pipelines
221
277
  // Depend on configuration service for validation rules and constants
222
278
  this.logger.log('SankeyVisualization: Creating data processing services...');
223
279
  await this.createDataServices();
280
+ if (this.destroyed) {
281
+ return;
282
+ }
224
283
 
225
284
  // LAYER 3: MATHEMATICAL CALCULATION SERVICES
226
- // Perform complex energy flow calculations with performance optimizations
285
+ // Perform complex energy flow calculations with performance optimizations
227
286
  // Depend on data services for input and configuration for mathematical constants
228
287
  this.logger.log('SankeyVisualization: Creating calculation services...');
229
288
  await this.createCalculationServices();
289
+ if (this.destroyed) {
290
+ return;
291
+ }
230
292
 
231
293
  // LAYER 4: VISUAL RENDERING SERVICES
232
294
  // Generate SVG elements and manage visual output
233
295
  // Depend on calculation services for positioning data and configuration for styling
234
296
  this.logger.log('SankeyVisualization: Creating rendering services...');
235
297
  await this.createRenderingServices();
298
+ if (this.destroyed) {
299
+ return;
300
+ }
236
301
 
237
302
  // LAYER 5: ANIMATION CONTROL SERVICES
238
303
  // Manage timeline navigation and smooth transitions between years
239
304
  // Depend on rendering services for visual updates and calculation services for data
240
305
  this.logger.log('SankeyVisualization: Creating animation services...');
241
306
  await this.createAnimationService();
307
+ if (this.destroyed) {
308
+ return;
309
+ }
242
310
 
243
311
  // LAYER 6: USER INTERACTION SERVICES
244
312
  // Handle mouse, keyboard, and touch events with accessibility support
245
313
  // Depend on animation services for playback control and rendering for visual feedback
246
314
  this.logger.log('SankeyVisualization: Creating interaction services...');
247
315
  await this.createInteractionServices();
316
+ if (this.destroyed) {
317
+ return;
318
+ }
248
319
 
249
320
  // DOM INITIALIZATION: Create visualization structure in browser
250
321
  // Must happen after all services are created as services may reference DOM elements
@@ -255,28 +326,39 @@ export default class Sankey {
255
326
  // Triggers the complete data → calculation → render pipeline for the first time
256
327
  this.logger.log('SankeyVisualization: Performing initial render...');
257
328
  await this.performInitialRender();
329
+ if (this.destroyed) {
330
+ return;
331
+ }
258
332
 
259
333
  const totalInitializationTime = performance.now() - initializationStartTime;
260
334
 
261
- // LIFECYCLE EVENT: Signal system fully ready for use
262
- // Public API methods are safe to call after this event
263
- this.eventBus.emit({
335
+ const readyData: SankeyReadyEventData = {
336
+ totalInitTime: totalInitializationTime,
337
+ dataPointCount: this.options.data.length,
338
+ yearRange: [
339
+ Math.min(...this.options.data.map(d => d.year)),
340
+ Math.max(...this.options.data.map(d => d.year))
341
+ ]
342
+ };
343
+
344
+ const readyEvent: SankeyPublicEvent<'system.ready'> = {
264
345
  type: 'system.ready',
265
346
  timestamp: Date.now(),
266
347
  source: 'SankeyVisualization',
267
- data: {
268
- totalInitTime: totalInitializationTime,
269
- dataPointCount: this.options.data.length,
270
- yearRange: [
271
- Math.min(...this.options.data.map(d => d.year)),
272
- Math.max(...this.options.data.map(d => d.year))
273
- ]
274
- }
275
- });
348
+ data: readyData
349
+ };
350
+
351
+ // LIFECYCLE EVENT: Signal system fully ready for use
352
+ // Public API methods are safe to call after this event
353
+ this.eventBus.emit(readyEvent);
276
354
 
277
355
  // SYSTEM STATE: Mark initialization complete
278
356
  this.initialized = true;
279
357
 
358
+ // Latch readiness so callers that subscribe after this point can
359
+ // still observe it through whenReady().
360
+ this.resolveReady(readyEvent);
361
+
280
362
  // PERFORMANCE LOGGING: Track initialization time for regression detection
281
363
  this.logger.log(`SankeyVisualization: Complete initialization in ${totalInitializationTime.toFixed(2)}ms`);
282
364
 
@@ -512,47 +594,13 @@ export default class Sankey {
512
594
  * Creates the DOM structure needed for controls, timeline, and chart display
513
595
  */
514
596
  private injectHTML(): void {
515
- const country = this.options.country;
516
- const firstYear = this.services.dataService!.firstYear!;
517
- const lastYear = this.services.dataService!.lastYear!;
518
-
519
- let html = `
520
- <div class="evs-sankey evs-title-container">
521
- <div class="evs-header-content">
522
- <div class="evs-header-logo">
523
- <a href="https://www.rdcep.org/" target="_blank">
524
- <img src="https://images.squarespace-cdn.com/content/v1/54dcfad0e4b0eaff5e0068bf/1446137765478-FX9WM00VV1LWAFUJRZBI/rdcep+sig2.png"
525
- alt="The Center for Robust Decision-making on Climate and Energy Policy (RDCEP)"
526
- title="The Center for Robust Decision-making on Climate and Energy Policy (RDCEP)">
527
- </a>
528
- </div>
529
-
530
- <div class="evs-header-main">
531
- <div class="evs-header-title-section">
532
- <h1 class="evs-main-title">${country} energy usage</h1>
533
- <div class="evs-energy-usage-overlay">
534
- <!-- SVG overlay for energy usage will be positioned here -->
535
- </div>
536
- </div>
537
- </div>
538
-
539
- <div class="evs-header-year">
540
- <div class="evs-year-overlay">
541
- <!-- SVG overlay for animated year will be positioned here -->
542
- </div>
543
- </div>
544
-
545
- <div class="evs-header-info">
546
- <div class="evs-subtitle">Energy Transitions in ${country} History, ${firstYear}-${lastYear}</div>
547
- <div class="evs-attribution">Suits, Matteson, and Moyer (2020)</div>
548
- </div>
549
-
550
- <div class="evs-header-affiliation">
551
- <div class="evs-affiliation-text">Center for Robust Decision-making on</div>
552
- <div class="evs-affiliation-text">Climate and Energy Policy, UChicago</div>
553
- </div>
554
- </div>
555
- </div>
597
+ const header = resolveHeader(this.options.header, {
598
+ country: this.options.country,
599
+ firstYear: this.services.dataService!.firstYear!,
600
+ lastYear: this.services.dataService!.lastYear!
601
+ });
602
+
603
+ let html = `${renderHeaderHtml(header)}
556
604
  <div class="evs-us-energy-sankey-wrapper" style="width: ${this.services['configurationService']?.WIDTH}px;">
557
605
  <div class="evs-sankey" style="line-height: 0;"></div>
558
606
  `;
@@ -767,24 +815,114 @@ export default class Sankey {
767
815
  this.subscriptions.push(errorSubscription, yearChangeSubscription);
768
816
  }
769
817
 
818
+ /**
819
+ * Register handlers supplied through the `events` constructor option.
820
+ * Runs before initialize() so that no lifecycle event is dropped.
821
+ */
822
+ private registerConfiguredEventHandlers(): void {
823
+ const configured = this.options.events;
824
+ if (!configured) {
825
+ return;
826
+ }
827
+
828
+ (Object.keys(configured) as SankeyPublicEventType[]).forEach(type => {
829
+ const handler = configured[type] as SankeyEventListener<any> | undefined;
830
+ if (typeof handler === 'function') {
831
+ this.addListener(type, handler, handler);
832
+ }
833
+ });
834
+ }
835
+
836
+ /**
837
+ * Shared registration path for on(), once() and the `events` option.
838
+ *
839
+ * @param identity what off() matches on - the handler the caller passed
840
+ * @param invoke what actually runs, which differs from identity for once()
841
+ */
842
+ private addListener(
843
+ type: SankeyPublicEventType,
844
+ identity: SankeyEventListener<any>,
845
+ invoke: SankeyEventListener<any>
846
+ ): SankeyUnsubscribe {
847
+ if (typeof identity !== 'function' || typeof invoke !== 'function') {
848
+ throw new SankeyError(`SankeyVisualization: event handler for '${type}' must be a function`);
849
+ }
850
+
851
+ if (this.destroyed) {
852
+ console.warn(`SankeyVisualization: cannot subscribe to '${type}' - instance has been destroyed`);
853
+ return () => { /* no-op */
854
+ };
855
+ }
856
+
857
+ // HANDLER IDENTITY ISOLATION - do not remove.
858
+ // EventBus stores handlers in a Set keyed by function identity. Passing
859
+ // the same function object twice collapses into a single Set entry, and
860
+ // unsubscribing either subscription would then silently remove BOTH.
861
+ // Allocating a fresh closure per registration keeps every registration
862
+ // independently removable. Covered by tests/event-bus.test.ts.
863
+ const wrapped: EventHandler<any> = (event) => invoke(event as SankeyPublicEvent<any>);
864
+
865
+ const record: PublicListenerRecord = {
866
+ type,
867
+ identity,
868
+ subscription: this.eventBus.subscribe<any>(type, wrapped)
869
+ };
870
+ this.publicListeners.push(record);
871
+
872
+ let alreadyRemoved = false;
873
+ return () => {
874
+ if (alreadyRemoved) {
875
+ return;
876
+ }
877
+ alreadyRemoved = true;
878
+ this.removeListener(record);
879
+ };
880
+ }
881
+
882
+ /**
883
+ * Remove a single public subscription and its bus registration
884
+ */
885
+ private removeListener(record: PublicListenerRecord): void {
886
+ const index = this.publicListeners.indexOf(record);
887
+ if (index === -1) {
888
+ return;
889
+ }
890
+ this.publicListeners.splice(index, 1);
891
+
892
+ // After destroy() the bus has already been cleared; unsubscribing again
893
+ // would only log a spurious "non-existent subscription" warning.
894
+ if (!this.destroyed) {
895
+ this.eventBus.unsubscribe(record.subscription);
896
+ }
897
+ }
898
+
770
899
  /**
771
900
  * Handle initialization errors
772
901
  */
773
902
  private handleInitializationError(error: any): void {
774
- console.error('SankeyVisualization: Initialization failed:', error);
903
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
904
+
905
+ console.error('SankeyVisualization: Initialization failed:', normalizedError);
775
906
 
776
907
  this.eventBus.emit({
777
908
  type: 'system.error',
778
909
  timestamp: Date.now(),
779
910
  source: 'SankeyVisualization',
780
911
  data: {
781
- error: error instanceof Error ? error : new Error(String(error)),
912
+ error: normalizedError,
782
913
  context: 'initialization',
783
914
  recoverable: false
784
915
  },
785
916
  });
786
917
 
787
- // Clean up any partially initialized state
918
+ // Settle whenReady() with the real cause BEFORE destroy(), which would
919
+ // otherwise reject first with a generic "destroyed" error and lose it.
920
+ this.rejectReady(normalizedError);
921
+
922
+ // Clean up any partially initialized state.
923
+ // NOTE: the emit above is already in flight and still delivers. emit()
924
+ // captures its handler Set synchronously and clear() empties the Map
925
+ // rather than the captured Sets, so 'system.error' handlers still run.
788
926
  this.destroy();
789
927
 
790
928
  throw error;
@@ -899,6 +1037,86 @@ export default class Sankey {
899
1037
  return this.initialized;
900
1038
  }
901
1039
 
1040
+ // ==================== PUBLIC EVENT API ====================
1041
+
1042
+ /**
1043
+ * Subscribe to a visualization event
1044
+ *
1045
+ * Handlers run asynchronously, one microtask after the event is produced,
1046
+ * and are error-isolated: a throwing handler cannot break the visualization
1047
+ * or prevent other handlers from running.
1048
+ *
1049
+ * LIFECYCLE TIMING: `system.ready` and `system.error` are produced during the
1050
+ * asynchronous initialization the constructor starts. Subscribing in the same
1051
+ * synchronous tick as `new Sankey(...)` is soon enough; subscribing later (for
1052
+ * example after `await nextTick()`) is not. For those, use the `events`
1053
+ * constructor option or {@link whenReady}.
1054
+ *
1055
+ * Registering the same function twice registers it twice and it is called
1056
+ * twice; each call returns its own unsubscribe.
1057
+ *
1058
+ * @returns an unsubscribe function, safe to call more than once
1059
+ */
1060
+ public on<K extends SankeyPublicEventType>(
1061
+ type: K,
1062
+ handler: SankeyEventListener<K>
1063
+ ): SankeyUnsubscribe {
1064
+ const listener = handler as SankeyEventListener<any>;
1065
+ return this.addListener(type, listener, listener);
1066
+ }
1067
+
1068
+ /**
1069
+ * Subscribe until the first delivery, then unsubscribe automatically
1070
+ *
1071
+ * Cancellable either with the returned function or with `off(type, handler)`.
1072
+ */
1073
+ public once<K extends SankeyPublicEventType>(
1074
+ type: K,
1075
+ handler: SankeyEventListener<K>
1076
+ ): SankeyUnsubscribe {
1077
+ let unsubscribe: SankeyUnsubscribe = () => { /* replaced below */
1078
+ };
1079
+
1080
+ const invoke: SankeyEventListener<any> = (event) => {
1081
+ // Remove BEFORE invoking so a throwing handler cannot fire twice.
1082
+ unsubscribe();
1083
+ return (handler as SankeyEventListener<any>)(event);
1084
+ };
1085
+
1086
+ // `handler` is recorded as the identity so that off(type, handler)
1087
+ // cancels a pending once() even though the bus holds `invoke`.
1088
+ unsubscribe = this.addListener(type, handler as SankeyEventListener<any>, invoke);
1089
+ return unsubscribe;
1090
+ }
1091
+
1092
+ /**
1093
+ * Remove every registration of `handler` for `type`, including a pending once()
1094
+ *
1095
+ * Removes all matching registrations rather than one, so teardown code
1096
+ * reliably stops delivery. No-op if the handler was never registered.
1097
+ */
1098
+ public off<K extends SankeyPublicEventType>(
1099
+ type: K,
1100
+ handler: SankeyEventListener<K>
1101
+ ): this {
1102
+ // Snapshot first: removeListener() mutates this.publicListeners.
1103
+ this.publicListeners
1104
+ .filter(record => record.type === type && record.identity === handler)
1105
+ .forEach(record => this.removeListener(record));
1106
+
1107
+ return this;
1108
+ }
1109
+
1110
+ /**
1111
+ * Resolve when initialization completes, or reject if it failed
1112
+ *
1113
+ * Unlike `on('system.ready', ...)` this is a latch: it resolves even when
1114
+ * called long after the event was emitted. Safe to call any number of times.
1115
+ */
1116
+ public whenReady(): Promise<SankeyPublicEvent<'system.ready'>> {
1117
+ return this.readyPromise;
1118
+ }
1119
+
902
1120
  /**
903
1121
  * Get array of available years in dataset
904
1122
  * @returns Readonly array of years available for visualization
@@ -966,6 +1184,10 @@ export default class Sankey {
966
1184
  this.subscriptions.forEach(sub => this.eventBus.unsubscribe(sub));
967
1185
  this.subscriptions = [];
968
1186
 
1187
+ // Release consumer closures. eventBus.clear() below drops the underlying
1188
+ // handlers; this drops our bookkeeping references to them.
1189
+ this.publicListeners = [];
1190
+
969
1191
  // Clean up event bus
970
1192
  this.eventBus.clear();
971
1193
 
@@ -990,6 +1212,12 @@ export default class Sankey {
990
1212
  this.destroyed = true;
991
1213
  this.initialized = false;
992
1214
 
1215
+ // Settle whenReady() so callers awaiting an instance that never came up
1216
+ // are not left hanging. No-op once the promise has already settled, so
1217
+ // this is harmless on the happy path. The constructor's no-op catch
1218
+ // prevents an unhandled rejection here.
1219
+ this.rejectReady(new SankeyError('SankeyVisualization: destroyed before initialization completed'));
1220
+
993
1221
  // Resource cleanup completed successfully
994
1222
  }
995
1223
 
@@ -1013,6 +1241,8 @@ export default class Sankey {
1013
1241
 
1014
1242
  // Validate data structure
1015
1243
  this.validateDataStructure(options.data);
1244
+
1245
+ validateHeaderOptions(options.header);
1016
1246
  }
1017
1247
 
1018
1248
  private validateDataStructure(data: EnergyDataPoint[]): void {
@@ -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>;