integration layer; merge work on indicators from forks with existing ingestion pipeline
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { vi } from 'vitest';
|
||||
import { PlotlyChart } from './plotly-chart';
|
||||
import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
const mocks = { load: vi.fn(), react: vi.fn(), purge: vi.fn(), resize: vi.fn() };
|
||||
|
||||
describe('PlotlyChart lifecycle', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mocks.react.mockResolvedValue(undefined);
|
||||
mocks.resize.mockResolvedValue(undefined);
|
||||
mocks.load.mockResolvedValue({ react: mocks.react, purge: mocks.purge, Plots: { resize: mocks.resize } });
|
||||
TestBed.configureTestingModule({ imports: [PlotlyChart], providers: [{ provide: PLOTLY_LOADER, useValue: mocks.load }] });
|
||||
});
|
||||
it('monta el host, actualiza inputs y desconecta ResizeObserver', async () => {
|
||||
const disconnect = vi.fn(); const observe = vi.fn();
|
||||
vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; });
|
||||
const fixture = TestBed.createComponent(PlotlyChart);
|
||||
fixture.componentRef.setInput('figure', { data: [], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve();
|
||||
expect(observe).toHaveBeenCalledWith(fixture.nativeElement.querySelector('.plot'));
|
||||
expect(mocks.react).toHaveBeenCalledTimes(1);
|
||||
fixture.componentRef.setInput('figure', { data: [{ y: [1] }], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve();
|
||||
expect(mocks.react).toHaveBeenCalledTimes(2);
|
||||
fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(mocks.purge).toHaveBeenCalled();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
it('muestra error asíncrono y se recupera con reintento', async () => {
|
||||
mocks.react.mockRejectedValueOnce(new Error('render failed'));
|
||||
const fixture = TestBed.createComponent(PlotlyChart);
|
||||
fixture.componentRef.setInput('figure', { data: [], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No se pudo representar');
|
||||
fixture.nativeElement.querySelector('button').click();
|
||||
await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.status()).toBe('ready'); fixture.destroy();
|
||||
});
|
||||
it('UX-07C comunica sólo cambios reales de ancho, agrupa notificaciones y cancela al destruir', async () => {
|
||||
const frames: FrameRequestCallback[] = [], cancel = vi.fn(), disconnect = vi.fn();
|
||||
let notify!: ResizeObserverCallback;
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { frames.push(callback); return frames.length; });
|
||||
vi.stubGlobal('cancelAnimationFrame', cancel);
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
constructor(callback: ResizeObserverCallback) { notify = callback; }
|
||||
observe = vi.fn(); disconnect = disconnect;
|
||||
});
|
||||
const fixture = TestBed.createComponent(PlotlyChart), widths: number[] = [];
|
||||
fixture.componentInstance.widthChanged.subscribe(width => widths.push(width));
|
||||
fixture.componentRef.setInput('figure', { data: [], layout: {} }); fixture.detectChanges();
|
||||
const host = fixture.nativeElement.querySelector('.plot') as HTMLElement;
|
||||
let width = 640;
|
||||
vi.spyOn(host, 'getBoundingClientRect').mockImplementation(() => ({ width } as DOMRect));
|
||||
const resize = () => notify([], {} as ResizeObserver);
|
||||
const flush = () => frames.splice(0).forEach(callback => callback(0));
|
||||
const pending = frames.length; // Angular may also schedule a render frame.
|
||||
resize(); resize(); expect(frames).toHaveLength(pending);
|
||||
flush(); expect(widths).toEqual([640]);
|
||||
resize(); flush(); expect(widths).toEqual([640]); // Height-only notification.
|
||||
width = 900; resize(); flush(); expect(widths).toEqual([640, 900]);
|
||||
width = 0; resize(); flush(); expect(widths).toEqual([640, 900]); // Hidden host.
|
||||
resize(); fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(cancel).toHaveBeenCalled();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { AfterViewInit, Component, inject, ElementRef, Input, OnChanges, OnDestroy, output, signal, ViewChild } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
||||
import { PlotlyController } from './plotly-controller';
|
||||
import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
|
||||
@Component({
|
||||
selector: 'app-plotly-chart',
|
||||
imports: [MatButtonModule, MatProgressBarModule],
|
||||
template: `
|
||||
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Representando figura" /> }
|
||||
@if (status() === 'error') {
|
||||
<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>
|
||||
@if (showNotes && status() === 'ready' && notes.length) {
|
||||
<section class="notes" aria-label="Notas completas de la figura">
|
||||
<h2>Notas de la figura</h2>
|
||||
@for (note of notes; track $index) { <p [innerHTML]="note"></p> }
|
||||
</section>
|
||||
}
|
||||
`,
|
||||
styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-width: var(--plot-min-width, 0px); min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`,
|
||||
})
|
||||
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
|
||||
@Input() showNotes = true;
|
||||
@Input() label = 'Figura estadística';
|
||||
@Input({ required: true }) figure!: PlotlyFigure;
|
||||
@ViewChild('host', { static: true }) host!: ElementRef<HTMLElement>;
|
||||
readonly renderError = output<void>();
|
||||
readonly widthChanged = output<number>();
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
get notes(): string[] {
|
||||
const annotations = this.figure?.layout['annotations'];
|
||||
if (!Array.isArray(annotations)) return [];
|
||||
return annotations.flatMap(annotation =>
|
||||
annotation && typeof annotation.text === 'string' ? [annotation.text] : []);
|
||||
}
|
||||
private readonly loadPlotly = inject(PLOTLY_LOADER);
|
||||
private controller?: PlotlyController;
|
||||
private observer?: ResizeObserver;
|
||||
private lastWidth = 0;
|
||||
private widthFrame?: number;
|
||||
private readonly windowResize = () => {
|
||||
this.controller?.resize();
|
||||
if (this.widthFrame !== undefined) return;
|
||||
this.widthFrame = requestAnimationFrame(() => {
|
||||
this.widthFrame = undefined;
|
||||
const width = Math.floor(this.host.nativeElement.getBoundingClientRect().width);
|
||||
if (width > 0 && width !== this.lastWidth) { this.lastWidth = width; this.widthChanged.emit(width); }
|
||||
});
|
||||
};
|
||||
ngAfterViewInit() {
|
||||
this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => {
|
||||
this.status.set(state);
|
||||
if (state === 'error') this.renderError.emit();
|
||||
});
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
this.observer = new ResizeObserver(this.windowResize);
|
||||
this.observer.observe(this.host.nativeElement);
|
||||
} else window.addEventListener('resize', this.windowResize);
|
||||
this.controller.setFigure(this.figure);
|
||||
// Also supply the initial width in browsers without ResizeObserver.
|
||||
this.windowResize();
|
||||
}
|
||||
ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); }
|
||||
retry() { this.controller?.setFigure(this.figure); }
|
||||
ngOnDestroy() {
|
||||
this.observer?.disconnect();
|
||||
if (this.widthFrame !== undefined) cancelAnimationFrame(this.widthFrame);
|
||||
window.removeEventListener('resize', this.windowResize);
|
||||
this.controller?.destroy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { syntheticFigures } from '../../features/indicadores/indicadores.synthetic-fixtures';
|
||||
import { vi } from 'vitest';
|
||||
import { PlotlyController } 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('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('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(); }
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
||||
import { PlotlyRuntime } from './plotly-runtime';
|
||||
|
||||
// One serialized queue owns the host. A completed stale operation cannot expose
|
||||
// its graph or overwrite a newer react operation. Resize uses the same queue.
|
||||
export class PlotlyController {
|
||||
private desired?: PlotlyFigure;
|
||||
private version = 0;
|
||||
private rendered = -1;
|
||||
private busy = false;
|
||||
private destroyed = false;
|
||||
private resizePending = false;
|
||||
private plotly?: PlotlyRuntime;
|
||||
private frameCount = 0;
|
||||
constructor(private host: HTMLElement, private load: () => Promise<PlotlyRuntime>,
|
||||
private state: (state: 'loading' | 'ready' | 'error') => void) {}
|
||||
|
||||
setFigure(figure: PlotlyFigure) {
|
||||
if (this.destroyed) return;
|
||||
this.desired = figure;
|
||||
this.version++;
|
||||
this.host.style.visibility = 'hidden';
|
||||
this.state('loading');
|
||||
void this.drain();
|
||||
}
|
||||
resize() {
|
||||
if (this.destroyed || this.rendered < 0) return;
|
||||
this.resizePending = true;
|
||||
void this.drain();
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
this.host.style.visibility = 'hidden';
|
||||
this.plotly?.purge(this.host);
|
||||
}
|
||||
private async drain() {
|
||||
if (this.busy || this.destroyed) return;
|
||||
this.busy = true;
|
||||
try {
|
||||
this.plotly ??= await this.load();
|
||||
while (!this.destroyed && (this.rendered !== this.version || this.resizePending)) {
|
||||
const version = this.version;
|
||||
try {
|
||||
if (this.rendered !== version && this.desired) {
|
||||
// Plotly may mutate inputs; clone the complete JSON without changing values.
|
||||
const figure = structuredClone(this.desired);
|
||||
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'],
|
||||
});
|
||||
if (this.destroyed) break;
|
||||
if (version !== this.version) continue;
|
||||
if (figure.frames?.length) {
|
||||
await this.plotly.addFrames(this.host, figure.frames);
|
||||
this.frameCount = figure.frames.length;
|
||||
}
|
||||
if (this.destroyed) break;
|
||||
if (version !== this.version) continue;
|
||||
this.rendered = version;
|
||||
this.host.style.visibility = 'visible';
|
||||
this.state('ready');
|
||||
} else {
|
||||
this.resizePending = false;
|
||||
await this.plotly.Plots.resize(this.host);
|
||||
}
|
||||
} catch {
|
||||
if (this.destroyed) break;
|
||||
if (version !== this.version) continue;
|
||||
this.rendered = version;
|
||||
this.resizePending = false;
|
||||
this.host.style.visibility = 'hidden';
|
||||
this.state('error');
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
if (!this.destroyed) this.state('error');
|
||||
} finally {
|
||||
this.busy = false;
|
||||
// A pending react can recreate internal resources after the first purge.
|
||||
if (this.destroyed) this.plotly?.purge(this.host);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { vi } from 'vitest';
|
||||
import { loadPlotly } from './plotly-runtime';
|
||||
|
||||
it('carga una sola instancia oficial con el esquema requerido por C1/C2/C3r', async () => {
|
||||
// No chart rendering in jsdom. Schema inspection only needs browser globals.
|
||||
const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
|
||||
try {
|
||||
const first = loadPlotly();
|
||||
expect(loadPlotly()).toBe(first);
|
||||
const runtime = await first as unknown as { version: string; PlotSchema: { get(): any } };
|
||||
expect(runtime.version).toBe('4.1.2');
|
||||
const schema = runtime.PlotSchema.get();
|
||||
expect(schema.traces.scatter).toBeDefined();
|
||||
expect(schema.traces.bar).toBeDefined();
|
||||
expect(schema.traces.box).toBeDefined();
|
||||
expect(schema.traces.scatter.attributes.error_y).toBeDefined();
|
||||
expect(schema.layout.layoutAttributes.xaxis.type.values).toContain('multicategory');
|
||||
expect(schema.traces.scatter.layoutAttributes.scattermode.values).toContain('group');
|
||||
expect(schema.traces.box.layoutAttributes.boxmode.values).toContain('group');
|
||||
for (const key of ['q1', 'median', 'q3', 'lowerfence', 'upperfence']) expect(schema.traces.box.attributes[key]).toBeDefined();
|
||||
for (const key of ['annotations', 'template', 'paper_bgcolor', 'plot_bgcolor']) expect(schema.layout.layoutAttributes[key]).toBeDefined();
|
||||
} finally { canvas.mockRestore(); }
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
||||
|
||||
// Narrow boundary for the official partial bundle, which ships without declarations.
|
||||
export interface PlotlyRuntime {
|
||||
react(host: HTMLElement, data: PlotlyFigure['data'], layout: PlotlyFigure['layout'], config: Record<string, unknown>): Promise<unknown>;
|
||||
purge(host: HTMLElement): void;
|
||||
Plots: { resize(host: HTMLElement): Promise<unknown> };
|
||||
addFrames(host: HTMLElement, frames: Record<string, unknown>[]): Promise<unknown>;
|
||||
deleteFrames(host: HTMLElement, indices: number[]): Promise<unknown>;
|
||||
}
|
||||
let runtime: Promise<PlotlyRuntime> | undefined;
|
||||
export function loadPlotly(): Promise<PlotlyRuntime> {
|
||||
return runtime ??= import('plotly.js-cartesian-dist-min')
|
||||
.then(module => (module.default ?? module) as unknown as PlotlyRuntime)
|
||||
.catch(error => { runtime = undefined; throw error; });
|
||||
}
|
||||
|
||||
export const PLOTLY_LOADER = new InjectionToken<() => Promise<PlotlyRuntime>>('PLOTLY_LOADER', { providedIn: 'root', factory: () => loadPlotly });
|
||||
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
declare module 'plotly.js-cartesian-dist-min';
|
||||
Reference in New Issue
Block a user