{{ indicador.titulo }}
+El indicador no tiene figuras disponibles.
} +-
+ @for (line of interpretation; track $index) {
- {{ line }} } +
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.
+Cargando figura…
{{ state.message }}
Filtro general incompatible con esta figura.
{{ state.message }}
{{ state.message }}
+No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.
+ } + +Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}
+ } @else { +{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}
+ } + @if (chartFigure) { +{{ note }}
} +Nombres completos de las categorías
+-
+ @for (label of state.categoryLabels; track $index) {
+
- {{ label.abbreviated }}: {{ label.original }} + } +
Intervalos no disponibles' }, + { text: 'Uso exclusivo de investigación. No usar para decisiones clínicas.' }, + { text: 'Supresión: consulta las notas completas' }, + ] }, frames: [] }; + const snapshot = JSON.stringify(figure); + ready(figure); await settle(); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(chart.figure.layout['annotations']).toEqual(figure.layout['annotations']); + expect(chart.notes).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text)); + expect(JSON.stringify(figure)).toBe(snapshot); + expect(fixture.nativeElement.querySelector('.plot-viewport')?.getAttribute('tabindex')).toBe('0'); + }); + it.each(['claro', 'oscuro'] as const)('UX-06E.P0.2 conserva el tema %s sin duplicar anotaciones en HTML', async tema => { + fixture.componentRef.setInput('tema', tema); + const annotation = 'Advertencia metodológica única de la figura.'; + const original: PlotlyFigure = { data: [{ y: [1] }], layout: { annotations: [{ text: annotation }] } }; + ready(original); await settle(); + const card = fixture.nativeElement.querySelector('.figure-card'); + expect(card.classList.contains('dark')).toBe(tema === 'oscuro'); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + expect(fixture.nativeElement.textContent).not.toContain(annotation); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(chart.notes).toEqual([annotation]); + expect(JSON.stringify(original)).toContain(annotation); + }); + it('UX-06D mantiene relaciones de detalle únicas incluso con separadores en IDs publicados', () => { + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a--b' }); + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'idle' }); + const first = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'); + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a' }); + fixture.componentRef.setInput('figuraId', 'b--fig_c2_apiladas'); + fixture.detectChanges(); + const second = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'); + expect(first).not.toBe(second); + expect(fixture.nativeElement.querySelector('[id]').id).toBe(second); + }); + it.each(['tea', 'cacu', 'cama'])('UX-06E.B1 conserva C1 de %s íntegro con condiciones críticas visibles', dominio => { + fixture.componentRef.setInput('dominio', dominio); + state({ status: 'idle' }); + const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; + const button = section.querySelector('button')!; + const detail = section.querySelector('[hidden]') as HTMLElement; + expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); + // jsdom does not perform native Enter/Space activation; leave both keys + // available to the browser and validate activation in Chrome. + for (const key of ['Enter', ' ']) { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); + } + expect(button.textContent).toContain('Cómo leer'); + expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba · ' + dominio + ' · fig_c1_puntos'); + expect(button.getAttribute('aria-expanded')).toBe('false'); + expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true); + const warnings = detail.querySelector('ul')!; + expect(warnings.closest('[hidden]')).not.toBeNull(); + expect(warnings.textContent).toContain('100 % no implica certeza poblacional'); + expect(warnings.textContent).toContain('suprimidos no representan tasas observadas de 0 %'); + if (dominio === 'tea') { + expect(warnings.textContent).toContain('Wilson al 95 %'); + expect(warnings.textContent).toContain('No se infieren intervalos cuando faltan'); + expect(warnings.textContent).toContain('denominadores pequeños'); + } else expect(warnings.textContent).toContain('no entregan intervalos Wilson efectivos'); + expect([...warnings.querySelectorAll('li')].map(p => p.textContent)) + .toEqual(fixture.componentInstance.interpretation); + button.focus(); button.click(); fixture.detectChanges(); + expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(false); + expect(button.getAttribute('aria-expanded')).toBe('true'); + button.click(); fixture.detectChanges(); + expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(true); + }); + it('UX-06E.P0.2 mantiene la oración mixta C3r y sus límites en ayuda cerrada', () => { + fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); state({ status: 'idle' }); + const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; + expect(section.querySelector('[hidden]')).not.toBeNull(); + expect(section.querySelector('button')).not.toBeNull(); + expect([...section.querySelectorAll('.methodology-detail li')].map(p => p.textContent)).toEqual([ + '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.', + 'Los puntos suprimidos no representan tasas observadas de 0 %.', + ]); + }); + it('UX-06E.P0.2 al alternar ayuda conserva Plotly, JSON y observadores sin react ni purge', async () => { + const original: PlotlyFigure = { data: [{ y: [42, null] }], layout: { annotations: [{ text: 'Advertencia íntegra del servicio' }] } }; + const copy = ready(original); await settle(); + const snapshot = JSON.stringify(original), copySnapshot = JSON.stringify(copy); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance; + const host = fixture.nativeElement.querySelector('.plot'); + const button = fixture.nativeElement.querySelector('.methodology-toggle'); + const calls = react.mock.calls.length, observers = observe.mock.calls.length; + for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); await settle(); } + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart); + expect(fixture.nativeElement.querySelector('.plot')).toBe(host); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + expect(react).toHaveBeenCalledTimes(calls); expect(observe).toHaveBeenCalledTimes(observers); + expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled(); + expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot); + }); + +}); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts new file mode 100644 index 0000000..fbfdd16 --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -0,0 +1,120 @@ +import { Component, Input, output, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatIconModule } from '@angular/material/icon'; +import { MatCardModule } from '@angular/material/card'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './indicadores.models'; +import { figureTitle } from './indicadores.presentation'; +import { figureDisplayName } from './indicadores-figure-labels'; +import { CategoryLabel } from './indicadores-axis-labels'; +import { figureIdentity, identityElementId } from './indicadores-identities'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; + +// The panel owns requests; the card receives the original and its presentation copy. +export interface FigureState { + status: 'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'; + figure?: PlotlyFigure; + presentationFigure?: PlotlyFigure; + footnotes?: readonly string[]; + categoryLabels?: readonly CategoryLabel[]; + minimumPlotWidth?: number; + message?: string; +} + +// Presentation only: contract semantics documented in G3 and G5C. +const CONTRACT_INTERPRETATIONS: Readonly
%{y:.1f}%
{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}
+Filtro general aplicado: {{ appliedSummary }}
+{{ title }}
+ @if (loading) {{{ value }}@if (unit) { {{ unit }} }
+ } + @if (temporalReference) {{{ temporalReference }}
} +{{ state }}
+ @if (informationLine) {{{ informationLine }}
} +Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.
} +@if (!types.includes(state.tipo)) {La granularidad del borrador ya no está publicada para este proyecto. Elige una granularidad disponible.
} +Consultando periodos disponibles…
} + @else if (availability.status === 'error') { +No se pudo completar la consulta de periodos disponibles.
+ + } @else if (!options.length) {Sin reportes disponibles para esta granularidad.
} + @if (entry.draft.mode === 'explicit' && unavailableSelection.length) {La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.
} +} +@if (!availability && entry.draft.mode !== 'todos') { +Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.
+{{ error }}
} +Selección en edición: {{ summary }}
+@if (!canApply) {Selecciona al menos un periodo válido para aplicar.
} +@if (!hasPending) {Sin cambios pendientes.
} +@if (hasPending) {Hay cambios sin aplicar.
} + +Filtro general aplicado: {{ appliedSummary }}
+%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})
IC %{error_y.array}
dato suprimido (conteo bajo)
dato suprimido (conteo bajo)
%{y}', '%{customdata[0]}', ['%{x}'], ['%{x}', null]])('fallback de hover desconocido o incompatible: %j', template => { + const figure = source(); figure.data[0]['hovertemplate'] = template; + expect(present(figure).figure.data).toEqual(figure.data); + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + expect(present(figure).categoryLabels).toEqual([]); + }); + it.each(['linear', 'date', 'log', 'multicategory'])('no adapta un eje simple declarado %s', type => { + const figure = source(); figure.layout['xaxis'] = { type }; + expect(present(figure).figure.data).toEqual(figure.data); + expect(present(figure).figure.layout['xaxis']).toEqual({ type }); + }); + it.each(['2025-01', '2025-S1', '2025-10-14T14:00:00', 'Primer semestre del año 2025', '1234567890123456789012345'])('no abrevia fechas, periodos ni texto numérico: %s', label => { + expect(abbreviateCategories([label], 8).get(label)).toBe(label); + }); + it.each([{ ticktext: ['Alias'] }, { tickmode: 'auto' }, { labelalias: { [long]: 'Alias' } }, { range: [0, 2] }, + { showticklabels: false }, { tickprefix: 'Grupo: ' }, { matches: 'x2' }])('respeta ticks/semántica explícita del eje: %j', axis => { + const figure = source(); figure.layout['xaxis'] = { type: 'category', ...axis }; + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + }); + it('respeta ticks heredados de una plantilla y una orientación publicada', () => { + const figure = source(); figure.layout['template'] = { layout: { xaxis: { ticktext: ['Alias'] } } }; + expect(present(figure).categoryLabels).toEqual([]); + delete figure.layout['template']; (figure.layout['xaxis'] as Record
%{x:.1f}%
%{x:.1f}%
Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: 2025-08-01
Uso exclusivo de investigación. No usar para decisiones clínicas.', + xref: 'paper', yref: 'paper', x: 0, y: -0.22, xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 }, + }]; + const result = present(figure); + expect(result.footnotes).toHaveLength(1); expect(result.figure.layout['annotations']).toEqual([]); + expect(result.categoryLabels[0].original).toBe(long); + }); + it.each(['cacu', 'cama'] as const)('mantiene la adaptación mensual %s con el perfil legible', dominio => { + const figure: PlotlyFigure = { data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01'], y: [null, 0], hovertemplate: hover }], layout: {} }; + const result = figurePresentation(figure, { ...selection, dominio, figura: 'fig_c1_puntos', tipoPeriodo: 'mes' }, READABLE_VISUAL_PROFILE); + expect(result.figure.layout['xaxis']).toMatchObject({ categoryarray: ['2025-01', '2025-03'], ticktext: ['2025-01', '2025-03'] }); + expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]); + }); +}); diff --git a/src/app/features/indicadores/indicadores-axis-labels.ts b/src/app/features/indicadores/indicadores-axis-labels.ts new file mode 100644 index 0000000..42de694 --- /dev/null +++ b/src/app/features/indicadores/indicadores-axis-labels.ts @@ -0,0 +1,191 @@ +import { PlotlyFigure } from './indicadores.models'; +import { AxisLabelOptions } from './indicadores-visual-profile'; + +export interface CategoryLabel { + readonly axis: 'x' | 'y'; + readonly abbreviated: string; + readonly original: string; +} + +const graphemes = new Intl.Segmenter('es', { granularity: 'grapheme' }); +const characters = (text: string) => [...graphemes.segment(text)].map(part => part.segment); +function record(value: unknown): value is Record
Dashboard de indicadores
+Explora las figuras de indicadores {{ domainLabels[dominio] }} generadas por el servicio de reportes.
+Filtros generales de {{ domainLabels[dominio] }}
+La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.
+Indicadores destacados
+La vista inicial busca el último dato visible de cada indicador. Al aplicar Todos con reporte se toma el último reporte disponible. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.
+Indicadores gráficos
+ @if (!catalogLoading() && !catalogError() && catalog().length) { +{{ catalog().length }} indicadores publicados
+ } +Cargando catálogo de indicadores…
+ } @else if (catalogError()) { +{{ catalogError() }}
+No hay indicadores disponibles en el catálogo.
++ @if (searchResults().active) { + @if (searchResults().count) { + {{ searchResults().count }} coincidencias de {{ catalog().length }} indicadores. Todos permanecen disponibles. + } @else { + No se encontraron coincidencias. El catálogo completo permanece disponible; los indicadores fijados aparecen primero. + } + } +
+ } +Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: 2025-08-01
Uso exclusivo de investigación. No usar para decisiones clínicas.', + xref: 'paper', yref: 'paper', x: 0, y: -0.22, xanchor: 'left', yanchor: 'top', + align: 'left', showarrow: false, font: { size: 11, color: '#52514e' }, +}; +function freezeDeep(value: unknown) { + if (value && typeof value === 'object') { + Object.values(value).forEach(freezeDeep); + Object.freeze(value); + } +} +function original(): PlotlyFigure { + return { + data: [{ type: 'bar', x: [['2025-S1', '2025-S2'], ['Área extensa de ejemplo', 'Otra área']], y: [null, 0], + marker: { color: ['gray', 'blue'] }, customdata: [[null, 'SUPRIMIDO'], [0, 10]], future: { untouched: true } }], + layout: { title: 'Título', xaxis: { type: 'multicategory', future: 17 }, yaxis: { range: [0, 100] }, + font: { future: 2 }, margin: { b: 150, future: 3 }, annotations: [structuredClone(footer)], future: { keep: true } }, + config: { staticPlot: false }, future: { keep: [1, null] }, + }; +} +describe('UX-07B perfiles y pies metodológicos', () => { + it('deriva desde el original congelado, preserva íntegramente trazas, frames y atributos desconocidos', () => { + const source = original(); source.frames = [{ name: 'frame', data: [{ y: [null, 0] }], layout: { annotations: [footer] }, future: 9 }]; + const before = structuredClone(source); freezeDeep(source); + const result = figurePresentation(source, selection, DEMO_VISUAL_PROFILE); + expect(source).toEqual(before); + expect(result.figure.data).toEqual(before.data); expect(result.figure.data).not.toBe(source.data); + expect(result.figure.frames).toEqual(before.frames); expect(result.figure.frames).not.toBe(source.frames); + expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']); + expect(result.figure.layout['future']).toEqual(before.layout['future']); + expect(result.figure.layout['xaxis']).toMatchObject({ type: 'multicategory', future: 17 }); + expect(result.figure.layout['font']).toMatchObject({ future: 2 }); + expect(result.figure.layout['margin']).toMatchObject({ b: 150, future: 3 }); + expect(result.footnotes).toEqual([]); // An animated annotation could otherwise reappear. + expect(result.figure.layout['annotations']).toEqual(before.layout['annotations']); + }); + it('aplica y revierte el perfil sin acumular estilos ni mutaciones del runtime', () => { + const source = original(), snapshot = structuredClone(source); + const base = figurePresentation(source, selection); + const demo = figurePresentation(source, selection, DEMO_VISUAL_PROFILE); + expect(demo.figure.layout).toMatchObject({ paper_bgcolor: '#f2f7fc', plot_bgcolor: '#ffffff', height: 640, + font: { family: 'Arial, sans-serif', size: 15 }, xaxis: { type: 'multicategory', showgrid: true, gridcolor: '#c6d7e8' } }); + demo.figure.data[0]['y'] = [999]; demo.figure.layout['annotations'] = [{ text: 'runtime' }]; + expect(figurePresentation(source, selection, BASE_VISUAL_PROFILE)).toEqual(base); + expect(source).toEqual(snapshot); + }); + it('extrae sólo el pie reconocido, preserva texto y orden sin duplicarlo en Plotly', () => { + const source = original(); const annotation = { text: 'Meta', x: 1, y: 90 }; + const second = { ...footer, text: footer.text.replace('Explicación sintética.', 'Segunda explicación.') }; + source.layout['annotations'] = [footer, annotation, second]; + const result = figurePresentation(source, selection); + expect(result.footnotes).toEqual([footer.text.replaceAll('
', '\n'), second.text.replaceAll('
', '\n')]); + expect(result.figure.layout['annotations']).toEqual([annotation]); + expect(source.layout['annotations']).toEqual([footer, annotation, second]); + expect(result.figure.layout['margin']).toEqual(source.layout['margin']); + }); + it.each([ + { xref: 'x' }, { yref: 'y' }, { y: -0.23 }, { x: 0.1 }, { showarrow: true }, + { xanchor: 'center' }, { yanchor: 'bottom' }, { align: 'center' }, { opacity: 0.4 }, + { font: { size: 11, future: true } }, { text: 'Nota desconocida' }, + { text: footer.text.replace('Explicación sintética.', 'Explicación sintética.') }, + { text: footer.text.replace('Explicación sintética.', '<script>') }, + { text: footer.text.replace('Explicación sintética.', '
', '
'); + source.layout['annotations'] = [{ ...footer, text }]; + expect(figurePresentation(source, selection).footnotes).toEqual([footer.text.replaceAll('
', '\n')]); + }); + it('reconoce los tres pies de fixtures sintéticos existentes sin alterar los datos', () => { + const tea = syntheticFigures.filter(item => item.name.startsWith('tea')); + expect(tea).toHaveLength(3); + for (const item of tea) { + const result = figurePresentation(item.figure, selection); + expect(result.footnotes).toHaveLength(1); + const annotations = item.figure.layout['annotations'] as { text: string }[]; + expect(result.footnotes[0]).toBe(annotations[0].text.replaceAll('
', '\n')); + expect(result.figure.layout['annotations']).toEqual([]); expect(result.figure.data).toEqual(item.figure.data); + } + }); + it('respeta dimensiones fijas y no crea ejes para figuras que no los publican', () => { + const source = { data: [], layout: { width: 800, height: 400, autosize: false } }; + const result = figurePresentation(source, selection, DEMO_VISUAL_PROFILE); + expect(result.figure.layout).toMatchObject({ width: 800, height: 400, autosize: false }); + expect(result.figure.layout['xaxis']).toBeUndefined(); + }); + it('reduce sólo la reserva conocida de un eje simple con automargin efectivo', () => { + const source = original(); source.data = [{ type: 'bar', x: ['Grupo'], y: [0] }]; + source.layout['xaxis'] = { type: 'category', automargin: true }; + expect(figurePresentation(source, selection).figure.layout['margin']).toMatchObject({ b: 80, future: 3 }); + expect(source.layout['margin']).toMatchObject({ b: 150 }); + for (const change of [{ xaxis: { type: 'multicategory', automargin: true } }, { legend: { y: -0.2 } }, + { legend: { orientation: 'h' } }, { legend: { y: 0, yanchor: 'top' } }, + { shapes: [] }, { xaxis2: { automargin: true } }, { height: 620 }, { xaxis: { type: 'category' } }]) { + expect(figurePresentation({ ...source, layout: { ...source.layout, ...change } }, selection).figure.layout['margin']).toMatchObject({ b: 150 }); + } + }); + it.each(['cacu', 'cama'] as const)('conserva adaptación mensual de %s con ambos perfiles', dominio => { + const source: PlotlyFigure = { data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01'], y: [null, 0] }], layout: { xaxis: { future: true } } }; + for (const profile of [BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE]) { + const result = figurePresentation(source, { ...selection, dominio, figura: 'fig_c1_puntos', tipoPeriodo: 'mes' }, profile); + expect(result.figure.layout['xaxis']).toMatchObject({ type: 'category', categoryarray: ['2025-01', '2025-03'], ticktext: ['2025-01', '2025-03'], automargin: true, future: true }); + expect(result.figure.data).toEqual(source.data); + } + }); +}); + +describe('UX-07D.2 pies documentales de familias verificadas', () => { + const note = { ...footer, text: 'Fuente: ejemplo sintético.' }; + const donutTotal = { text: '12', xref: 'paper', yref: 'paper', x: 0.5, y: 0.5, + showarrow: false, font: { size: 18, color: '#000000' } }; + const selected = (dominio: 'tea' | 'cacu' | 'cama', figura = 'fig_c2_barras'): FigureSelection => + ({ ...selection, dominio, figura }); + const figure = (annotations: unknown[] = [note]): PlotlyFigure => ({ + data: [{ type: 'bar', x: ['Categoría íntegra'], y: [null, 0], customdata: ['SUPRIMIDO', 'SIN_DATO'], + hovertemplate: '%{x}: %{y}', marker: { color: 'gray' }, future: { untouched: true } }], + layout: { margin: { b: 150 }, annotations, future: { untouched: true } }, + config: { displaylogo: false }, future: { unchanged: true }, + }); + it.each(['cacu', 'cama'] as const)('extrae pies de barras, donas y cajas %s con la firma completa', dominio => { + for (const id of ['fig_c2_barras', 'fig_c2_donas', 'fig_c3r_caja']) { + const source = figure([donutTotal, note]); + const result = figurePresentation(source, selected(dominio, id)); + expect(result.footnotes).toEqual([note.text]); + expect(result.figure.layout['annotations']).toEqual([donutTotal]); + expect(result.figure.data).toEqual(source.data); + expect(result.figure.layout['margin']).toEqual({ b: 150 }); + } + }); + it.each(['fig_c2_barras', 'fig_c2_donas'])('amplía TEA %s conservando su firma de fuente e investigación', id => { + expect(figurePresentation(figure([donutTotal, footer]), selected('tea', id)).footnotes) + .toEqual([footer.text.replaceAll('
', '\n')]); + expect(figurePresentation(figure(), selected('tea', id)).footnotes).toEqual([]); + }); + it.each(['Fuente: X.', 'Nota: ' + 'Texto extenso. '.repeat(100), 'Primera\n\nSegunda
Tercera
Cuarta', + ' Fuente: A & B · «Sin dato» ≤ 5 — 日本語\n '])('preserva texto independientemente de longitud o saltos: %s', text => { + const result = figurePresentation(figure([{ ...note, text }]), selected('cama')); + expect(result.footnotes).toEqual([text.replace(/
/gi, '\n')]); + expect(result.figure.layout['annotations']).toEqual([]); + }); + it.each([ + { text: 'Nota' }, { text: '' }, { text: '<img>' }, + { text: 'Fuente' }, { text: 'Texto & más' }, + { text: ' \n ' }, { text: 17 }, { xref: 'x' }, { yref: 'y' }, { yref: 'y domain' }, + { y: -0.23 }, { x: 0.5 }, { y: 0.5 }, { showarrow: true }, { ax: 0, ay: 20 }, + { xanchor: 'center' }, { yanchor: 'bottom' }, { align: 'center' }, { opacity: 0.5 }, + { visible: false }, { name: 'unknown' }, { font: { size: 11, future: true } }, + ])('conserva en Plotly marcado, geometría o atributos incompatibles: %j', change => { + const source = figure([{ ...note, ...change }]); + for (const domain of ['cacu', 'cama'] as const) { + const result = figurePresentation(source, selected(domain)); + expect(result.footnotes).toEqual([]); + expect(result.figure.layout['annotations']).toEqual(source.layout['annotations']); + } + }); + it('particiona cada ocurrencia una sola vez, en orden, conservando anotaciones internas', () => { + const internal = [{ text: 'Dato', xref: 'x', yref: 'y', x: 1, y: 3, showarrow: false }, + { text: 'Observación', x: 1, y: 3, showarrow: true }, donutTotal, + { text: 'Larga\n'.repeat(100), xref: 'paper', yref: 'paper', y: -0.22 }]; + const annotations = [note, internal[0], { ...note, text: 'Segunda
línea' }, ...internal.slice(1), note]; + const source = figure(annotations), before = structuredClone(source); freezeDeep(source); + const result = figurePresentation(source, selected('cacu')); + expect(result.footnotes).toEqual([note.text, 'Segunda\nlínea', note.text]); + expect(result.figure.layout['annotations']).toEqual(internal); + expect(result.footnotes.length + internal.length).toBe(annotations.length); + expect(source).toEqual(before); expect(result.figure.data).toEqual(before.data); + expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']); + expect(result.figure.layout['future']).toEqual(before.layout['future']); + }); + it('conserva animaciones, plantilla, ejes multicategoría y atributos desconocidos', () => { + const source = figure(); source.frames = [{ name: 'frame', layout: { annotations: [note] }, future: 1 }]; + source.layout['template'] = { layout: { annotations: [note] } }; + source.layout['xaxis'] = { type: 'multicategory', future: 3 }; + const result = figurePresentation(source, selected('cama')); + expect(result.footnotes).toEqual([]); expect(result.figure.frames).toEqual(source.frames); + expect(result.figure.layout['annotations']).toEqual([note]); + expect(result.figure.layout['template']).toEqual(source.layout['template']); + expect(result.figure.layout['xaxis']).toEqual(source.layout['xaxis']); + }); + it('no impone nuevas reducciones de márgenes ni cambia multicategoría al extraer', () => { + const source = figure(); source.layout['xaxis'] = { type: 'multicategory', automargin: true }; + source.layout['legend'] = { orientation: 'h', y: -0.3 }; source.layout['height'] = 620; + const result = figurePresentation(source, selected('cama')); + expect(result.footnotes).toEqual([note.text]); + expect(result.figure.layout['xaxis']).toEqual(source.layout['xaxis']); + expect(result.figure.layout['margin']).toEqual(source.layout['margin']); + expect(result.figure.layout['legend']).toEqual(source.layout['legend']); + expect(result.figure.layout['height']).toBe(620); + }); + it('no inventa pies para figuras sin notas ni familias desconocidas', () => { + expect(figurePresentation(figure([]), selected('cacu')).footnotes).toEqual([]); + const source = figure(); + for (const id of ['fig_c1_puntos', 'fig_desconocida']) { + const result = figurePresentation(source, selected('cacu', id)); + expect(result.footnotes).toEqual([]); expect(result.figure.layout['annotations']).toEqual([note]); + } + }); + it('deriva las mismas notas desde el original al alternar perfiles y anchos', () => { + const source = figure(), snapshot = structuredClone(source); + for (const profile of [BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, BASE_VISUAL_PROFILE]) { + for (const width of [230, 320, 768, 1440]) { + const result = figurePresentation(source, selected('cama'), profile, width); + expect(result.footnotes).toEqual([note.text]); + expect(result.figure.data).toEqual(snapshot.data); + } + } + expect(source).toEqual(snapshot); + }); +}); diff --git a/src/app/features/indicadores/indicadores-visual-profile.ts b/src/app/features/indicadores/indicadores-visual-profile.ts new file mode 100644 index 0000000..4cfb857 --- /dev/null +++ b/src/app/features/indicadores/indicadores-visual-profile.ts @@ -0,0 +1,31 @@ +// Presentation preferences. Trace colours retain their published semantic roles. +export interface AxisLabelOptions { + readonly enabled: boolean; + readonly maxCharacters?: number; + readonly preferWords?: boolean; + readonly preserveWhenFits?: boolean; + readonly multicategory?: 'preserve' | 'fit'; +} + +export interface FigureVisualProfile { + readonly axisLabels?: AxisLabelOptions; + readonly paperBackground?: string; + readonly plotBackground?: string; + readonly font?: Readonly<{ family?: string; size?: number; color?: string }>; + readonly margin?: Readonly<{ l?: number; r?: number; t?: number; b?: number; pad?: number }>; + readonly grid?: Readonly<{ color?: string; visible?: boolean }>; + readonly minimumHeight?: number; +} + +// Base keeps the received styling plus the dashboard's existing adaptations. +export const BASE_VISUAL_PROFILE: FigureVisualProfile = Object.freeze({}); +export const READABLE_VISUAL_PROFILE: FigureVisualProfile = Object.freeze({ + axisLabels: Object.freeze({ enabled: true, maxCharacters: 22, preferWords: true, preserveWhenFits: true, multicategory: 'fit' }), +}); +export const DEMO_VISUAL_PROFILE: FigureVisualProfile = Object.freeze({ + paperBackground: '#f2f7fc', plotBackground: '#ffffff', + font: Object.freeze({ family: 'Arial, sans-serif', size: 15, color: '#17324d' }), + margin: Object.freeze({ t: 30, pad: 8 }), + grid: Object.freeze({ color: '#c6d7e8', visible: true }), + minimumHeight: 640, +}); diff --git a/src/app/features/indicadores/indicadores.models.spec.ts b/src/app/features/indicadores/indicadores.models.spec.ts new file mode 100644 index 0000000..87c0c28 --- /dev/null +++ b/src/app/features/indicadores/indicadores.models.spec.ts @@ -0,0 +1,59 @@ +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); + }); +}); + +it('deduplica meses en orden estable y valida el calendario sin mezclar tipos', () => { + expect(parsePeriodos('2025-12, 2025-01,2025-12', 'mes')).toEqual(['2025-12', '2025-01']); + for (const value of ['', '2025-00', '2025-13', '2025-1', '2025-S1', '2025-01,2025-S1']) { + expect(parsePeriodos(value, 'mes')).toBeNull(); + } + expect(parsePeriodos('2025-S1,2025-01', 'semestre')).toBeNull(); +}); +it('no interpreta NaN ni null como porcentajes cero', () => { + expect(hasNoVisibleValues({ data: [{ y: [NaN, null] }], layout: {} })).toBe(true); +}); + +it.each(['0000-S1', '0000-S2', '10000-S1'])('rechaza año fuera de rango %s', value => { + expect(parsePeriodos(value)).toBeNull(); +}); +it.each(['0000-01', '10000-01', '2025-00', '2025-13'])('rechaza mes o año fuera de rango %s', value => { + expect(parsePeriodos(value, 'mes')).toBeNull(); +}); +it('acepta extremos canónicos de año', () => { + expect(parsePeriodos('0001-S1,9999-S2')).toEqual(['0001-S1', '9999-S2']); + expect(parsePeriodos('0001-01,9999-12', 'mes')).toEqual(['0001-01', '9999-12']); +}); + +it.each([ + [{ type: 'bar', orientation: 'h', x: [null], y: ['grupo'] }, true], + [{ type: 'bar', orientation: 'h', x: [0], y: ['grupo'] }, false], + [{ type: 'bar', y: [null], x: ['grupo'] }, true], + [{ type: 'bar', y: [0] }, false], + [{ type: 'pie', values: [null] }, true], + [{ type: 'pie', values: [0] }, false], + [{ type: 'pie', values: { bdata: 'AAAA' } }, false], + [{ type: 'bar', orientation: 'unknown', y: [null] }, false], + [{ type: 'bar', y: ['unknown'] }, false], +])('interpreta magnitudes de forma conservadora %j', (trace, empty) => { + expect(hasNoVisibleValues({ data: [trace as Record
con contexto', font: { size: 18 } }, xaxis: { gridcolor: 'gray' }, annotations: [{ text: 'Nota' }] }, + frames: [{ name: 'original' }], config: { displayModeBar: true }, future: { preserved: true }, +}; +describe('Dashboard presentation', () => { + it.each(['cacu', 'cama'] as const)('ordena ticks mensuales de %s sin cambiar observaciones ni HTTP', dominio => { + const original = structuredClone(monthly); + const adapted = presentationFigure(monthly, { ...selection, dominio }); + expect(monthly).toEqual(original); + expect(adapted.data).toEqual(original.data); + expect(adapted.data).not.toBe(monthly.data); + expect(adapted.frames).toEqual(original.frames); + expect(adapted.config).toEqual(original.config); + expect(adapted['future']).toEqual(original['future']); + expect(adapted.layout['annotations']).toEqual(original.layout['annotations']); + expect(adapted.layout['xaxis']).toEqual({ gridcolor: 'gray', type: 'category', categoryorder: 'array', categoryarray: ['2025-01', '2025-02', '2025-03'], tickmode: 'array', tickvals: ['2025-01', '2025-02', '2025-03'], ticktext: ['2025-01', '2025-02', '2025-03'], tickangle: 0, automargin: true }); + expect(figureTitle(monthly, 'catálogo')).toBe('Título completo
con contexto'); + expect(adapted.layout['title']).toEqual({ text: '', font: { size: 18 } }); + }); + it.each(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c3r_caja'])('preserva ejes y trazas de %s', figura => { + const adapted = presentationFigure(monthly, { ...selection, figura }); + expect(adapted.layout['xaxis']).toEqual(monthly.layout['xaxis']); + expect(adapted.data).toEqual(monthly.data); + }); + it('conserva semestres, TEA, representaciones binarias y figuras vacías', () => { + for (const input of [monthly, { data: [], layout: {} }, { data: [{ type: 'scatter', mode: 'markers', x: ['2025-S1', '2025-S2'], y: { dtype: 'f8', bdata: 'AAAAAAAAVEAAAAAAAABJQA==' } }], layout: { xaxis: { type: 'category' } } }] as PlotlyFigure[]) { + const original = structuredClone(input); + for (const request of [{ ...selection, tipoPeriodo: 'semestre' as const }, { ...selection, dominio: 'tea' as const }, selection]) { + const adapted = presentationFigure(input, request); + expect(adapted.data).toEqual(original.data); + if (input !== monthly || request !== selection) expect(adapted.layout['xaxis']).toEqual(original.layout['xaxis']); + } + expect(input).toEqual(original); + } + }); + it('conserva títulos string y usa catálogo cuando no hay título', () => { + expect(figureTitle({ data: [], layout: { title: 'Título completo' } }, 'fallback')).toBe('Título completo'); + expect(figureTitle({ data: [], layout: { title: { text: '' } } }, 'Catálogo')).toBe('Catálogo'); + }); +}); diff --git a/src/app/features/indicadores/indicadores.presentation.ts b/src/app/features/indicadores/indicadores.presentation.ts new file mode 100644 index 0000000..0b5bd89 --- /dev/null +++ b/src/app/features/indicadores/indicadores.presentation.ts @@ -0,0 +1,161 @@ +import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { BASE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; +import { applyAxisLabels, categoryMinimumWidth, CategoryLabel } from './indicadores-axis-labels'; + +export interface FigurePresentation { + figure: PlotlyFigure; + // Plain text, including original line breaks; never an HTML fragment. + footnotes: readonly string[]; + categoryLabels: readonly CategoryLabel[]; + minimumPlotWidth?: number; +} + +const TEA_FOOTER_FIGURES = new Set(['fig_c1_grupos', 'fig_c1_puntos', 'fig_c2_apiladas', 'fig_c3r_caja']); +// Verified published families share the complete documentary footer geometry. +// Donut totals (paper 0.5, 0.5), data labels and callouts do not match it. +const DISTRIBUTION_FOOTER_FIGURES = new Set(['fig_c2_barras', 'fig_c2_donas', 'fig_c3r_caja']); +const FOOTER_KEYS = new Set(['text', 'xref', 'yref', 'x', 'y', 'xanchor', 'yanchor', 'align', 'showarrow', 'font']); +function record(value: unknown): value is Record
/gi, '\n'); + // Rich markup, encoded markup, links and unknown formatting stay in Plotly. + if (!text.trim() || /[<>]|&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);/i.test(text)) return undefined; + // CaCu/CaMa publish plain documentary text in this exact exterior slot. + // No length threshold, keywords or indicator-name inference is involved. + if (!tea) return text; + // Retain UX-07B's additional TEA source/restriction guarantees. + const lines = text.split('\n'); + if (lines.length < 3 || !lines[0].trim() + || !/^Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: \d{4}-\d{2}-\d{2}$/.test(lines.at(-2)!) + || lines.at(-1) !== 'Uso exclusivo de investigación. No usar para decisiones clínicas.') return undefined; + return text; +} + +function applyVisualProfile(figure: PlotlyFigure, profile: FigureVisualProfile, availableWidth?: number) { + const layout = figure.layout; + if (profile.paperBackground !== undefined) layout['paper_bgcolor'] = profile.paperBackground; + if (profile.plotBackground !== undefined) layout['plot_bgcolor'] = profile.plotBackground; + if (profile.font) { + // A larger inherited legend/tick font can hide multicategory labels on + // narrow cards. Bound only the optional profile enlargement, not the source. + const narrowCategories = profile.axisLabels?.enabled && availableWidth !== undefined && availableWidth > 0 && availableWidth < 360 + && record(layout['xaxis']) && ['category', 'multicategory'].includes(String(layout['xaxis']['type'])) + && figure.data.every(trace => ['scatter', 'bar'].includes(String(trace['type']))); + layout['font'] = { ...(record(layout['font']) ? layout['font'] : {}), ...profile.font, + ...(narrowCategories && profile.font.size !== undefined && profile.font.size > 12 ? { size: 12 } : {}) }; + } + if (profile.margin) layout['margin'] = { ...(record(layout['margin']) ? layout['margin'] : {}), ...profile.margin }; + if (profile.grid) { + for (const key of Object.keys(layout).filter(key => /^[xy]axis\d*$/.test(key))) { + const axis = layout[key]; + if (!record(axis)) continue; + layout[key] = { ...axis, + ...(profile.grid.color !== undefined ? { gridcolor: profile.grid.color } : {}), + ...(profile.grid.visible !== undefined ? { showgrid: profile.grid.visible } : {}), + }; + } + } + // Respect fixed-size figures and animated layouts. No width feedback loop. + if (profile.minimumHeight !== undefined && Number.isFinite(profile.minimumHeight) && profile.minimumHeight > 0 + && !figure.frames?.length && layout['autosize'] !== false && layout['width'] === undefined + && (layout['height'] === undefined || typeof layout['height'] === 'number')) { + layout['height'] = Math.max(typeof layout['height'] === 'number' ? layout['height'] : 620, profile.minimumHeight); + } +} + +function relaxFooterMargin(figure: PlotlyFigure) { + const layout = figure.layout, axis = layout['xaxis'], margin = layout['margin']; + const template = layout['template']; + const templateLayout = record(template) ? template['layout'] : undefined; + const templateAxis = record(templateLayout) ? templateLayout['xaxis'] : undefined; + const legend = layout['legend']; + // Only the known footer reserve on a single, automatic Cartesian axis. + // Multicategory ticks, lower legends and other paper objects keep their space. + if (!record(axis) || !record(margin) || margin['b'] !== 150 + || (axis['automargin'] !== true && !(record(templateAxis) && templateAxis['automargin'] === true)) + || axis['type'] === 'multicategory' || figure.data.some(trace => !['scatter', 'bar', 'box'].includes(String(trace['type'])) + || (Array.isArray(trace['x']) && trace['x'].some(Array.isArray))) + || Object.keys(layout).some(key => /^[xy]axis[1-9]\d*$/.test(key)) + || ['shapes', 'images', 'sliders', 'updatemenus'].some(key => layout[key] !== undefined) + || (record(legend) && (legend['orientation'] === 'h' || (typeof legend['y'] === 'number' && legend['y'] <= 0))) + || layout['autosize'] === false || layout['width'] !== undefined || layout['height'] !== undefined) return; + layout['margin'] = { ...margin, b: 80 }; +} + +export function figureTitle(figure: PlotlyFigure, fallback: string): string { + const title = figure.layout['title']; + if (typeof title === 'string' && title.trim()) return title; + if (title && typeof title === 'object' && 'text' in title + && typeof title.text === 'string' && title.text.trim()) return title.text; + return fallback; +} + +// Adapt only the dashboard copy; HTTP figures and all observations stay intact. +export function figurePresentation(original: PlotlyFigure, selection: FigureSelection, + profile: FigureVisualProfile = BASE_VISUAL_PROFILE, availableWidth?: number): FigurePresentation { + const figure = structuredClone(original); + const title = figure.layout['title']; + figure.layout['title'] = title && typeof title === 'object' ? { ...title, text: '' } : { text: '' }; + if ((selection.dominio === 'cacu' || selection.dominio === 'cama') + && selection.figura === 'fig_c1_puntos' && selection.tipoPeriodo === 'mes' + && figure.data.length > 0 + && figure.data.every(trace => trace['type'] === 'scatter' && trace['mode'] === 'markers' + && Array.isArray(trace['x']) && trace['x'].length > 0 + && trace['x'].every(x => typeof x === 'string' && /^[0-9]{4}-(0[1-9]|1[0-2])$/.test(x)))) { + const periods = [...new Set(figure.data.flatMap(trace => trace['x'] as string[]))].sort(); + figure.layout['xaxis'] = { + ...(figure.layout['xaxis'] as Record
%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})
%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})
Base depurada del proyecto TEA \u00b7 Centro M\u00e9dico ISSSTELE\u00d3N \u2013 UANL \u00b7 Fecha de corte: 2025-08-01
Uso exclusivo de investigaci\u00f3n. No usar para decisiones cl\u00ednicas.", + "x": 0, + "xanchor": "left", + "xref": "paper", + "y": -0.22, + "yanchor": "top", + "yref": "paper" + } + ] + } + } + }, + { + "name": "cacu_C1", + "figure": { + "data": [ + { + "hovertemplate": "%{x}
dato suprimido (conteo bajo)
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})
dato suprimido (conteo bajo)
%{x}
%{y:.1f}% (%{customdata})
%{x}
%{y:.1f}% (%{customdata})
%{x}
%{y:.1f}% (%{customdata})
%{x}
%{y:.1f}% (%{customdata})
Base depurada del proyecto TEA \u00b7 Centro M\u00e9dico ISSSTELE\u00d3N \u2013 UANL \u00b7 Fecha de corte: 2025-08-01
Uso exclusivo de investigaci\u00f3n. No usar para decisiones cl\u00ednicas.", + "x": 0, + "xanchor": "left", + "xref": "paper", + "y": -0.22, + "yanchor": "top", + "yref": "paper" + } + ] + } + } + }, + { + "name": "tea_C3r", + "figure": { + "data": [ + { + "customdata": [ + 7 + ], + "hovertemplate": "2025-S1
%{x}
n = %{customdata}
Base depurada del proyecto TEA \u00b7 Centro M\u00e9dico ISSSTELE\u00d3N \u2013 UANL \u00b7 Fecha de corte: 2025-08-01
Uso exclusivo de investigaci\u00f3n. No usar para decisiones cl\u00ednicas.", + "x": 0, + "xanchor": "left", + "xref": "paper", + "y": -0.22, + "yanchor": "top", + "yref": "paper" + } + ] + } + } + } +]; diff --git a/src/app/shared/plotly/plotly-chart.spec.ts b/src/app/shared/plotly/plotly-chart.spec.ts new file mode 100644 index 0000000..75b325d --- /dev/null +++ b/src/app/shared/plotly/plotly-chart.spec.ts @@ -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(); + }); +}); + + diff --git a/src/app/shared/plotly/plotly-chart.ts b/src/app/shared/plotly/plotly-chart.ts new file mode 100644 index 0000000..e5015ab --- /dev/null +++ b/src/app/shared/plotly/plotly-chart.ts @@ -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') {
No se pudo representar la figura. Puedes reintentar.
+
+