Compare commits

...

1 Commits

Author SHA1 Message Date
Angel Capetillo Zavala a66205b725 feat(indicadores): agregar prototipo de dashboard TEA
Implementa el prototipo del dashboard de indicadores TEA.

- Integra catálogo y figuras mediante WebApi.
- Incorpora visualizaciones interactivas con Plotly.js.
- Agrega controles de indicadores, figuras, periodos y temas.
- Implementa estados de carga, errores y diseño responsive.
- Incluye explicaciones para los contratos C1, C2 y C3r.
- Incorpora pruebas unitarias y de integración de componentes.

Prototipo para investigación con datos sintéticos.
2026-10-12 10:43:00 -06:00
22 changed files with 990 additions and 3 deletions
+3 -1
View File
@@ -2,7 +2,8 @@
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"cli": {
"packageManager": "npm"
"packageManager": "npm",
"analytics": false
},
"newProjectRoot": "projects",
"projects": {
@@ -59,6 +60,7 @@
},
"serve": {
"builder": "@angular/build:dev-server",
"options": { "proxyConfig": "proxy.conf.json" },
"configurations": {
"production": {
"buildTarget": "WebApp:build:production"
+7
View File
@@ -16,6 +16,7 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},
@@ -6481,6 +6482,12 @@
"node": ">=16.20.0"
}
},
"node_modules/plotly.js-cartesian-dist-min": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/plotly.js-cartesian-dist-min/-/plotly.js-cartesian-dist-min-4.1.2.tgz",
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
"license": "MIT"
},
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
+1
View File
@@ -19,6 +19,7 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},
+4
View File
@@ -0,0 +1,4 @@
{
"/tea/**": { "target": "http://127.0.0.1:5000", "secure": false },
"/health": { "target": "http://127.0.0.1:5000", "secure": false }
}
+3 -1
View File
@@ -1,3 +1,4 @@
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
@@ -5,6 +6,7 @@ import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes)
provideRouter(routes),
provideHttpClient()
]
};
+16
View File
@@ -0,0 +1,16 @@
import { routes } from './app.routes';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresPage } from './features/indicadores/indicadores-page';
it('permite acceso directo a /indicadores sin guard ni autenticación', async () => {
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/indicadores', IndicadoresPage);
expect(harness.routeNativeElement?.textContent).toContain('Dashboard de indicadores');
const http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]);
http.verify();
});
+3 -1
View File
@@ -1,3 +1,5 @@
import { Routes } from '@angular/router';
export const routes: Routes = [];
export const routes: Routes = [
{ path: 'indicadores', loadComponent: () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage) },
];
@@ -0,0 +1,79 @@
<section class="dashboard" aria-labelledby="dashboard-title">
<header>
<span class="domain">Dominio TEA · Investigación</span>
<h1 id="dashboard-title">Dashboard de indicadores</h1>
<p>Explora las figuras de indicadores TEA generadas por el servicio de reportes.</p>
</header>
<p class="notice">Uso exclusivo de investigación. No usar para decisiones clínicas.</p>
@if (catalogLoading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
<p role="status">Cargando catálogo de indicadores…</p>
} @else if (catalogError()) {
<mat-card class="state" role="alert"><p>{{ catalogError() }}</p>
<button mat-stroked-button (click)="retryCatalog()">Reintentar catálogo</button></mat-card>
} @else if (!catalog().length) {
<mat-card class="state"><p role="status">No hay indicadores disponibles en el catálogo.</p>
<button mat-stroked-button (click)="retryCatalog()">Actualizar catálogo</button></mat-card>
} @else {
<mat-card class="filters" aria-label="Selección de figura">
<div class="fields">
<mat-form-field class="indicator"><mat-label>Indicador</mat-label>
<mat-select [ngModel]="indicadorId" (ngModelChange)="selectIndicador($event)">
@for (item of catalog(); track item.id) { <mat-option [value]="item.id">{{ item.titulo }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Figura</mat-label>
<mat-select [ngModel]="figuraId" (ngModelChange)="selectFigura($event)" [disabled]="!selected?.figuras?.length">
@for (figure of selected?.figuras ?? []; track $index) { <mat-option [value]="figure">{{ figure }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Periodos</mat-label>
<mat-select [ngModel]="periodMode" (ngModelChange)="changePeriodMode($event)">
<mat-option value="todos">Todos los periodos con reporte</mat-option>
<mat-option value="manual">Selección manual</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Tema de la figura</mat-label>
<mat-select [ngModel]="tema" (ngModelChange)="changeTema($event)">
<mat-option value="claro">Claro</mat-option><mat-option value="oscuro">Oscuro</mat-option>
</mat-select>
</mat-form-field>
@if (periodMode === 'manual') {
<mat-form-field class="periods"><mat-label>Semestres (AAAA-S1,AAAA-S2)</mat-label>
<input matInput [ngModel]="periodText" (ngModelChange)="changePeriodText($event)" [attr.aria-invalid]="!!periodError" aria-describedby="period-help" />
<mat-hint id="period-help">Escribe los semestres a consultar. Su disponibilidad depende de los reportes.</mat-hint>
</mat-form-field>
}
</div>
@if (periodError) { <p class="validation" role="alert">{{ periodError }}</p> }
<p class="contract">Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.</p>
</mat-card>
@if (selected) {
<section class="interpretation" aria-labelledby="interpretation-title">
<h2 id="interpretation-title">Cómo leer esta figura · {{ selected?.contrato }}</h2>
<ul>
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
</ul>
<p class="period-note">Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.</p>
</section>
}
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" aria-label="Resultado de la selección" [attr.aria-busy]="result().status === 'loading'">
@if (result().status === 'loading') {
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
<p class="state" role="status">Cargando figura…</p>
} @else if (result().status === 'error') {
<div class="state" role="alert"><p>{{ result().message }}</p>
<button mat-stroked-button (click)="requestFigure()">Reintentar solicitud</button></div>
} @else if (result().figure; as figure) {
@if (hasNoVisibleValues(figure)) {
<p class="state" role="status">No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.</p>
}
<h2 class="figure-title">{{ selected?.titulo }}</h2>
<app-plotly-chart [figure]="figure" />
} @else {
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
}
</mat-card>
}
</section>
@@ -0,0 +1,29 @@
:host { display: block; }
.dashboard { max-width: 1440px; margin: 0 auto; }
h1 { font: var(--mat-sys-headline-large); margin: .65rem 0; }
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
.notice { padding: 1rem 1.25rem; border-left: 4px solid var(--mat-sys-primary); background: var(--mat-sys-surface-container); border-radius: 8px; }
.filters { padding: 1.5rem; margin: 1.5rem 0; }
.fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem 1rem; }
.indicator { grid-column: span 2; }
.periods { grid-column: 1 / -1; margin-bottom: 1rem; }
mat-form-field { width: 100%; min-width: 0; }
.contract { color: var(--mat-sys-on-surface-variant); margin: .5rem 0 0; }
.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; }
.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); }
.interpretation ul { margin: 0; padding-left: 1.25rem; }
.interpretation li + li { margin-top: .25rem; }
.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); }
.validation { color: var(--mat-sys-error); }
.figure-card { overflow: hidden; min-width: 0; }
.figure-title { display: none; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; }
.state { padding: 1.25rem; margin: 0; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
@media (max-width: 850px) { .figure-title { display: block; } .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 550px) {
.fields { grid-template-columns: minmax(0, 1fr); }
.indicator { grid-column: auto; }
.filters, .interpretation { padding: 1rem; }
h1 { font: var(--mat-sys-headline-medium); }
}
@@ -0,0 +1,170 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { PlotlyFigure } from './indicadores.models';
import { Component } from '@angular/core';
import { IndicadoresPage } from './indicadores-page';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' })
class ChartStub { figure?: PlotlyFigure; }
const catalog = [
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'] },
{ id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'] },
{ id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [] },
];
describe('IndicadoresPage', () => {
let page: IndicadoresPage;
let http: HttpTestingController;
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresPage);
page = fixture.componentInstance;
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { fixture.destroy(); http.verify(); });
function load() { http.expectOne('/tea/indicadores').flush(catalog); }
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
it('presenta carga y elige una primera figura válida desde el catálogo', () => {
expect(page.catalogLoading()).toBe(true);
load();
expect(page.indicadorId).toBe('i1');
expect(page.figuraId).toBe('f1');
expect(page.result().status).toBe('loading');
const request = figure();
expect(request.request.params.has('periodos')).toBe(false);
request.flush({ data: [], layout: {} });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
expect(fixture.nativeElement.textContent).toContain('Uso exclusivo de investigación');
});
it.each([
['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']],
['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']],
['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']],
['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']],
['toString', ['No hay una explicación específica']],
])('explica el contrato %s y conserva el aviso de investigación', (contract, expected) => {
http.expectOne('/tea/indicadores').flush([{ ...catalog[0], contrato: contract }]);
figure().flush({ data: [], layout: {} });
fixture.detectChanges();
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
for (const text of expected) expect(help).toContain(text);
if (contract === 'C3r') {
expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados');
expect(help).not.toMatch(/serving|corrección|fase independiente/i);
}
expect(fixture.nativeElement.querySelector('.notice').textContent).toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.');
expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables');
});
it('actualiza la explicación al cambiar indicador, incluso durante la carga', () => {
load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Wilson');
page.selectIndicador('i2'); fixture.detectChanges();
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
expect(help).toContain('min/max'); expect(help).not.toContain('Wilson');
figure().flush({ data: [], layout: {} });
});
it('entrega al gráfico el JSON íntegro sin modificarlo al presentar la ayuda', () => {
load();
const received: PlotlyFigure = {
data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }],
layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true },
config: { staticPlot: false }, frames: [], extra: { preserved: true },
};
const original = JSON.stringify(received);
figure().flush(received); fixture.detectChanges();
expect(JSON.stringify(received)).toBe(original);
expect(page.result().figure).toEqual(received);
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
expect(chart.figure).toBe(page.result().figure);
expect(JSON.stringify(chart.figure)).toBe(original);
});
it('muestra catálogo vacío y permite recargar', () => {
http.expectOne('/tea/indicadores').flush([]);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
page.retryCatalog();
load();
figure().flush({ data: [], layout: {} });
});
it('cancela solicitudes previas al cambiar indicador y no muestra figura antigua', () => {
load();
const old = figure();
page.selectIndicador('i2');
expect(old.cancelled).toBe(true);
expect(page.figuraId).toBe('box');
expect(page.result().figure).toBeUndefined();
figure().flush({ data: [{ type: 'box', median: [2] }], layout: {} });
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
expect(page.result().figure?.data[0]['median']).toEqual([2]);
});
it('soporta varias figuras, volver al indicador y selección sin figuras', () => {
load(); figure().flush({ data: [], layout: {} });
page.selectFigura('f2');
expect(figure().request.url).toContain('/i1/figuras/f2');
// Cancel the previous request and verify its cancellation explicitly below.
page.selectIndicador('empty');
expect(page.figuraId).toBe('');
expect(page.result().status).toBe('idle');
page.selectIndicador('i1');
expect(page.figuraId).toBe('f1');
figure().flush({ data: [], layout: {} });
});
it('valida manuales antes del HTTP y vuelve a Todos sin query', () => {
load(); figure().flush({ data: [], layout: {} });
page.changePeriodMode('manual');
expect(page.periodError).not.toBe('');
http.expectNone(req => req.url.includes('/figuras/'));
page.changePeriodText('2025-S1, 2025-S2');
const manual = figure();
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
page.changePeriodText('2025-S3');
expect(manual.cancelled).toBe(true);
expect(page.result().figure).toBeUndefined();
page.changePeriodMode('todos');
const all = figure();
expect(all.request.params.has('periodos')).toBe(false);
all.flush({ data: [], layout: {} });
});
it('cancela figuras al cambiar tema rápidamente', () => {
load();
const old = figure();
page.changeTema('oscuro');
const dark = figure();
expect(old.cancelled).toBe(true);
expect(dark.request.params.get('tema')).toBe('oscuro');
page.changeTema('claro');
expect(dark.cancelled).toBe(true);
figure().flush({ data: [], layout: {} });
});
it.each([
[400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'],
])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => {
load();
figure().flush('<html>error privado</html>', { status: status as number, statusText: 'Error' });
expect(page.result().status).toBe('error');
expect(page.result().message).toContain(message);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).not.toContain('error privado');
page.requestFigure();
figure().flush({ data: [], layout: {} });
expect(page.result().status).toBe('ready');
});
it('distingue conexión fallida y cancela HTTP al destruirse', () => {
load(); figure().error(new ProgressEvent('error'));
expect(page.result().message).toContain('conectar');
page.requestFigure();
const pending = figure();
fixture.destroy();
expect(pending.cancelled).toBe(true);
});
it('controla errores de catálogo y puede recuperarse', () => {
http.expectOne('/tea/indicadores').flush('Error', { status: 500, statusText: 'Error' });
expect(page.catalogError()).toContain('error interno');
page.retryCatalog(); load(); figure().flush({ data: [], layout: {} });
});
});
@@ -0,0 +1,119 @@
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
import { FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
export function httpMessage(error: unknown, catalog = false): string {
if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.';
if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.';
if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.';
if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.';
if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.';
return 'No se pudo completar la solicitud. Intenta nuevamente.';
}
// Presentation only: contract semantics documented in G3 and G5C.
const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
C1: [
'El punto representa la proporción observada.',
'La línea vertical representa el intervalo de confianza Wilson al 95 %.',
'Los intervalos amplios pueden deberse a denominadores pequeños.',
'Un porcentaje observado del 100 % no implica certeza poblacional.',
],
C2: [
'Las barras muestran la composición porcentual de cada grupo y periodo.',
'Las categorías corresponden a la distribución de cada grupo y periodo.',
'SIN_DATO, cuando aparece, es una categoría legítima de la representación.',
],
C3r: [
'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
'Los límites de dibujo no representan necesariamente extremos observados.',
'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
],
};
const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.'];
type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; message?: string };
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
private readonly service = inject(IndicadoresService);
private readonly destroyRef = inject(DestroyRef);
private readonly catalogRequests = new Subject<void>();
private readonly figureRequests = new Subject<FigureSelection | null>();
readonly catalog = signal<Indicador[]>([]);
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
readonly result = signal<FigureState>({ status: 'idle' });
readonly hasNoVisibleValues = hasNoVisibleValues;
indicadorId = '';
figuraId = '';
periodMode: 'todos' | 'manual' = 'todos';
periodText = '';
periodError = '';
tema: Tema = 'claro';
get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); }
get interpretation(): readonly string[] {
const contract = this.selected?.contrato;
return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract)
? CONTRACT_INTERPRETATIONS[contract] : UNKNOWN_INTERPRETATION;
}
constructor() {
this.figureRequests.pipe(switchMap(selection => selection
? this.service.figura(selection).pipe(
map(figure => ({ status: 'ready', figure }) as FigureState),
catchError(error => of({ status: 'error', message: httpMessage(error) } as FigureState)),
startWith({ status: 'loading' } as FigureState))
: of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef))
.subscribe(state => this.result.set(state));
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
this.catalogLoading.set(true);
this.catalogError.set('');
this.catalog.set([]);
this.indicadorId = this.figuraId = '';
this.figureRequests.next(null);
return this.service.catalogo().pipe(map(items => ({ items, error: '' })),
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
this.catalogLoading.set(false);
this.catalog.set(items);
this.catalogError.set(error);
if (items.length) this.selectIndicador(items[0].id);
});
}
retryCatalog() { this.catalogRequests.next(); }
selectIndicador(id: string) {
this.indicadorId = id;
this.figuraId = this.selected?.figuras[0] ?? '';
this.requestFigure();
}
selectFigura(id: string) { this.figuraId = id; this.requestFigure(); }
changePeriodMode(mode: 'todos' | 'manual') { this.periodMode = mode; this.requestFigure(); }
changePeriodText(text: string) { this.periodText = text; this.requestFigure(); }
changeTema(tema: Tema) { this.tema = tema; this.requestFigure(); }
requestFigure() {
this.periodError = '';
const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText) : undefined;
if (periodos === null) this.periodError = 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.';
if (!this.selected || !this.selected.figuras.includes(this.figuraId) || periodos === null) {
this.figureRequests.next(null);
return;
}
this.figureRequests.next({ indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos });
}
}
@@ -0,0 +1,23 @@
import { hasNoVisibleValues, parsePeriodos } from './indicadores.models';
describe('Periodos y visibilidad conservadora', () => {
it('normaliza espacios y duplicados sin inventar periodos', () => {
expect(parsePeriodos('2025-S1, 2025-S2,2025-S1')).toEqual(['2025-S1', '2025-S2']);
expect(parsePeriodos('1900-S2')).toEqual(['1900-S2']);
});
it.each(['', '2025', '25-S1', '2025-S3', '2025-S1,', '2025-s1', '2025-S1 2025-S2'])('rechaza %s', value => {
expect(parsePeriodos(value)).toBeNull();
});
it('detecta trazos vacíos, nulos y cajas sin mediana', () => {
expect(hasNoVisibleValues({ data: [], layout: {} })).toBe(true);
expect(hasNoVisibleValues({ data: [{ type: 'scatter', y: [null] }, { type: 'bar', y: [] }, { type: 'box', median: [null] }], layout: {} })).toBe(true);
});
it('conserva cero, supresión y medianas válidas como valores visibles', () => {
expect(hasNoVisibleValues({ data: [{ y: [0] }], layout: {} })).toBe(false);
expect(hasNoVisibleValues({ data: [{ type: 'box', median: [10] }], layout: {} })).toBe(false);
});
it('no declara vacíos los formatos desconocidos o binarios', () => {
expect(hasNoVisibleValues({ data: [{ y: { bdata: 'AAAA', dtype: 'f8' } }], layout: {} })).toBe(false);
expect(hasNoVisibleValues({ data: [{ type: 'heatmap', z: [] }], layout: {} })).toBe(false);
});
});
@@ -0,0 +1,36 @@
export interface Indicador {
id: string;
titulo: string;
contrato: string;
figuras: string[];
}
// Keep the complete HTTP figure, including future attributes and interpretation notes.
export interface PlotlyFigure {
data: Record<string, unknown>[];
layout: Record<string, unknown>;
frames?: Record<string, unknown>[];
config?: Record<string, unknown>;
[key: string]: unknown;
}
export type Tema = 'claro' | 'oscuro';
export interface FigureSelection { indicador: string; figura: string; tema: Tema; periodos?: string[]; }
export function parsePeriodos(value: string): string[] | null {
const parts = value.split(',').map(part => part.trim());
return parts.length && parts.every(part => /^[0-9]{4}-S[12]$/.test(part))
? [...new Set(parts)] : null;
}
// Only assert emptiness for known TEA traces with ordinary arrays. Unknown/binary
// representations remain indeterminate; never infer counts or suppression causes.
export function hasNoVisibleValues(figure: PlotlyFigure): boolean {
return figure.data.every(trace => {
if (trace['visible'] === false || trace['visible'] === 'legendonly') return true;
const type = trace['type'] ?? 'scatter';
const values = type === 'box' ? trace['median'] ?? trace['y']
: type === 'scatter' || type === 'bar' ? trace['y'] : undefined;
if (!Array.isArray(values)) return false;
return !values.some(value => typeof value === 'number' && Number.isFinite(value));
});
}
@@ -0,0 +1,53 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresService } from './indicadores.service';
describe('IndicadoresService HTTP', () => {
let service: IndicadoresService;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
service = TestBed.inject(IndicadoresService);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('consume un arreglo directo sin hardcodear catálogo', () => {
const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'] }];
let actual: unknown;
service.catalogo().subscribe(value => actual = value);
http.expectOne('/tea/indicadores').flush(data);
expect(actual).toEqual(data);
});
it('acepta catálogo vacío y rechaza envelope inesperado', () => {
service.catalogo().subscribe(value => expect(value).toEqual([]));
http.expectOne('/tea/indicadores').flush([]);
let error: unknown;
service.catalogo().subscribe({ error: value => error = value });
http.expectOne('/tea/indicadores').flush({ items: [] });
expect(error).toBeInstanceOf(Error);
});
it('codifica segmentos y omite periodos en Todos', () => {
service.figura({ indicador: 'a/b ü', figura: 'f?#', tema: 'claro' }).subscribe();
const request = http.expectOne(req => req.url === '/tea/indicadores/a%2Fb%20%C3%BC/figuras/f%3F%23');
expect(request.request.method).toBe('GET');
expect(request.request.params.get('tema')).toBe('claro');
expect(request.request.params.has('periodos')).toBe(false);
request.flush({ data: [], layout: {} });
});
it('envía semestres y conserva atributos desconocidos, nulos y notas', () => {
const figure = { data: [{ y: [null, 0], customdata: [null] }], layout: { annotations: [{ text: 'Uso exclusivo de investigación' }] }, extension: { future: true }, frames: [] };
service.figura({ indicador: 'i', figura: 'f', tema: 'oscuro', periodos: ['2025-S1', '2025-S2'] })
.subscribe(value => expect(value).toEqual(figure));
const request = http.expectOne(req => req.url.endsWith('/i/figuras/f'));
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2');
expect(request.request.params.get('tema')).toBe('oscuro');
request.flush(figure);
});
it('rechaza una figura estructuralmente inválida', () => {
let error: unknown;
service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe({ error: value => error = value });
http.expectOne(req => req.url.endsWith('/i/figuras/f')).flush({ data: null, layout: {} });
expect(error).toBeInstanceOf(Error);
});
});
@@ -0,0 +1,33 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { FigureSelection, Indicador, PlotlyFigure } from './indicadores.models';
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
@Injectable({ providedIn: 'root' })
export class IndicadoresService {
private readonly http = inject(HttpClient);
catalogo() {
return this.http.get<unknown>('/tea/indicadores').pipe(map(value => {
if (!Array.isArray(value) || !value.every(item => record(item)
&& typeof item['id'] === 'string' && typeof item['titulo'] === 'string'
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
&& item['figuras'].every((figure: unknown) => typeof figure === 'string'))) {
throw new Error('Respuesta de catálogo inválida');
}
return value as Indicador[];
}));
}
figura(selection: FigureSelection) {
let params = new HttpParams().set('tema', selection.tema);
if (selection.periodos?.length) params = params.set('periodos', selection.periodos.join(','));
const url = `/tea/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`;
return this.http.get<unknown>(url, { params }).pipe(map(value => {
if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record)
|| !record(value['layout'])) throw new Error('Respuesta de figura inválida');
return value as unknown as PlotlyFigure;
}));
}
}
@@ -0,0 +1,41 @@
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();
});
});
+61
View File
@@ -0,0 +1,61 @@
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 #host class="plot" role="img" aria-label="Figura del indicador seleccionado" [attr.aria-hidden]="status() !== 'ready'"></div>
@if (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 { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { display: none; padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } @media (max-width: 850px) { .notes { display: block; } }`,
})
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
@Input({ required: true }) figure!: PlotlyFigure;
@ViewChild('host', { static: true }) host!: ElementRef<HTMLElement>;
readonly renderError = output<void>();
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 readonly windowResize = () => this.controller?.resize();
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);
}
ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); }
retry() { this.controller?.setFigure(this.figure); }
ngOnDestroy() {
this.observer?.disconnect();
window.removeEventListener('resize', this.windowResize);
this.controller?.destroy();
}
}
@@ -0,0 +1,178 @@
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();
}
});
});
@@ -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(); }
});
+20
View File
@@ -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 });
+1
View File
@@ -0,0 +1 @@
declare module 'plotly.js-cartesian-dist-min';