From 11337679dc530a8b362f5262761b8a4af9ef54d7 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 15 Oct 2026 13:45:59 -0600 Subject: [PATCH] =?UTF-8?q?feat(indicadores):=20mejorar=20presentaci=C3=B3?= =?UTF-8?q?n=20y=20legibilidad=20de=20figuras=20multidominio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicador-catalog-card.spec.ts | 41 ++++ .../indicadores/indicador-catalog-card.ts | 12 +- .../indicadores/indicador-figure-card.html | 19 +- .../indicadores/indicador-figure-card.scss | 19 ++ .../indicadores/indicador-figure-card.spec.ts | 78 +++++- .../indicadores/indicador-figure-card.ts | 16 +- .../indicador-figure-panel.spec.ts | 80 ++++++ .../indicadores/indicador-figure-panel.ts | 50 +++- .../indicadores-axis-labels.spec.ts | 230 ++++++++++++++++++ .../indicadores/indicadores-axis-labels.ts | 191 +++++++++++++++ .../indicadores-figure-labels.spec.ts | 28 +++ .../indicadores/indicadores-figure-labels.ts | 17 ++ .../indicadores/indicadores-page.spec.ts | 4 +- .../indicadores-visual-profile.spec.ts | 228 +++++++++++++++++ .../indicadores/indicadores-visual-profile.ts | 31 +++ .../indicadores/indicadores.presentation.ts | 134 +++++++++- src/app/shared/plotly/plotly-chart.spec.ts | 26 ++ src/app/shared/plotly/plotly-chart.ts | 18 +- 18 files changed, 1197 insertions(+), 25 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-axis-labels.spec.ts create mode 100644 src/app/features/indicadores/indicadores-axis-labels.ts create mode 100644 src/app/features/indicadores/indicadores-figure-labels.spec.ts create mode 100644 src/app/features/indicadores/indicadores-figure-labels.ts create mode 100644 src/app/features/indicadores/indicadores-visual-profile.spec.ts create mode 100644 src/app/features/indicadores/indicadores-visual-profile.ts diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts index 0327366..1427933 100644 --- a/src/app/features/indicadores/indicador-catalog-card.spec.ts +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -32,6 +32,47 @@ describe('UX-06E.D.2.1 selector de representación', () => { function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); } function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); } + it.each(['C1', 'C2', 'C3r'])('UX-07A omite IDs y contrato %s y conserva título y contador', contrato => { + fixture.componentRef.setInput('indicador', { id: 'K05_eeg_20_minutos', titulo: 'EEG con ≥ 20 min de registro', contrato, + figuras: ['fig_c1_grupos', 'fig_c1_puntos'], tipos_periodo: ['semestre'] }); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro'); + expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull(); + expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); + // The internal panel heading is deliberately visually hidden and retains identity. + const copy = fixture.nativeElement.cloneNode(true) as HTMLElement; + copy.querySelectorAll('.visually-hidden').forEach(node => node.remove()); + expect(copy.textContent).not.toMatch(/K05_eeg_20_minutos|Contrato|fig_c1_/); + expect(fixture.componentInstance.indicador.id).toBe('K05_eeg_20_minutos'); + expect(fixture.componentInstance.indicador.contrato).toBe(contrato); + http.expectNone(() => true); + }); + it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => { + fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']); + expect(select().options.map(option => [option.value, option.viewValue])).toEqual([ + ['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'], + ['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'], + ]); + http.expectNone(() => true); + open(); request('fig_c1_grupos').flush({ data: [], layout: {} }); + for (const [id, label] of [ + ['fig_c2_apiladas', 'Barras apiladas'], + ['fig_c2_barras', 'Barras'], + ['fig_c2_donas', 'Donas'], + ['fig_c9_futura', 'Representación 5'], + ]) { + select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges(); + const pending = request(id); + expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id); + expect(pending.request.params.get('tema')).toBe('claro'); + expect(pending.request.params.get('periodos')).toBe('2025-S1'); + pending.flush({ data: [], layout: {} }); fixture.detectChanges(); + expect(fixture.componentInstance.selectedFigure).toBe(id); + expect(TestBed.inject(IndicadoresMemory).figure('cacu', 'i')).toBe(id); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`); + } + http.expectNone(() => true); + }); it('una opción publicada está deshabilitada y sólo consulta esa figura', () => { fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true); expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 4fc63e5..f35a152 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -8,6 +8,8 @@ import { Dominio, Indicador, Tema } from './indicadores.models'; import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities'; import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { figureDisplayName } from './indicadores-figure-labels'; +import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; @Component({ selector: 'app-indicador-catalog-card', @@ -17,7 +19,6 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';

{{ indicador.titulo }}

-

{{ indicador.id }}

- + @if (selectedFigure) { Representación gráfica - @for (figure of indicador.figuras; track figure) { {{ figure }} } + @for (figure of indicador.figuras; track figure) { {{ figureDisplayName(figure, indicador.figuras) }} }
@for (figure of [selectedFigure]; track panelIdentity(figure)) { - + }
} @else {

El indicador no tiene figuras disponibles.

} @@ -53,7 +54,6 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; .card-identity { min-width: 0; } h2, p { overflow-wrap: anywhere; } h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; } - .indicator-id { margin: var(--issste-space-1) 0 0; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } .pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto; min-width: 48px; min-height: 48px; color: var(--issste-text); } .pin-toggle mat-icon { flex-shrink: 0; } @@ -65,11 +65,13 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; `, }) export class IndicadorCatalogCard implements OnChanges { + readonly figureDisplayName = figureDisplayName; @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) indicador!: Indicador; @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() pinned = false; + @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; readonly pinChanged = output(); @ViewChild('visibilityRegion') visibilityRegion?: ElementRef; readonly host = inject>(ElementRef); diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index e295488..7378b91 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -31,13 +31,28 @@

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

}

-

Figura: {{ figuraId }}

