diff --git a/src/app/features/indicadores/indicador-confirmacion-citologia.scss b/src/app/features/indicadores/indicador-confirmacion-citologia.scss index c8a2798..00d0c7a 100644 --- a/src/app/features/indicadores/indicador-confirmacion-citologia.scss +++ b/src/app/features/indicadores/indicador-confirmacion-citologia.scss @@ -5,6 +5,15 @@ p, h3, summary { overflow-wrap: anywhere; } .methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } .selection-status { font-weight: 600; } .legend { display: grid; gap: .6rem; margin-block: 1rem; } +.families { display: flex; flex-wrap: wrap; gap: .75rem; } +.family { flex: 1 1 16rem; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--issste-border); border-radius: 1rem; background: var(--issste-surface); } +.family button { display: inline-flex; align-items: center; gap: .55rem; } +.family .parent { width: 100%; justify-content: flex-start; border: 0; border-radius: 0; border-bottom: 1px solid var(--issste-border); font-weight: 650; background: color-mix(in srgb, var(--swatch) 14%, var(--issste-surface)); } +.family .children { display: flex; flex-wrap: wrap; gap: .4rem; padding: .55rem; } +.family .child { flex: 1 1 8rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); } +.family .parent[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 24%, var(--issste-surface)); box-shadow: inset 0 -3px 0 var(--swatch); } +.family .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); transform: scale(1.03); } +.family .swatch { width: .35rem; height: 1.15rem; border: 0; border-radius: .2rem; background: var(--swatch); } .keys { display: flex; flex-wrap: wrap; gap: .5rem; } .legend > button { justify-self: start; } button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border); diff --git a/src/app/features/indicadores/indicador-histopatologia-cama.html b/src/app/features/indicadores/indicador-histopatologia-cama.html index cc12406..93cf34f 100644 --- a/src/app/features/indicadores/indicador-histopatologia-cama.html +++ b/src/app/features/indicadores/indicador-histopatologia-cama.html @@ -43,20 +43,24 @@

Resultado de la biopsia, {{ m.periodo }}

