feat(ui): completar presentacion de figuras UX-06D

This commit is contained in:
Angel Capetillo Zavala
2026-10-13 13:41:45 -06:00
parent 41be0c343f
commit 37c4eacf84
12 changed files with 250 additions and 29 deletions
+9 -1
View File
@@ -7,6 +7,14 @@
</div>
</header>
<main id="contenido-principal" tabindex="-1">
<main #mainContent id="contenido-principal" tabindex="-1">
<router-outlet />
</main>
@if (showBackToTop()) {
<button class="back-to-top" type="button" aria-label="Volver al inicio" (click)="backToTop()">
<svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24">
<path d="M12 19V5m-7 7 7-7 7 7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
</svg>
</button>
}
+21 -1
View File
@@ -39,7 +39,7 @@
}
main {
padding: var(--issste-space-4) var(--issste-page-gutter);
padding: var(--issste-space-4) var(--issste-page-gutter) 5.5rem;
scroll-margin-top: var(--issste-header-clearance);
}
@@ -87,3 +87,23 @@ main {
text-align: center;
}
}
.back-to-top {
position: fixed;
right: max(var(--issste-page-gutter), env(safe-area-inset-right));
bottom: max(var(--issste-space-4), env(safe-area-inset-bottom));
z-index: 90;
display: grid;
place-items: center;
width: 48px;
height: 48px;
padding: 0;
border: 1px solid var(--issste-text);
border-radius: 50%;
background: var(--issste-text);
color: var(--issste-surface);
cursor: pointer;
}
.back-to-top:hover { background: var(--issste-text-secondary); }
.back-to-top:focus-visible { outline: 3px solid var(--issste-text); outline-offset: 4px; }
+65
View File
@@ -54,3 +54,68 @@ describe('App — UX-06B', () => {
TestBed.inject(HttpTestingController).verify();
});
});
describe('App — UX-06D volver al inicio', () => {
let scrollY: number;
beforeEach(() => {
scrollY = 0;
vi.spyOn(window, 'scrollY', 'get').mockImplementation(() => scrollY);
TestBed.configureTestingModule({ imports: [App], providers: [provideRouter([])] });
});
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
function render() {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
return fixture;
}
function scroll(fixture: ReturnType<typeof render>, position: number) {
scrollY = position;
window.dispatchEvent(new Event('scroll'));
fixture.detectChanges();
}
it('oculta al inicio y en el umbral, muestra después y vuelve a ocultar al subir', () => {
const fixture = render();
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
scroll(fixture, 400);
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
scroll(fixture, 401);
expect(fixture.nativeElement.querySelector('.back-to-top')).not.toBeNull();
scroll(fixture, 0);
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
});
it('reconoce una posición restaurada al montar el shell', () => {
scrollY = 900;
expect(render().nativeElement.querySelector('.back-to-top')).not.toBeNull();
});
it.each([false, true])('activa un botón nativo y respeta movimiento reducido=%s', reduced => {
const matchMedia = vi.fn().mockReturnValue({ matches: reduced } as MediaQueryList);
vi.stubGlobal('matchMedia', matchMedia);
const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
const fixture = render();
scroll(fixture, 900);
const button = fixture.nativeElement.querySelector('.back-to-top') as HTMLButtonElement;
const main = fixture.nativeElement.querySelector('main') as HTMLElement;
const focus = vi.spyOn(main, 'focus');
expect(button.type).toBe('button');
expect(button.tabIndex).toBe(0);
expect(button.getAttribute('aria-label')).toBe('Volver al inicio');
expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');
button.click();
expect(matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)');
expect(scrollTo).toHaveBeenCalledWith({ top: 0, behavior: reduced ? 'instant' : 'smooth' });
expect(focus).toHaveBeenCalledWith({ preventScroll: true });
// Native Enter/Space activation is checked in Chrome, not emulated by jsdom.
});
it('registra un listener pasivo y elimina exactamente el mismo al destruir', () => {
const add = vi.spyOn(window, 'addEventListener');
const remove = vi.spyOn(window, 'removeEventListener');
const fixture = render();
const registration = add.mock.calls.find(call => call[0] === 'scroll')!;
expect(registration[2]).toEqual({ passive: true });
fixture.destroy();
expect(remove).toHaveBeenCalledWith('scroll', registration[1]);
scrollY = 900;
window.dispatchEvent(new Event('scroll'));
expect(fixture.componentInstance.showBackToTop()).toBe(false);
});
});
+23 -2
View File
@@ -1,4 +1,5 @@
import { Component } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { Component, ElementRef, inject, OnDestroy, OnInit, signal, ViewChild } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
@@ -7,6 +8,26 @@ import { RouterOutlet } from '@angular/router';
styleUrl: './app.scss',
templateUrl: './app.html',
})
export class App {
export class App implements OnInit, OnDestroy {
protected readonly title = 'Plataforma de Indicadores';
readonly showBackToTop = signal(false);
@ViewChild('mainContent') private mainContent?: ElementRef<HTMLElement>;
private readonly browserWindow = inject(DOCUMENT).defaultView;
private readonly updateScroll = () => this.showBackToTop.set((this.browserWindow?.scrollY ?? 0) > 400);
ngOnInit() {
this.updateScroll();
this.browserWindow?.addEventListener('scroll', this.updateScroll, { passive: true });
}
backToTop() {
const reducedMotion = this.browserWindow?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
// Keep keyboard focus near the destination when the floating button disappears.
this.mainContent?.nativeElement.focus({ preventScroll: true });
this.browserWindow?.scrollTo({ top: 0, behavior: reducedMotion ? 'instant' : 'smooth' });
}
ngOnDestroy() {
this.browserWindow?.removeEventListener('scroll', this.updateScroll);
}
}
@@ -2,8 +2,18 @@
<section class="interpretation" aria-label="Cómo leer esta figura">
<h2>Cómo leer esta figura · {{ selected?.contrato }}</h2>
<ul>
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
@for (line of visibleInterpretation; track $index) { <li>{{ line }}</li> }
</ul>
@if (methodologyDetail.length) {
<button mat-stroked-button type="button" class="methodology-toggle"
[attr.aria-expanded]="methodologyExpanded()" [attr.aria-controls]="methodologyId"
(click)="methodologyExpanded.set(!methodologyExpanded())">
{{ methodologyExpanded() ? 'Ocultar detalle metodológico' : 'Mostrar detalle metodológico' }}
</button>
<div [id]="methodologyId" [hidden]="!methodologyExpanded()">
@for (line of methodologyDetail; track $index) { <p>{{ line }}</p> }
</div>
}
<p class="period-note">Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.</p>
</section>
}
@@ -1,12 +1,22 @@
:host { display: block; min-width: 0; }
.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; }
.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); }
.interpretation {
padding: var(--issste-space-4);
margin-bottom: var(--issste-space-4);
border-left: 3px solid var(--issste-accent);
color: var(--issste-text);
font-family: var(--issste-font-body);
line-height: 1.5;
overflow-wrap: anywhere;
}
.interpretation h2 { margin: 0 0 .5rem; font-family: var(--issste-font-heading); font-size: 1.125rem; }
.interpretation ul { margin: 0; padding-left: 1.25rem; }
.interpretation li + li { margin-top: .25rem; }
.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); }
.figure-card { overflow: hidden; min-width: 0; }
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; }
.state { padding: 1.25rem; margin: 0; }
.period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); }
.methodology-toggle { margin-top: var(--issste-space-3); min-height: 44px; max-width: 100%; height: auto; white-space: normal; }
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.figure-card { overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
@media (max-width: 550px) { .interpretation { padding: 1rem; } }
@media (max-width: 550px) { .interpretation { padding: var(--issste-space-3); } }
@@ -128,4 +128,67 @@ describe('IndicadorFigureCard', () => {
expect(purge).toHaveBeenCalledWith(secondHost);
expect(disconnect).toHaveBeenCalledTimes(2);
});
it('UX-06D pliega solo el detalle complementario local C2 y mantiene advertencias visibles', () => {
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
state({ status: 'idle' });
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
expect(section.querySelector('ul')?.textContent).toContain('Las barras muestran la composición porcentual');
expect(section.querySelector('ul')?.textContent).toContain('SIN_DATO');
expect(section.querySelector('ul')?.textContent).toContain('suprimidos no representan tasas');
expect(section.querySelector('.period-note')?.textContent).toContain('no permite determinar la disponibilidad');
const button = section.querySelector('button')!;
const detail = section.querySelector('[id]') as HTMLElement;
expect(button.getAttribute('aria-expanded')).toBe('false');
expect(button.getAttribute('aria-controls')).toBe(detail.id);
expect(detail.hidden).toBe(true);
expect(detail.textContent?.trim()).toBe('Las categorías corresponden a la distribución de cada grupo y periodo.');
expect([...section.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.visibleInterpretation);
button.click(); fixture.detectChanges();
expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true');
state({ status: 'loading' });
expect(detail.hidden).toBe(false);
button.click(); fixture.detectChanges();
expect(detail.hidden).toBe(true);
});
it.each(['fig_c1_puntos', 'fig_c3r_cajas', 'desconocida'])('UX-06D mantiene íntegra la interpretación %s sin separación insegura', figura => {
fixture.componentRef.setInput('figuraId', figura);
if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' });
state({ status: 'idle' });
expect(fixture.nativeElement.querySelector('.methodology-toggle')).toBeNull();
expect([...fixture.nativeElement.querySelectorAll('.interpretation li')].map((li: any) => li.textContent))
.toEqual(fixture.componentInstance.interpretation);
});
it.each(['cacu', 'cama'])('UX-06D mantiene toda la interpretación C2 de %s visible', dominio => {
fixture.componentRef.setInput('dominio', dominio);
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
state({ status: 'loading' });
expect(fixture.nativeElement.querySelector('.methodology-toggle')).toBeNull();
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %');
});
it('UX-06D conserva completas todas las anotaciones, sin clasificar ni plegar notas del backend', async () => {
const figure: PlotlyFigure = { data: [{ y: [null, 0] }], layout: { annotations: [
{ text: 'Denominador pequeño<br>Intervalos no disponibles' },
{ text: 'Uso exclusivo de investigación. No usar para decisiones clínicas.' },
{ text: 'Supresión: consulta las notas completas' },
] }, frames: [] };
const snapshot = JSON.stringify(figure);
ready(figure); await settle();
const notes = fixture.nativeElement.querySelector('.notes') as HTMLElement;
expect(notes.closest('[hidden]')).toBeNull();
expect([...notes.querySelectorAll('p')].map(p => p.innerHTML)).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text));
expect(JSON.stringify(figure)).toBe(snapshot);
expect(fixture.nativeElement.querySelector('.plot-viewport')?.getAttribute('tabindex')).toBe('0');
});
it('UX-06D mantiene relaciones de detalle únicas incluso con separadores en IDs publicados', () => {
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a--b' });
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
state({ status: 'idle' });
const first = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls');
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a' });
fixture.componentRef.setInput('figuraId', 'b--fig_c2_apiladas');
fixture.detectChanges();
const second = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls');
expect(first).not.toBe(second);
expect(fixture.nativeElement.querySelector('[id]').id).toBe(second);
});
});
@@ -1,9 +1,10 @@
import { Component, Input, output } from '@angular/core';
import { Component, Input, output, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
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 { figureIdentity, identityElementId } from './indicadores-identities';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
// The panel owns requests; the card receives the original and its presentation copy.
@@ -49,6 +50,19 @@ export class IndicadorFigureCard {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) tema!: Tema;
readonly retry = output<void>();
readonly methodologyExpanded = signal(false);
get methodologyId(): string {
return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology';
}
// Only this exact local C2 sentence is complementary. Backend notes and
// uncertainty/suppression warnings are never classified or collapsed.
get methodologyDetail(): readonly string[] {
return this.interpretation.filter(line => line === CONTRACT_INTERPRETATIONS['C2'][1]);
}
get visibleInterpretation(): readonly string[] {
return this.interpretation.filter(line => line !== CONTRACT_INTERPRETATIONS['C2'][1]);
}
readonly hasNoVisibleValues = hasNoVisibleValues;
readonly figureTitle = figureTitle;
@@ -9,7 +9,6 @@
<a mat-button [routerLink]="['/indicadores', domain]" [attr.aria-current]="dominio === domain ? 'page' : null">{{ domainLabels[domain] }}</a>
}
</nav>
<p class="notice">Uso exclusivo de investigación. No usar para decisiones clínicas.</p>
@if (catalogLoading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
@@ -21,11 +20,6 @@
<mat-card class="state"><p role="status">No hay indicadores disponibles en el catálogo.</p>
<button mat-stroked-button (click)="retryCatalog()">Actualizar catálogo</button></mat-card>
} @else {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Tema del dominio</mat-label>
<mat-select [ngModel]="tema" (ngModelChange)="changeTema($event)">
<mat-option value="claro">Claro</mat-option><mat-option value="oscuro">Oscuro</mat-option>
</mat-select>
</mat-form-field>
<p role="status">{{ catalog().length }} indicadores publicados</p>
@if (searchVisible()) {
<div class="catalog-search">
@@ -3,7 +3,6 @@
h1 { font: var(--mat-sys-headline-large); font-family: var(--issste-font-heading); font-weight: 700; margin: .65rem 0; }
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
.notice { padding: 1rem 1.25rem; border-left: 4px solid var(--mat-sys-primary); background: var(--mat-sys-surface-container); border-radius: 8px; }
.state { padding: 1.25rem; margin: 0; }
mat-form-field { width: 100%; max-width: 24rem; }
@media (max-width: 550px) { h1 { font-size: var(--mat-sys-headline-medium-size); line-height: var(--mat-sys-headline-medium-line-height); } }
@@ -109,12 +109,12 @@ describe('UX-05B catálogo expandible', () => {
}
});
it('UX-06B conserva el selector técnico claro/oscuro y no vuelve a cargar el catálogo', async () => {
it('UX-06D retira el selector visual, inicia claro y conserva oscuro sin recargar catálogo', async () => {
load();
await fixture.whenStable(); fixture.detectChanges();
const select = fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect;
expect(select.options.map(option => option.value)).toEqual(['claro', 'oscuro']);
expect(select.value).toBe('claro');
expect(fixture.debugElement.query(By.directive(MatSelect))).toBeNull();
expect(fixture.nativeElement.textContent).not.toContain('Tema del dominio');
expect(page.tema).toBe('claro');
page.changeTema('oscuro'); fixture.detectChanges();
expect(page.tema).toBe('oscuro');
expect(cards().every(card => !card.expanded)).toBe(true);
@@ -180,6 +180,23 @@ describe('UX-05B catálogo expandible', () => {
expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(b.selectedPeriods).toEqual(['2026-01']);
themedA.flush({ data: [], layout: {} }); themedB.flush({ data: [], layout: {} });
});
it('UX-06D expandir metodología conserva panel, figura y borrador sin generar HTTP', () => {
load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); flushAll();
const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
const filters = control();
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add();
const draft = structuredClone(filters.entry.draft), applied = structuredClone(panel.filters!.applied);
const result = panel.result();
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
for (let i = 0; i < 2; i++) {
button.click(); fixture.detectChanges();
expect(button.getAttribute('aria-expanded')).toBe(i === 0 ? 'true' : 'false');
expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result);
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart);
expect(filters.entry.draft).toEqual(draft); expect(panel.filters!.applied).toEqual(applied);
http.expectNone(() => true);
}
});
it('cerrar y reabrir restaura borrador y aplicado por figura sin confirmar borradores', () => {
load([item]); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add();
panels()[0].applyFilters(); request('f1').flush({ data: [], layout: {} }); a.unit = 'S2'; a.add();
@@ -282,8 +299,9 @@ describe('UX-05B catálogo expandible', () => {
expect(writes).not.toHaveBeenCalled(); expect(saves).not.toHaveBeenCalled();
expect(panels()[0].result()).toBe(state); http.expectNone(() => true);
});
it('mantiene el aviso de investigación en el catálogo', () => {
load(); expect(fixture.nativeElement.querySelector('.notice').textContent).toBe('Uso exclusivo de investigación. No usar para decisiones clínicas.');
it('UX-06D retira solo el aviso general del catálogo', () => {
load(); expect(fixture.nativeElement.querySelector('.notice')).toBeNull();
expect(fixture.nativeElement.textContent).not.toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.');
});
it('IDs distintos con el mismo título y figura conservan paneles y etiquetas independientes', () => {
load([{ ...item, figuras: ['f1'] }, { ...second, titulo: item.titulo, figuras: ['f1'] }]);
+2 -3
View File
@@ -14,7 +14,7 @@ import { PLOTLY_LOADER } from './plotly-runtime';
<div role="alert"><p>No se pudo representar la figura. Puedes reintentar.</p>
<button mat-stroked-button (click)="retry()">Reintentar renderizado</button></div>
}
<div #host class="plot" role="img" [attr.aria-label]="label" [attr.aria-hidden]="status() !== 'ready'"></div>
<div class="plot-viewport" tabindex="0" role="region" [attr.aria-label]="label + ' · Área de figura'"><div #host class="plot" role="img" [attr.aria-label]="label" [attr.aria-hidden]="status() !== 'ready'"></div></div>
@if (status() === 'ready' && notes.length) {
<section class="notes" aria-label="Notas completas de la figura">
<h2>Notas de la figura</h2>
@@ -22,7 +22,7 @@ import { PLOTLY_LOADER } from './plotly-runtime';
</section>
}
`,
styles: `:host { display: block; min-width: 0; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { display: none; padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } @media (max-width: 850px) { .notes { display: block; } }`,
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; }`,
})
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
@Input() label = 'Figura estadística';
@@ -59,4 +59,3 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
this.controller?.destroy();
}
}