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