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.
@@ -1,6 +1,11 @@
1
1
  import * as d3 from 'd3';
2
2
  import {GraphData, SankeyOptions} from '@/types';
3
3
  import {EventBus} from '@/core/events/EventBus';
4
+ import type {
5
+ SankeyAnimationEventData,
6
+ SankeySpeedChangedEventData,
7
+ SankeyYearChangedEventData
8
+ } from '@/core/types/public-events';
4
9
  import {SummaryService} from '@/services/calculation/SummaryService';
5
10
  import {GraphService} from '@/services/calculation/GraphService';
6
11
  import {Logger} from "@/utils/Logger";
@@ -505,16 +510,20 @@ export class AnimationService {
505
510
 
506
511
  // EVENT SYSTEM INTEGRATION: Notify other services of year change
507
512
  // Enables coordinated updates across the entire visualization system
513
+ // Annotated against the public payload type so that any drift between
514
+ // what is emitted and what SankeyEventMap advertises fails type-check.
515
+ const yearChangedData: SankeyYearChangedEventData = {
516
+ year, // New target year
517
+ previousYear, // Previous year for transition context
518
+ yearIndex, // Array index for efficient data access
519
+ isAnimating: this.state.isAnimating // Animation state for context
520
+ };
521
+
508
522
  this.eventBus.emit({
509
523
  type: 'year.changed',
510
524
  timestamp: Date.now(),
511
525
  source: 'AnimationControlService',
512
- data: {
513
- year, // New target year
514
- previousYear, // Previous year for transition context
515
- yearIndex, // Array index for efficient data access
516
- isAnimating: this.state.isAnimating // Animation state for context
517
- },
526
+ data: yearChangedData,
518
527
  });
519
528
  }
520
529
 
@@ -823,15 +832,17 @@ export class AnimationService {
823
832
 
824
833
  // EVENT SYSTEM INTEGRATION: Broadcast animation start to other services
825
834
  // Enables coordinated behavior across visualization components during playback
835
+ const startedData: SankeyAnimationEventData = {
836
+ isPlaying: true,
837
+ currentYear: this.getCurrentYear(), // Starting year for context
838
+ speed: this.state.speed // Playback speed for coordination
839
+ };
840
+
826
841
  this.eventBus.emit({
827
842
  type: 'animation.started',
828
843
  timestamp: Date.now(),
829
844
  source: 'AnimationControlService',
830
- data: {
831
- isPlaying: true,
832
- currentYear: this.getCurrentYear(), // Starting year for context
833
- speed: this.state.speed // Playback speed for coordination
834
- },
845
+ data: startedData,
835
846
  });
836
847
  }
837
848
 
@@ -877,15 +888,17 @@ export class AnimationService {
877
888
 
878
889
  // EVENT SYSTEM INTEGRATION: Broadcast animation stop to other services
879
890
  // Enables coordinated pause behavior across visualization components
891
+ const stoppedData: SankeyAnimationEventData = {
892
+ isPlaying: false,
893
+ currentYear: this.getCurrentYear(), // Current position preserved
894
+ speed: this.state.speed // Speed settings maintained
895
+ };
896
+
880
897
  this.eventBus.emit({
881
898
  type: 'animation.stopped',
882
899
  timestamp: Date.now(),
883
900
  source: 'AnimationControlService',
884
- data: {
885
- isPlaying: false,
886
- currentYear: this.getCurrentYear(), // Current position preserved
887
- speed: this.state.speed // Speed settings maintained
888
- }
901
+ data: stoppedData
889
902
  });
890
903
  }
891
904
 
@@ -927,13 +940,15 @@ export class AnimationService {
927
940
  }
928
941
 
929
942
  // Emit speed changed event
943
+ const speedChangedData: SankeySpeedChangedEventData = {
944
+ speed
945
+ };
946
+
930
947
  this.eventBus.emit({
931
948
  type: 'speed.changed',
932
949
  timestamp: Date.now(),
933
950
  source: 'AnimationControlService',
934
- data: {
935
- speed
936
- }
951
+ data: speedChangedData
937
952
  });
938
953
 
939
954
  // Animation speed updated for timeline playback
@@ -1,4 +1,10 @@
1
1
  import {EventBus} from '@/core/events/EventBus';
2
+ import type {
3
+ SankeyButtonEventData,
4
+ SankeyElementInteractionEventData,
5
+ SankeyKeypressEventData,
6
+ SankeySliderEventData
7
+ } from '@/core/types/public-events';
2
8
  import {DataService} from "@/services/data/DataService";
3
9
  import {AnimationService} from "@/services/AnimationService";
4
10
  import {Logger} from "@/utils/Logger";
