diff --git a/src/app/features/indicadores/indicador-eu7-escenario.html b/src/app/features/indicadores/indicador-eu7-escenario.html
index d084249..26db2f9 100644
--- a/src/app/features/indicadores/indicador-eu7-escenario.html
+++ b/src/app/features/indicadores/indicador-eu7-escenario.html
@@ -48,14 +48,14 @@
diff --git a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts
index 0120d8f..a0e8c86 100644
--- a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts
+++ b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts
@@ -14,7 +14,7 @@ import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub {
- figure = input(); label = input(); showNotes = input();
+ figure = input(); label = input(); showNotes = input(); animated = input();
plotClick = output();
}
describe('EU7 integración Angular y caché compartida', () => {
@@ -46,6 +46,7 @@ describe('EU7 integración Angular y caché compartida', () => {
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
flush(); expect(f.componentInstance.model!.total).toBe(946);
+ expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]);
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682');
@@ -70,10 +71,13 @@ describe('EU7 integración Angular y caché compartida', () => {
}
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush();
expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364);
+ const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub);
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined();
+ expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts);
+ expect(charts.map(chart => chart.animated())).toEqual([true, true]);
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
});
diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts
index fd35bd1..4ed77e2 100644
--- a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts
+++ b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts
@@ -42,8 +42,11 @@ describe('EU7 modelo de presentación del entregable', () => {
expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1)))
.toEqual(['5.0', '24.3', '21.7', '7.8']);
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
- expect(category.data).toHaveLength(1);
- expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
+ // Same traces in every selection (animation identity); unselected ones are zero-width.
+ expect(category.data.map(t => t['uid'])).toEqual(f.data.map(t => t['uid']));
+ const lieag = category.data.find(t => t['uid'] === 'LIEAG')!;
+ expect(lieag['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
+ expect(category.data.filter(t => t !== lieag).every(t => (t['x'] as number[]).every(v => v === 0) && t['hoverinfo'] === 'skip')).toBe(true);
expect((category.layout['annotations'] as { text: string }[]).map(a => a.text))
.toEqual(m.escenarios.map(s => `${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} % (${s.celdas['LIEAG'].n}/${s.den})`));
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
@@ -74,7 +77,10 @@ describe('EU7 modelo de presentación del entregable', () => {
else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 });
else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 });
const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro');
- expect(m.escenarios[0].den).toBeNull(); expect(f.data[0]['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
+ expect(m.escenarios[0].den).toBeNull(); expect(f.data.find(t => t['uid'] === 'LIEAG')!['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
+ expect(f.data.every(t => (t['x'] as unknown[])[0] === null)).toBe(true);
+ expect(f.data.filter(t => t['uid'] !== 'LIEAG').every(t =>
+ t['hoverinfo'] === 'skip' && (t['customdata'] as unknown[]).length === 0)).toBe(true);
expect(JSON.stringify(f)).not.toContain('123456');
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
});
@@ -95,6 +101,7 @@ describe('EU7 modelo de presentación del entregable', () => {
(data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0);
const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]);
expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
+ expect(barras(m, { categoria: 'LIEAG' }, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })]));
});
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
@@ -102,4 +109,20 @@ describe('EU7 modelo de presentación del entregable', () => {
const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]);
expect(m.celdas['NORMAL'].n).toBeNull();
});
+ it('selección jerárquica y Volver conservan UID, orden, denominadores y datos fuente', () => {
+ const original = structuredClone(data), m = model(), snapshot = structuredClone(m);
+ const ids = m.categorias.map(c => c.id);
+ for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, {}]) {
+ const f = barras(m, selection, 'claro');
+ expect(f.data.map(t => t['uid'])).toEqual(ids);
+ expect(new Set(f.data.map(t => t['uid'])).size).toBe(ids.length);
+ f.data.forEach((t, i) => {
+ if (t['hoverinfo'] === 'skip') {
+ expect(t['customdata']).toEqual([]); expect(t['text']).toEqual(m.escenarios.map(() => ''));
+ } else expect(t['x']).toEqual(m.escenarios.map(s => porcentaje(s, ids[i])));
+ });
+ dona(m, selection, 'claro');
+ }
+ expect(m).toEqual(snapshot); expect(data).toEqual(original);
+ });
});
diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts
index 4324199..aca81aa 100644
--- a/src/app/features/indicadores/indicadores-eu7-escenario.ts
+++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts
@@ -217,13 +217,20 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
const y = m.escenarios.map(s => escapar(s.etiqueta));
const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0));
- return { data: m.categorias.filter(c => visibles.includes(c.id)).map(c => {
- const x = m.escenarios.map(s => porcentaje(s, c.id));
- return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x,
- marker: { color: c.color, line: { color: p.background, width: 1 } },
- text: x.map(v => v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
- customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]),
- hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` };
+ // Every category keeps its trace (same uid and count) so a selection animates;
+ // an unselected category is a zero-width bar without text or hover, never data.
+ return { data: m.categorias.map(c => {
+ const visible = visibles.includes(c.id);
+ const x = m.escenarios.map(s => {
+ const value = porcentaje(s, c.id);
+ return value === null ? null : visible ? value : 0;
+ });
+ return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x,
+ marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } },
+ text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
+ customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [],
+ ...(visible ? { hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` }
+ : { hoverinfo: 'skip' }) };
}), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65),
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
diff --git a/src/app/shared/plotly/plotly-chart.spec.ts b/src/app/shared/plotly/plotly-chart.spec.ts
index 75b325d..52dfadd 100644
--- a/src/app/shared/plotly/plotly-chart.spec.ts
+++ b/src/app/shared/plotly/plotly-chart.spec.ts
@@ -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);
diff --git a/src/app/shared/plotly/plotly-chart.ts b/src/app/shared/plotly/plotly-chart.ts
index 22925d3..2212a1b 100644
--- a/src/app/shared/plotly/plotly-chart.ts
+++ b/src/app/shared/plotly/plotly-chart.ts
@@ -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],
@@ -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;
readonly renderError = output();
@@ -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);
diff --git a/src/app/shared/plotly/plotly-controller.spec.ts b/src/app/shared/plotly/plotly-controller.spec.ts
index da71695..0fb746c 100644
--- a/src/app/shared/plotly/plotly-controller.spec.ts
+++ b/src/app/shared/plotly/plotly-controller.spec.ts
@@ -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((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 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();
+ });
+});
diff --git a/src/app/shared/plotly/plotly-controller.ts b/src/app/shared/plotly/plotly-controller.ts
index 2a98f3f..9286055 100644
--- a/src/app/shared/plotly/plotly-controller.ts
+++ b/src/app/shared/plotly/plotly-controller.ts
@@ -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;
+}
+const nextAnimationFrame = () => new Promise(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 | undefined;
+ const marker = trace['marker'] as Record | 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,
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');
}