feat(eu7): incorporar transiciones animadas en dona y barras
This commit is contained in:
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user