@@ -416,16 +422,18 @@ export class InteractionService {
416
422
  // Emit keyboard navigation event - Event-Driven Architecture Integration
417
423
  // Enables other services to react to keyboard interactions
418
424
  // Provides rich event context (key + modifiers) for advanced interactions
425
+ const keypressData: SankeyKeypressEventData = {
426
+ key, // Primary key pressed (normalized to lowercase)
427
+ ctrlKey: event.ctrlKey, // Enables Ctrl+key shortcuts
428
+ shiftKey: event.shiftKey, // Enables Shift+key shortcuts
429
+ altKey: event.altKey // Enables Alt+key shortcuts (power user features)
430
+ };
431
+
419
432
  this.eventBus.emit({
420
433
  type: 'interaction.keypress',
421
434
  timestamp: Date.now(),
422
435
  source: 'InteractionService',
423
- data: {
424
- key, // Primary key pressed (normalized to lowercase)
425
- ctrlKey: event.ctrlKey, // Enables Ctrl+key shortcuts
426
- shiftKey: event.shiftKey, // Enables Shift+key shortcuts
427
- altKey: event.altKey // Enables Alt+key shortcuts (power user features)
428
- }
436
+ data: keypressData
429
437
  });
430
438
 
431
439
  // Call custom handler if provided - Extensibility Pattern
@@ -477,14 +485,16 @@ export class InteractionService {
477
485
  // Emit slider interaction event - Event-Driven Architecture
478
486
  // Enables other services to react to timeline position changes
479
487
  // Provides structured event data for logging and analytics
488
+ const sliderData: SankeySliderEventData = {
489
+ year, // Selected year value (numeric)
490
+ value: year // Duplicate for backwards compatibility
491
+ };
492
+
480
493
  this.eventBus.emit({
481
494
  type: 'interaction.slider',
482
495
  timestamp: Date.now(),
483
496
  source: 'InteractionService',
484
- data: {
485
- year, // Selected year value (numeric)
486
- value: year // Duplicate for backwards compatibility
487
- }
497
+ data: sliderData
488
498
  });
489
499
 
490
500
  // Call custom handler if provided - Extensibility Pattern
@@ -544,14 +554,16 @@ export class InteractionService {
544
554
  // Emit button interaction event - Event-Driven Architecture
545
555
  // Enables other services to react to animation state changes
546
556
  // Note: Action reflects the RESULT of the button press, not the current state
557
+ const playButtonData: SankeyButtonEventData = {
558
+ buttonId: 'evs-play-button',
559
+ action: this.animationControlService.isPlaying() ? 'play' : 'pause'
560
+ };
561
+
547
562
  this.eventBus.emit({
548
563
  type: 'interaction.button',
549
564
  timestamp: Date.now(),
550
565
  source: 'InteractionService',
551
- data: {
552
- buttonId: 'evs-play-button',
553
- action: this.animationControlService.isPlaying() ? 'play' : 'pause'
554
- }
566
+ data: playButtonData
555
567
  });
556
568
  };
557
569
 
@@ -572,15 +584,17 @@ export class InteractionService {
572
584
 
573
585
  // Emit speed change event - Event-Driven Architecture
574
586
  // Enables UI updates (active button state, speed indicator)
587
+ const speedButtonData: SankeyButtonEventData = {
588
+ buttonId: target.id,
589
+ action: 'speed-change',
590
+ speed // New animation speed in milliseconds
591
+ };
592
+
575
593
  this.eventBus.emit({
576
594
  type: 'interaction.button',
577
595
  timestamp: Date.now(),
578
596
  source: 'InteractionService',
579
- data: {
580
- buttonId: target.id,
581
- action: 'speed-change',
582
- speed // New animation speed in milliseconds
583
- }
597
+ data: speedButtonData
584
598
  });
585
599
  };
586
600
 
@@ -704,16 +718,18 @@ export class InteractionService {
704
718
 
705
719
  // Emit hover event - Event-Driven Architecture
706
720
  // Provides rich context for tooltip display, analytics, and custom behavior
721
+ const hoverData: SankeyElementInteractionEventData = {
722
+ elementType: element.classList.contains('evs-flow') ? 'flow' : 'box', // Element classification
723
+ fuel: element.getAttribute('data-fuel'), // Energy source identification
724
+ sector: element.getAttribute('data-sector'), // Consumption sector identification
725
+ mousePosition: {x: event.clientX, y: event.clientY} // Coordinates for tooltip positioning
726
+ };
727
+
707
728
  this.eventBus.emit({
708
729
  type: 'interaction.hover',
709
730
  timestamp: Date.now(),
710
731
  source: 'InteractionService',
711
- data: {
712
- elementType: element.classList.contains('evs-flow') ? 'flow' : 'box', // Element classification
713
- fuel: element.getAttribute('data-fuel'), // Energy source identification
714
- sector: element.getAttribute('data-sector'), // Consumption sector identification
715
- mousePosition: {x: event.clientX, y: event.clientY} // Coordinates for tooltip positioning
716
- }
732
+ data: hoverData
717
733
  });
718
734
 
719
735
  // Call custom handler if provided - Extensibility Pattern
@@ -758,16 +774,18 @@ export class InteractionService {
758
774
 
759
775
  // Emit click event - Event-Driven Architecture
760
776
  // Provides comprehensive click context for analytics, tooltips, and custom behavior
777
+ const clickData: SankeyElementInteractionEventData = {
778
+ elementType: element.classList.contains('evs-flow') ? 'flow' : 'box', // Element classification
779
+ fuel: element.getAttribute('data-fuel'), // Energy source identification
780
+ sector: element.getAttribute('data-sector'), // Consumption sector identification
781
+ mousePosition: {x: event.clientX, y: event.clientY} // Click coordinates for UI positioning
782
+ };
783
+
761
784
  this.eventBus.emit({
762
785
  type: 'interaction.click',
763
786
  timestamp: Date.now(),
764
787
  source: 'InteractionService',
765
- data: {
766
- elementType: element.classList.contains('evs-flow') ? 'flow' : 'box', // Element classification
767
- fuel: element.getAttribute('data-fuel'), // Energy source identification
768
- sector: element.getAttribute('data-sector'), // Consumption sector identification
769
- mousePosition: {x: event.clientX, y: event.clientY} // Click coordinates for UI positioning
770
- }
788
+ data: clickData
771
789
  });
772
790
 
773
791
  // Call custom handler if provided - Extensibility Pattern
@@ -1,6 +1,7 @@
1
1
  import type {EnergyDataPoint} from '@/types';
2
2
  import {DataValidationError} from '@/types';
3
3
  import {EventBus} from '@/core/events/EventBus';
4
+ import type {SankeyErrorEventData} from '@/core/types/public-events';
4
5
  import {Logger} from "@/utils/Logger";
5
6
  import {ConfigurationService} from "@/services/ConfigurationService";
6
7
 
@@ -135,15 +136,17 @@ export class DataValidationService {
135
136
  // Emit validation error event for error handling - Error Recovery Architecture
136
137
  // Enables centralized error handling and user notification systems
137
138
  // Marks validation errors as non-recoverable (require data fix)
139
+ const validationErrorData: SankeyErrorEventData = {
140
+ error: error instanceof Error ? error : new Error(String(error)),
141
+ context: 'data_validation', // Error categorization for debugging
142
+ recoverable: false // Validation errors require data correction
143
+ };
144
+
138
145
  this.eventBus.emit({
139
146
  type: 'system.error',
140
147
  timestamp: Date.now(),
141
148
  source: 'DataValidationService',
142
- data: {
143
- error: error instanceof Error ? error : new Error(String(error)),
144
- context: 'data_validation', // Error categorization for debugging
145
- recoverable: false // Validation errors require data correction
146
- }
149
+ data: validationErrorData
147
150
  });
148
151
 
149
152
  // Re-throw error to maintain validation contract - Fail-Fast Pattern
@@ -19,6 +19,11 @@
19
19
  *
20
20
  */
21
21
 
22
+ // Relative on purpose. The exact `@/types` alias entry is mis-rewritten by
23
+ // tsc-alias to the public barrel, so alias imports reaching the declaration
24
+ // surface are unsafe. Relative specifiers are never rewritten.
25
+ import type {SankeyEventHandlers} from '../core/types/public-events';
26
+
22
27
  // Error types
23
28
  export class SankeyError extends Error {
24
29
  constructor(message: string, public code?: string) {
@@ -85,6 +90,17 @@ export interface SankeyOptions {
85
90
  readonly heatBoxY?: number;
86
91
  readonly loopAnimation?: boolean;
87
92
  readonly debugLogging?: boolean;
93
+
94
+ /**
95
+ * Event handlers registered before asynchronous initialization begins.
96
+ *
97
+ * Prefer this over `.on()` for lifecycle events. `system.ready` and
98
+ * `system.error` are produced during the initialization the constructor
99
+ * starts, and the event bus drops events that have no subscriber at emit
100
+ * time, so a subscription added later can miss them entirely. Interaction
101
+ * events can be attached either way.
102
+ */
103
+ readonly events?: SankeyEventHandlers;
88
104
  }
89
105
 
90
106
  // Mathematical structures
@@ -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
+ });