+

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) {
- + + @if (state.footnotes?.length) { +
+ @for (note of state.footnotes; track $index) {

{{ note }}

} +
+ } + @if (state.categoryLabels?.length) { +
+ Nombres completos de las categorías +
    + @for (label of state.categoryLabels; track $index) { +
  • {{ label.abbreviated }}: {{ label.original }}
  • + } +
+
+ }
} diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index ac364c4..c62cf22 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -28,6 +28,25 @@ .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } +.methodological-footnotes { + padding: .75rem 1rem 1rem; + min-width: 0; + max-width: 100%; + box-sizing: border-box; + font: var(--mat-sys-body-small); + font-family: var(--issste-font-body); + font-size: .875rem; + color: var(--issste-text-secondary); + line-height: 1.5; +} +.dark .methodological-footnotes { color: var(--mat-sys-outline); } +.methodological-footnotes p { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; } +.methodological-footnotes p + p { margin-top: .75rem; } +.category-labels { padding: 0 1rem 1rem; overflow-wrap: anywhere; font: var(--mat-sys-body-small); line-height: 1.5; } +.category-labels summary { cursor: pointer; min-height: 44px; align-content: center; } +.category-labels summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } +.category-labels ul { margin: .25rem 0 0; padding-left: 1.25rem; } +.category-labels li + li { margin-top: .5rem; } .figure-skeleton { min-height: 620px; display: flex; flex-direction: column; } .skeleton { flex: 1; margin: 0 1.25rem 1.25rem; border-radius: var(--issste-radius); background: var(--issste-border); opacity: .35; } diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index 80640b2..8df5a30 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -46,6 +46,57 @@ describe('IndicadorFigureCard', () => { state({ status: 'ready', figure: original, presentationFigure: copy }); return copy; } + it.each(['tea', 'cacu', 'cama'])('UX-07D.2 presenta notas %s como texto seguro inmediatamente después del gráfico', dominio => { + fixture.componentRef.setInput('dominio', dominio); + const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} }; + const notes = ['Fuente: A & B\nSegunda línea', '', 'ID_'.repeat(150)]; + state({ status: 'ready', figure: original, presentationFigure: original, footnotes: notes, + minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] }); + const section = fixture.nativeElement.querySelector('.methodological-footnotes') as HTMLElement; + expect(section.getAttribute('aria-label')).toBe('Notas al pie de la figura'); + expect([...section.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes); + expect(section.querySelector('img, script, a')).toBeNull(); + expect(section.previousElementSibling?.tagName).toBe('APP-PLOTLY-CHART'); + expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull(); + expect(section.nextElementSibling?.classList.contains('category-labels')).toBe(true); + for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) { + state({ status }); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + } + state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] }); + expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota nueva'); + }); + it('UX-07D conserva el ancho desplazable durante carga y lo revierte sin recrear el host', async () => { + const original: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: {} }; + state({ status: 'ready', figure: original, presentationFigure: original, minimumPlotWidth: 598 }); await settle(); + const chart = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement; + const host = chart.querySelector('.plot'); + expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px'); + expect(chart.querySelector('.plot-viewport')!.getAttribute('tabindex')).toBe('0'); + state({ status: 'loading' }); await settle(); + expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px'); + state({ status: 'ready', figure: original, presentationFigure: original }); await settle(); + expect(chart.style.getPropertyValue('--plot-min-width')).toBe(''); + expect(chart.querySelector('.plot')).toBe(host); expect(original.data[0]['y']).toEqual([0, null, 20]); + }); + it('UX-07C ofrece nombres completos en un details nativo sin rerenderizar Plotly ni ocultar notas', async () => { + const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} }; + const copy = presentationFigure(original, { indicador: 'i1', figura: 'fig_c1_puntos', tema: 'claro' }); + state({ status: 'ready', figure: original, presentationFigure: copy, + categoryLabels: [{ axis: 'x', abbreviated: 'Fármaco…', original: 'Fármaco de riesgo para el neurodesarrollo' }], + footnotes: ['Nota metodológica siempre visible'] }); await settle(); + const details = fixture.nativeElement.querySelector('details') as HTMLDetailsElement; + const summary = details.querySelector('summary')!; + expect(summary.textContent).toContain('Nombres completos'); expect(details.open).toBe(false); + expect(details.querySelector('li')!.textContent).toContain('Fármaco de riesgo para el neurodesarrollo'); + const plot = fixture.nativeElement.querySelector('.plot'), calls = react.mock.calls.length; + summary.focus(); summary.click(); fixture.detectChanges(); await settle(); + expect(details.open).toBe(true); expect(document.activeElement).toBe(summary); + expect(react).toHaveBeenCalledTimes(calls); expect(fixture.nativeElement.querySelector('.plot')).toBe(plot); + expect(fixture.nativeElement.querySelector('.methodological-footnotes').closest('details')).toBeNull(); + state({ status: 'loading' }); expect(fixture.nativeElement.querySelector('.category-labels')).toBeNull(); + expect(fixture.nativeElement.querySelector('.plot').closest('[hidden]')).not.toBeNull(); + }); it('muestra carga, error y emite reintento sin coordinar HTTP', () => { state({ status: 'loading' }); expect(fixture.nativeElement.querySelector('mat-card').getAttribute('aria-busy')).toBe('true'); @@ -65,7 +116,7 @@ describe('IndicadorFigureCard', () => { fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('El indicador no tiene figuras disponibles'); }); - it('presenta título del JSON, identificación secundaria y conserva datos incluso si Plotly los muta', async () => { + it('presenta título del JSON, nombre amigable y conserva datos incluso si Plotly los muta', async () => { const original: PlotlyFigure = { data: [{ type: 'scatter', y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], x: { dtype: 'i1', bdata: 'AAE=' } }], layout: { title: { text: 'Título publicado', font: { size: 20 } }, annotations: [{ text: 'Nota de supresión' }] }, @@ -79,7 +130,8 @@ describe('IndicadorFigureCard', () => { const copy = ready(original); await settle(); expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Título publicado'); - expect(fixture.nativeElement.querySelector('.figure-id').textContent).toContain('fig_c1_puntos'); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe('Figura: Puntos'); + expect(fixture.nativeElement.textContent).not.toContain('fig_c1_puntos'); expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.figure).toBe(copy); expect(JSON.stringify(original)).toBe(snapshot); expect(copy.data).toEqual(original.data); @@ -94,6 +146,19 @@ describe('IndicadorFigureCard', () => { await settle(); expect(fixture.nativeElement.textContent).not.toContain('No hay valores visibles'); }); + it('UX-07B representa pies como texto seguro, sin duplicación ni notas genéricas', async () => { + const figure = { data: [{ y: [42] }], layout: {} }; + const note = 'Primera línea\n\nAviso completo'; + state({ status: 'ready', figure, presentationFigure: figure, footnotes: [note] }); await settle(); + const notes = fixture.nativeElement.querySelector('.methodological-footnotes'); + expect(notes.textContent).toBe(note); expect(notes.querySelector('img')).toBeNull(); + expect(fixture.nativeElement.querySelectorAll('.methodological-footnotes p')).toHaveLength(1); + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.showNotes).toBe(false); + state({ status: 'loading' }); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + state({ status: 'ready', figure, presentationFigure: figure, footnotes: [] }); await settle(); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + }); it.each(['cacu', 'cama'])('conserva advertencias específicas de %s durante la carga', dominio => { fixture.componentRef.setInput('dominio', dominio); state({ status: 'loading' }); @@ -174,6 +239,15 @@ describe('IndicadorFigureCard', () => { expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls')) .toBe(fixture.nativeElement.querySelector('.methodology-detail').id); }); + it.each([ + ['fig_c2_barras', 'Barras'], + ['fig_c2_donas', 'Donas'], + ])('UX-07D.1 identifica %s con el nombre %s en la tarjeta de figura', (id, label) => { + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', figuras: [id] }); + fixture.componentRef.setInput('figuraId', id); + ready({ data: [], layout: {} }); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`); + }); it.each(['fig_c3r_cajas', 'desconocida'])('UX-06E.P0.2 mantiene íntegra la interpretación %s dentro de la ayuda', figura => { fixture.componentRef.setInput('figuraId', figura); if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' }); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index b5eb099..fbfdd16 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -5,6 +5,8 @@ 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'; @@ -13,6 +15,9 @@ export interface FigureState { status: 'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'; figure?: PlotlyFigure; presentationFigure?: PlotlyFigure; + footnotes?: readonly string[]; + categoryLabels?: readonly CategoryLabel[]; + minimumPlotWidth?: number; message?: string; } @@ -49,9 +54,13 @@ export class IndicadorFigureCard { // Keep the mounted host's last presentation only. The template hides it whenever // it is not the current result; this is neither applied state nor a results cache. chartFigure?: PlotlyFigure; + chartMinimumWidth?: number; @Input({ required: true }) set state(value: FigureState) { this.currentState = value; - if (value.status === 'ready') this.chartFigure = value.presentationFigure; + if (value.status === 'ready') { + this.chartFigure = value.presentationFigure; + this.chartMinimumWidth = value.minimumPlotWidth; + } } get state() { return this.currentState; } @Input() selected?: Indicador; @@ -59,6 +68,10 @@ export class IndicadorFigureCard { @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) tema!: Tema; readonly retry = output(); + readonly plotWidthChanged = output(); + reportPlotWidth(width: unknown) { + if (typeof width === 'number') this.plotWidthChanged.emit(width); + } readonly methodologyExpanded = signal(false); get methodologyId(): string { return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology'; @@ -83,6 +96,7 @@ export class IndicadorFigureCard { } readonly hasNoVisibleValues = hasNoVisibleValues; readonly figureTitle = figureTitle; + readonly figureDisplayName = figureDisplayName; get interpretation(): readonly string[] { const contract = this.contract; diff --git a/src/app/features/indicadores/indicador-figure-panel.spec.ts b/src/app/features/indicadores/indicador-figure-panel.spec.ts index 3badbd6..570d589 100644 --- a/src/app/features/indicadores/indicador-figure-panel.spec.ts +++ b/src/app/features/indicadores/indicador-figure-panel.spec.ts @@ -10,6 +10,7 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorFigureCard } from './indicador-figure-card'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) class ChartStub { figure?: PlotlyFigure; } @@ -47,6 +48,60 @@ describe('IndicadorFigurePanel', () => { function load() { fixture.detectChanges(); } function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } + it('UX-07D.2 conserva notas al cambiar perfil/ancho y elimina resultados obsoletos durante carga', () => { + fixture.componentRef.setInput('dominio', 'cama'); + fixture.componentRef.setInput('indicador', { ...catalog[0], figuras: ['fig_c2_barras'], contrato: 'C2' }); + fixture.componentRef.setInput('figuraId', 'fig_c2_barras'); + const request = () => http.expectOne(req => req.url.includes('/cama/indicadores/') && req.url.includes('/figuras/')); + const response = (text: string): PlotlyFigure => ({ data: [{ type: 'bar', x: ['A'], y: [0] }], + layout: { annotations: [{ text, xref: 'paper', yref: 'paper', x: 0, y: -0.22, + xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 } }] } }); + load(); request().flush(response('Nota vigente')); fixture.detectChanges(); + for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE]) { + fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges(); + for (const width of [230, 320, 768, 1440]) page.updatePlotWidth(width); + expect(page.result().footnotes).toEqual(['Nota vigente']); http.expectNone(() => true); + } + page.requestFigure(); const old = request(); fixture.detectChanges(); + expect(page.result().footnotes).toBeUndefined(); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); + expect(old.cancelled).toBe(true); + const current = request(); current.flush(response('Nota del periodo actual')); fixture.detectChanges(); + expect(page.result().footnotes).toEqual(['Nota del periodo actual']); + expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota del periodo actual'); + http.expectNone(() => true); + }); + + it('UX-07C alterna etiquetas desde el original sin HTTP, conserva el host y restaura hover/categorías', () => { + const label = 'Fármaco de riesgo para el neurodesarrollo'; + const received: PlotlyFigure = { data: [{ type: 'bar', x: [label], y: [0], customdata: [null], + hovertemplate: '%{x}
%{y:.1f}%' }], layout: { xaxis: { type: 'category' } } }; + load(); figure().flush(received); fixture.detectChanges(); + const before = structuredClone(received), host = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; + expect(page.result().categoryLabels?.[0].original).toBe(label); + expect(fixture.nativeElement.querySelector('.category-labels')).not.toBeNull(); + page.updatePlotWidth(1400); fixture.detectChanges(); + expect(page.result().categoryLabels).toEqual([]); + const unchanged = page.result(); + for (const width of [1400.7, 1399, 1350, 0, NaN]) page.updatePlotWidth(width); + expect(page.result()).toBe(unchanged); + page.updatePlotWidth(320); fixture.detectChanges(); + expect(page.result().categoryLabels).toHaveLength(1); + http.expectNone(() => true); + for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE, BASE_VISUAL_PROFILE]) { + fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges(); + http.expectNone(() => true); + expect(page.result().figure).toEqual(before); + expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(host); + if (profile === BASE_VISUAL_PROFILE) { + expect(page.result().presentationFigure?.data).toEqual(before.data); + expect(page.result().categoryLabels).toEqual([]); + } else expect(page.result().categoryLabels).toHaveLength(1); + } + expect(received).toEqual(before); + }); + 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']], @@ -132,6 +187,31 @@ describe('IndicadorFigurePanel', () => { expect(all.request.params.has('periodos')).toBe(false); all.flush({ data: [], layout: {} }); }); + it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => { + load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 }; + figure().flush(received); fixture.detectChanges(); + const base = structuredClone(page.result().presentationFigure); + const original = page.result().figure; + const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; + const applied = page.applied; + fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges(); + expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc'); + expect(page.result().figure).toBe(original); expect(page.applied).toBe(applied); + expect(page.result().presentationFigure?.data).toEqual(received.data); + expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart); + http.expectNone(() => true); + fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges(); + expect(page.result().presentationFigure).toEqual(base); + expect(page.result().figure).toEqual(received); http.expectNone(() => true); + }); + it('UX-07B cambiar perfil durante carga no cancela ni inicia solicitudes', () => { + load(); const pending = figure(); + fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges(); + expect(pending.cancelled).toBe(false); http.expectNone(() => true); + pending.flush({ data: [], layout: {} }); fixture.detectChanges(); + expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc'); + http.expectNone(() => true); + }); it('cancela figuras al cambiar tema rápidamente', () => { load(); const old = figure(); diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index b605e7b..c1c3b6a 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -1,10 +1,11 @@ -import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core'; +import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; import { Dominio, FigureSelection, Indicador, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -import { presentationFigure } from './indicadores.presentation'; +import { figurePresentation } from './indicadores.presentation'; +import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory'; import { httpMessage } from './indicadores-http'; @@ -18,7 +19,7 @@ import { figureIdentity, identityElementId } from './indicadores-identities';

{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}

Filtro general aplicado: {{ appliedSummary }}

+ [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" /> `, styles: ` @@ -38,6 +39,9 @@ export class IndicadorFigurePanel implements OnChanges { @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() visible = true; + @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; + private readySelection?: FigureSelection; + private plotWidth?: number; private readonly service = inject(IndicadoresService); private readonly destroyRef = inject(DestroyRef); private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>(); @@ -49,7 +53,7 @@ export class IndicadorFigurePanel implements OnChanges { constructor() { this.figureRequests.pipe(switchMap(request => request ? defer(() => this.service.figura(request.selection)).pipe( - map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, request.selection) }) as FigureState), + map(figure => this.present(figure, request.selection)), catchError(error => of({ status: 'error', message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 @@ -57,17 +61,43 @@ export class IndicadorFigurePanel implements OnChanges { ? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''), } as FigureState)), startWith({ status: 'loading' } as FigureState), - map(state => ({ state, revision: request.revision, generation: request.generation }))) - : of({ state: { status: 'idle' } as FigureState, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef)) - .subscribe(({ state, revision, generation }) => { - if (generation === this.generation && revision === this.applied?.revision) this.result.set(state); + map(state => ({ state, selection: request.selection, revision: request.revision, generation: request.generation }))) + : of({ state: { status: 'idle' } as FigureState, selection: undefined, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef)) + .subscribe(({ state, selection, revision, generation }) => { + if (generation === this.generation && revision === this.applied?.revision) { + if (state.status === 'ready') this.readySelection = selection; + this.result.set(state); + } }); } - ngOnChanges() { + private present(figure: NonNullable, selection: FigureSelection): FigureState { + const presentation = figurePresentation(figure, selection, this.visualProfile, this.plotWidth); + return { status: 'ready', figure, presentationFigure: presentation.figure, footnotes: presentation.footnotes, + categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth }; + } + updatePlotWidth(width: number) { + if (!Number.isFinite(width) || width <= 0 || Math.floor(width) === this.plotWidth) return; + this.plotWidth = Math.floor(width); + const state = this.result(); + if (this.visualProfile.axisLabels?.enabled && state.status === 'ready' && state.figure && this.readySelection) { + const next = this.present(state.figure, this.readySelection); + // A width change within the same label budget must not hide/repaint an + // equivalent graph (for example when only the scrollbar gutter changes). + if (JSON.stringify([next.presentationFigure, next.categoryLabels, next.minimumPlotWidth]) + !== JSON.stringify([state.presentationFigure, state.categoryLabels, state.minimumPlotWidth])) this.result.set(next); + } + } + ngOnChanges(changes: SimpleChanges) { const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); this.titleId = identityElementId(identity) + '-title'; const key = this.requestKey(); - if (key === this.currentKey) return; + if (key === this.currentKey) { + const state = this.result(); + if (changes['visualProfile'] && state.status === 'ready' && state.figure && this.readySelection) { + this.result.set(this.present(state.figure, this.readySelection)); + } + return; + } if (this.visible) this.requestFigure(); else { // Cancel stale work immediately but retain the panel and its Plotly host. diff --git a/src/app/features/indicadores/indicadores-axis-labels.spec.ts b/src/app/features/indicadores/indicadores-axis-labels.spec.ts new file mode 100644 index 0000000..24ace9f --- /dev/null +++ b/src/app/features/indicadores/indicadores-axis-labels.spec.ts @@ -0,0 +1,230 @@ +import { abbreviateCategories, categoryMinimumWidth } from './indicadores-axis-labels'; +import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { figurePresentation } from './indicadores.presentation'; +import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile'; + +const selection: FigureSelection = { dominio: 'tea', indicador: 'synthetic', figura: 'fig_c1_grupos', tema: 'claro' }; +const long = 'Fármaco de riesgo para el neurodesarrollo'; +const hover = '2025-S1
%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})'; +function source(): PlotlyFigure { + return { data: [{ type: 'scatter', mode: 'markers', x: [long, 'Otra'], y: [20, null], + customdata: [[2, 10], [null, 'SUPRIMIDO']], error_y: { array: [5, null] }, hovertemplate: hover, + future: { keep: true } }], layout: { xaxis: { type: 'category', categoryorder: 'array', categoryarray: [long, 'Otra'], future: 7 }, + yaxis: { range: [0, 100] }, margin: { b: 150 }, annotations: [{ text: 'Nota desconocida', y: -0.3 }] }, + config: { displaylogo: false }, future: { keep: [null, 0] } }; +} +const present = (figure: PlotlyFigure) => figurePresentation(figure, selection, READABLE_VISUAL_PROFILE); +function freezeDeep(value: unknown) { + if (value && typeof value === 'object') { Object.values(value).forEach(freezeDeep); Object.freeze(value); } +} + +describe('UX-07C etiquetas de ejes', () => { + it('UX-07D reserva espacio para las cinco áreas cortas sin perder ticks ni modificar observaciones', () => { + const figure: PlotlyFigure = { data: [{ type: 'bar', name: 'Desarrollo adecuado', x: ['Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo'], y: [20, null, 0, 40, 60] }], + layout: { xaxis: {}, margin: { l: 60, r: 30 } } }; + const before = structuredClone(figure); freezeDeep(figure); + const result = figurePresentation(figure, { ...selection, figura: 'fig_c2_apiladas' }, READABLE_VISUAL_PROFILE, 253); + expect(result.minimumPlotWidth).toBeGreaterThan(253); + expect(result.figure.layout['xaxis']).toMatchObject({ type: 'category', tickmode: 'linear', dtick: 1, automargin: true }); + expect(result.figure.data).toEqual(before.data); expect(figure).toEqual(before); + expect(figurePresentation(figure, selection, BASE_VISUAL_PROFILE, 253).minimumPlotWidth).toBeUndefined(); + expect(figurePresentation(figure, { ...selection, dominio: 'cacu' }, READABLE_VISUAL_PROFILE, 253).minimumPlotWidth).toBeUndefined(); + expect(figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, result.minimumPlotWidth).minimumPlotWidth).toBe(result.minimumPlotWidth); + }); + it('UX-07D mantiene todos los pares semestre/área con un mínimo estable y sin ticks simples', () => { + const figure: PlotlyFigure = { data: [{ type: 'bar', x: [Array(5).fill('2025-S1').concat(Array(5).fill('2025-S2')), + ['Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo', 'Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo']], y: Array(10).fill(null) }], layout: { xaxis: {} } }; + const before = structuredClone(figure); + const result = figurePresentation(figure, { ...selection, figura: 'fig_c2_apiladas' }, READABLE_VISUAL_PROFILE, 253); + expect(result.minimumPlotWidth).toBeGreaterThan(253); + expect(result.figure.layout['xaxis']).toEqual({}); expect(result.figure.data).toEqual(before.data); + expect(figure).toEqual(before); + }); + it('UX-07D no reserva ancho en estructuras desconocidas, ejes numéricos, notas sin reconocer o dimensiones fijas', () => { + const base: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: { xaxis: { type: 'category' } } }; + for (const layout of [{ width: 700 }, { autosize: false }, { xaxis2: {} }, { annotations: [{ text: 'Advertencia desconocida' }] }, { xaxis: { type: 'date' } }, { template: { layout: { xaxis: { tickvals: ['A'] } } } }]) { + expect(categoryMinimumWidth({ ...base, layout: { ...base.layout, ...layout } })).toBeUndefined(); + } + expect(categoryMinimumWidth({ ...base, data: [{ type: 'box', x: ['A', 'B', 'C'], y: [0, null, 20] }] })).toBeUndefined(); + expect(categoryMinimumWidth({ ...base, frames: [{}] })).toBeUndefined(); + }); + it('deja las etiquetas cortas intactas y abrevia por palabras sólo las extensas', () => { + expect([...abbreviateCategories(['Corta', long], 22)]).toEqual([['Corta', 'Corta'], [long, 'Fármaco de riesgo…']]); + const result = present(source()); + expect(result.figure.layout['xaxis']).toMatchObject({ tickvals: [long, 'Otra'], ticktext: ['Fármaco de riesgo…', 'Otra'], + categoryarray: [long, 'Otra'], categoryorder: 'array', future: 7, automargin: true }); + expect(result.categoryLabels).toEqual([{ axis: 'x', original: long, abbreviated: 'Fármaco de riesgo…' }]); + }); + it('sin etiquetas extensas no crea ticks ni cambia el hover', () => { + const figure = source(); figure.data[0]['x'] = ['Corta', 'Otra']; figure.layout['xaxis'] = { type: 'category' }; + expect(present(figure).figure.data).toEqual(figure.data); + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + expect(present(figure).categoryLabels).toEqual([]); + }); + it('conserva etiquetas completas cuando hay ancho suficiente y abrevia al estrechar la misma figura', () => { + const figure = source(), before = structuredClone(figure); + const spacious = figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, 1400); + expect(spacious.categoryLabels).toEqual([]); expect(spacious.figure.data).toEqual(before.data); + expect(spacious.figure.layout['xaxis']).toEqual(before.layout['xaxis']); + expect(figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, 320).categoryLabels).toHaveLength(1); + expect(figurePresentation(figure, selection, { axisLabels: { enabled: true, preserveWhenFits: false } }, 1400).categoryLabels).toHaveLength(1); + expect(figure).toEqual(before); + }); + it('acota la ampliación tipográfica opcional en tarjetas estrechas sin cambiar la fuente original ni el perfil amplio', () => { + const figure = source(); figure.layout['font'] = { size: 13, future: true }; + const profile = { ...DEMO_VISUAL_PROFILE, ...READABLE_VISUAL_PROFILE }; + expect(figurePresentation(figure, selection, profile, 270).figure.layout['font']).toMatchObject({ size: 12, future: true }); + expect(figurePresentation(figure, selection, profile, 646).figure.layout['font']).toMatchObject({ size: 15 }); + expect(figure.layout['font']).toEqual({ size: 13, future: true }); + }); + it('las colisiones y las abreviaciones iguales a otra categoría vuelven al original', () => { + const a = 'Fármaco de riesgo para el neurodesarrollo', b = 'Fármaco de riesgo para otra condición'; + const labels = abbreviateCategories([a, b, 'Fármaco de riesgo…'], 22); + expect([...labels.values()]).toEqual([a, b, 'Fármaco de riesgo…']); + expect(new Set(labels.values()).size).toBe(labels.size); + }); + it('deduplica la correspondencia sin retirar puntos duplicados', () => { + const figure = source(); figure.data[0]['x'] = [long, long]; + const result = present(figure); + expect(result.categoryLabels).toHaveLength(1); + expect(result.figure.data[0]['x']).toEqual([long, long]); + expect((result.figure.layout['xaxis'] as Record)['tickvals']).toEqual([long, 'Otra']); + }); + it('conserva grafemas Unicode, acentos, símbolos y palabras indivisibles', () => { + const value = 'Área 👩🏽‍⚕️ y comunicación extensa'; + expect(abbreviateCategories([value], 12).get(value)).toBe('Área 👩🏽‍⚕️ y…'); + const word = 'Neurodesarrollosuperextenso'; + expect(abbreviateCategories([word], 10).get(word)).toBe(word); + expect(abbreviateCategories([word], 10, false).get(word)).toBe('Neurodesa…'); + const symbol = 'Área α ± lenguaje y comunicación'; + expect(abbreviateCategories([symbol], 12).get(symbol)).toBe('Área α ±…'); + }); + it('preserva profundamente el original, datos, customdata, anotaciones, configuración y atributos desconocidos', () => { + const figure = source(), before = structuredClone(figure); freezeDeep(figure); + const result = present(figure); + expect(figure).toEqual(before); + const { hovertemplate: ignored, ...observations } = result.figure.data[0]; + const { hovertemplate: originalHover, ...originalObservations } = before.data[0]; + expect(observations).toEqual(originalObservations); + expect(result.figure.data[0]).not.toBe(figure.data[0]); + expect(result.figure.layout['annotations']).toEqual(before.layout['annotations']); + expect(result.figure.layout['margin']).toEqual(before.layout['margin']); + expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']); + }); + it('restituye exclusivamente la categoría en hover y conserva porcentajes, intervalos y conteos', () => { + const figure = source(); figure.data[0]['hovertemplate'] = hover.replace('', '
IC %{error_y.array}'); + const result = present(figure); + expect(result.figure.data[0]['hovertemplate']).toEqual([long, 'Otra'].map(label => + (figure.data[0]['hovertemplate'] as string).replace('%{x}', label))); + expect(figure.data[0]['hovertemplate']).toContain('%{x}'); + }); + it('conserva símbolos de reemplazo y ampersands como texto literal en el hover', () => { + const figure = source(), label = 'Área $& y salud & comunicación extensa'; + figure.data[0]['x'] = [label, 'Otra']; + expect((present(figure).figure.data[0]['hovertemplate'] as string[])[0]).toBe(hover.replace('%{x}', () => label.replaceAll('&', '&'))); + }); + it.each([NaN, 0, 7, 81, 20.5])('opciones inválidas conservan los ejes: %s', maxCharacters => { + const figure = source(); + const result = figurePresentation(figure, selection, { axisLabels: { enabled: true, maxCharacters } }); + expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]); + }); + it('conserva plantillas por punto, hovertext, hoverinfo y contenido suprimido sin exponer valores', () => { + const figure = source(); figure.data[0]['hovertemplate'] = [hover, '%{x}
dato suprimido (conteo bajo)']; + figure.data[0]['hovertext'] = ['Observación publicada', 'SUPRIMIDO']; figure.data[0]['hoverinfo'] = 'text'; + const result = present(figure).figure.data[0]; + expect((result['hovertemplate'] as string[])[1]).toBe('Otra
dato suprimido (conteo bajo)'); + expect((result['hovertemplate'] as string[])[1]).not.toMatch(/customdata|%\{y|20|0 %/); + expect(result['hovertext']).toEqual(figure.data[0]['hovertext']); expect(result['customdata']).toEqual(figure.data[0]['customdata']); + expect(result['hoverinfo']).toBe('text'); expect(result['y']).toEqual([20, null]); + }); + it.each([undefined, '%{x:.2f}
%{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)['tickangle'] = 30; + expect(present(figure).figure.layout['xaxis']).toMatchObject({ tickangle: 30 }); + }); + it('soporta barras horizontales sin cambiar categorías Y ni valores X', () => { + const figure: PlotlyFigure = { data: [{ type: 'bar', orientation: 'h', y: [long], x: [0], customdata: [null], + hovertemplate: '%{y}
%{x:.1f}%' }], layout: { yaxis: { type: 'category' } } }; + const result = present(figure); + expect(result.figure.layout['yaxis']).toMatchObject({ ticktext: ['Fármaco de riesgo…'], tickvals: [long] }); + expect(result.figure.data[0]['x']).toEqual([0]); expect(result.figure.data[0]['y']).toEqual([long]); + expect(result.figure.data[0]['hovertemplate']).toEqual([long + '
%{x:.1f}%']); + }); + it('multicategoría conserva niveles, periodos, agrupación, hover y reserva de margen', () => { + const figure = source(); figure.data[0]['type'] = 'bar'; figure.data[0]['x'] = [['2025-S1', '2025-S2'], [long, long]]; + figure.layout['xaxis'] = { type: 'multicategory', future: true }; + const result = present(figure); + expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]); + expect(result.figure.layout['xaxis']).toEqual({ type: 'multicategory', future: true, automargin: true, tickfont: { size: 11 } }); + expect(result.figure.layout['margin']).toEqual(figure.layout['margin']); + const preserve = figurePresentation(figure, selection, { axisLabels: { enabled: true, multicategory: 'preserve' } }); + expect(preserve.figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + }); + it.each([{ levels: [['2025-S1'], [long, long]] }, { levels: [['Grupo', 'Grupo'], [long, long]] }, + { levels: [['2025-S1', '2025-S2'], [long, long], ['a', 'b']] }])('preserva multicategorías no validadas: %j', ({ levels }) => { + const figure = source(); figure.data[0]['x'] = levels; figure.layout['xaxis'] = { type: 'multicategory' }; + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + expect(present(figure).figure.data).toEqual(figure.data); + }); + it.each(['pie', 'box', 'heatmap', 'future'])('conserva familias incompatibles: %s', type => { + const figure = source(); figure.data[0]['type'] = type; + expect(present(figure).categoryLabels).toEqual([]); expect(present(figure).figure.data).toEqual(figure.data); + }); + it('conserva frames/menús/subplots y no infiere identidades o HTML', () => { + for (const extra of [{ frames: [{ name: 'f', data: [{ x: [long] }], future: 3 }] }, + { layout: { ...source().layout, updatemenus: [] } }, { layout: { ...source().layout, xaxis2: {} } }]) { + const figure = { ...source(), ...extra }, before = structuredClone(figure); + expect(present(figure).figure.data).toEqual(before.data); expect(present(figure).figure.frames).toEqual(before.frames); + expect(present(figure).categoryLabels).toEqual([]); + } + for (const label of ['Texto extenso publicado', 'Área & texto extenso', 'Área %{customdata} muy extensa']) { + const figure = source(); figure.data[0]['x'] = [label, 'Otra']; + expect(present(figure).categoryLabels).toEqual([]); + } + }); + it('revierte al perfil base desde el original y combina el perfil de demostración sin acumulación', () => { + const figure = source(), original = structuredClone(figure); + const compact = present(figure); compact.figure.data[0]['x'] = ['mutación del runtime']; + const restored = figurePresentation(figure, selection, BASE_VISUAL_PROFILE); + expect(restored.figure.data).toEqual(original.data); expect(restored.categoryLabels).toEqual([]); + expect(restored.figure.layout['xaxis']).toEqual(original.layout['xaxis']); + const demo = figurePresentation(figure, selection, { ...DEMO_VISUAL_PROFILE, ...READABLE_VISUAL_PROFILE }); + expect(demo.figure.layout['paper_bgcolor']).toBe('#f2f7fc'); expect(demo.categoryLabels).toHaveLength(1); + expect(figure).toEqual(original); + }); + it('extrae el pie TEA sin perder el mapa de categorías ni alterar anotaciones desconocidas', () => { + const figure = source(); figure.layout['annotations'] = [{ + text: 'Nota sintética.
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 { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +function plainLabel(value: unknown): value is string { + return typeof value === 'string' && value.trim().length > 0 + && !/[<>]|&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);|%\{/i.test(value); +} +function temporalOrNumeric(value: string): boolean { + // Conservative: published years, dates, semester/month codes and numeric text. + return /(?:^|\D)\d{4}(?:\D|$)/u.test(value) || /^[\d\s.,+−\-/%:]+$/u.test(value) + || /^(?:S[12]|T[1-4]|Q[1-4]|\d{1,2}[-/]\d{1,2})$/iu.test(value); +} + +/** A collision falls back to the original; identical categories share one label. */ +export function abbreviateCategories(values: readonly string[], limit: number, preferWords = true): Map { + const originals = [...new Set(values)]; + const labels = new Map(originals.map(value => { + if (temporalOrNumeric(value) || characters(value).length <= limit) return [value, value]; + let prefix = characters(value).slice(0, limit - 1).join(''); + if (preferWords && !/^\s/u.test(characters(value)[limit - 1] ?? '')) { + const boundary = prefix.search(/\s+\S*$/u); + if (boundary < 1) return [value, value]; // Do not split an indivisible word. + prefix = prefix.slice(0, boundary); + } + return [value, prefix.trimEnd() + '…']; + })); + const counts = new Map(); + for (const label of labels.values()) counts.set(label, (counts.get(label) ?? 0) + 1); + for (const [original, label] of labels) { + if ((counts.get(label) ?? 0) > 1 || (label !== original && labels.has(label))) labels.set(original, original); + } + return labels; +} + +function templates(trace: Record, coordinate: 'x' | 'y', size: number): string[] | undefined { + const template = trace['hovertemplate']; + const list = typeof template === 'string' ? Array(size).fill(template) + : Array.isArray(template) && template.length === size ? template : undefined; + // Do not reconstruct default hovers, formatted coordinates, expressions, or + // templates whose category is in a different field. Preserve those axes. + return list?.every(text => typeof text === 'string' && text.includes(`%{${coordinate}}`) + && !text.includes(`%{${coordinate}:`) && !text.includes(`%{${coordinate}|`)) ? list : undefined; +} + +// Keep dense categories readable inside the existing keyboard-scrollable plot +// viewport. The minimum is independent of the measured host width, preventing +// ResizeObserver feedback when the host grows to this minimum. +export function categoryMinimumWidth(figure: PlotlyFigure): number | undefined { + const published = figure.layout['xaxis']; + const template = figure.layout['template']; + const templateLayout = record(template) && record(template['layout']) ? template['layout'] : {}; + const axis = { ...(record(templateLayout['xaxis']) ? templateLayout['xaxis'] : {}), ...(record(published) ? published : {}) }; + if ((published !== undefined && !record(published)) || (axis['type'] !== undefined && !['category', 'multicategory'].includes(String(axis['type']))) + || figure.frames?.length || figure.layout['width'] !== undefined || figure.layout['autosize'] === false + || ['annotations', 'shapes', 'images', 'sliders', 'updatemenus'].some(key => { + const value = figure.layout[key]; return value !== undefined && (!Array.isArray(value) || value.length > 0); + }) || Object.keys(figure.layout).some(key => /^[xy]axis\d+$/.test(key)) + || ['tickvals', 'ticktext', 'tickmode', 'dtick', 'tick0', 'range', 'matches', 'overlaying', 'ticklabelstep'].some(key => axis[key] !== undefined) + || !figure.data.length) return undefined; + const multi = figure.data.some(trace => Array.isArray(trace['x']) && trace['x'].some(Array.isArray)); + if ((multi && axis['type'] === 'category') || (!multi && axis['type'] === 'multicategory')) return undefined; + const positions: string[] = []; + for (const trace of figure.data) { + if (!['scatter', 'bar'].includes(String(trace['type'])) || trace['orientation'] === 'h' + || ['transforms', 'xsrc', 'ysrc'].some(key => trace[key] !== undefined) + || (trace['xaxis'] !== undefined && trace['xaxis'] !== 'x') || (trace['yaxis'] !== undefined && trace['yaxis'] !== 'y') + || !Array.isArray(trace['x']) || !Array.isArray(trace['y'])) return undefined; + const x = trace['x'] as unknown[], y = trace['y'] as unknown[]; + if (y.some(value => value !== null && typeof value !== 'number')) return undefined; + if (multi) { + if (trace['type'] !== 'bar' || x.length !== 2 || !x.every(Array.isArray) + || x.some(level => level.length !== y.length) || !(x[0] as unknown[]).every(value => typeof value === 'string' && /^\d{4}-S[12]$/.test(value)) + || !(x[1] as unknown[]).every(plainLabel)) return undefined; + (x[0] as string[]).forEach((period, index) => positions.push(JSON.stringify([period, (x[1] as string[])[index]]))); + } else { + if (x.length !== y.length || !x.every(plainLabel) || x.some(temporalOrNumeric)) return undefined; + positions.push(...x as string[]); + } + } + const count = new Set(positions).size; + if (count < 3) return undefined; + const font = record(figure.layout['font']) ? figure.layout['font'] : {}; + const tickfont = record(axis['tickfont']) ? axis['tickfont'] : font; + const size = typeof tickfont['size'] === 'number' ? tickfont['size'] : 12; + const legend = record(figure.layout['legend']) ? figure.layout['legend'] : {}; + const legendWidth = figure.layout['showlegend'] === false || legend['orientation'] === 'h' ? 0 + : Math.max(0, ...figure.data.filter(trace => trace['showlegend'] !== false).map(trace => + characters(String(trace['name'] ?? '')).length * 7 + 48)); + const margin = record(figure.layout['margin']) ? figure.layout['margin'] : {}; + return Math.ceil(count * Math.max(20, size * 1.8) + legendWidth + + (typeof margin['l'] === 'number' ? margin['l'] : 80) + + (typeof margin['r'] === 'number' ? margin['r'] : 80)); +} + +/** Mutates only the independent presentation clone supplied by figurePresentation. */ +export function applyAxisLabels(figure: PlotlyFigure, options?: AxisLabelOptions, availableWidth?: number): CategoryLabel[] { + const result: CategoryLabel[] = []; + const limit = options?.maxCharacters ?? 22; + if (!options?.enabled || !Number.isInteger(limit) || limit < 8 || limit > 80 || figure.frames?.length + || figure.layout['updatemenus'] !== undefined || figure.layout['sliders'] !== undefined) return result; + // Multiple/linked axes and subplots require an explicit mapping contract. + if (Object.keys(figure.layout).some(key => /^[xy]axis\d+$/.test(key))) return result; + for (const coordinate of ['x', 'y'] as const) { + const axisKey = `${coordinate}axis`, other = coordinate === 'x' ? 'y' : 'x'; + const published = figure.layout[axisKey]; + if (published !== undefined && !record(published)) continue; + const axis = record(published) ? published : {}; + const templateLayout = record(figure.layout['template']) ? figure.layout['template']['layout'] : undefined; + const templateAxis = record(templateLayout) && record(templateLayout[axisKey]) ? templateLayout[axisKey] : {}; + const effective = { ...templateAxis, ...axis }; + if (['tickvals', 'ticktext', 'tickmode', 'labelalias', 'tickformat', 'tickprefix', 'ticksuffix', 'dtick', 'tick0', + 'ticklabelstep', 'range', 'matches', 'overlaying', 'ticklabelindex'].some(key => effective[key] !== undefined) + || effective['showticklabels'] === false) continue; + const traces = figure.data; + if (!traces.length || traces.some(trace => !['scatter', 'bar'].includes(String(trace['type'])) + || (trace[axisKey] !== undefined && trace[axisKey] !== coordinate) + || ['transforms', 'hovertemplatesrc', `${coordinate}src`].some(key => trace[key] !== undefined) + || !Array.isArray(trace[coordinate]) || !Array.isArray(trace[other]) + || (trace[other] as unknown[]).some(value => value !== null && typeof value !== 'number'))) continue; + const arrays = traces.map(trace => trace[coordinate] as unknown[]); + const fits = (values: readonly string[], count: number): boolean => { + if (coordinate !== 'x' || options.preserveWhenFits === false || !Number.isFinite(availableWidth) || !count) return false; + const margin = record(figure.layout['margin']) ? figure.layout['margin'] : {}; + const font = record(effective['tickfont']) ? effective['tickfont'] + : record(figure.layout['font']) ? figure.layout['font'] : {}; + const fontSize = typeof font['size'] === 'number' ? font['size'] : 12; + const textWidth = (text: string) => characters(text).reduce((size, char) => size + + fontSize * (/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Extended_Pictographic}]/u.test(char) ? 1.1 : 0.58), 0); + const legend = record(figure.layout['legend']) ? figure.layout['legend'] : {}; + const legendSize = figure.layout['showlegend'] === false || legend['orientation'] === 'h' ? 0 + : Math.max(0, ...traces.filter(trace => trace['showlegend'] !== false).map(trace => + textWidth(String(trace['name'] ?? '')) + 40)); + const width = availableWidth! - (typeof margin['l'] === 'number' ? margin['l'] : 80) + - (typeof margin['r'] === 'number' ? margin['r'] : 80) - legendSize; + // A conservative estimate with padding; no SVG measurements or font loads. + return values.every(value => textWidth(value) + 16 <= width / count); + }; + const multi = arrays.some(values => values.some(Array.isArray)); + if (multi) { + // Plotly 4.1.2 does not safely map tickvals/ticktext to both levels. + // Keep every published coordinate, grouping, period and hover unchanged. + if (coordinate !== 'x' || options.multicategory !== 'fit' || traces.some(trace => trace['type'] !== 'bar') + || (effective['type'] !== undefined && effective['type'] !== 'multicategory') + || arrays.some((levels, i) => levels.length !== 2 || !levels.every(Array.isArray) + || (levels[0] as unknown[]).length !== (levels[1] as unknown[]).length + || (levels[0] as unknown[]).length !== (traces[i][other] as unknown[]).length + || !(levels[0] as unknown[]).every(value => typeof value === 'string' && /^\d{4}-S[12]$/.test(value)) + || !(levels[1] as unknown[]).every(plainLabel)) + || !arrays.some(levels => (levels[1] as string[]).some(value => characters(value).length > limit))) continue; + if (fits(arrays.flatMap(levels => levels[1] as string[]), Math.max(...arrays.map(levels => (levels[1] as string[]).length)))) continue; + const font = record(effective['tickfont']) ? effective['tickfont'] : {}; + figure.layout[axisKey] = { ...axis, automargin: true, + tickfont: { ...font, size: Math.min(typeof font['size'] === 'number' ? font['size'] : 12, 11) } }; + continue; + } + if ((effective['type'] !== undefined && effective['type'] !== 'category') + || arrays.some((values, i) => values.length !== (traces[i][other] as unknown[]).length || !values.every(plainLabel))) continue; + const order = effective['categoryarray']; + if (order !== undefined && (!Array.isArray(order) || !order.every(plainLabel))) continue; + const values = [...new Set([...(Array.isArray(order) ? order as string[] : []), ...arrays.flat() as string[]])]; + if (fits(values, values.length)) continue; + const labels = abbreviateCategories(values, limit, options.preferWords ?? true); + if (![...labels].some(([original, label]) => original !== label)) continue; + const hoverTemplates = traces.map((trace, i) => templates(trace, coordinate, arrays[i].length)); + if (hoverTemplates.some(value => value === undefined)) continue; + // Only the bare coordinate token changes, per point. All statistical and + // suppression tokens/text remain exactly as published; no customdata added. + traces.forEach((trace, i) => { + trace['hovertemplate'] = hoverTemplates[i]!.map((template, j) => template.replaceAll( + `%{${coordinate}}`, () => (arrays[i][j] as string).replaceAll('&', '&'))); + }); + figure.layout[axisKey] = { ...axis, type: 'category', tickmode: 'array', tickvals: values, + ticktext: values.map(value => labels.get(value)!), automargin: true, + ...(effective['tickangle'] === undefined ? { tickangle: coordinate === 'x' ? -60 : 0 } : {}) }; + for (const [original, abbreviated] of labels) { + if (original !== abbreviated) result.push({ axis: coordinate, original, abbreviated }); + } + } + return result; +} diff --git a/src/app/features/indicadores/indicadores-figure-labels.spec.ts b/src/app/features/indicadores/indicadores-figure-labels.spec.ts new file mode 100644 index 0000000..1e6db48 --- /dev/null +++ b/src/app/features/indicadores/indicadores-figure-labels.spec.ts @@ -0,0 +1,28 @@ +import { figureDisplayName } from './indicadores-figure-labels'; + +describe('UX-07A nombres de representaciones', () => { + it.each([ + ['fig_c1_grupos', 'Grupos'], + ['fig_c1_puntos', 'Puntos'], + ['fig_c2_apiladas', 'Barras apiladas'], + ['fig_c2_barras', 'Barras'], + ['fig_c2_donas', 'Donas'], + ['fig_c3r_caja', 'Caja de cuartiles'], + ])('presenta %s como %s', (id, label) => { + expect(figureDisplayName(id, [id])).toBe(label); + }); + + it('no infiere tipos por prefijo y distingue opciones desconocidas en orden de publicación', () => { + const figures = ['fig_c1_grupos', 'fig_c1_futura', 'fig_c2_futura']; + const snapshot = [...figures]; + expect(figureDisplayName(figures[1], figures)).toBe('Representación 2'); + expect(figureDisplayName(figures[2], figures)).toBe('Representación 3'); + expect(figureDisplayName(figures[1], [...figures])).toBe('Representación 2'); + expect(figures).toEqual(snapshot); + }); + + it('no usa propiedades heredadas ni revela IDs ajenos al catálogo', () => { + expect(figureDisplayName('constructor', ['constructor'])).toBe('Representación 1'); + expect(figureDisplayName('sin_publicar', [])).toBe('Representación adicional'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-figure-labels.ts b/src/app/features/indicadores/indicadores-figure-labels.ts new file mode 100644 index 0000000..46c48dd --- /dev/null +++ b/src/app/features/indicadores/indicadores-figure-labels.ts @@ -0,0 +1,17 @@ +// Presentation labels for representations confirmed in the published catalog. +// Exact IDs remain the option values and HTTP identities; never infer a type +// from a prefix. Unknown options keep a neutral label in publication order. +const FIGURE_LABELS: Readonly> = { + fig_c1_grupos: 'Grupos', + fig_c1_puntos: 'Puntos', + fig_c2_apiladas: 'Barras apiladas', + fig_c2_barras: 'Barras', + fig_c2_donas: 'Donas', + fig_c3r_caja: 'Caja de cuartiles', +}; + +export function figureDisplayName(figureId: string, publishedFigures: readonly string[]): string { + if (Object.hasOwn(FIGURE_LABELS, figureId)) return FIGURE_LABELS[figureId]; + const index = publishedFigures.indexOf(figureId); + return index >= 0 ? `Representación ${index + 1}` : 'Representación adicional'; +} diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 0dc65d8..67eb0b6 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -86,7 +86,9 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(host.querySelector('header button')).toBeNull(); expect(host.querySelector('mat-select')).toBeTruthy(); expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente'); - expect(host.textContent).toContain('Contrato C1'); http.expectNone(() => true); + expect(host.textContent).not.toContain('Contrato C1'); + expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); + http.expectNone(() => true); }); it('D.3.A conserva encabezado y contenido al salir del viewport', () => { load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); diff --git a/src/app/features/indicadores/indicadores-visual-profile.spec.ts b/src/app/features/indicadores/indicadores-visual-profile.spec.ts new file mode 100644 index 0000000..0dc955b --- /dev/null +++ b/src/app/features/indicadores/indicadores-visual-profile.spec.ts @@ -0,0 +1,228 @@ +import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { figurePresentation } from './indicadores.presentation'; +import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE } from './indicadores-visual-profile'; +import { syntheticFigures } from './indicadores.synthetic-fixtures'; + +const selection: FigureSelection = { dominio: 'tea', indicador: 'synthetic', figura: 'fig_c1_grupos', tema: 'claro' }; +const footer = { + text: 'Explicación sintética. Los valores suprimidos no son cero.
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.', '') }, + ])('conserva anotaciones ambiguas o marcado no trasladable: %j', change => { + const source = original(); source.layout['annotations'] = [{ ...footer, ...change }]; + const result = figurePresentation(source, selection); + expect(result.footnotes).toEqual([]); expect(result.figure.layout['annotations']).toEqual(source.layout['annotations']); + }); + it.each([{ dominio: 'cacu' as const }, { figura: 'fig_c3r_cajas' }, { dominio: undefined }])('no infiere familias ni dominios: %j', change => { + const source = original(); const result = figurePresentation(source, { ...selection, ...change }); + expect(result.footnotes).toEqual([]); expect(result.figure.layout['annotations']).toEqual(source.layout['annotations']); + }); + it.each([{ data: [] }, { data: [{ y: [null, null], customdata: ['SUPRIMIDO', 'SIN_DATO'] }] }, { data: [{ y: [0, NaN, null] }] }])('preserva vacíos, supresión, nulos y cero: %j', ({ data }) => { + const source = { ...original(), data }; const snapshot = structuredClone(source); + expect(figurePresentation(source, selection, DEMO_VISUAL_PROFILE).figure.data).toEqual(snapshot.data); + expect(source).toEqual(snapshot); + }); + it('admite saltos br equivalentes y conserva cada línea sin trim ni HTML', () => { + const source = original(); const text = footer.text.replaceAll('
', '
'); + 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.presentation.ts b/src/app/features/indicadores/indicadores.presentation.ts index acaac56..0b5bd89 100644 --- a/src/app/features/indicadores/indicadores.presentation.ts +++ b/src/app/features/indicadores/indicadores.presentation.ts @@ -1,4 +1,102 @@ 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 { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function footerText(annotation: unknown, selection: FigureSelection): string | undefined { + const tea = selection.dominio === 'tea'; + const verifiedFamily = tea + ? TEA_FOOTER_FIGURES.has(selection.figura) || DISTRIBUTION_FOOTER_FIGURES.has(selection.figura) + : (selection.dominio === 'cacu' || selection.dominio === 'cama') && DISTRIBUTION_FOOTER_FIGURES.has(selection.figura); + if (!verifiedFamily || !record(annotation) + || Object.keys(annotation).some(key => !FOOTER_KEYS.has(key)) + || annotation['xref'] !== 'paper' || annotation['yref'] !== 'paper' + || annotation['x'] !== 0 || annotation['y'] !== -0.22 + || annotation['xanchor'] !== 'left' || annotation['yanchor'] !== 'top' + || annotation['align'] !== 'left' || annotation['showarrow'] !== false + || !record(annotation['font']) || annotation['font']['size'] !== 11 + || Object.keys(annotation['font']).some(key => !['size', 'color'].includes(key)) + || typeof annotation['text'] !== 'string') return undefined; + const text = annotation['text'].replace(//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']; @@ -9,7 +107,8 @@ export function figureTitle(figure: PlotlyFigure, fallback: string): string { } // Adapt only the dashboard copy; HTTP figures and all observations stay intact. -export function presentationFigure(original: PlotlyFigure, selection: FigureSelection): PlotlyFigure { +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: '' }; @@ -27,5 +126,36 @@ export function presentationFigure(original: PlotlyFigure, selection: FigureSele tickangle: 0, automargin: true, }; } - return figure; + const footnotes: string[] = []; + const annotations = figure.layout['annotations']; + // Frames may reintroduce annotations. Keep animated figures entirely in Plotly. + if (!figure.frames?.length && Array.isArray(annotations)) { + figure.layout['annotations'] = annotations.filter(annotation => { + const text = footerText(annotation, selection); + if (text === undefined) return true; + footnotes.push(text); + return false; + }); + // Only the previously verified TEA reserve can be relaxed. Newly supported + // families keep their margins, legends, colorbars and fixed dimensions. + if (footnotes.length && selection.dominio === 'tea' && TEA_FOOTER_FIGURES.has(selection.figura) + && (figure.layout['annotations'] as unknown[]).length === 0) relaxFooterMargin(figure); + } + applyVisualProfile(figure, profile, availableWidth); + const minimumPlotWidth = profile.axisLabels?.enabled && Number.isFinite(availableWidth) && availableWidth! > 0 + && selection.dominio === 'tea' && ['fig_c1_grupos', 'fig_c2_apiladas'].includes(selection.figura) + ? categoryMinimumWidth(figure) : undefined; + const categoryLabels = applyAxisLabels(figure, profile.axisLabels, availableWidth); + if (minimumPlotWidth !== undefined && !categoryLabels.length + && figure.data.every(trace => Array.isArray(trace['x']) && !trace['x'].some(Array.isArray))) { + figure.layout['xaxis'] = { ...(record(figure.layout['xaxis']) ? figure.layout['xaxis'] : {}), + type: 'category', tickmode: 'linear', dtick: 1, automargin: true }; + } + return { figure, footnotes, categoryLabels, minimumPlotWidth }; +} + +// Compatibility for existing consumers that only need the Plotly copy. +export function presentationFigure(original: PlotlyFigure, selection: FigureSelection, + profile: FigureVisualProfile = BASE_VISUAL_PROFILE): PlotlyFigure { + return figurePresentation(original, selection, profile).figure; } diff --git a/src/app/shared/plotly/plotly-chart.spec.ts b/src/app/shared/plotly/plotly-chart.spec.ts index 7d69942..75b325d 100644 --- a/src/app/shared/plotly/plotly-chart.spec.ts +++ b/src/app/shared/plotly/plotly-chart.spec.ts @@ -36,6 +36,32 @@ describe('PlotlyChart lifecycle', () => { 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 index ba2ea24..e5015ab 100644 --- a/src/app/shared/plotly/plotly-chart.ts +++ b/src/app/shared/plotly/plotly-chart.ts @@ -22,7 +22,7 @@ import { PLOTLY_LOADER } from './plotly-runtime'; } `, - styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`, + styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-width: var(--plot-min-width, 0px); min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`, }) export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { @Input() showNotes = true; @@ -30,6 +30,7 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { @Input({ required: true }) figure!: PlotlyFigure; @ViewChild('host', { static: true }) host!: ElementRef; readonly renderError = output(); + readonly widthChanged = output(); readonly status = signal<'loading' | 'ready' | 'error'>('loading'); get notes(): string[] { const annotations = this.figure?.layout['annotations']; @@ -40,7 +41,17 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { private readonly loadPlotly = inject(PLOTLY_LOADER); private controller?: PlotlyController; private observer?: ResizeObserver; - private readonly windowResize = () => this.controller?.resize(); + private lastWidth = 0; + private widthFrame?: number; + private readonly windowResize = () => { + this.controller?.resize(); + if (this.widthFrame !== undefined) return; + this.widthFrame = requestAnimationFrame(() => { + this.widthFrame = undefined; + const width = Math.floor(this.host.nativeElement.getBoundingClientRect().width); + if (width > 0 && width !== this.lastWidth) { this.lastWidth = width; this.widthChanged.emit(width); } + }); + }; ngAfterViewInit() { this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => { this.status.set(state); @@ -51,11 +62,14 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { this.observer.observe(this.host.nativeElement); } else window.addEventListener('resize', this.windowResize); this.controller.setFigure(this.figure); + // Also supply the initial width in browsers without ResizeObserver. + this.windowResize(); } ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); } retry() { this.controller?.setFigure(this.figure); } ngOnDestroy() { this.observer?.disconnect(); + if (this.widthFrame !== undefined) cancelAnimationFrame(this.widthFrame); window.removeEventListener('resize', this.windowResize); this.controller?.destroy(); }