422 lines
26 KiB
TypeScript
422 lines
26 KiB
TypeScript
import { syntheticFigures } from '../../features/indicadores/indicadores.synthetic-fixtures';
|
|
import { vi } from 'vitest';
|
|
import { cubicInOut, pieFrame, piesInterpolable, PlotlyController, TRANSITION_MS } from './plotly-controller';
|
|
import { PlotlyRuntime } from './plotly-runtime';
|
|
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
|
function deferred() {
|
|
let resolve!: (value?: unknown) => void;
|
|
let reject!: (reason?: unknown) => void;
|
|
const promise = new Promise<unknown>((yes, no) => { resolve = yes; reject = no; });
|
|
return { promise, resolve, reject };
|
|
}
|
|
async function settle() { for (let i = 0; i < 12; i++) await Promise.resolve(); }
|
|
const fig = (value: number): PlotlyFigure => ({ data: [{ type: 'scatter', y: [value, null] }], layout: { annotations: [{ text: 'No usar para decisiones clínicas' }] } });
|
|
describe('PlotlyController async', () => {
|
|
let host: HTMLElement;
|
|
let plotly: PlotlyRuntime;
|
|
let state: ReturnType<typeof vi.fn<(state: 'loading' | 'ready' | 'error') => void>>;
|
|
let controller: PlotlyController;
|
|
beforeEach(() => {
|
|
host = document.createElement('div');
|
|
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();
|
|
controller = new PlotlyController(host, () => Promise.resolve(plotly), state);
|
|
});
|
|
it('conserva valores y anotaciones, aislando mutaciones de Plotly', async () => {
|
|
const figure = fig(0);
|
|
vi.mocked(plotly.react).mockImplementation(async (_host, data) => { data[0]['y'] = [123]; });
|
|
controller.setFigure(figure); await settle();
|
|
expect(figure.data[0]['y']).toEqual([0, null]);
|
|
expect(plotly.react).toHaveBeenCalledWith(host, expect.any(Array), figure.layout, expect.objectContaining({ displaylogo: false }));
|
|
expect(host.style.visibility).toBe('visible');
|
|
expect(state).toHaveBeenLastCalledWith('ready');
|
|
});
|
|
it('suscribe click una vez, ignora clicks durante react y retira listener al destruir', async () => {
|
|
let listener!: (event: unknown) => void;
|
|
const on = vi.fn((_name, callback) => { listener = callback; });
|
|
const removeListener = vi.fn(), click = vi.fn();
|
|
Object.assign(host, { on, removeListener });
|
|
controller = new PlotlyController(host, () => Promise.resolve(plotly), state, click);
|
|
controller.setFigure(fig(1)); await settle();
|
|
listener({ points: [1] }); expect(click).toHaveBeenCalledTimes(1);
|
|
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
|
|
controller.setFigure(fig(2)); await settle(); listener({ points: [2] });
|
|
expect(click).toHaveBeenCalledTimes(1);
|
|
pending.resolve(); await settle(); expect(on).toHaveBeenCalledTimes(1);
|
|
listener({ points: [3] }); expect(click).toHaveBeenCalledTimes(2);
|
|
controller.destroy(); expect(removeListener).toHaveBeenCalledWith('plotly_click', listener);
|
|
listener({ points: [4] }); expect(click).toHaveBeenCalledTimes(2);
|
|
});
|
|
it('desactiva el envío externo sin alterar el JSON ni las opciones locales recibidas', async () => {
|
|
const figure: PlotlyFigure = {
|
|
...fig(1),
|
|
config: { showSendToCloud: true, displaylogo: true, scrollZoom: true, doubleClick: 'reset+autosize' },
|
|
frames: [{ name: 'uno', data: [{ y: [2, null] }] }],
|
|
};
|
|
const original = JSON.stringify(figure);
|
|
controller.setFigure(figure); await settle();
|
|
expect(plotly.react).toHaveBeenCalledWith(host, figure.data, figure.layout, {
|
|
responsive: false, displaylogo: false, showSendToCloud: false,
|
|
modeBarButtonsToRemove: ['sendChartToCloud'], scrollZoom: true, doubleClick: 'reset+autosize',
|
|
});
|
|
expect(plotly.addFrames).toHaveBeenCalledWith(host, figure.frames);
|
|
expect(JSON.stringify(figure)).toBe(original);
|
|
});
|
|
it('elige sólo la figura reciente si la importación sigue pendiente', async () => {
|
|
const load = deferred();
|
|
controller = new PlotlyController(host, () => load.promise as Promise<PlotlyRuntime>, state);
|
|
controller.setFigure(fig(1)); controller.setFigure(fig(2));
|
|
load.resolve(plotly); await settle();
|
|
expect(plotly.react).toHaveBeenCalledTimes(1);
|
|
expect(vi.mocked(plotly.react).mock.calls[0][1][0]['y']).toEqual([2, null]);
|
|
});
|
|
it('serializa react y oculta completados obsoletos', async () => {
|
|
const old = deferred(); const latest = deferred();
|
|
vi.mocked(plotly.react).mockReturnValueOnce(old.promise).mockReturnValueOnce(latest.promise);
|
|
controller.setFigure(fig(1)); await settle();
|
|
controller.setFigure(fig(2));
|
|
expect(plotly.react).toHaveBeenCalledTimes(1);
|
|
old.resolve(); await settle();
|
|
expect(plotly.react).toHaveBeenCalledTimes(2);
|
|
expect(host.style.visibility).toBe('hidden');
|
|
expect(state).not.toHaveBeenCalledWith('ready');
|
|
latest.resolve(); await settle();
|
|
expect(host.style.visibility).toBe('visible');
|
|
expect(state).toHaveBeenLastCalledWith('ready');
|
|
});
|
|
it('ignora rechazo antiguo y representa la siguiente figura', async () => {
|
|
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
|
|
controller.setFigure(fig(1)); await settle(); controller.setFigure(fig(2));
|
|
pending.reject(new Error('old')); await settle();
|
|
expect(state).not.toHaveBeenCalledWith('error');
|
|
expect(state).toHaveBeenLastCalledWith('ready');
|
|
});
|
|
it('maneja error asíncrono y permite reintentar', async () => {
|
|
vi.mocked(plotly.react).mockRejectedValueOnce(new Error('failed'));
|
|
controller.setFigure(fig(1)); await settle();
|
|
expect(state).toHaveBeenLastCalledWith('error');
|
|
expect(host.style.visibility).toBe('hidden');
|
|
controller.setFigure(fig(1)); await settle();
|
|
expect(state).toHaveBeenLastCalledWith('ready');
|
|
});
|
|
it('maneja importación fallida y recupera el cargador', async () => {
|
|
const load = vi.fn().mockRejectedValueOnce(new Error()).mockResolvedValue(plotly);
|
|
controller = new PlotlyController(host, load, state);
|
|
controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('error');
|
|
controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('ready');
|
|
});
|
|
it('purga al destruir y nuevamente tras terminar react pendiente', async () => {
|
|
const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise);
|
|
controller.setFigure(fig(1)); await settle();
|
|
controller.destroy(); expect(plotly.purge).toHaveBeenCalledTimes(1);
|
|
pending.resolve(); await settle(); expect(plotly.purge).toHaveBeenCalledTimes(2);
|
|
expect(state).not.toHaveBeenCalledWith('ready');
|
|
controller.setFigure(fig(2)); controller.resize(); await settle();
|
|
expect(plotly.react).toHaveBeenCalledTimes(1);
|
|
expect(plotly.Plots.resize).not.toHaveBeenCalled();
|
|
});
|
|
it('no renderiza tras destruir durante la importación', async () => {
|
|
const pending = deferred(); controller = new PlotlyController(host, () => pending.promise as Promise<PlotlyRuntime>, state);
|
|
controller.setFigure(fig(1)); controller.destroy(); pending.resolve(plotly); await settle();
|
|
expect(plotly.react).not.toHaveBeenCalled(); expect(plotly.purge).toHaveBeenCalledWith(host);
|
|
});
|
|
it('serializa resize y el siguiente react', async () => {
|
|
controller.setFigure(fig(1)); await settle();
|
|
const resize = deferred(); vi.mocked(plotly.Plots.resize).mockReturnValueOnce(resize.promise);
|
|
controller.resize(); await settle(); controller.setFigure(fig(2));
|
|
expect(plotly.react).toHaveBeenCalledTimes(1);
|
|
resize.resolve(); await settle(); expect(plotly.react).toHaveBeenCalledTimes(2);
|
|
});
|
|
it('conserva frames y los retira al cambiar figura', async () => {
|
|
controller.setFigure({ ...fig(1), frames: [{ name: 'uno', data: [] }] }); await settle();
|
|
expect(plotly.addFrames).toHaveBeenCalledWith(host, [{ name: 'uno', data: [] }]);
|
|
controller.setFigure(fig(2)); await settle();
|
|
expect(plotly.deleteFrames).toHaveBeenCalledWith(host, [0]);
|
|
});
|
|
});
|
|
|
|
|
|
// Exercise the installed bundle in jsdom: no cloud action is clicked.
|
|
describe('PlotlyController con Plotly instalado', () => {
|
|
let runtime: PlotlyRuntime & {
|
|
version: string;
|
|
PlotSchema: { get(): { config: Record<string, { valType: string }> } };
|
|
};
|
|
beforeAll(async () => {
|
|
// jsdom has no canvas renderer; cartesian SVG only needs this import-time probe.
|
|
const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext')
|
|
.mockReturnValue({ measureText: () => ({ width: 0 }) } as unknown as CanvasRenderingContext2D);
|
|
try {
|
|
const module = await import('plotly.js-cartesian-dist-min');
|
|
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;
|
|
expect(config['showSendToCloud'].valType).toBe('boolean');
|
|
expect(config['displaylogo'].valType).toBe('boolean');
|
|
expect(config['modeBarButtonsToRemove'].valType).toBe('any');
|
|
});
|
|
it.each([
|
|
['C1', { type: 'scatter', x: [1, 2], y: [3, 4] }],
|
|
['C2', { type: 'bar', x: ['grupo'], y: [100] }],
|
|
['C3r', { type: 'box', x: ['grupo'], q1: [23.5], median: [45], q3: [55], lowerfence: [23.5], upperfence: [55] }],
|
|
])('genera la modebar %s sin envío externo y conserva zoom/pan/restauración', async (_contract, trace) => {
|
|
const host = document.createElement('div');
|
|
document.body.append(host);
|
|
const figure: PlotlyFigure = { data: [trace], layout: { width: 600, height: 400 } };
|
|
const original = JSON.stringify(figure);
|
|
let controller!: PlotlyController;
|
|
try {
|
|
await new Promise<void>((resolve, reject) => {
|
|
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
|
|
if (state === 'ready') resolve();
|
|
if (state === 'error') reject(new Error('Plotly failed to render'));
|
|
});
|
|
controller.setFigure(figure);
|
|
});
|
|
const buttons = Array.from(host.querySelectorAll<HTMLElement>('.modebar-btn'));
|
|
const titles = buttons.map(button => button.getAttribute('data-title'));
|
|
expect(titles).not.toContain('Share chart...');
|
|
expect(titles).toEqual(expect.arrayContaining(['Zoom', 'Pan', 'Zoom in', 'Zoom out', 'Autoscale', 'Reset axes', 'Download plot as a PNG']));
|
|
expect(host.querySelector('.modebar a[href]')).toBeNull();
|
|
const rendered = host as unknown as HTMLElement & { _fullLayout: { dragmode: string } };
|
|
for (const [title, mode] of [['Pan', 'pan'], ['Zoom', 'zoom']]) {
|
|
buttons.find(button => button.getAttribute('data-title') === title)!
|
|
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
await vi.waitFor(() => expect(rendered._fullLayout.dragmode).toBe(mode));
|
|
}
|
|
expect(JSON.stringify(figure)).toBe(original);
|
|
} finally {
|
|
controller?.destroy(); host.remove();
|
|
}
|
|
});
|
|
it.each(syntheticFigures)('renderiza el JSON G7D.2B $name sin convertir nulos, IC ni bdata', async ({ figure }) => {
|
|
const host = document.createElement('div');
|
|
document.body.append(host);
|
|
const original = JSON.stringify(figure);
|
|
let controller!: PlotlyController;
|
|
try {
|
|
await new Promise<void>((resolve, reject) => {
|
|
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
|
|
if (state === 'ready') resolve();
|
|
if (state === 'error') reject(new Error('Plotly synthetic fixture failed'));
|
|
});
|
|
controller.setFigure(figure);
|
|
});
|
|
expect(host.querySelector('.main-svg')).not.toBeNull();
|
|
expect(host.style.visibility).toBe('visible');
|
|
expect(JSON.stringify(figure)).toBe(original);
|
|
} finally { controller?.destroy(); host.remove(); }
|
|
});
|
|
|
|
});
|
|
|
|
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();
|
|
});
|
|
});
|