import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; import { PlotlyRuntime } from './plotly-runtime'; // One serialized queue owns the host. A completed stale operation cannot expose // its graph or overwrite a newer react operation. Resize uses the same queue. export class PlotlyController { private desired?: PlotlyFigure; private version = 0; private rendered = -1; private busy = false; private destroyed = false; private resizePending = false; private plotly?: PlotlyRuntime; private frameCount = 0; constructor(private host: HTMLElement, private load: () => Promise, private state: (state: 'loading' | 'ready' | 'error') => void) {} setFigure(figure: PlotlyFigure) { if (this.destroyed) return; this.desired = figure; this.version++; this.host.style.visibility = 'hidden'; this.state('loading'); void this.drain(); } resize() { if (this.destroyed || this.rendered < 0) return; this.resizePending = true; void this.drain(); } destroy() { this.destroyed = true; this.host.style.visibility = 'hidden'; this.plotly?.purge(this.host); } private async drain() { if (this.busy || this.destroyed) return; this.busy = true; try { this.plotly ??= await this.load(); while (!this.destroyed && (this.rendered !== this.version || this.resizePending)) { const version = this.version; try { if (this.rendered !== version && this.desired) { // Plotly may mutate inputs; clone the complete JSON without changing values. const figure = structuredClone(this.desired); if (this.frameCount) await this.plotly.deleteFrames(this.host, Array.from({ length: this.frameCount }, (_, i) => i)); this.frameCount = 0; if (this.destroyed) break; await this.plotly.react(this.host, figure.data, figure.layout, { ...figure.config, responsive: false, displaylogo: false, showSendToCloud: false, modeBarButtonsToRemove: ['sendChartToCloud'], }); if (this.destroyed) break; if (version !== this.version) continue; if (figure.frames?.length) { await this.plotly.addFrames(this.host, figure.frames); this.frameCount = figure.frames.length; } if (this.destroyed) break; if (version !== this.version) continue; this.rendered = version; this.host.style.visibility = 'visible'; this.state('ready'); } else { this.resizePending = false; await this.plotly.Plots.resize(this.host); } } catch { if (this.destroyed) break; if (version !== this.version) continue; this.rendered = version; this.resizePending = false; this.host.style.visibility = 'hidden'; this.state('error'); } } } catch { if (!this.destroyed) this.state('error'); } finally { this.busy = false; // A pending react can recreate internal resources after the first purge. if (this.destroyed) this.plotly?.purge(this.host); } } }