@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) { - + } @else {

{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}

}
-
- @for (g of m.grupos; track g.id; let i = $index) { - - } -
-
- @for (c of m.categorias; track c.id; let i = $index) { - +
+ @for (g of m.grupos; track g.id; let gi = $index) { +
+ +
+ @for (c of m.categorias; track c.id; let ci = $index) { + @if (c.grupo === g.id) { + + } + } +
+
}
diff --git a/src/app/features/indicadores/indicadores-c2-palette.ts b/src/app/features/indicadores/indicadores-c2-palette.ts index b3557e0..eb15784 100644 --- a/src/app/features/indicadores/indicadores-c2-palette.ts +++ b/src/app/features/indicadores/indicadores-c2-palette.ts @@ -38,10 +38,10 @@ export type Tono = 'frio' | 'calido' | 'neutro'; /** Metadata id: cool for normal groups, warm for abnormal ones. Unknown ids stay neutral. */ export function tonoDe(clave: string | undefined | null): Tono { if (!clave) return 'neutro'; - const id = clave.toUpperCase(); + const id = clave.normalize('NFD').replace(/\p{M}/gu, '').toUpperCase().replace(/[^A-Z0-9]+/g, '_'); if (id.includes('SIN_DATO') || id.includes('SIN_BIOPSIA')) return 'neutro'; - if (id.includes('NO_ANORMAL') || id.includes('NO_MALIG') || id.includes('BENIGN') || id.includes('NO_ALTER')) return 'frio'; - if (id.includes('ANORMAL') || id.includes('MALIG') || id.includes('INVAS') || id.includes('IN_SITU') || id.includes('LIEAG') || id.includes('ALTER')) return 'calido'; + if (id.includes('NO_METAST') || id.includes('SIN_METAST') || id.includes('NO_ANORMAL') || id.includes('NO_MALIG') || id.includes('BENIGN') || id.includes('NO_ALTER')) return 'frio'; + if (id.includes('METAST') || id.includes('CARCINOMA') || id.includes('ANORMAL') || id.includes('MALIG') || id.includes('INVAS') || id.includes('IN_SITU') || id.includes('LIEAG') || id.includes('ALTER')) return 'calido'; if (/^(B4|B4A|B4B|B4C|B5|B6)$/.test(id) || /^BIRADS_[456]/.test(id)) return 'calido'; return 'neutro'; } diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts index 70c3b99..3d5bc3b 100644 --- a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts @@ -22,7 +22,7 @@ import { clicHistopatologia, donaHistopatologia, estadoTasa, figuraTasas, Histop periodosHistopatologia, rangoTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama'; @Component({ selector: 'app-plotly-chart', template: '' }) -class ChartStub { figure = input(); label = input(); showNotes = input(); plotClick = output(); } +class ChartStub { figure = input(); label = input(); showNotes = input(); animated = input(); plotClick = output(); } const estrato = () => structuredClone(estratoFixture) as unknown as IndicadorDatos & { filas: Record[]; totales_estrato: Record[]; valores_estrato: string[]; categorias: Record }; const fila = (d: { filas: Record[] }, e: string, c: string) => d.filas.find(f => f['estrato'] === e && f['categoria'] === c)!; @@ -35,7 +35,10 @@ describe('Histopatología por BI-RADS: modelo', () => { expect(m.filas.map(f => f.id)).toEqual(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']); expect(m.filas.map(f => f.etiqueta)).toEqual(['BI-RADS 4 sin subtipo', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']); expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR']); - expect(m.categorias.map(c => c.color)).toEqual(['#9DBFE3', '#2F6DB3', C2_PALETTE.calidos[0], C2_PALETTE.calidos[1]]); + expect(m.categorias.map(c => c.color)).toEqual([C2_PALETTE.frios[0], C2_PALETTE.frios[4], C2_PALETTE.calidos[1], C2_PALETTE.calidos[2]]); + expect(m.grupos.map(g => g.color)).toEqual([C2_PALETTE.frios[3], C2_PALETTE.calidos[0]]); + const tasas = figuraTasas(m, seleccionBase(m), 'claro'); + expect((tasas.data[0]['marker'] as { color: string[] }).color).toEqual([...C2_PALETTE.calidos]); expect(m.grupos.map(g => [g.id, g.etiqueta, g.categorias])).toEqual([ ['NO_MALIGNO', 'No maligno', ['BENIGNO', 'RIESGO_B3']], ['MALIGNO', 'Maligno', ['IN_SITU', 'INVASOR']]]); expect(m.base).toBe('MALIGNO'); @@ -193,15 +196,21 @@ describe('Histopatología por BI-RADS: tasas, selección y figuras', () => { expect((estrecho.layout['xaxis'] as { title: { text: string }; nticks: number })).toMatchObject({ title: { text: 'Porcentaje' }, nticks: 3 }); expect((ancho.layout['yaxis'] as Record)['ticktext']).toBeUndefined(); }); - it('dona de dos anillos: grupos dentro, categorías fuera; la selección atenúa sin cambiar valores y el centro dice «k de N con resultado»', () => { + it('dona de dos anillos: grupos dentro, categorías fuera; la selección agranda el trozo sin cambiar el color y el centro dice «k de N con resultado»', () => { const m = base(), d = donaHistopatologia(m, seleccionBase(m), 'claro'); - expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']); + expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias', 'grupos', 'categorias']); expect(d.data[1]['values']).toEqual([12, 13]); expect(d.data[2]['values']).toEqual([7, 5, 6, 7]); + expect(d.data[4]['values']).toEqual(d.data[2]['values']); expect(d.data[0]['text']).toEqual(['13
de 25 con resultado']); + expect((d.data[2]['marker'] as { colors: string[] }).colors).toEqual(m.categorias.map(c => c.color)); + expect((d.data[4]['marker'] as { colors: string[] }).colors).toEqual(['rgba(0,0,0,0)', 'rgba(0,0,0,0)', m.categorias[2].color, m.categorias[3].color]); + const baseSpan = ((d.data[2]['domain'] as { x: number[] }).x[1] - (d.data[2]['domain'] as { x: number[] }).x[0]); + const zoomSpan = ((d.data[4]['domain'] as { x: number[] }).x[1] - (d.data[4]['domain'] as { x: number[] }).x[0]); + expect(zoomSpan).toBeGreaterThan(baseSpan); const otra = donaHistopatologia(m, { grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }, 'claro'); expect(otra.data[2]['values']).toEqual(d.data[2]['values']); - const colores = (otra.data[2]['marker'] as { colors: string[] }).colors; - expect(colores[1]).toMatch(/,1\)$/); expect(colores[0]).toMatch(/,0.3\)$/); + expect((otra.data[2]['marker'] as { colors: string[] }).colors).toEqual(m.categorias.map(c => c.color)); + expect((otra.data[4]['marker'] as { colors: string[] }).colors[1]).toBe(m.categorias[1].color); expect(otra.data[0]['text']).toEqual(['5
de 25 con resultado']); }); it('el histórico usa el C2 general con las seis categorías, sin necesidad del estrato', () => { @@ -232,7 +241,7 @@ describe('Histopatología por BI-RADS: componente', () => { expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO); r.flush(body as Record); f.detectChanges(); } - const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement; + const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.families button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement; it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => { f.componentRef.setInput('visible', false); f.detectChanges(); @@ -241,8 +250,11 @@ describe('Histopatología por BI-RADS: componente', () => { flush(); expect(f.componentInstance.status()).toBe('ready'); const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[]; expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']); - expect([...f.nativeElement.querySelectorAll('.keys button')].map((b: Element) => b.textContent!.trim())) - .toEqual(['No maligno', 'Maligno', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']); + expect([...f.nativeElement.querySelectorAll('.families button')].map((b: Element) => b.textContent!.trim())) + .toEqual(['No maligno', 'Benigno', 'Lesión de riesgo (B3)', 'Maligno', 'Carcinoma in situ', 'Carcinoma invasor']); + expect(f.nativeElement.querySelectorAll('.family')).toHaveLength(2); + expect([...f.nativeElement.querySelectorAll('.family')[1].querySelectorAll('button')].map((b: Element) => b.textContent!.trim())) + .toEqual(['Maligno', 'Carcinoma in situ', 'Carcinoma invasor']); const grafica = f.nativeElement.querySelector('.figures') as HTMLElement; const seleccion = f.nativeElement.querySelector('.selection-status') as HTMLElement; expect(grafica.nextElementSibling?.classList.contains('legend')).toBe(true); diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.ts index d5127b1..35d1e92 100644 --- a/src/app/features/indicadores/indicadores-histopatologia-cama.ts +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.ts @@ -31,6 +31,11 @@ const APARTE_IDS: readonly string[] = APARTE.map(a => a.id); // The group the base view reads: the malignant results, the true positives of the suspicion. const CATEGORIA_BASE = 'INVASOR'; const COLOR_RESPALDO = '#8A9199'; +// Chosen from the logo scheme: cool for a normal result, warm for an abnormal one, each slice a different hue. +const COLOR_RESULTADO: Readonly> = { + BENIGNO: C2_PALETTE.frios[0], RIESGO_B3: C2_PALETTE.frios[4], IN_SITU: C2_PALETTE.calidos[1], INVASOR: C2_PALETTE.calidos[2], +}; +const COLOR_GRUPO: Readonly> = { NO_MALIGNO: C2_PALETTE.frios[3], MALIGNO: C2_PALETTE.calidos[0] }; export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; } export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; } @@ -77,9 +82,16 @@ function promedio(colores: string[]): string { return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length) .toString(16).padStart(2, '0')).join(''); } -function rgba(hex: string, alfa: number): string { - const v = parseInt(hex.slice(1), 16); - return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; +const ZOOM_GRUPO = 1.12; +const ZOOM_HIJO = 1.08; +const ZOOM_ELEGIDO = 1.16; +const ZOOM_PADRE = 1.06; +const CAJA_GRUPO = [0.2, 0.8, 0.2, 0.8] as const; +const CAJA_CATEGORIA = [0.1, 0.9, 0.1, 0.9] as const; +function caja(base: readonly [number, number, number, number], zoom: number) { + const [x0, x1, y0, y1] = base; + const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, hx = (x1 - x0) / 2 * zoom, hy = (y1 - y0) / 2 * zoom; + return { x: [cx - hx, cx + hx], y: [cy - hy, cy + hy] }; } /** Validated periods of one stratified response, in request order or sorted. */ @@ -111,14 +123,16 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && c['color'] !== undefined && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color']))) || typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Categorías de biopsia incompatibles.'); const publicado = (c['color'] as string | null | undefined) ?? COLOR_RESPALDO; - const tono = tonoDe(c['grupo']); - return { id, etiqueta: c['etiqueta'], color: c2Color(publicado, curso[tono]++, tono), grupo: c['grupo'] }; + const tono = tonoDe(c['grupo']) === 'neutro' ? tonoDe(c['etiqueta']) : tonoDe(c['grupo']); + const asignado = c['color'] == null ? c2Color(publicado, curso[tono]++, tono) : COLOR_RESULTADO[id] ?? c2Color(publicado, curso[tono]++, tono); + return { id, etiqueta: c['etiqueta'], color: asignado, grupo: c['grupo'] }; }); const grupos: GrupoCategorias[] = [...new Set(categorias.map(c => c.grupo))].map(id => { const propias = categorias.filter(c => c.grupo === id); - const tono = tonoDe(id); - const color = tono === 'calido' ? C2_PALETTE.calidos[0] : tono === 'frio' ? C2_PALETTE.frios[0] : promedio(propias.map(c => c.color)); - return { id, etiqueta: id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : etiquetaGrupo(nombres[id])!, color, categorias: propias.map(c => c.id) }; + const etiqueta = id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : etiquetaGrupo(nombres[id])!; + const tono = tonoDe(id) === 'neutro' ? tonoDe(etiqueta) : tonoDe(id); + const color = COLOR_GRUPO[id] ?? (tono === 'calido' ? '#C24269' : tono === 'frio' ? '#42C29C' : promedio(propias.map(c => c.color))); + return { id, etiqueta, color, categorias: propias.map(c => c.id) }; }); if (grupos.length !== 2) return fail('Se esperaban dos grupos de resultados.'); const base = categorias.find(c => c.id === CATEGORIA_BASE)!.grupo; @@ -217,11 +231,14 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi const p = c2Theme(tema); const valores = tasas(m, sel); const color = sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color; + const tono = tonoDe(sel.categoria ?? sel.grupo); + const familia = tono === 'frio' ? C2_PALETTE.frios : tono === 'calido' ? C2_PALETTE.calidos : [color]; const y = valores.map(t => t.fila.etiqueta); + const colores = sel.categoria ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]); return { data: [{ type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), - marker: { size: 12, color }, cliponaxis: false, - error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6, + marker: { size: 12, color: colores }, cliponaxis: false, + error_x: { type: 'data', symmetric: false, color: colores, thickness: 2, width: 6, array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) }, customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]), hovertemplate: '%{y}
%{customdata[0]} (%{customdata[1]}/%{customdata[2]})
IC 95 %: %{customdata[3]}–%{customdata[4]} %', @@ -239,7 +256,7 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi }, config: { displayModeBar: false } }; } -/** Donut on the right: result groups inside, categories outside; selection dims, values stay. Empty over an incomplete matrix. */ +/** Donut on the right: groups inside, categories outside. Selection zooms those slices; colours stay. */ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema): PlotlyFigure { if (m.conResultado === null || m.conResultado === 0) return { data: [], layout: {} }; const p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado; @@ -249,16 +266,30 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' }; const hover = { hovertemplate: '%{label}
%{customdata[0]} pacientes con resultado, %{customdata[1]}' }; const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]); + const zoomGrupo = (id: string, hijos: readonly string[]) => + sel.categoria ? (hijos.includes(sel.categoria) ? ZOOM_PADRE : 1) : sel.grupo === id ? ZOOM_GRUPO : 1; + const zoomCategoria = (id: string) => sel.categoria === id ? ZOOM_ELEGIDO : !sel.categoria && activos.has(id) ? ZOOM_HIJO : 1; + const zoomDe = (values: number[]) => Math.max(1, ...values); + const tinta = (colores: string[], zoom: number[]) => colores.map((color, i) => zoom[i] > 1 ? color : 'rgba(0,0,0,0)'); + const gruposZoom = m.grupos.map(g => zoomGrupo(g.id, g.categorias)); + const categoriasZoom = m.categorias.map(c => zoomCategoria(c.id)); + const anillo = (name: string, values: number[], labels: string[], hole: number, base: readonly [number, number, number, number], zoom: number[], colores: string[]) => ({ + ...comun, ...hover, name, values, labels, hole, customdata: custom(values), + domain: caja(base, zoomDe(zoom)), + marker: { colors: tinta(colores, zoom), line: { color: 'rgba(0,0,0,0)', width: 0 } }, + }); return { data: [ - { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside', + { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside', text: [`${miles(k)}
de ${miles(total)} con resultado`], textfont: { size: 16, color: p.text }, marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '' }, - { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] }, + { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: caja(CAJA_GRUPO, 1), labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior), - marker: { colors: m.grupos.map(g => rgba(g.color, g.categorias.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } }, - { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, + marker: { colors: m.grupos.map(g => g.color), line: { color: p.background, width: 2 } } }, + { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1), labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior), - marker: { colors: m.categorias.map(c => rgba(c.color, activos.has(c.id) ? 1 : .3)), line: { color: p.background, width: 2 } } }, - ], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, + marker: { colors: m.categorias.map(c => c.color), line: { color: p.background, width: 2 } } }, + anillo('grupos', interior, m.grupos.map(g => escapar(g.etiqueta)), .62, CAJA_GRUPO, gruposZoom, m.grupos.map(g => g.color)), + anillo('categorias', exterior, m.categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, m.categorias.map(c => c.color)), + ], layout: { autosize: true, height: 360, margin: { t: 16, l: 16, r: 16, b: 16 }, paper_bgcolor: p.background, font: { color: p.text } }, config: { displayModeBar: false } }; } diff --git a/src/app/shared/plotly/plotly-controller.spec.ts b/src/app/shared/plotly/plotly-controller.spec.ts index 0fb746c..8ed9c3c 100644 --- a/src/app/shared/plotly/plotly-controller.spec.ts +++ b/src/app/shared/plotly/plotly-controller.spec.ts @@ -280,6 +280,10 @@ describe('PlotlyController transiciones opcionales', () => { expect(dimmed.data[1]['values']).toEqual([4, 6]); expect(dimmed.data[1]['text']).toEqual(['4', '6']); expect((dimmed.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']); expect(pieFrame(pie([4, 6]), pie([4, 6]), .5).data[1]).toEqual(pie([4, 6]).data[1]); + const grown = pieFrame({ ...pie([4, 6]), data: pie([4, 6]).data.map(t => ({ ...t, pull: [0, 0] })) }, + { ...pie([4, 6]), data: pie([4, 6]).data.map(t => ({ ...t, pull: [0, 0.12] })) }, .5); + expect(grown.data[1]['pull']).toEqual([0, 0.06]); + expect(grown.data[1]['text']).toEqual(['4', '6']); }); it('la dona interpola en varios react sin ocultar el host ni pasar por carga, y termina en la figura exacta', async () => { const c = controller(); diff --git a/src/app/shared/plotly/plotly-controller.ts b/src/app/shared/plotly/plotly-controller.ts index 9286055..5789734 100644 --- a/src/app/shared/plotly/plotly-controller.ts +++ b/src/app/shared/plotly/plotly-controller.ts @@ -27,6 +27,25 @@ function mixColor(from: unknown, to: unknown, t: number): unknown { return `rgba(${v.slice(0, 3).map(Math.round).join(',')},${+v[3].toFixed(3)})`; } const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(n => typeof n === 'number' && Number.isFinite(n)); +function mixDomain(from: unknown, to: unknown, t: number): { x: number[]; y: number[] } | undefined { + const read = (value: unknown) => { + if (!value || typeof value !== 'object') return undefined; + const x = (value as { x?: unknown }).x, y = (value as { y?: unknown }).y; + if (!numbers(x) || !numbers(y) || x.length !== 2 || y.length !== 2) return undefined; + return { x, y }; + }; + const start = read(from), end = read(to); + if (!start || !end) return undefined; + if (start.x.every((v, i) => v === end.x[i]) && start.y.every((v, i) => v === end.y[i])) return undefined; + const mix = (a: number[], b: number[]) => b.map((v, i) => a[i] + (v - a[i]) * t); + return { x: mix(start.x, end.x), y: mix(start.y, end.y) }; +} +function mixPull(from: unknown, to: unknown, length: number, t: number): number[] | undefined { + const start = from === undefined ? Array(length).fill(0) : from; + const end = to === undefined ? Array(length).fill(0) : to; + if (!numbers(start) || !numbers(end) || start.length !== length || end.length !== length || start.every((v, i) => v === end[i])) return undefined; + return end.map((v, i) => start[i] + (v - start[i]) * t); +} /** Pies cannot use layout.transition: both figures must have the same pies and value shapes. */ export function piesInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean { return to.data.length > 0 && from.data.length === to.data.length && to.data.every((trace, i) => { @@ -46,12 +65,16 @@ export function pieFrame(from: PlotlyFigure, to: PlotlyFigure, t: number): Plotl const marker = trace['marker'] as Record | undefined; const oldColors = oldMarker?.['colors'], colors = marker?.['colors']; const sameValues = a.every((v, j) => v === b[j]); + const clear = (list: unknown) => Array.isArray(list) && list.some(c => typeof c === 'string' && /,\s*0\)$/.test(c)); const mixColors = !!marker && Array.isArray(colors) && Array.isArray(oldColors) && oldColors.length === colors.length - && colors.some((c, j) => c !== oldColors[j]); - if (sameValues && !mixColors && !moving) return trace; + && !clear(colors) && !clear(oldColors) && colors.some((c, j) => c !== oldColors[j]); + const pull = mixPull(from.data[i]['pull'], trace['pull'], b.length, t); + const domain = mixDomain(from.data[i]['domain'], trace['domain'], t); + if (sameValues && !mixColors && !moving && !pull && !domain) return trace; // Geometry is illustrative until the exact target render. Hide all clinical // readouts (including the centre) and never attach counts to moving slices. return { ...trace, ...(sameValues ? {} : { values: b.map((v, j) => a[j] + (v - a[j]) * t) }), + ...(pull ? { pull } : {}), ...(domain ? { domain } : {}), ...(moving ? { text: b.map(() => ''), textinfo: 'none', texttemplate: '', hoverinfo: 'skip', hovertemplate: null, hovertext: [], customdata: [] } : {}), ...(mixColors ? { marker: { ...marker, colors: (colors as unknown[]).map((c, j) => mixColor((oldColors as unknown[])[j], c, t)) } } : {}) };