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.
@@ -4447,6 +4447,207 @@ class Logger {
4447
4447
  }
4448
4448
  }
4449
4449
 
4450
+ /**
4451
+ * Header configuration: defaults, validation, placeholder substitution and
4452
+ * HTML rendering for the title block above the chart.
4453
+ *
4454
+ * Every value that reaches the markup goes through escapeHtml(). Header text and
4455
+ * `country` come from host configuration that, in the Energy Visualization
4456
+ * Platform, is user-entered and rendered on public share pages, so they must
4457
+ * never be interpreted as HTML.
4458
+ */
4459
+ const RDCEP_NAME = 'The Center for Robust Decision-making on Climate and Energy Policy (RDCEP)';
4460
+ /** The header shown when no `header` option is given (unchanged from earlier releases). */
4461
+ const DEFAULT_HEADER = {
4462
+ title: '{country} energy usage',
4463
+ subtitle: 'Energy Transitions in {country} History, {firstYear}-{lastYear}',
4464
+ attribution: 'Suits, Matteson, and Moyer (2020)',
4465
+ affiliation: ['Center for Robust Decision-making on', 'Climate and Energy Policy, UChicago'],
4466
+ logo: {
4467
+ src: 'https://images.squarespace-cdn.com/content/v1/54dcfad0e4b0eaff5e0068bf/1446137765478-FX9WM00VV1LWAFUJRZBI/rdcep+sig2.png',
4468
+ href: 'https://www.rdcep.org/',
4469
+ alt: RDCEP_NAME
4470
+ }
4471
+ };
4472
+ const HEADER_KEYS = ['title', 'subtitle', 'attribution', 'affiliation', 'logo'];
4473
+ const LOGO_KEYS = ['src', 'href', 'alt'];
4474
+ function escapeHtml(value) {
4475
+ return value
4476
+ .replace(/&/g, '&')
4477
+ .replace(/</g, '&lt;')
4478
+ .replace(/>/g, '&gt;')
4479
+ .replace(/"/g, '&quot;')
4480
+ .replace(/'/g, '&#39;');
4481
+ }
4482
+ function isHttpsUrl(value) {
4483
+ try {
4484
+ return new URL(value).protocol === 'https:';
4485
+ }
4486
+ catch (_a) {
4487
+ return false;
4488
+ }
4489
+ }
4490
+ function invalid(message) {
4491
+ throw new SankeyError(`Invalid header option: ${message}`, 'INVALID_HEADER');
4492
+ }
4493
+ function checkText(value, field) {
4494
+ if (value !== undefined && value !== null && typeof value !== 'string') {
4495
+ invalid(`${field} must be a string or null`);
4496
+ }
4497
+ }
4498
+ /**
4499
+ * Validate the shape of the `header` option. Throws SankeyError so a bad
4500
+ * configuration fails at construction time, like the existing data checks.
4501
+ */
4502
+ function validateHeaderOptions(header) {
4503
+ if (header === undefined) {
4504
+ return;
4505
+ }
4506
+ if (header === null || typeof header !== 'object' || Array.isArray(header)) {
4507
+ invalid('header must be an object');
4508
+ }
4509
+ const h = header;
4510
+ for (const key of Object.keys(h)) {
4511
+ if (!HEADER_KEYS.includes(key)) {
4512
+ invalid(`unknown key "${key}"`);
4513
+ }
4514
+ }
4515
+ checkText(h.title, 'title');
4516
+ checkText(h.subtitle, 'subtitle');
4517
+ checkText(h.attribution, 'attribution');
4518
+ if (h.affiliation !== undefined && h.affiliation !== null) {
4519
+ if (!Array.isArray(h.affiliation) || !h.affiliation.every(line => typeof line === 'string')) {
4520
+ invalid('affiliation must be an array of strings or null');
4521
+ }
4522
+ }
4523
+ if (h.logo !== undefined && h.logo !== null) {
4524
+ if (typeof h.logo !== 'object' || Array.isArray(h.logo)) {
4525
+ invalid('logo must be an object or null');
4526
+ }
4527
+ const logo = h.logo;
4528
+ for (const key of Object.keys(logo)) {
4529
+ if (!LOGO_KEYS.includes(key)) {
4530
+ invalid(`unknown logo key "${key}"`);
4531
+ }
4532
+ }
4533
+ if (typeof logo.src !== 'string' || !isHttpsUrl(logo.src)) {
4534
+ invalid('logo.src must be an https:// URL');
4535
+ }
4536
+ if (logo.href !== undefined && (typeof logo.href !== 'string' || !isHttpsUrl(logo.href))) {
4537
+ invalid('logo.href must be an https:// URL');
4538
+ }
4539
+ if (logo.alt !== undefined && typeof logo.alt !== 'string') {
4540
+ invalid('logo.alt must be a string');
4541
+ }
4542
+ }
4543
+ }
4544
+ function substitute(template, context) {
4545
+ return template
4546
+ .replace(/\{country\}/g, context.country)
4547
+ .replace(/\{firstYear\}/g, String(context.firstYear))
4548
+ .replace(/\{lastYear\}/g, String(context.lastYear));
4549
+ }
4550
+ /** `undefined` -> default, `null` -> hidden, blank after substitution -> hidden. */
4551
+ function resolveText(value, fallback, context) {
4552
+ if (value === null) {
4553
+ return null;
4554
+ }
4555
+ const text = substitute(value !== null && value !== void 0 ? value : fallback, context).trim();
4556
+ return text === '' ? null : text;
4557
+ }
4558
+ function resolveLogo(logo) {
4559
+ var _a, _b;
4560
+ if (logo === null) {
4561
+ return null;
4562
+ }
4563
+ if (logo === undefined) {
4564
+ return { ...DEFAULT_HEADER.logo };
4565
+ }
4566
+ return { src: logo.src, href: (_a = logo.href) !== null && _a !== void 0 ? _a : null, alt: (_b = logo.alt) !== null && _b !== void 0 ? _b : '' };
4567
+ }
4568
+ function resolveHeader(header, context) {
4569
+ var _a;
4570
+ const h = header !== null && header !== void 0 ? header : {};
4571
+ let affiliation = null;
4572
+ if (h.affiliation !== null) {
4573
+ const lines = ((_a = h.affiliation) !== null && _a !== void 0 ? _a : DEFAULT_HEADER.affiliation)
4574
+ .map(line => substitute(line, context).trim())
4575
+ .filter(line => line !== '');
4576
+ affiliation = lines.length > 0 ? lines : null;
4577
+ }
4578
+ return {
4579
+ title: resolveText(h.title, DEFAULT_HEADER.title, context),
4580
+ subtitle: resolveText(h.subtitle, DEFAULT_HEADER.subtitle, context),
4581
+ attribution: resolveText(h.attribution, DEFAULT_HEADER.attribution, context),
4582
+ affiliation,
4583
+ logo: resolveLogo(h.logo)
4584
+ };
4585
+ }
4586
+ /**
4587
+ * Render the header block. The `.evs-energy-usage-overlay` and
4588
+ * `.evs-year-overlay` containers are always emitted: RenderingService mounts the
4589
+ * animated W/capita total and year into them, whatever text is hidden.
4590
+ */
4591
+ function renderHeaderHtml(header) {
4592
+ let logoHtml = '';
4593
+ if (header.logo) {
4594
+ const alt = escapeHtml(header.logo.alt);
4595
+ const titleAttr = alt ? ` title="${alt}"` : '';
4596
+ const img = `<img src="${escapeHtml(header.logo.src)}" alt="${alt}"${titleAttr}>`;
4597
+ const content = header.logo.href
4598
+ ? `<a href="${escapeHtml(header.logo.href)}" target="_blank" rel="noopener noreferrer">${img}</a>`
4599
+ : img;
4600
+ logoHtml = `
4601
+ <div class="evs-header-logo">
4602
+ ${content}
4603
+ </div>
4604
+ `;
4605
+ }
4606
+ const titleHtml = header.title
4607
+ ? `<h1 class="evs-main-title">${escapeHtml(header.title)}</h1>`
4608
+ : '';
4609
+ let infoHtml = '';
4610
+ if (header.subtitle || header.attribution) {
4611
+ infoHtml = `
4612
+ <div class="evs-header-info">
4613
+ ${header.subtitle ? `<div class="evs-subtitle">${escapeHtml(header.subtitle)}</div>` : ''}
4614
+ ${header.attribution ? `<div class="evs-attribution">${escapeHtml(header.attribution)}</div>` : ''}
4615
+ </div>
4616
+ `;
4617
+ }
4618
+ let affiliationHtml = '';
4619
+ if (header.affiliation) {
4620
+ const lines = header.affiliation
4621
+ .map(line => `<div class="evs-affiliation-text">${escapeHtml(line)}</div>`)
4622
+ .join('\n ');
4623
+ affiliationHtml = `
4624
+ <div class="evs-header-affiliation">
4625
+ ${lines}
4626
+ </div>
4627
+ `;
4628
+ }
4629
+ return `
4630
+ <div class="evs-sankey evs-title-container">
4631
+ <div class="evs-header-content">${logoHtml}
4632
+ <div class="evs-header-main">
4633
+ <div class="evs-header-title-section">
4634
+ ${titleHtml}
4635
+ <div class="evs-energy-usage-overlay">
4636
+ <!-- SVG overlay for energy usage will be positioned here -->
4637
+ </div>
4638
+ </div>
4639
+ </div>
4640
+
4641
+ <div class="evs-header-year">
4642
+ <div class="evs-year-overlay">
4643
+ <!-- SVG overlay for animated year will be positioned here -->
4644
+ </div>
4645
+ </div>
4646
+ ${infoHtml}${affiliationHtml}
4647
+ </div>
4648
+ </div>`;
4649
+ }
4650
+
4450
4651
  /**
4451
4652
  * Configuration Service - Mathematical Constants & Visual Parameters
4452
4653
  *
@@ -5014,15 +5215,16 @@ class DataValidationService {
5014
5215
  // Emit validation error event for error handling - Error Recovery Architecture
5015
5216
  // Enables centralized error handling and user notification systems
5016
5217
  // Marks validation errors as non-recoverable (require data fix)
5218
+ const validationErrorData = {
5219
+ error: error instanceof Error ? error : new Error(String(error)),
5220
+ context: 'data_validation', // Error categorization for debugging
5221
+ recoverable: false // Validation errors require data correction
5222
+ };
5017
5223
  this.eventBus.emit({
5018
5224
  type: 'system.error',
5019
5225
  timestamp: Date.now(),
5020
5226
  source: 'DataValidationService',
5021
- data: {
5022
- error: error instanceof Error ? error : new Error(String(error)),
5023
- context: 'data_validation', // Error categorization for debugging
5024
- recoverable: false // Validation errors require data correction
5025
- }
5227
+ data: validationErrorData
5026
5228
  });
5027
5229
  // Re-throw error to maintain validation contract - Fail-Fast Pattern
5028
5230
  // Prevents invalid data from propagating to calculation services
@@ -6672,52 +6874,6 @@ class RenderingService {
6672
6874
  }
6673
6875
  }
6674
6876
 
6675
- /**
6676
- * Main Sankey Visualization Class - Event-Driven Architecture Orchestrator
6677
- *
6678
- * ARCHITECTURE PATTERN: Service Orchestration with Event-Driven Communication
6679
- *
6680
- * This class implements the Orchestrator pattern from Clean Architecture,
6681
- * coordinating between focused, single-responsibility services through
6682
- * a type-safe event bus. It acts as the application boundary, managing
6683
- * the complete lifecycle from initialization to destruction.
6684
- *
6685
- * SERVICE COMPOSITION ARCHITECTURE:
6686
- * 1. Infrastructure Layer: ConfigurationService (mathematical constants)
6687
- * 2. Data Layer: DataService, ValidationService, TransformService
6688
- * 3. Calculation Layer: SummaryService, GraphService, PositionService
6689
- * 4. Presentation Layer: RenderingService, AnimationService
6690
- * 5. Interaction Layer: InteractionService, TooltipService
6691
- *
6692
- * DEPENDENCY INJECTION PATTERN:
6693
- * - Constructor Injection: Services receive dependencies via constructor
6694
- * - Service Locator: Services are registered in central container
6695
- * - Event Bus Mediation: Services communicate without direct coupling
6696
- * - Lifecycle Management: Services created in dependency order
6697
- *
6698
- * EVENT-DRIVEN COMMUNICATION BENEFITS:
6699
- * - Loose Coupling: Services don't hold references to each other
6700
- * - Testability: Services can be mocked and tested in isolation
6701
- * - Maintainability: Changes to one service don't affect others
6702
- * - Performance: Async event dispatch prevents blocking operations
6703
- *
6704
- * PUBLIC API COMPATIBILITY:
6705
- * Maintains complete API compatibility with previous versions while
6706
- * providing enhanced functionality including configurable animation
6707
- * looping, improved error handling, and comprehensive performance monitoring.
6708
- *
6709
- * Usage Example:
6710
- * ```typescript
6711
- * const sankey = new SankeyVisualization('container', {
6712
- * data: energyData,
6713
- * includeControls: true,
6714
- * loopAnimation: false
6715
- * });
6716
- *
6717
- * // Chain-able API maintained for compatibility
6718
- * sankey.play().setSpeed(100).setYear(2020);
6719
- * ```
6720
- */
6721
6877
  class Sankey {
6722
6878
  constructor(containerId, options) {
6723
6879
  // SERVICE DEPENDENCY CONTAINER: Holds all service instances after creation
@@ -6732,6 +6888,10 @@ class Sankey {
6732
6888
  // Critical for memory leak prevention in long-running applications
6733
6889
  // Each subscription must be explicitly unsubscribed during destroy()
6734
6890
  this.subscriptions = [];
6891
+ // PUBLIC SUBSCRIPTION REGISTRY: consumer-facing on()/once() registrations.
6892
+ // Kept separate from `subscriptions` (internal service wiring) so that off()
6893
+ // and destroy() can reason about the two independently.
6894
+ this.publicListeners = [];
6735
6895
  this.logger = new Logger(options);
6736
6896
  // Initialize core system components
6737
6897
  // 1. Validate inputs using comprehensive validation logic
@@ -6743,9 +6903,23 @@ class Sankey {
6743
6903
  this.wasteHeatVisible = this.options.showWasteHeat !== false;
6744
6904
  // 4. Create core event bus
6745
6905
  this.eventBus = new EventBus(this.logger);
6746
- // 5. Setup system event listeners
6906
+ // 5. Arm the readiness latch before any asynchronous work starts.
6907
+ // The no-op catch is REQUIRED: without it, a failed initialization
6908
+ // produces a fresh unhandled rejection for every caller that never
6909
+ // uses whenReady(), which would be a behaviour change.
6910
+ this.readyPromise = new Promise((resolve, reject) => {
6911
+ this.resolveReady = resolve;
6912
+ this.rejectReady = reject;
6913
+ });
6914
+ this.readyPromise.catch(() => {
6915
+ });
6916
+ // 6. Setup system event listeners
6747
6917
  this.setupSystemEventListeners();
6748
- // 6. Initialize services and visualization
6918
+ // 7. Register handlers supplied through the `events` option. MUST happen
6919
+ // before initialize(): the event bus drops events that have no
6920
+ // subscriber at emit time and there is no replay.
6921
+ this.registerConfiguredEventHandlers();
6922
+ // 8. Initialize services and visualization
6749
6923
  this.initialize();
6750
6924
  }
6751
6925
  /**
@@ -6820,31 +6994,54 @@ class Sankey {
6820
6994
  // Must be created first as other services depend on configuration constants
6821
6995
  this.logger.log('SankeyVisualization: Creating infrastructure services...');
6822
6996
  await this.createConfigurationService();
6823
- // LAYER 2: DATA PROCESSING SERVICES
6997
+ // CANCELLATION CHECK: destroy() empties the service container, so a
6998
+ // destroy() issued while initialization is still in flight would
6999
+ // otherwise leave the remaining layers reading undefined services and
7000
+ // throwing asynchronously, where nothing can catch it. Each await is
7001
+ // a suspension point at which that can happen.
7002
+ if (this.destroyed) {
7003
+ return;
7004
+ }
7005
+ // LAYER 2: DATA PROCESSING SERVICES
6824
7006
  // Handle input validation, data access, and transformation pipelines
6825
7007
  // Depend on configuration service for validation rules and constants
6826
7008
  this.logger.log('SankeyVisualization: Creating data processing services...');
6827
7009
  await this.createDataServices();
7010
+ if (this.destroyed) {
7011
+ return;
7012
+ }
6828
7013
  // LAYER 3: MATHEMATICAL CALCULATION SERVICES
6829
- // Perform complex energy flow calculations with performance optimizations
7014
+ // Perform complex energy flow calculations with performance optimizations
6830
7015
  // Depend on data services for input and configuration for mathematical constants
6831
7016
  this.logger.log('SankeyVisualization: Creating calculation services...');
6832
7017
  await this.createCalculationServices();
7018
+ if (this.destroyed) {
7019
+ return;
7020
+ }
6833
7021
  // LAYER 4: VISUAL RENDERING SERVICES
6834
7022
  // Generate SVG elements and manage visual output
6835
7023
  // Depend on calculation services for positioning data and configuration for styling
6836
7024
  this.logger.log('SankeyVisualization: Creating rendering services...');
6837
7025
  await this.createRenderingServices();
7026
+ if (this.destroyed) {
7027
+ return;
7028
+ }
6838
7029
  // LAYER 5: ANIMATION CONTROL SERVICES
6839
7030
  // Manage timeline navigation and smooth transitions between years
6840
7031
  // Depend on rendering services for visual updates and calculation services for data
6841
7032
  this.logger.log('SankeyVisualization: Creating animation services...');
6842
7033
  await this.createAnimationService();
7034
+ if (this.destroyed) {
7035
+ return;
7036
+ }
6843
7037
  // LAYER 6: USER INTERACTION SERVICES
6844
7038
  // Handle mouse, keyboard, and touch events with accessibility support
6845
7039
  // Depend on animation services for playback control and rendering for visual feedback
6846
7040
  this.logger.log('SankeyVisualization: Creating interaction services...');
6847
7041
  await this.createInteractionServices();
7042
+ if (this.destroyed) {
7043
+ return;
7044
+ }
6848
7045
  // DOM INITIALIZATION: Create visualization structure in browser
6849
7046
  // Must happen after all services are created as services may reference DOM elements
6850
7047
  this.logger.log('SankeyVisualization: Initializing DOM structure...');
@@ -6853,24 +7050,32 @@ class Sankey {
6853
7050
  // Triggers the complete data → calculation → render pipeline for the first time
6854
7051
  this.logger.log('SankeyVisualization: Performing initial render...');
6855
7052
  await this.performInitialRender();
7053
+ if (this.destroyed) {
7054
+ return;
7055
+ }
6856
7056
  const totalInitializationTime = performance.now() - initializationStartTime;
6857
- // LIFECYCLE EVENT: Signal system fully ready for use
6858
- // Public API methods are safe to call after this event
6859
- this.eventBus.emit({
7057
+ const readyData = {
7058
+ totalInitTime: totalInitializationTime,
7059
+ dataPointCount: this.options.data.length,
7060
+ yearRange: [
7061
+ Math.min(...this.options.data.map(d => d.year)),
7062
+ Math.max(...this.options.data.map(d => d.year))
7063
+ ]
7064
+ };
7065
+ const readyEvent = {
6860
7066
  type: 'system.ready',
6861
7067
  timestamp: Date.now(),
6862
7068
  source: 'SankeyVisualization',
6863
- data: {
6864
- totalInitTime: totalInitializationTime,
6865
- dataPointCount: this.options.data.length,
6866
- yearRange: [
6867
- Math.min(...this.options.data.map(d => d.year)),
6868
- Math.max(...this.options.data.map(d => d.year))
6869
- ]
6870
- }
6871
- });
7069
+ data: readyData
7070
+ };
7071
+ // LIFECYCLE EVENT: Signal system fully ready for use
7072
+ // Public API methods are safe to call after this event
7073
+ this.eventBus.emit(readyEvent);
6872
7074
  // SYSTEM STATE: Mark initialization complete
6873
7075
  this.initialized = true;
7076
+ // Latch readiness so callers that subscribe after this point can
7077
+ // still observe it through whenReady().
7078
+ this.resolveReady(readyEvent);
6874
7079
  // PERFORMANCE LOGGING: Track initialization time for regression detection
6875
7080
  this.logger.log(`SankeyVisualization: Complete initialization in ${totalInitializationTime.toFixed(2)}ms`);
6876
7081
  // INITIALIZATION BENCHMARK: Performance regression detection system
@@ -7059,46 +7264,12 @@ class Sankey {
7059
7264
  */
7060
7265
  injectHTML() {
7061
7266
  var _a;
7062
- const country = this.options.country;
7063
- const firstYear = this.services.dataService.firstYear;
7064
- const lastYear = this.services.dataService.lastYear;
7065
- let html = `
7066
- <div class="evs-sankey evs-title-container">
7067
- <div class="evs-header-content">
7068
- <div class="evs-header-logo">
7069
- <a href="https://www.rdcep.org/" target="_blank">
7070
- <img src="https://images.squarespace-cdn.com/content/v1/54dcfad0e4b0eaff5e0068bf/1446137765478-FX9WM00VV1LWAFUJRZBI/rdcep+sig2.png"
7071
- alt="The Center for Robust Decision-making on Climate and Energy Policy (RDCEP)"
7072
- title="The Center for Robust Decision-making on Climate and Energy Policy (RDCEP)">
7073
- </a>
7074
- </div>
7075
-
7076
- <div class="evs-header-main">
7077
- <div class="evs-header-title-section">
7078
- <h1 class="evs-main-title">${country} energy usage</h1>
7079
- <div class="evs-energy-usage-overlay">
7080
- <!-- SVG overlay for energy usage will be positioned here -->
7081
- </div>
7082
- </div>
7083
- </div>
7084
-
7085
- <div class="evs-header-year">
7086
- <div class="evs-year-overlay">
7087
- <!-- SVG overlay for animated year will be positioned here -->
7088
- </div>
7089
- </div>
7090
-
7091
- <div class="evs-header-info">
7092
- <div class="evs-subtitle">Energy Transitions in ${country} History, ${firstYear}-${lastYear}</div>
7093
- <div class="evs-attribution">Suits, Matteson, and Moyer (2020)</div>
7094
- </div>
7095
-
7096
- <div class="evs-header-affiliation">
7097
- <div class="evs-affiliation-text">Center for Robust Decision-making on</div>
7098
- <div class="evs-affiliation-text">Climate and Energy Policy, UChicago</div>
7099
- </div>
7100
- </div>
7101
- </div>
7267
+ const header = resolveHeader(this.options.header, {
7268
+ country: this.options.country,
7269
+ firstYear: this.services.dataService.firstYear,
7270
+ lastYear: this.services.dataService.lastYear
7271
+ });
7272
+ let html = `${renderHeaderHtml(header)}
7102
7273
  <div class="evs-us-energy-sankey-wrapper" style="width: ${(_a = this.services['configurationService']) === null || _a === void 0 ? void 0 : _a.WIDTH}px;">
7103
7274
  <div class="evs-sankey" style="line-height: 0;"></div>
7104
7275
  `;
@@ -7283,22 +7454,97 @@ class Sankey {
7283
7454
  });
7284
7455
  this.subscriptions.push(errorSubscription, yearChangeSubscription);
7285
7456
  }
7457
+ /**
7458
+ * Register handlers supplied through the `events` constructor option.
7459
+ * Runs before initialize() so that no lifecycle event is dropped.
7460
+ */
7461
+ registerConfiguredEventHandlers() {
7462
+ const configured = this.options.events;
7463
+ if (!configured) {
7464
+ return;
7465
+ }
7466
+ Object.keys(configured).forEach(type => {
7467
+ const handler = configured[type];
7468
+ if (typeof handler === 'function') {
7469
+ this.addListener(type, handler, handler);
7470
+ }
7471
+ });
7472
+ }
7473
+ /**
7474
+ * Shared registration path for on(), once() and the `events` option.
7475
+ *
7476
+ * @param identity what off() matches on - the handler the caller passed
7477
+ * @param invoke what actually runs, which differs from identity for once()
7478
+ */
7479
+ addListener(type, identity, invoke) {
7480
+ if (typeof identity !== 'function' || typeof invoke !== 'function') {
7481
+ throw new SankeyError(`SankeyVisualization: event handler for '${type}' must be a function`);
7482
+ }
7483
+ if (this.destroyed) {
7484
+ console.warn(`SankeyVisualization: cannot subscribe to '${type}' - instance has been destroyed`);
7485
+ return () => {
7486
+ };
7487
+ }
7488
+ // HANDLER IDENTITY ISOLATION - do not remove.
7489
+ // EventBus stores handlers in a Set keyed by function identity. Passing
7490
+ // the same function object twice collapses into a single Set entry, and
7491
+ // unsubscribing either subscription would then silently remove BOTH.
7492
+ // Allocating a fresh closure per registration keeps every registration
7493
+ // independently removable. Covered by tests/event-bus.test.ts.
7494
+ const wrapped = (event) => invoke(event);
7495
+ const record = {
7496
+ type,
7497
+ identity,
7498
+ subscription: this.eventBus.subscribe(type, wrapped)
7499
+ };
7500
+ this.publicListeners.push(record);
7501
+ let alreadyRemoved = false;
7502
+ return () => {
7503
+ if (alreadyRemoved) {
7504
+ return;
7505
+ }
7506
+ alreadyRemoved = true;
7507
+ this.removeListener(record);
7508
+ };
7509
+ }
7510
+ /**
7511
+ * Remove a single public subscription and its bus registration
7512
+ */
7513
+ removeListener(record) {
7514
+ const index = this.publicListeners.indexOf(record);
7515
+ if (index === -1) {
7516
+ return;
7517
+ }
7518
+ this.publicListeners.splice(index, 1);
7519
+ // After destroy() the bus has already been cleared; unsubscribing again
7520
+ // would only log a spurious "non-existent subscription" warning.
7521
+ if (!this.destroyed) {
7522
+ this.eventBus.unsubscribe(record.subscription);
7523
+ }
7524
+ }
7286
7525
  /**
7287
7526
  * Handle initialization errors
7288
7527
  */
7289
7528
  handleInitializationError(error) {
7290
- console.error('SankeyVisualization: Initialization failed:', error);
7529
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
7530
+ console.error('SankeyVisualization: Initialization failed:', normalizedError);
7291
7531
  this.eventBus.emit({
7292
7532
  type: 'system.error',
7293
7533
  timestamp: Date.now(),
7294
7534
  source: 'SankeyVisualization',
7295
7535
  data: {
7296
- error: error instanceof Error ? error : new Error(String(error)),
7536
+ error: normalizedError,
7297
7537
  context: 'initialization',
7298
7538
  recoverable: false
7299
7539
  },
7300
7540
  });
7301
- // Clean up any partially initialized state
7541
+ // Settle whenReady() with the real cause BEFORE destroy(), which would
7542
+ // otherwise reject first with a generic "destroyed" error and lose it.
7543
+ this.rejectReady(normalizedError);
7544
+ // Clean up any partially initialized state.
7545
+ // NOTE: the emit above is already in flight and still delivers. emit()
7546
+ // captures its handler Set synchronously and clear() empties the Map
7547
+ // rather than the captured Sets, so 'system.error' handlers still run.
7302
7548
  this.destroy();
7303
7549
  throw error;
7304
7550
  }
@@ -7402,6 +7648,69 @@ class Sankey {
7402
7648
  isInitialized() {
7403
7649
  return this.initialized;
7404
7650
  }
7651
+ // ==================== PUBLIC EVENT API ====================
7652
+ /**
7653
+ * Subscribe to a visualization event
7654
+ *
7655
+ * Handlers run asynchronously, one microtask after the event is produced,
7656
+ * and are error-isolated: a throwing handler cannot break the visualization
7657
+ * or prevent other handlers from running.
7658
+ *
7659
+ * LIFECYCLE TIMING: `system.ready` and `system.error` are produced during the
7660
+ * asynchronous initialization the constructor starts. Subscribing in the same
7661
+ * synchronous tick as `new Sankey(...)` is soon enough; subscribing later (for
7662
+ * example after `await nextTick()`) is not. For those, use the `events`
7663
+ * constructor option or {@link whenReady}.
7664
+ *
7665
+ * Registering the same function twice registers it twice and it is called
7666
+ * twice; each call returns its own unsubscribe.
7667
+ *
7668
+ * @returns an unsubscribe function, safe to call more than once
7669
+ */
7670
+ on(type, handler) {
7671
+ const listener = handler;
7672
+ return this.addListener(type, listener, listener);
7673
+ }
7674
+ /**
7675
+ * Subscribe until the first delivery, then unsubscribe automatically
7676
+ *
7677
+ * Cancellable either with the returned function or with `off(type, handler)`.
7678
+ */
7679
+ once(type, handler) {
7680
+ let unsubscribe = () => {
7681
+ };
7682
+ const invoke = (event) => {
7683
+ // Remove BEFORE invoking so a throwing handler cannot fire twice.
7684
+ unsubscribe();
7685
+ return handler(event);
7686
+ };
7687
+ // `handler` is recorded as the identity so that off(type, handler)
7688
+ // cancels a pending once() even though the bus holds `invoke`.
7689
+ unsubscribe = this.addListener(type, handler, invoke);
7690
+ return unsubscribe;
7691
+ }
7692
+ /**
7693
+ * Remove every registration of `handler` for `type`, including a pending once()
7694
+ *
7695
+ * Removes all matching registrations rather than one, so teardown code
7696
+ * reliably stops delivery. No-op if the handler was never registered.
7697
+ */
7698
+ off(type, handler) {
7699
+ // Snapshot first: removeListener() mutates this.publicListeners.
7700
+ this.publicListeners
7701
+ .filter(record => record.type === type && record.identity === handler)
7702
+ .forEach(record => this.removeListener(record));
7703
+ return this;
7704
+ }
7705
+ /**
7706
+ * Resolve when initialization completes, or reject if it failed
7707
+ *
7708
+ * Unlike `on('system.ready', ...)` this is a latch: it resolves even when
7709
+ * called long after the event was emitted. Safe to call any number of times.
7710
+ */
7711
+ whenReady() {
7712
+ return this.readyPromise;
7713
+ }
7405
7714
  /**
7406
7715
  * Get array of available years in dataset
7407
7716
  * @returns Readonly array of years available for visualization
@@ -7459,6 +7768,9 @@ class Sankey {
7459
7768
  // Clean up event subscriptions
7460
7769
  this.subscriptions.forEach(sub => this.eventBus.unsubscribe(sub));
7461
7770
  this.subscriptions = [];
7771
+ // Release consumer closures. eventBus.clear() below drops the underlying
7772
+ // handlers; this drops our bookkeeping references to them.
7773
+ this.publicListeners = [];
7462
7774
  // Clean up event bus
7463
7775
  this.eventBus.clear();
7464
7776
  // Clean up DOM
@@ -7479,6 +7791,11 @@ class Sankey {
7479
7791
  this.services = {};
7480
7792
  this.destroyed = true;
7481
7793
  this.initialized = false;
7794
+ // Settle whenReady() so callers awaiting an instance that never came up
7795
+ // are not left hanging. No-op once the promise has already settled, so
7796
+ // this is harmless on the happy path. The constructor's no-op catch
7797
+ // prevents an unhandled rejection here.
7798
+ this.rejectReady(new SankeyError('SankeyVisualization: destroyed before initialization completed'));
7482
7799
  // Resource cleanup completed successfully
7483
7800
  }
7484
7801
  // ==================== VALIDATION METHODS ====================
@@ -7497,6 +7814,7 @@ class Sankey {
7497
7814
  }
7498
7815
  // Validate data structure
7499
7816
  this.validateDataStructure(options.data);
7817
+ validateHeaderOptions(options.header);
7500
7818
  }
7501
7819
  validateDataStructure(data) {
7502
7820
  // Comprehensive data structure validation
@@ -7946,16 +8264,19 @@ class AnimationService {
7946
8264
  this.updateYearDisplay(year);
7947
8265
  // EVENT SYSTEM INTEGRATION: Notify other services of year change
7948
8266
  // Enables coordinated updates across the entire visualization system
8267
+ // Annotated against the public payload type so that any drift between
8268
+ // what is emitted and what SankeyEventMap advertises fails type-check.
8269
+ const yearChangedData = {
8270
+ year, // New target year
8271
+ previousYear, // Previous year for transition context
8272
+ yearIndex, // Array index for efficient data access
8273
+ isAnimating: this.state.isAnimating // Animation state for context
8274
+ };
7949
8275
  this.eventBus.emit({
7950
8276
  type: 'year.changed',
7951
8277
  timestamp: Date.now(),
7952
8278
  source: 'AnimationControlService',
7953
- data: {
7954
- year, // New target year
7955
- previousYear, // Previous year for transition context
7956
- yearIndex, // Array index for efficient data access
7957
- isAnimating: this.state.isAnimating // Animation state for context
7958
- },
8279
+ data: yearChangedData,
7959
8280
  });
7960
8281
  }
7961
8282
  /**
@@ -8225,15 +8546,16 @@ class AnimationService {
8225
8546
  }, this.state.speed); // Configurable timing (50-1000ms typically)
8226
8547
  // EVENT SYSTEM INTEGRATION: Broadcast animation start to other services
8227
8548
  // Enables coordinated behavior across visualization components during playback
8549
+ const startedData = {
8550
+ isPlaying: true,
8551
+ currentYear: this.getCurrentYear(), // Starting year for context
8552
+ speed: this.state.speed // Playback speed for coordination
8553
+ };
8228
8554
  this.eventBus.emit({
8229
8555
  type: 'animation.started',
8230
8556
  timestamp: Date.now(),
8231
8557
  source: 'AnimationControlService',
8232
- data: {
8233
- isPlaying: true,
8234
- currentYear: this.getCurrentYear(), // Starting year for context
8235
- speed: this.state.speed // Playback speed for coordination
8236
- },
8558
+ data: startedData,
8237
8559
  });
8238
8560
  }
8239
8561
  /**
@@ -8275,15 +8597,16 @@ class AnimationService {
8275
8597
  }
8276
8598
  // EVENT SYSTEM INTEGRATION: Broadcast animation stop to other services
8277
8599
  // Enables coordinated pause behavior across visualization components
8600
+ const stoppedData = {
8601
+ isPlaying: false,
8602
+ currentYear: this.getCurrentYear(), // Current position preserved
8603
+ speed: this.state.speed // Speed settings maintained
8604
+ };
8278
8605
  this.eventBus.emit({
8279
8606
  type: 'animation.stopped',
8280
8607
  timestamp: Date.now(),
8281
8608
  source: 'AnimationControlService',
8282
- data: {
8283
- isPlaying: false,
8284
- currentYear: this.getCurrentYear(), // Current position preserved
8285
- speed: this.state.speed // Speed settings maintained
8286
- }
8609
+ data: stoppedData
8287
8610
  });
8288
8611
  }
8289
8612
  /**
@@ -8318,13 +8641,14 @@ class AnimationService {
8318
8641
  }, 100);
8319
8642
  }
8320
8643
  // Emit speed changed event
8644
+ const speedChangedData = {
8645
+ speed
8646
+ };
8321
8647
  this.eventBus.emit({
8322
8648
  type: 'speed.changed',
8323
8649
  timestamp: Date.now(),
8324
8650
  source: 'AnimationControlService',
8325
- data: {
8326
- speed
8327
- }
8651
+ data: speedChangedData
8328
8652
  });
8329
8653
  // Animation speed updated for timeline playback
8330
8654
  }
@@ -8729,16 +9053,17 @@ class InteractionService {
8729
9053
  // Emit keyboard navigation event - Event-Driven Architecture Integration
8730
9054
  // Enables other services to react to keyboard interactions
8731
9055
  // Provides rich event context (key + modifiers) for advanced interactions
9056
+ const keypressData = {
9057
+ key, // Primary key pressed (normalized to lowercase)
9058
+ ctrlKey: event.ctrlKey, // Enables Ctrl+key shortcuts
9059
+ shiftKey: event.shiftKey, // Enables Shift+key shortcuts
9060
+ altKey: event.altKey // Enables Alt+key shortcuts (power user features)
9061
+ };
8732
9062
  this.eventBus.emit({
8733
9063
  type: 'interaction.keypress',
8734
9064
  timestamp: Date.now(),
8735
9065
  source: 'InteractionService',
8736
- data: {
8737
- key, // Primary key pressed (normalized to lowercase)
8738
- ctrlKey: event.ctrlKey, // Enables Ctrl+key shortcuts
8739
- shiftKey: event.shiftKey, // Enables Shift+key shortcuts
8740
- altKey: event.altKey // Enables Alt+key shortcuts (power user features)
8741
- }
9066
+ data: keypressData
8742
9067
  });
8743
9068
  // Call custom handler if provided - Extensibility Pattern
8744
9069
  // Allows external code to extend keyboard navigation behavior
@@ -8786,14 +9111,15 @@ class InteractionService {
8786
9111
  // Emit slider interaction event - Event-Driven Architecture
8787
9112
  // Enables other services to react to timeline position changes
8788
9113
  // Provides structured event data for logging and analytics
9114
+ const sliderData = {
9115
+ year, // Selected year value (numeric)
9116
+ value: year // Duplicate for backwards compatibility
9117
+ };
8789
9118
  this.eventBus.emit({
8790
9119
  type: 'interaction.slider',
8791
9120
  timestamp: Date.now(),
8792
9121
  source: 'InteractionService',
8793
- data: {
8794
- year, // Selected year value (numeric)
8795
- value: year // Duplicate for backwards compatibility
8796
- }
9122
+ data: sliderData
8797
9123
  });
8798
9124
  // Call custom handler if provided - Extensibility Pattern
8799
9125
  // Supports application-specific slider interaction behavior
@@ -8849,14 +9175,15 @@ class InteractionService {
8849
9175
  // Emit button interaction event - Event-Driven Architecture
8850
9176
  // Enables other services to react to animation state changes
8851
9177
  // Note: Action reflects the RESULT of the button press, not the current state
9178
+ const playButtonData = {
9179
+ buttonId: 'evs-play-button',
9180
+ action: this.animationControlService.isPlaying() ? 'play' : 'pause'
9181
+ };
8852
9182
  this.eventBus.emit({
8853
9183
  type: 'interaction.button',
8854
9184
  timestamp: Date.now(),
8855
9185
  source: 'InteractionService',
8856
- data: {
8857
- buttonId: 'evs-play-button',
8858
- action: this.animationControlService.isPlaying() ? 'play' : 'pause'
8859
- }
9186
+ data: playButtonData
8860
9187
  });
8861
9188
  };
8862
9189
  this.addEventListener(playButton, 'click', playButtonHandler);
@@ -8873,15 +9200,16 @@ class InteractionService {
8873
9200
  this.animationControlService.setSpeed(speed);
8874
9201
  // Emit speed change event - Event-Driven Architecture
8875
9202
  // Enables UI updates (active button state, speed indicator)
9203
+ const speedButtonData = {
9204
+ buttonId: target.id,
9205
+ action: 'speed-change',
9206
+ speed // New animation speed in milliseconds
9207
+ };
8876
9208
  this.eventBus.emit({
8877
9209
  type: 'interaction.button',
8878
9210
  timestamp: Date.now(),
8879
9211
  source: 'InteractionService',
8880
- data: {
8881
- buttonId: target.id,
8882
- action: 'speed-change',
8883
- speed // New animation speed in milliseconds
8884
- }
9212
+ data: speedButtonData
8885
9213
  });
8886
9214
  };
8887
9215
  this.addEventListener(button, 'click', speedButtonHandler);
@@ -8992,16 +9320,17 @@ class InteractionService {
8992
9320
  });
8993
9321
  // Emit hover event - Event-Driven Architecture
8994
9322
  // Provides rich context for tooltip display, analytics, and custom behavior
9323
+ const hoverData = {
9324
+ elementType: element.classList.contains('evs-flow') ? 'flow' : 'box', // Element classification
9325
+ fuel: element.getAttribute('data-fuel'), // Energy source identification
9326
+ sector: element.getAttribute('data-sector'), // Consumption sector identification
9327
+ mousePosition: { x: event.clientX, y: event.clientY } // Coordinates for tooltip positioning
9328
+ };
8995
9329
  this.eventBus.emit({
8996
9330
  type: 'interaction.hover',
8997
9331
  timestamp: Date.now(),
8998
9332
  source: 'InteractionService',
8999
- data: {
9000
- elementType: element.classList.contains('evs-flow') ? 'flow' : 'box', // Element classification
9001
- fuel: element.getAttribute('data-fuel'), // Energy source identification
9002
- sector: element.getAttribute('data-sector'), // Consumption sector identification
9003
- mousePosition: { x: event.clientX, y: event.clientY } // Coordinates for tooltip positioning
9004
- }
9333
+ data: hoverData
9005
9334
  });
9006
9335
  // Call custom handler if provided - Extensibility Pattern
9007
9336
  // Supports application-specific hover behavior
@@ -9043,16 +9372,17 @@ class InteractionService {
9043
9372
  // element.classList.add('selected');
9044
9373
  // Emit click event - Event-Driven Architecture
9045
9374
  // Provides comprehensive click context for analytics, tooltips, and custom behavior
9375
+ const clickData = {
9376
+ elementType: element.classList.contains('evs-flow') ? 'flow' : 'box', // Element classification
9377
+ fuel: element.getAttribute('data-fuel'), // Energy source identification
9378
+ sector: element.getAttribute('data-sector'), // Consumption sector identification
9379
+ mousePosition: { x: event.clientX, y: event.clientY } // Click coordinates for UI positioning
9380
+ };
9046
9381
  this.eventBus.emit({
9047
9382
  type: 'interaction.click',
9048
9383
  timestamp: Date.now(),
9049
9384
  source: 'InteractionService',
9050
- data: {
9051
- elementType: element.classList.contains('evs-flow') ? 'flow' : 'box', // Element classification
9052
- fuel: element.getAttribute('data-fuel'), // Energy source identification
9053
- sector: element.getAttribute('data-sector'), // Consumption sector identification
9054
- mousePosition: { x: event.clientX, y: event.clientY } // Click coordinates for UI positioning
9055
- }
9385
+ data: clickData
9056
9386
  });
9057
9387
  // Call custom handler if provided - Extensibility Pattern
9058
9388
  // Supports application-specific click behavior