From 078db53ae4df06195ae6eb1bb4a53801857e310b Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 4 Nov 2026 22:09:02 -0600 Subject: [PATCH] =?UTF-8?q?feat(tea):=20pesta=C3=B1a=20Evoluci=C3=B3n=20y?= =?UTF-8?q?=20paleta=20con=20el=20verde=20de=20ISSSTELEON?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Pestaña Evolución (solo TEA), entre Resumen y Seguimiento: una figura por indicador con todos los periodos publicados, mensual o semestral. Barras apiladas para C2, línea con intervalo de confianza para C1 y mediana con cuartiles para C3r. Los periodos suprimidos se sombrean, no se dibujan como cero. - Paleta: verde #A8C243 y rojo ladrillo #B8433A, comprobados para daltonismo. Las líneas usan un verde más oscuro sobre fondo claro. - «Sin EEG» conserva su color en M21 y M22. Co-Authored-By: Claude Opus 5.5 --- .../indicadores/indicadores-c1-donut.spec.ts | 8 ++ .../indicadores/indicadores-c1-donut.ts | 19 +-- .../indicadores-c2-adapter.spec.ts | 8 +- .../indicadores-c2-general-selection.spec.ts | 2 +- .../indicadores/indicadores-c2-palette.ts | 8 +- .../indicadores-evolucion-figures.ts | 129 +++++++++++++++++ .../indicadores/indicadores-evolucion.spec.ts | 127 +++++++++++++++++ .../indicadores/indicadores-evolucion.ts | 132 ++++++++++++++++++ .../indicadores/indicadores-page.html | 6 + .../indicadores/indicadores-page.spec.ts | 4 +- .../features/indicadores/indicadores-page.ts | 18 ++- .../indicadores/indicadores-sections.spec.ts | 20 +-- 12 files changed, 447 insertions(+), 34 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-evolucion-figures.ts create mode 100644 src/app/features/indicadores/indicadores-evolucion.spec.ts create mode 100644 src/app/features/indicadores/indicadores-evolucion.ts diff --git a/src/app/features/indicadores/indicadores-c1-donut.spec.ts b/src/app/features/indicadores/indicadores-c1-donut.spec.ts index 45dc12b..49cb7a7 100644 --- a/src/app/features/indicadores/indicadores-c1-donut.spec.ts +++ b/src/app/features/indicadores/indicadores-c1-donut.spec.ts @@ -59,6 +59,14 @@ describe('Dona de dos anillos para C1', () => { expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']); expect(result.highlight.items[0].center).toBe('34.8 %
16 a 23 meses'); }); + it('«Sin EEG» conserva su color rojo en M21 y en M22', () => { + const anillos = c1DonutFigure(datos(), selection); + if (anillos.status !== 'supported') throw new Error('sin figura'); + expect((anillos.figure.data[1] as { marker: { colors: string[] } }).marker.colors).toEqual(['rgba(168,194,67,1)', 'rgba(184,67,58,1)']); + const barras = c1DonutFigure({ ...datos(), id: 'M22_diagnosticados_sin_eeg' }, { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' }); + if (barras.status !== 'supported') throw new Error('sin figura'); + expect((barras.figure.data[0] as { marker: { color: string } }).marker.color).toBe('#B8433A'); + }); it('barras por grupo de edad: una barra por grupo con su porcentaje', () => { const result = c1DonutFigure({ ...datos([fila('16-23', 8, 24), fila('24-29', 5, 18), fila('30-36', 5, 22)]), id: 'M22_diagnosticados_sin_eeg' }, { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' }); diff --git a/src/app/features/indicadores/indicadores-c1-donut.ts b/src/app/features/indicadores/indicadores-c1-donut.ts index d67b6f8..d713b1f 100644 --- a/src/app/features/indicadores/indicadores-c1-donut.ts +++ b/src/app/features/indicadores/indicadores-c1-donut.ts @@ -1,7 +1,7 @@ import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario'; import { percentNumber, shareText } from './indicadores-format'; import { donaHighlight, FigureHighlight } from './indicadores-highlight'; -import { c2Theme } from './indicadores-c2-palette'; +import { C2_PALETTE, c2Theme } from './indicadores-c2-palette'; import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models'; // Figures by age group for a C1 proportion over one semester, built from the age-stratified C1 rows: @@ -20,8 +20,10 @@ const EVENT_LABELS: Readonly> = { M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'], M24_confirmacion_diagnostico: ['Con diagnóstico positivo de TEA', 'Sin diagnóstico de TEA'], }; -// The CaCu ring colours: blue for the event, orange for its complement; age groups get lighter shades. -const RING_COLORS = ['#2F6DB3', '#D9822B'] as const; +// Green for the event, red for its complement; age groups get lighter shades. +const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const; +// M22's event is M21's complement: «Sin EEG» keeps its colour across both indicators. +const ringColors = (indicador: string): readonly [string, string] => indicador === 'M22_diagnosticados_sin_eeg' ? [RING_COLORS[1], RING_COLORS[0]] : RING_COLORS; export type C1DonutResult = { status: 'unsupported'; reason: string } | { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] }; @@ -63,14 +65,15 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): const title = { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period }; const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0); if (selection.figura === C1_AGE_BARS) { - const figure = ageBars(strata, labels[0], selection); + const colors = ringColors(data.id); + const figure = ageBars(strata, labels[0], colors[0], selection); figure.layout = { ...figure.layout, title }; const highlight: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todos los grupos de edad', - items: strata.map((s, i) => ({ id: s.id, label: s.label, color: RING_COLORS[0], points: [{ trace: 0, index: i }] })) }; + items: strata.map((s, i) => ({ id: s.id, label: s.label, color: colors[0], points: [{ trace: 0, index: i }] })) }; return { status: 'supported', figure, highlight, total, notes }; } - const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] })); + const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: ringColors(data.id)[g] })); const categorias: Categoria[] = [], celdas: Modelo['celdas'] = {}; grupos.forEach((g, gi) => strata.forEach((s, i) => { const id = g.id + ':' + s.id, n = gi ? (s.denominador as number) - (s.numerador as number) : s.numerador as number; @@ -120,11 +123,11 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): // "Con EEG" -> "con EEG", to follow «pacientes». const what = (label: string) => label.charAt(0).toLowerCase() + label.slice(1); // One bar per age group: the share of its patients with the event. -function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, selection: FigureSelection): PlotlyFigure { +function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, color: string, selection: FigureSelection): PlotlyFigure { const theme = c2Theme(selection.tema); const x = strata.map(s => escape(s.label)); const y = strata.map(s => (s.denominador as number) ? 100 * (s.numerador as number) / (s.denominador as number) : null); - return { data: [{ type: 'bar', x, y, marker: { color: RING_COLORS[0], line: { color: theme.background, width: 1 } }, + return { data: [{ type: 'bar', x, y, marker: { color, line: { color: theme.background, width: 1 } }, text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false, customdata: strata.map(s => [s.numerador, s.denominador]), hovertemplate: '%{x}
%{y:.1f} % (%{customdata[0]} de %{customdata[1]} pacientes)' }], diff --git a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts index 7aaf06b..76fb1b6 100644 --- a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts +++ b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts @@ -43,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => { const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final); const legend = donutLegend(final), view = donutSimpleView(final); expect(legend).toEqual([ - { label: 'A', color: '#7184A2' }, { label: 'B', color: '#A4B88A' }, { label: 'C', color: '#D0B778' }, + { label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' }, ]); expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } }); expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] }); @@ -161,12 +161,12 @@ describe('paleta C2 institucional y semántica', () => { it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => { const data = c2Fixture(); (data['categorias'] as Record>)['A']['color'] = '#D98E4A'; const figure = supported(data, { ...selection, tema }).figure; - expect((figure.data[0]['marker'] as Record)['colors']).toEqual(['#D98E4A', '#A4B88A', '#D0B778']); + expect((figure.data[0]['marker'] as Record)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']); expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background); expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text }); expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2'); - expect(c2Color(undefined, 0)).toBe('#7184A2'); expect(c2Color(undefined, 1)).toBe('#A4B88A'); - expect(c2Color(undefined, 2)).toBe('#D0B778'); expect(c2Color(undefined, 3)).toBe('#B78B8E'); + expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A'); + expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778'); expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined(); }); it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => { diff --git a/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts b/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts index 5419e30..bd0220c 100644 --- a/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts +++ b/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts @@ -19,7 +19,7 @@ describe('selección local segura de barras generales C2', () => { it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => { const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source }); const view = c2GeneralSelection(source, data, selection, local)!; - expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#A4B88A', '#D0B778'] } }); + expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } }); expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] }); expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' }); expect(view.context).toContain('G2, 2025-S2'); diff --git a/src/app/features/indicadores/indicadores-c2-palette.ts b/src/app/features/indicadores/indicadores-c2-palette.ts index 5042997..6c9d577 100644 --- a/src/app/features/indicadores/indicadores-c2-palette.ts +++ b/src/app/features/indicadores/indicadores-c2-palette.ts @@ -3,10 +3,12 @@ import { Tema } from './indicadores.models'; // Matches src/styles.scss: interface tokens are the source of these candidates, // not a certified brand guide. Published semantic colours always take priority. export const C2_PALETTE = Object.freeze({ - series: Object.freeze(['#7184A2', '#A4B88A', '#D0B778', '#B78B8E']), + // ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness. + series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']), states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }), - claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1' }), - oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F' }), + // line: the green for thin marks; the brand green itself is too light to read as a line on white. + claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }), + oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }), }); export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; } export function c2Color(published: string | undefined, index: number): string { diff --git a/src/app/features/indicadores/indicadores-evolucion-figures.ts b/src/app/features/indicadores/indicadores-evolucion-figures.ts new file mode 100644 index 0000000..ab0ef6b --- /dev/null +++ b/src/app/features/indicadores/indicadores-evolucion-figures.ts @@ -0,0 +1,129 @@ +import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette'; +import { sortedPeriods } from './indicadores-periodos'; + +export interface EvolucionFigura { + figure: PlotlyFigure; + comoLeer: string; + suprimidos: string[]; + sinDato: string[]; +} +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +// sortedPeriods lists the newest first, for selectors; time here runs left to right. +export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse(); + +function validar(data: IndicadorDatos) { + for (const row of data.filas) { + if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de evolución inválida'); + } + return cronologico(data.periodos); +} +function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string) { + const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes'; + return { + autosize: true, height: 380, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, + margin: { l: 64, r: 16, t: 16, b: mensual ? 96 : 64 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.3 : -0.12, itemclick: false, itemdoubleclick: false }, + // A label for every month does not fit: one per quarter is still readable with the full period on hover. + xaxis: { type: 'category', categoryorder: 'array', categoryarray: periodos, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0, + tickmode: 'array', tickvals: periodos.filter((_, i) => periodos.length <= 12 || i % 3 === 0) }, + yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false }, + // Shaded, because an empty space alone reads as zero. Text below the figure says the same. + shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 }, + x0: periodos.indexOf(periodo) - .5, x1: periodos.indexOf(periodo) + .5, fillcolor: C2_PALETTE.states.suppressed, opacity: .18 })), + }; +} +// One polygon per run of consecutive values: a band must not bridge a gap in the line. +function banda(periodos: string[], bajo: (number | null)[], alto: (number | null)[], name: string, color: string) { + const x: (string | null)[] = [], y: (number | null)[] = []; + let run: number[] = []; + const cerrar = () => { + if (run.length) { + if (x.length) { x.push(null); y.push(null); } + x.push(...run.map(i => periodos[i]), ...[...run].reverse().map(i => periodos[i])); + y.push(...run.map(i => alto[i]), ...[...run].reverse().map(i => bajo[i])); + } + run = []; + }; + periodos.forEach((_, i) => { if (bajo[i] !== null && alto[i] !== null) run.push(i); else cerrar(); }); + cerrar(); + return { type: 'scatter', mode: 'lines', name, x, y, fill: 'toself', fillcolor: color + '40', line: { width: 0 }, hoverinfo: 'skip' }; +} +// Separate rows from what is missing or suppressed; a period is judged by its only row. +function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record) => boolean) { + const filas = new Map(data.filas.map(row => [row['periodo'] as string, row])); + if (filas.size !== data.filas.length) throw new Error('Filas ambiguas'); + const suprimidos: string[] = [], sinDato: string[] = []; + const validas = periodos.map(periodo => { + const row = filas.get(periodo); + if (row?.['suprimido'] === 1) { suprimidos.push(periodo); return null; } + if (!row || !valor(row)) { sinDato.push(periodo); return null; } + return row; + }); + return { validas, suprimidos, sinDato }; +} +const campo = (filas: (Record | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null); + +function porcentaje(data: IndicadorDatos, tema: Tema): EvolucionFigura { + const periodos = validar(data); + const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor'])); + const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'); + return { + figure: { data: [ + banda(periodos, campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', c2Theme(tema).line), + { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos, y: campo(validas, 'valor'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 }, + text: validas.map(row => row ? `${row['valor']} %
${row['numerador']} de ${row['denominador']}
IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''), + hovertemplate: '%{x}
%{text}' }, + ], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, + comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.', + suprimidos, sinDato, + }; +} +function mediana(data: IndicadorDatos, tema: Tema): EvolucionFigura { + const periodos = validar(data); + const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana'])); + return { + figure: { data: [ + banda(periodos, campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', c2Theme(tema).line), + { type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos, y: campo(validas, 'mediana'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 }, + text: validas.map(row => row ? `Mediana: ${row['mediana']} días
Q1 a Q3: ${row['q1']} a ${row['q3']} días
${row['n']} pacientes` : ''), + hovertemplate: '%{x}
%{text}' }, + ], layout: ejes(data, periodos, suprimidos, tema, 'Días') }, + comoLeer: 'La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de los pacientes.', + suprimidos, sinDato, + }; +} +function conteo(data: IndicadorDatos, tema: Tema): EvolucionFigura { + const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}; + const celdas = new Map>(), categorias = new Map(); + for (const row of data.filas) { + const id = row['categoria'], key = JSON.stringify([id, row['periodo']]); + if (typeof id !== 'string' || !id || !numero(row['orden']) || celdas.has(key)) throw new Error('Fila de evolución inválida'); + celdas.set(key, row); + categorias.set(id, row['orden']); + } + const orden = [...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id); + const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo]))); + const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1)); + const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n']))); + return { + figure: { data: orden.map((id, i) => { + const meta = record(catalogo[id]) ? catalogo[id] : {}; + const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined; + const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; }); + return { type: 'bar', name: escape(typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : id), x: periodos, y: valores, + marker: { color: c2Color(color, i) }, hovertemplate: '%{y}%{fullData.name}' }; + }), layout: { ...ejes(data, periodos, suprimidos, tema, 'Pacientes'), barmode: 'stack', bargap: .15, hovermode: 'x unified' } }, + comoLeer: 'Cada barra es el total de pacientes del periodo, y sus partes muestran cuántos hay en cada categoría.', + suprimidos, sinDato, + }; +} +// The plot follows from what the contract's numbers mean: counts add up to a total, percentages +// and medians do not, so those two are never stacked. +export function evolucionFigura(data: IndicadorDatos, tema: Tema): EvolucionFigura { + if (data.contrato === 'C2') return conteo(data, tema); + if (data.contrato === 'C1') return porcentaje(data, tema); + if (data.contrato === 'C3r') return mediana(data, tema); + throw new Error('Representación no soportada'); +} diff --git a/src/app/features/indicadores/indicadores-evolucion.spec.ts b/src/app/features/indicadores/indicadores-evolucion.spec.ts new file mode 100644 index 0000000..e42a6de --- /dev/null +++ b/src/app/features/indicadores/indicadores-evolucion.spec.ts @@ -0,0 +1,127 @@ +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { IndicadoresEvolucion } from './indicadores-evolucion'; +import { evolucionFigura } from './indicadores-evolucion-figures'; +import { Indicador, IndicadorDatos } from './indicadores.models'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub {} +const traza = (d: IndicadorDatos, i: number) => evolucionFigura(d, 'claro').figure.data[i] as Record & { x: unknown[]; y: unknown[] }; +const base = { id: 'i', tipo_periodo: 'mes' as const, periodos: ['2024-03', '2024-01', '2024-02'] }; +const c1 = (periodo: string, valor: number | null, suprimido = 0) => ({ periodo, suprimido, valor, numerador: valor, denominador: valor === null ? null : 100, + ic_bajo: valor === null ? null : valor - 5, ic_alto: valor === null ? null : valor + 5 }); +const c2 = (periodo: string, categoria: string, n: number | null, orden: number, suprimido = 0) => ({ periodo, categoria, n, orden, suprimido }); + +describe('Figuras de evolución', () => { + it('C2 apila conteos en orden cronológico, por categoría y con el color publicado', () => { + const data: IndicadorDatos = { ...base, contrato: 'C2', categorias: { B: { etiqueta: 'Bé ', color: '#112233' } }, filas: base.periodos.flatMap(p => [c2(p, 'B', 2, 1), c2(p, 'A', 1, 0)]) }; + const { figure, suprimidos, sinDato } = evolucionFigura(data, 'claro'); + expect(figure.layout['barmode']).toBe('stack'); + expect(figure.data.map(t => t['name'])).toEqual(['A', 'Bé <b>']); + expect(figure.data[0]['x']).toEqual(['2024-01', '2024-02', '2024-03']); + expect((figure.data[1]['marker'] as { color: string }).color).toBe('#112233'); + expect(suprimidos).toEqual([]); expect(sinDato).toEqual([]); + }); + it('C2 no dibuja como cero una celda suprimida y sombrea su periodo', () => { + const data: IndicadorDatos = { ...base, contrato: 'C2', filas: [c2('2024-01', 'A', 5, 0), c2('2024-02', 'A', null, 0, 1), c2('2024-03', 'A', 0, 0)] }; + const { figure, suprimidos } = evolucionFigura(data, 'claro'); + expect(figure.data[0]['y']).toEqual([5, null, 0]); + expect(suprimidos).toEqual(['2024-02']); + expect(figure.layout['shapes']).toEqual([expect.objectContaining({ x0: .5, x1: 1.5 })]); + }); + it('C1 es una línea que no cruza huecos y su banda tampoco', () => { + const data: IndicadorDatos = { ...base, contrato: 'C1', filas: [c1('2024-01', 40), c1('2024-02', null, 1), c1('2024-03', 60)] }; + const { suprimidos, figure } = evolucionFigura(data, 'claro'); + expect(traza(data, 1).y).toEqual([40, null, 60]); + expect(traza(data, 0).x).toEqual(['2024-01', '2024-01', null, '2024-03', '2024-03']); + expect(traza(data, 0).y).toEqual([45, 35, null, 65, 55]); + expect(suprimidos).toEqual(['2024-02']); + expect(figure.layout['barmode']).toBeUndefined(); + expect((figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 100]); + }); + it('C3r muestra la mediana con la banda entre cuartiles y distingue sin dato de suprimido', () => { + const data: IndicadorDatos = { ...base, periodos: ['2024-01', '2024-02'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }; + const { sinDato, suprimidos } = evolucionFigura(data, 'claro'); + expect(traza(data, 1).y).toEqual([20, null]); + expect(traza(data, 0).y).toEqual([30, 10]); + expect(sinDato).toEqual(['2024-02']); expect(suprimidos).toEqual([]); + }); + it('las líneas usan el verde legible en cada tema', () => { + const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }; + const color = (tema: 'claro' | 'oscuro') => (evolucionFigura(data, tema).figure.data[1]['line'] as { color: string }).color; + expect(color('claro')).toBe('#6A8000'); expect(color('oscuro')).toBe('#A8C243'); + }); + it('rechaza contratos sin representación y filas ambiguas', () => { + expect(() => evolucionFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada'); + expect(() => evolucionFigura({ ...base, contrato: 'C1', filas: [c1('2024-01', 1), c1('2024-01', 2)] }, 'claro')).toThrow('ambiguas'); + }); +}); + +describe('Pestaña Evolución', () => { + let http: HttpTestingController; + let fixture: ComponentFixture; + const catalog: Indicador[] = [{ id: 'm1', titulo: 'Uno', contrato: 'C1', figuras: [], tipos_periodo: ['semestre', 'mes'] }]; + const periodos = { id: 'm1', version: '1', periodos: [ + { periodo: '2024-01', tipo: 'mes', report_id: 1, periodo_inicio: '2024-01-01', periodo_fin: '2024-02-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' }, + { periodo: '2024-02', tipo: 'mes', report_id: 2, periodo_inicio: '2024-02-01', periodo_fin: '2024-03-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' }, + { periodo: '2024-S1', tipo: 'semestre', report_id: 3, periodo_inicio: '2024-01-01', periodo_fin: '2024-07-01', fecha_corte: '2024-08-01', generado_en: '2024-08-01T00:00:00+00:00' }, + ] }; + const datos = (tipo: string, ps: string[]) => ({ id: 'm1', contrato: 'C1', tipo_periodo: tipo, periodos: ps, filas: ps.map(p => c1(p, 50)) }); + const datosUrl = '/tea/indicadores/m1/datos'; + const render = () => { TestBed.tick(); fixture.detectChanges(); }; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadoresEvolucion, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + fixture = TestBed.createComponent(IndicadoresEvolucion); + fixture.componentRef.setInput('dominio', 'tea'); + fixture.componentRef.setInput('catalog', catalog); + fixture.componentRef.setInput('tema', 'claro'); + render(); + }); + afterEach(() => http.verify()); + const abrir = () => { + fixture.componentRef.setInput('active', true); render(); + http.expectOne('/tea/indicadores/m1/periodos').flush(periodos); + }; + + it('no consulta hasta abrir la pestaña y entonces pide todos los periodos de una vez', () => { + http.expectNone(() => true); + abrir(); + const request = http.expectOne(r => r.url === datosUrl); + expect(request.request.params.get('periodos')!.split(',').sort()).toEqual(['2024-01', '2024-02']); + request.flush(datos('mes', ['2024-01', '2024-02'])); render(); + expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024-01 a 2024-02 (2 meses)'); + expect(fixture.nativeElement.querySelector('mat-select')).toBeNull(); + }); + it('cada intervalo se consulta una vez y cambiar de tema no vuelve a consultar', () => { + abrir(); + http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); + fixture.componentInstance.tipo.set('semestre'); render(); + const semestre = http.expectOne(r => r.url === datosUrl); + expect(semestre.request.params.get('periodos')).toBe('2024-S1'); + semestre.flush(datos('semestre', ['2024-S1'])); render(); + expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024-S1 a 2024-S1 (1 semestre)'); + fixture.componentInstance.tipo.set('mes'); render(); + fixture.componentRef.setInput('tema', 'oscuro'); render(); + http.expectNone(() => true); + }); + it('avisa del error sin perder la pestaña y reintenta', () => { + abrir(); + http.expectOne(r => r.url === datosUrl).flush({}, { status: 500, statusText: 'Error' }); render(); + expect(fixture.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); + fixture.nativeElement.querySelector('[role="alert"] button').click(); render(); + http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); + expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeNull(); + expect(fixture.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); + }); + it('un indicador sin reportes del intervalo lo dice sin consultar sus datos', () => { + fixture.componentRef.setInput('active', true); render(); + http.expectOne('/tea/indicadores/m1/periodos').flush({ ...periodos, periodos: [periodos.periodos[2]] }); render(); + http.expectNone(r => r.url === datosUrl); + expect(fixture.nativeElement.textContent).toContain('Sin reportes publicados'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-evolucion.ts b/src/app/features/indicadores/indicadores-evolucion.ts new file mode 100644 index 0000000..fffc2b8 --- /dev/null +++ b/src/app/features/indicadores/indicadores-evolucion.ts @@ -0,0 +1,132 @@ +import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { cronologico, evolucionFigura, EvolucionFigura } from './indicadores-evolucion-figures'; +import { httpMessage } from './indicadores-http'; +import { IndicadoresPeriodos } from './indicadores-periodos'; +import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; + +type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string }; +type Panel = { item: Indicador; rango?: string } & ( + { estado: 'cargando' | 'vacio' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: EvolucionFigura }); + +// Evolution of each indicator over every published period; only the granularity is chosen. +// Nothing is requested until the tab is first opened, and each granularity is requested once. +@Component({ + selector: 'app-indicadores-evolucion', + imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart], + template: ` +
+ Intervalo de análisis + + Mensual + Semestral + +
+
+ @for (panel of paneles(); track panel.item.id) { +
+

{{ panel.item.titulo }}

+ @if (panel.rango) {

{{ panel.rango }}

} + @switch (panel.estado) { + @case ('cargando') { } + @case ('vacio') {

Sin reportes publicados para este intervalo de análisis.

} + @case ('error') { +

{{ panel.mensaje }}

+
+ } + @case ('listo') { + +

{{ panel.figura.comoLeer }}

+ @if (panel.figura.suprimidos.length) { +

Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}

+ } + @if (panel.figura.sinDato.length) {

Sin dato: {{ panel.figura.sinDato.join(', ') }}.

} + } + } +
+ } +
+ `, + styles: ` + :host { display: block; min-width: 0; } + .controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6); + background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + .paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } + @container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } } + .panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; } + p { margin: var(--issste-space-3) 0 0; } + .rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } + app-plotly-chart { margin-top: var(--issste-space-3); } + `, +}) +export class IndicadoresEvolucion { + readonly dominio = input.required(); + readonly catalog = input.required(); + readonly tema = input.required(); + readonly active = input(false); + readonly tipo = signal('mes'); + private readonly service = inject(IndicadoresService); + private readonly periodos = inject(IndicadoresPeriodos); + private readonly cargas = signal>>>({}); + private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>(); + private solicitada?: string; + private catalogoCargado?: readonly Indicador[]; + + readonly paneles = computed(() => { + const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema(); + return this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(item => { + const carga = cargas?.[item.id]; + if (!carga) return { item, estado: 'cargando' }; + if (carga.estado !== 'listo') return { item, ...carga }; + const periodos = cronologico(carga.datos.periodos); + const unidad = tipo === 'mes' ? (periodos.length === 1 ? 'mes' : 'meses') : (periodos.length === 1 ? 'semestre' : 'semestres'); + const rango = `${periodos[0]} a ${periodos[periodos.length - 1]} (${periodos.length} ${unidad})`; + try { + return { item, rango, estado: 'listo', figura: evolucionFigura(carga.datos, tema) }; + } catch (error) { + return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de evolución inválidos' }; + } + }); + }); + + constructor() { + this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo)) + .map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))), + takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => { + this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) })); + }); + effect(() => { + const tipo = this.tipo(), items = this.catalog(); + if (!this.active() || !items.length) return; + untracked(() => { + if (this.catalogoCargado !== items) { this.catalogoCargado = items; this.cargas.set({}); this.solicitada = undefined; } + if (this.cargas()[tipo] || this.solicitada === tipo) return; + this.solicitada = tipo; + this.solicitudes.next({ tipo, items }); + }); + }); + } + private cargar(item: Indicador, tipo: TipoPeriodo): Observable { + return this.periodos.periodos(this.dominio(), item.id).pipe( + map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)), + switchMap((periodos): Observable => periodos.length + ? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos }))) + : of({ estado: 'vacio' })), + catchError(error => of({ estado: 'error', mensaje: httpMessage(error) }))); + } + reintentar() { + const tipo = this.tipo(); + this.solicitada = tipo; + this.cargas.update(({ [tipo]: _, ...resto }) => resto); + this.solicitudes.next({ tipo, items: this.catalog() }); + } +} diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 137009c..bace965 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -121,6 +121,12 @@ + @if (dominio === 'tea') { +
+ +
+ } +
diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 34e60fe..ae25aac 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -55,7 +55,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => { load(); expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores'); - expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3); + expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4); fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente'); expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de TEA'); @@ -63,7 +63,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title'); fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores'); - expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3); + expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4); expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento'); expect(page.activeSection()).toBe('resumen'); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 844b991..6481f10 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -27,21 +27,25 @@ import { httpMessage } from './indicadores-http'; import { IndicadoresInitialPeriod } from './indicadores-initial-period'; import { IndicadoresDefinitions } from './indicadores-definitions'; import { IndicadoresTracking } from './indicadores-tracking'; +import { IndicadoresEvolucion } from './indicadores-evolucion'; -type DashboardSection = 'resumen' | 'seguimiento' | 'datos'; +type DashboardSection = 'resumen' | 'evolucion' | 'seguimiento' | 'datos'; +const SECTIONS: readonly { id: DashboardSection; label: string }[] = [ + { id: 'resumen', label: 'Resumen' }, + { id: 'seguimiento', label: 'Seguimiento' }, + { id: 'datos', label: 'Datos y definiciones' }, +]; +// Only TEA has enough periods for an evolution to say anything. +const TEA_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'evolucion', label: 'Evolución' }, SECTIONS[1], SECTIONS[2]]; @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, TeaResumenPeriodo], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresEvolucion, TeaResumenPeriodo], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { - readonly sections: readonly { id: DashboardSection; label: string }[] = [ - { id: 'resumen', label: 'Resumen' }, - { id: 'seguimiento', label: 'Seguimiento' }, - { id: 'datos', label: 'Datos y definiciones' }, - ]; + get sections() { return this.dominio === 'tea' ? TEA_SECTIONS : SECTIONS; } readonly activeSection = signal('resumen'); readonly fichaPacienteAbierta = signal(false); setFichaPacienteAbierta(open: boolean) { diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index f518dff..c44a708 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -31,14 +31,16 @@ describe('Secciones compartidas por dominio', () => { }); afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); - it.each(DOMINIOS)('entrada directa en %s presenta tres pestañas y Resumen seleccionado', async domain => { + it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => { const harness = await RouterTestingHarness.create(); const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); - expect(tabs.map(t => t.textContent?.trim())).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']); - expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(['true', 'false', 'false']); + expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea' + ? ['Resumen', 'Evolución', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']); + expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.map((_, i) => String(i === 0))); + const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!; expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]); // Upstream moved domain selection to its own App shell; ours keeps it on // the page itself (see indicadores-page.html), since our shell is shared @@ -50,7 +52,7 @@ describe('Secciones compartidas por dominio', () => { expect(panel.hidden).toBe(tab.id !== 'tab-resumen'); } const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance); - tabs[1].click(); harness.detectChanges(); + tab('seguimiento').click(); harness.detectChanges(); if (domain === 'cacu' || domain === 'tea') { http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); harness.detectChanges(); @@ -70,9 +72,9 @@ describe('Secciones compartidas por dominio', () => { expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6'); expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0); } - tabs[2].click(); harness.detectChanges(); + tab('datos').click(); harness.detectChanges(); expect(root.querySelector('#panel-datos')!.hidden).toBe(false); - tabs[0].click(); harness.detectChanges(); + tab('resumen').click(); harness.detectChanges(); expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards); http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes. }); @@ -94,15 +96,15 @@ describe('Secciones compartidas por dominio', () => { const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges(); const tabs = Array.from(harness.routeNativeElement!.querySelectorAll('[role="tab"]')); - expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1]); + expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1, -1]); const focus = tabs.map(tab => vi.spyOn(tab, 'focus')); function key(index: number, key: string, target: number) { const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); tabs[index].dispatchEvent(event); expect(event.defaultPrevented).toBe(true); expect(focus[target]).toHaveBeenCalled(); expect(page.activeSection()).toBe('resumen'); } - key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 2); key(1, 'Home', 0); key(0, 'End', 2); - tabs[2].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, 0]); + key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 3); key(1, 'Home', 0); key(0, 'End', 3); + tabs[3].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, -1, 0]); http.expectNone(() => true); });