Files
WebApp/src/app/shared/plotly/plotly-controller.ts
T
2026-10-28 09:45:00 -06:00

203 lines
10 KiB
TypeScript

import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
import { PlotlyRuntime } from './plotly-runtime';
interface EventHost extends HTMLElement {
on?: (name: string, listener: (event: unknown) => void) => void;
removeListener?: (name: string, listener: (event: unknown) => void) => void;
}
export const TRANSITION_MS = 450;
export interface PlotlyControllerOptions {
// Evaluated per update: animate only an update of an already visible figure.
animate?: () => boolean;
// Resolves on the next animation frame with its timestamp (injectable for tests).
nextFrame?: () => Promise<number>;
}
const nextAnimationFrame = () => new Promise<number>(resolve => requestAnimationFrame(resolve));
// Plotly's 'cubic-in-out', reproduced for the interpolated pie frames.
export function cubicInOut(t: number): number {
return t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
}
const RGBA = /^rgba\((\d+),(\d+),(\d+),([\d.]+)\)$/;
function mixColor(from: unknown, to: unknown, t: number): unknown {
const a = typeof from === 'string' ? RGBA.exec(from.replace(/\s/g, '')) : null;
const b = typeof to === 'string' ? RGBA.exec(to.replace(/\s/g, '')) : null;
if (!a || !b) return to;
const v = [1, 2, 3, 4].map(i => Number(a[i]) + (Number(b[i]) - Number(a[i])) * t);
return `rgba(${v.slice(0, 3).map(Math.round).join(',')},${+v[3].toFixed(3)})`;
}
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(n => typeof n === 'number' && Number.isFinite(n));
/** Pies cannot use layout.transition: both figures must have the same pies and value shapes. */
export function piesInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean {
return to.data.length > 0 && from.data.length === to.data.length && to.data.every((trace, i) => {
const old = from.data[i];
return trace['type'] === 'pie' && old['type'] === 'pie' && trace['name'] === old['name']
&& JSON.stringify(trace['labels']) === JSON.stringify(old['labels'])
&& numbers(trace['values']) && numbers(old['values']) && trace['values'].length === old['values'].length;
});
}
/** One intermediate pie frame: values and rgba colors move, texts wait for the final frame. */
export function pieFrame(from: PlotlyFigure, to: PlotlyFigure, t: number): PlotlyFigure {
const moving = to.data.some((trace, i) => (trace['values'] as number[])
.some((v, j) => v !== (from.data[i]['values'] as number[])[j]));
return { ...to, data: to.data.map((trace, i) => {
const a = from.data[i]['values'] as number[], b = trace['values'] as number[];
const oldMarker = from.data[i]['marker'] as Record<string, unknown> | undefined;
const marker = trace['marker'] as Record<string, unknown> | undefined;
const oldColors = oldMarker?.['colors'], colors = marker?.['colors'];
const sameValues = a.every((v, j) => v === b[j]);
const mixColors = !!marker && Array.isArray(colors) && Array.isArray(oldColors) && oldColors.length === colors.length
&& colors.some((c, j) => c !== oldColors[j]);
if (sameValues && !mixColors && !moving) return trace;
// Geometry is illustrative until the exact target render. Hide all clinical
// readouts (including the centre) and never attach counts to moving slices.
return { ...trace, ...(sameValues ? {} : { values: b.map((v, j) => a[j] + (v - a[j]) * t) }),
...(moving ? { text: b.map(() => ''), textinfo: 'none', texttemplate: '',
hoverinfo: 'skip', hovertemplate: null, hovertext: [], customdata: [] } : {}),
...(mixColors ? { marker: { ...marker, colors: (colors as unknown[]).map((c, j) => mixColor((oldColors as unknown[])[j], c, t)) } } : {}) };
}) };
}
const transitionable = (figure: PlotlyFigure) => figure.data.length > 0
&& figure.data.every(trace => ['bar', 'scatter'].includes(String(trace['type'] ?? 'scatter')));
// A changed catalogue, scenario axis or availability mask is an exact redraw.
// In particular, never tween a published value into an unavailable/suppressed one.
function cartesianInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean {
return transitionable(from) && transitionable(to) && from.data.length === to.data.length
&& to.data.every((trace, i) => {
const old = from.data[i];
if (trace['type'] !== old['type'] || trace['uid'] !== old['uid']) return false;
return ['x', 'y'].every(axis => {
const a = old[axis], b = trace[axis];
if (!Array.isArray(a) || !Array.isArray(b)) return a === b;
return a.length === b.length && b.every((v, j) =>
typeof v === 'number' && typeof a[j] === 'number' ? true : v === a[j]);
});
});
}
// 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;
private listenerAttached = false;
// Last figure drawn on the host (target or intermediate frame); origin of the next transition.
private shown?: PlotlyFigure;
private animating = false;
private readonly handleClick = (event: unknown) => {
if (!this.destroyed && !this.busy && this.rendered === this.version) this.click?.(event);
};
constructor(private host: HTMLElement, private load: () => Promise<PlotlyRuntime>,
private state: (state: 'loading' | 'ready' | 'error') => void,
private click?: (event: unknown) => void,
private options: PlotlyControllerOptions = {}) {}
private get config() { return { responsive: false, displaylogo: false, showSendToCloud: false, modeBarButtonsToRemove: ['sendChartToCloud'] }; }
setFigure(figure: PlotlyFigure) {
if (this.destroyed) return;
this.desired = figure;
this.version++;
// A visible figure that will animate stays on screen; hiding it is the flash
// between selections. Every other update keeps the original hidden render.
this.animating = this.rendered >= 0 && this.host.style.visibility === 'visible' && !!this.shown && !!this.options.animate?.()
&& !this.shown.frames?.length && !figure.frames?.length
&& (piesInterpolable(this.shown, figure) || cartesianInterpolable(this.shown, figure));
if (this.animating) return void this.drain();
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;
if (this.listenerAttached) (this.host as EventHost).removeListener?.('plotly_click', this.handleClick);
this.listenerAttached = false;
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 target = structuredClone(this.desired);
const figure = structuredClone(target);
if (this.frameCount) await this.plotly.deleteFrames(this.host, Array.from({ length: this.frameCount }, (_, i) => i));
this.frameCount = 0;
if (this.destroyed) break;
const animate = this.animating && !!this.options.animate?.() && !!this.shown
&& !this.shown.frames?.length && !figure.frames?.length;
const config = { ...figure.config, ...this.config };
if (animate && piesInterpolable(this.shown!, figure)) {
const from = this.shown!, nextFrame = this.options.nextFrame ?? nextAnimationFrame;
const start = await nextFrame();
for (;;) {
const t = Math.min(1, ((await nextFrame()) - start) / TRANSITION_MS);
if (this.destroyed || version !== this.version || !this.options.animate?.() || t >= 1) break;
const frame = pieFrame(from, figure, cubicInOut(t));
const copy = structuredClone(frame);
await this.plotly.react(this.host, copy.data, copy.layout, config);
this.shown = frame;
}
if (this.destroyed) break;
if (version !== this.version) continue;
}
const layout = animate && this.shown && cartesianInterpolable(this.shown, figure)
&& figure.layout['transition'] === undefined
? { ...figure.layout, transition: { duration: TRANSITION_MS, easing: 'cubic-in-out' } } : figure.layout;
await this.plotly.react(this.host, figure.data, layout, config);
this.shown = target;
if (!this.destroyed && !this.listenerAttached && this.click && (this.host as EventHost).on) {
(this.host as EventHost).on!('plotly_click', this.handleClick);
this.listenerAttached = true;
}
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.shown = undefined;
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);
}
}
}