preliminary release
This commit is contained in:
@@ -26,6 +26,27 @@ describe('PlotlyChart lifecycle', () => {
|
||||
fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(mocks.purge).toHaveBeenCalled();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
it.each([[false, true], [true, false]])('animated respeta prefers-reduced-motion=%s (transición: %s) y es opcional', async (reduce, transition) => {
|
||||
vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: reduce }));
|
||||
const settle = async () => { await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve(); };
|
||||
const fixture = TestBed.createComponent(PlotlyChart);
|
||||
fixture.componentRef.setInput('animated', true);
|
||||
fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [1] }], layout: {} });
|
||||
fixture.detectChanges(); await settle();
|
||||
fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [2] }], layout: {} });
|
||||
fixture.detectChanges(); await settle();
|
||||
expect(mocks.react).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.react.mock.calls[1][2]['transition'] !== undefined).toBe(transition);
|
||||
fixture.destroy(); vi.unstubAllGlobals();
|
||||
});
|
||||
it('sin animated las actualizaciones no llevan transición', async () => {
|
||||
const fixture = TestBed.createComponent(PlotlyChart);
|
||||
fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [1] }], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve();
|
||||
fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [2] }], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve();
|
||||
expect(mocks.react.mock.calls[1][2]['transition']).toBeUndefined(); fixture.destroy();
|
||||
});
|
||||
it('muestra error asíncrono y se recupera con reintento', async () => {
|
||||
mocks.react.mockRejectedValueOnce(new Error('render failed'));
|
||||
const fixture = TestBed.createComponent(PlotlyChart);
|
||||
|
||||
@@ -5,6 +5,10 @@ import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
||||
import { PlotlyController } from './plotly-controller';
|
||||
import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
|
||||
function prefersReducedMotion(): boolean {
|
||||
return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-plotly-chart',
|
||||
imports: [MatButtonModule, MatProgressBarModule],
|
||||
@@ -14,7 +18,7 @@ import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
<div role="alert"><p>No se pudo representar la figura. Puedes reintentar.</p>
|
||||
<button mat-stroked-button (click)="retry()">Reintentar renderizado</button></div>
|
||||
}
|
||||
<div class="plot-viewport" tabindex="0" role="region" [attr.aria-label]="label + ' · Área de figura'"><div #host class="plot" role="img" [attr.aria-label]="label" [attr.aria-hidden]="status() !== 'ready'"></div></div>
|
||||
<div class="plot-viewport" tabindex="0" role="region" [attr.aria-label]="label + ', área de figura'"><div #host class="plot" role="img" [attr.aria-label]="label" [attr.aria-hidden]="status() !== 'ready'"></div></div>
|
||||
@if (showNotes && status() === 'ready' && notes.length) {
|
||||
<section class="notes" aria-label="Notas completas de la figura">
|
||||
<h2>Notas de la figura</h2>
|
||||
@@ -27,6 +31,8 @@ import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
|
||||
@Input() showNotes = true;
|
||||
@Input() label = 'Figura estadística';
|
||||
// Opt-in: updates of the same visible figure move smoothly instead of redrawing.
|
||||
@Input() animated = false;
|
||||
@Input({ required: true }) figure!: PlotlyFigure;
|
||||
@ViewChild('host', { static: true }) host!: ElementRef<HTMLElement>;
|
||||
readonly renderError = output<void>();
|
||||
@@ -57,7 +63,7 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
|
||||
this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => {
|
||||
this.status.set(state);
|
||||
if (state === 'error') this.renderError.emit();
|
||||
}, event => this.plotClick.emit(event));
|
||||
}, event => this.plotClick.emit(event), { animate: () => this.animated && !prefersReducedMotion() });
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
this.observer = new ResizeObserver(this.windowResize);
|
||||
this.observer.observe(this.host.nativeElement);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { syntheticFigures } from '../../features/indicadores/indicadores.synthetic-fixtures';
|
||||
import { vi } from 'vitest';
|
||||
import { PlotlyController } from './plotly-controller';
|
||||
import { cubicInOut, pieFrame, piesInterpolable, PlotlyController, TRANSITION_MS } from './plotly-controller';
|
||||
import { PlotlyRuntime } from './plotly-runtime';
|
||||
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
||||
function deferred() {
|
||||
@@ -151,6 +151,33 @@ describe('PlotlyController con Plotly instalado', () => {
|
||||
runtime = (module.default ?? module) as typeof runtime;
|
||||
} finally { canvas.mockRestore(); }
|
||||
});
|
||||
it('Plotly real acepta las transiciones de barras y los fotogramas de pies y termina en la figura destino', async () => {
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
let clock = 0, controller: PlotlyController | undefined;
|
||||
const ready = () => new Promise<void>((resolve, reject) => { pending = { resolve, reject }; });
|
||||
let pending!: { resolve: () => void; reject: (e: Error) => void };
|
||||
try {
|
||||
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
|
||||
if (state === 'ready') pending?.resolve();
|
||||
if (state === 'error') pending?.reject(new Error('Plotly transition failed'));
|
||||
}, undefined, { animate: () => true, nextFrame: () => Promise.resolve(clock += 150) });
|
||||
const bars = (x: number[]): PlotlyFigure => ({ data: x.map((v, i) => ({ type: 'bar', uid: 'c' + i, orientation: 'h', x: [v], y: ['A'] })), layout: { barmode: 'stack' } });
|
||||
let done = ready(); controller.setFigure(bars([40, 60])); await done;
|
||||
done = ready(); controller.setFigure(bars([0, 60])); await done;
|
||||
expect((host as unknown as { data: { x: number[] }[] }).data.map(t => t.x)).toEqual([[0], [60]]);
|
||||
controller.destroy(); controller = undefined;
|
||||
const pies = (values: number[]): PlotlyFigure => ({ data: [{ type: 'pie', name: 'grupos', values, marker: { colors: ['rgba(1,2,3,1)', 'rgba(4,5,6,1)'] } }], layout: {} });
|
||||
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
|
||||
if (state === 'ready') pending?.resolve();
|
||||
if (state === 'error') pending?.reject(new Error('Plotly pie frames failed'));
|
||||
}, undefined, { animate: () => true, nextFrame: () => Promise.resolve(clock += 150) });
|
||||
done = ready(); controller.setFigure(pies([10, 0])); await done;
|
||||
done = ready(); controller.setFigure(pies([3, 7])); await done;
|
||||
expect((host as unknown as { data: { values: number[] }[] }).data[0].values).toEqual([3, 7]);
|
||||
expect(host.style.visibility).toBe('visible');
|
||||
} finally { controller?.destroy(); host.remove(); }
|
||||
});
|
||||
it('usa propiedades admitidas por el esquema de Plotly 4.1.2', () => {
|
||||
expect(runtime.version).toBe('4.1.2');
|
||||
const config = runtime.PlotSchema.get().config;
|
||||
@@ -212,3 +239,183 @@ describe('PlotlyController con Plotly instalado', () => {
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('PlotlyController transiciones opcionales', () => {
|
||||
const pie = (values: number[], alpha = 1): PlotlyFigure => ({ data: [
|
||||
{ type: 'pie', name: 'centro', values: [1], text: ['Total'] },
|
||||
{ type: 'pie', name: 'grupos', values, text: values.map(String), marker: { colors: values.map(() => `rgba(10,20,30,${alpha})`) } },
|
||||
], layout: { height: 440 } });
|
||||
const bars = (x: number[]): PlotlyFigure => ({ data: x.map((v, i) => ({ type: 'bar', uid: 'c' + i, x: [v], y: ['A'] })), layout: {} });
|
||||
let host: HTMLElement, plotly: PlotlyRuntime, clock: number, animate: boolean;
|
||||
let state: ReturnType<typeof vi.fn<(state: 'loading' | 'ready' | 'error') => void>>;
|
||||
const nextFrame = () => Promise.resolve(clock += 100);
|
||||
beforeEach(() => {
|
||||
host = document.createElement('div'); clock = 0; animate = true;
|
||||
plotly = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) },
|
||||
addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined) };
|
||||
state = vi.fn();
|
||||
});
|
||||
const controller = () => new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, { animate: () => animate, nextFrame });
|
||||
async function settleLong() { for (let i = 0; i < 80; i++) await Promise.resolve(); }
|
||||
|
||||
it('easing cubic-in-out y fotogramas intermedios de pies: valores y alfa se mueven, textos esperan', () => {
|
||||
expect([0, .5, 1].map(cubicInOut)).toEqual([0, .5, 1]);
|
||||
expect(cubicInOut(.25)).toBeLessThan(.25); expect(cubicInOut(.75)).toBeGreaterThan(.75);
|
||||
const from = pie([10, 0], .3), to = pie([4, 6], 1);
|
||||
expect(piesInterpolable(from, to)).toBe(true);
|
||||
expect(piesInterpolable(from, bars([1]))).toBe(false);
|
||||
expect(piesInterpolable(from, { ...to, data: [to.data[0]] })).toBe(false);
|
||||
const half = pieFrame(from, to, .5);
|
||||
expect(half.data[0]['values']).toEqual([1]);
|
||||
expect(half.data[0]['text']).toEqual(['']);
|
||||
expect(half.data[1]['values']).toEqual([7, 3]); expect(half.data[1]['text']).toEqual(['', '']);
|
||||
expect((half.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']);
|
||||
expect(to.data[1]['values']).toEqual([4, 6]);
|
||||
for (const trace of half.data) {
|
||||
expect(trace['textinfo']).toBe('none'); expect(trace['hoverinfo']).toBe('skip');
|
||||
expect(trace['hovertemplate']).toBeNull(); expect(trace['customdata']).toEqual([]);
|
||||
}
|
||||
// Same values, only dimming (a selection that keeps the totals): colors move, texts stay.
|
||||
const dimmed = pieFrame(pie([4, 6], .3), pie([4, 6], 1), .5);
|
||||
expect(dimmed.data[1]['values']).toEqual([4, 6]); expect(dimmed.data[1]['text']).toEqual(['4', '6']);
|
||||
expect((dimmed.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']);
|
||||
expect(pieFrame(pie([4, 6]), pie([4, 6]), .5).data[1]).toEqual(pie([4, 6]).data[1]);
|
||||
});
|
||||
it('la dona interpola en varios react sin ocultar el host ni pasar por carga, y termina en la figura exacta', async () => {
|
||||
const c = controller();
|
||||
c.setFigure(pie([10, 0])); await settleLong();
|
||||
expect(host.style.visibility).toBe('visible'); state.mockClear(); vi.mocked(plotly.react).mockClear();
|
||||
const target = pie([4, 6]);
|
||||
c.setFigure(target);
|
||||
expect(host.style.visibility).toBe('visible'); expect(state).not.toHaveBeenCalledWith('loading');
|
||||
await settleLong();
|
||||
const calls = vi.mocked(plotly.react).mock.calls;
|
||||
// 100 ms per frame over TRANSITION_MS, plus the exact final figure.
|
||||
expect(calls.length).toBe(Math.ceil(TRANSITION_MS / 100));
|
||||
const values = calls.map(call => call[1][1]['values'] as number[]);
|
||||
expect(values[0][0]).toBeLessThan(10); expect(values[0][0]).toBeGreaterThan(4);
|
||||
for (let i = 1; i < values.length - 1; i++) expect(values[i][0]).toBeLessThan(values[i - 1][0]);
|
||||
expect(calls.at(-1)![1]).toEqual(target.data); expect(calls.at(-1)![2]).toEqual(target.layout);
|
||||
expect(state).toHaveBeenLastCalledWith('ready'); expect(host.style.visibility).toBe('visible');
|
||||
});
|
||||
it('las barras usan layout.transition de 450 ms cubic-in-out en un solo react', async () => {
|
||||
const c = controller();
|
||||
c.setFigure(bars([1, 2])); await settleLong();
|
||||
expect(vi.mocked(plotly.react).mock.calls[0][2]['transition']).toBeUndefined();
|
||||
c.setFigure(bars([3, 0])); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(2);
|
||||
expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toEqual({ duration: TRANSITION_MS, easing: 'cubic-in-out' });
|
||||
});
|
||||
it('sin animación (opción desactivada o movimiento reducido) conserva el renderizado oculto original', async () => {
|
||||
animate = false;
|
||||
const c = controller();
|
||||
c.setFigure(pie([10, 0])); await settleLong(); state.mockClear();
|
||||
c.setFigure(pie([4, 6]));
|
||||
expect(host.style.visibility).toBe('hidden'); expect(state).toHaveBeenCalledWith('loading');
|
||||
await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(2);
|
||||
expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toBeUndefined();
|
||||
});
|
||||
it('una selección nueva interrumpe la animación y parte del último fotograma dibujado', async () => {
|
||||
const c = controller();
|
||||
c.setFigure(pie([10, 0])); await settleLong(); vi.mocked(plotly.react).mockClear();
|
||||
c.setFigure(pie([0, 10]));
|
||||
for (let i = 0; i < 6; i++) await Promise.resolve();
|
||||
c.setFigure(pie([10, 0]));
|
||||
await settleLong();
|
||||
const last = vi.mocked(plotly.react).mock.calls.at(-1)!;
|
||||
expect(last[1][1]['values']).toEqual([10, 0]);
|
||||
expect(state).toHaveBeenLastCalledWith('ready');
|
||||
});
|
||||
|
||||
it('no interpola pies con nulos, otra identidad u orden de categorías', () => {
|
||||
const source = pie([10, 0]);
|
||||
const changed = pie([5, 5]); changed.data[1]['values'] = [null, 5];
|
||||
expect(piesInterpolable(source, changed)).toBe(false);
|
||||
changed.data[1]['values'] = [5, 5]; changed.data[1]['name'] = 'otro';
|
||||
expect(piesInterpolable(source, changed)).toBe(false);
|
||||
source.data[1]['labels'] = ['A', 'B'];
|
||||
const reordered = pie([5, 5]); reordered.data[1]['labels'] = ['B', 'A'];
|
||||
expect(piesInterpolable(source, reordered)).toBe(false);
|
||||
});
|
||||
it('ningún cuadro geométrico expone conteos, plantillas, tooltips ni el total destino adelantado', async () => {
|
||||
const source = pie([10, 0]), target = pie([4, 6]);
|
||||
target.data.forEach(trace => Object.assign(trace, { customdata: [[4, 40], [6, 60]],
|
||||
hovertemplate: '%{value} / %{customdata[0]}', hovertext: ['4', '6'], texttemplate: '%{value}' }));
|
||||
const original = structuredClone(target), c = controller();
|
||||
c.setFigure(source); await settleLong(); vi.mocked(plotly.react).mockClear();
|
||||
c.setFigure(target); await settleLong();
|
||||
const calls = vi.mocked(plotly.react).mock.calls;
|
||||
for (const call of calls.slice(0, -1)) for (const trace of call[1]) {
|
||||
expect(trace['hoverinfo']).toBe('skip'); expect(trace['hovertemplate']).toBeNull();
|
||||
expect(trace['customdata']).toEqual([]); expect(trace['hovertext']).toEqual([]);
|
||||
expect(trace['texttemplate']).toBe(''); expect(trace['textinfo']).toBe('none');
|
||||
expect((trace['text'] as string[]).every(text => text === '')).toBe(true);
|
||||
}
|
||||
expect(calls.at(-1)![1]).toEqual(target.data); expect(target).toEqual(original); c.destroy();
|
||||
});
|
||||
it('interrumpe tras un react pendiente y usa el último cuadro completado sin renders concurrentes', async () => {
|
||||
const frames: ((time: number) => void)[] = [];
|
||||
const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined,
|
||||
{ animate: () => true, nextFrame: () => new Promise(resolve => frames.push(resolve)) });
|
||||
const step = async (time: number) => { expect(frames.length).toBeGreaterThan(0); frames.shift()!(time); await settleLong(); };
|
||||
c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); vi.mocked(plotly.react).mockClear();
|
||||
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
|
||||
c.setFigure(pie([0, 10])); await settleLong(); await step(0); await step(150);
|
||||
const drawn = vi.mocked(plotly.react).mock.calls[0][1][1]['values'] as number[];
|
||||
c.setFigure(pie([8, 2])); c.resize(); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(1); expect(plotly.Plots.resize).not.toHaveBeenCalled();
|
||||
pending.resolve(); await settleLong();
|
||||
await step(200); // Discard stale frame; start the latest transition.
|
||||
await step(250); await step(400);
|
||||
const resumed = vi.mocked(plotly.react).mock.calls[1][1][1]['values'] as number[];
|
||||
expect(resumed[0]).toBeCloseTo(drawn[0] + (8 - drawn[0]) * cubicInOut(150 / TRANSITION_MS));
|
||||
await step(700);
|
||||
expect(vi.mocked(plotly.react).mock.calls.at(-1)![1]).toEqual(pie([8, 2]).data);
|
||||
expect(state.mock.calls).toEqual([['ready']]); expect(plotly.Plots.resize).toHaveBeenCalledTimes(1); c.destroy();
|
||||
});
|
||||
it('movimiento reducido durante la dona termina inmediatamente con datos exactos', async () => {
|
||||
const frames: ((time: number) => void)[] = [];
|
||||
const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined,
|
||||
{ animate: () => animate, nextFrame: () => new Promise(resolve => frames.push(resolve)) });
|
||||
c.setFigure(pie([10, 0])); await settleLong(); vi.mocked(plotly.react).mockClear();
|
||||
const target = pie([4, 6]); c.setFigure(target); await settleLong();
|
||||
frames.shift()!(0); await settleLong(); animate = false;
|
||||
frames.shift()!(150); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(1); expect(vi.mocked(plotly.react).mock.calls[0][1]).toEqual(target.data);
|
||||
expect(state).toHaveBeenLastCalledWith('ready'); c.destroy();
|
||||
});
|
||||
it('destruir mientras espera un fotograma no vuelve a dibujar ni a emitir ready', async () => {
|
||||
let frame!: (time: number) => void;
|
||||
const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined,
|
||||
{ animate: () => true, nextFrame: () => new Promise(resolve => frame = resolve) });
|
||||
c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); vi.mocked(plotly.react).mockClear();
|
||||
c.setFigure(pie([0, 10])); await settleLong(); c.destroy(); frame(0); await settleLong(); frame(100); await settleLong();
|
||||
expect(plotly.react).not.toHaveBeenCalled(); expect(state).not.toHaveBeenCalled();
|
||||
expect(host.style.visibility).toBe('hidden');
|
||||
});
|
||||
it.each(['uid', 'escenario', 'nulo', 'trazas'])('barras con cambio de %s se redibujan exactamente sin interpolación', async kind => {
|
||||
const c = controller(), target = bars([3, 4]);
|
||||
c.setFigure(bars([1, 2])); await settleLong();
|
||||
if (kind === 'uid') target.data[0]['uid'] = 'otro';
|
||||
if (kind === 'escenario') target.data[0]['y'] = ['Otro'];
|
||||
if (kind === 'nulo') target.data[0]['x'] = [null];
|
||||
if (kind === 'trazas') target.data.pop();
|
||||
state.mockClear(); c.setFigure(target);
|
||||
expect(host.style.visibility).toBe('hidden'); expect(state).toHaveBeenCalledWith('loading');
|
||||
await settleLong();
|
||||
expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toBeUndefined();
|
||||
expect(vi.mocked(plotly.react).mock.calls[1][1]).toEqual(target.data); c.destroy();
|
||||
});
|
||||
it('barras rápidas se serializan, descartan destinos intermedios y nunca anuncian ready obsoleto', async () => {
|
||||
const c = controller(); c.setFigure(bars([1, 2])); await settleLong(); state.mockClear();
|
||||
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
|
||||
c.setFigure(bars([0, 2])); await settleLong();
|
||||
c.setFigure(bars([3, 0])); c.setFigure(bars([4, 5])); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(2); expect(state).not.toHaveBeenCalled();
|
||||
pending.resolve(); await settleLong();
|
||||
expect(plotly.react).toHaveBeenCalledTimes(3);
|
||||
expect(vi.mocked(plotly.react).mock.calls.at(-1)![1]).toEqual(bars([4, 5]).data);
|
||||
expect(state.mock.calls).toEqual([['ready']]); expect(host.style.visibility).toBe('visible'); c.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,75 @@ interface EventHost extends HTMLElement {
|
||||
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 {
|
||||
@@ -18,17 +87,28 @@ export class PlotlyController {
|
||||
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 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();
|
||||
@@ -55,15 +135,33 @@ export class PlotlyController {
|
||||
try {
|
||||
if (this.rendered !== version && this.desired) {
|
||||
// Plotly may mutate inputs; clone the complete JSON without changing values.
|
||||
const figure = structuredClone(this.desired);
|
||||
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;
|
||||
await this.plotly.react(this.host, figure.data, figure.layout, {
|
||||
...figure.config, responsive: false, displaylogo: false,
|
||||
showSendToCloud: false,
|
||||
modeBarButtonsToRemove: ['sendChartToCloud'],
|
||||
});
|
||||
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;
|
||||
@@ -88,6 +186,7 @@ export class PlotlyController {
|
||||
if (version !== this.version) continue;
|
||||
this.rendered = version;
|
||||
this.resizePending = false;
|
||||
this.shown = undefined;
|
||||
this.host.style.visibility = 'hidden';
|
||||
this.state('error');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user