feat(tea): botones para resaltar grupos y categorías en las figuras
- Leyenda con botones, como la distribución de resultados citológicos de cáncer cervicouterino: el grupo o la categoría elegida conserva su color, el resto se atenúa, «Volver» retrocede y un clic en la figura equivale al botón (indicadores-highlight.ts). - M21, M22 y M24 con botones por grupo de edad; el centro de las donas muestra la selección. - En TEA, la dona C2 de un periodo (M23) se dibuja con ambos anillos y botones, y sus barras también los tienen.
This commit is contained in:
@@ -83,7 +83,23 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
@if (state.status === 'ready' && state.highlight; as h) {
|
||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
|
||||
@if (row.group; as g) {
|
||||
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
|
||||
}
|
||||
@for (c of row.items; track c.id) {
|
||||
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
|
||||
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
||||
@for (entry of state.donutLegend; track entry.label) {
|
||||
<span class="donut-static-legend__item" role="listitem">
|
||||
@@ -94,7 +110,7 @@
|
||||
}
|
||||
</div>
|
||||
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend || state.highlight ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
</div>
|
||||
}
|
||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||
|
||||
@@ -113,3 +113,16 @@
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
||||
}
|
||||
// Highlight buttons, as in CaCu's «Distribución de resultados citológicos».
|
||||
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||
.dark .highlight-legend { color: #eef1f7; }
|
||||
.highlight-status { margin: 0; font-weight: 600; }
|
||||
.highlight-back { justify-self: start; }
|
||||
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 999px; font: inherit; cursor: pointer; }
|
||||
.highlight-legend button:disabled { opacity: .45; cursor: default; }
|
||||
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||
.highlight-legend .highlight-group { font-weight: 600; }
|
||||
|
||||
@@ -12,6 +12,7 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||
|
||||
// The panel owns requests; the card receives the original and its presentation copy.
|
||||
export interface FigureState {
|
||||
@@ -24,6 +25,8 @@ export interface FigureState {
|
||||
donutLegend?: readonly DonutLegendEntry[];
|
||||
// The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is.
|
||||
ownLayout?: boolean;
|
||||
// Legend buttons that highlight one part of the figure (CaCu style).
|
||||
highlight?: FigureHighlight;
|
||||
plotWidth?: number;
|
||||
plotHeight?: number;
|
||||
message?: string;
|
||||
@@ -66,7 +69,7 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
}
|
||||
@Input({ required: true }) set state(value: FigureState) {
|
||||
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; }
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
|
||||
this.currentState = value;
|
||||
if (value.status === 'ready') {
|
||||
this.updateDonut();
|
||||
@@ -89,6 +92,7 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
||||
this.chartFigure = source && hierarchy
|
||||
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
||||
: source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
|
||||
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
|
||||
}
|
||||
expandParent(parent: string) {
|
||||
@@ -111,9 +115,28 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
target?.focus();
|
||||
}
|
||||
}
|
||||
highlightSelection: HighlightSelection = {};
|
||||
readonly highlightRows = highlightRows;
|
||||
get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; }
|
||||
highlight(kind: 'group' | 'item', id: string) {
|
||||
if (!this.state.highlight) return;
|
||||
this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id);
|
||||
this.updateDonut();
|
||||
}
|
||||
highlightBack() {
|
||||
const sel = this.highlightSelection;
|
||||
this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {};
|
||||
this.updateDonut();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
||||
const point = event.points[0];
|
||||
if (this.state.highlight) {
|
||||
const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number'
|
||||
? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined;
|
||||
if (hit) this.highlight(hit.kind, hit.id);
|
||||
return;
|
||||
}
|
||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
@@ -253,7 +254,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
const adapted = c1DonutFigure(data, selection);
|
||||
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
|
||||
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
|
||||
donutLegend: adapted.legend.length ? adapted.legend : undefined, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
|
||||
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
|
||||
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
|
||||
}));
|
||||
}
|
||||
@@ -277,6 +278,13 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
||||
}
|
||||
const adapted = c2Figure(data, selection);
|
||||
if (adapted.status === 'supported' && selection.dominio === 'tea') {
|
||||
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
|
||||
if (selection.figura === 'fig_c2_donas') {
|
||||
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
|
||||
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
|
||||
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
|
||||
}
|
||||
return adapted.status === 'supported'
|
||||
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
||||
|
||||
@@ -40,7 +40,9 @@ describe('Dona de dos anillos para C1', () => {
|
||||
if (small.status === 'supported') expect((small.figure.data[2] as { text: string[] }).text[4]).toBe('');
|
||||
expect(result.total).toBe(64);
|
||||
expect(result.notes).toEqual(['Datos ficticios.']);
|
||||
expect(result.legend.map(e => e.label)).toEqual(['Con EEG', 'Sin EEG', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.groups.map(g => g.label)).toEqual(['Con EEG', 'Sin EEG']);
|
||||
expect(result.highlight.items.map(i => i.short)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.groups[1].center).toBe('<b>18</b><br>Sin EEG');
|
||||
expect(result.figure.layout['title']).toEqual({ text: 'Porcentaje de pacientes con diagnóstico de TEA con EEG, 2025-S2' });
|
||||
});
|
||||
it('dona por grupo de edad: solo los pacientes con el evento, con el porcentaje total al centro', () => {
|
||||
@@ -53,7 +55,9 @@ describe('Dona de dos anillos para C1', () => {
|
||||
expect(ring.values).toEqual([16, 13, 17]);
|
||||
expect(ring.text[0]).toMatch(/^16 a 23 meses<br>34.8/);
|
||||
expect((result.figure.layout['annotations'] as { text: string }[])[0].text).toBe('<b>71.9 %</b>');
|
||||
expect(result.legend.map(e => e.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.groups).toEqual([]);
|
||||
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('<b>34.8 %</b><br>16 a 23 meses');
|
||||
});
|
||||
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' },
|
||||
@@ -64,7 +68,7 @@ describe('Dona de dos anillos para C1', () => {
|
||||
expect(bars.x).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(bars.text).toEqual(['33.3 %', '27.8 %', '22.7 %']);
|
||||
expect(JSON.stringify(result.figure.layout['yaxis'])).toContain('% de pacientes sin EEG');
|
||||
expect(result.legend).toEqual([]);
|
||||
expect(result.highlight.items.map(i => i.points)).toEqual([[{ trace: 0, index: 0 }], [{ trace: 0, index: 1 }], [{ trace: 0, index: 2 }]]);
|
||||
});
|
||||
it('usa etiquetas propias por indicador y neutrales para otros', () => {
|
||||
expect(c1DonutLabels('M24_confirmacion_diagnostico')).toEqual(['Con diagnóstico positivo de TEA', 'Sin diagnóstico de TEA']);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
import { DonutLegendEntry } from './indicadores-donut-drilldown';
|
||||
import { donaHighlight, FigureHighlight } from './indicadores-highlight';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
@@ -24,7 +24,7 @@ const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
|
||||
const RING_COLORS = ['#2F6DB3', '#D9822B'] as const;
|
||||
|
||||
export type C1DonutResult = { status: 'unsupported'; reason: string }
|
||||
| { status: 'supported'; figure: PlotlyFigure; legend: DonutLegendEntry[]; total: number; notes: string[] };
|
||||
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
|
||||
export function c1DonutCapability(contract: string, representation: string): boolean {
|
||||
return contract === 'C1' && C1_AGE_FIGURES.includes(representation);
|
||||
}
|
||||
@@ -65,7 +65,9 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection):
|
||||
if (selection.figura === C1_AGE_BARS) {
|
||||
const figure = ageBars(strata, labels[0], selection);
|
||||
figure.layout = { ...figure.layout, title };
|
||||
return { status: 'supported', figure, legend: [], total, notes };
|
||||
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 }] })) };
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
|
||||
const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] }));
|
||||
@@ -103,14 +105,16 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection):
|
||||
hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de los ' + numerador + ' ' + escape(what(labels[0])) + '<extra></extra>' }];
|
||||
figure.layout = { ...figure.layout, title, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false,
|
||||
text: '<b>' + percentNumber(100 * numerador / total) + ' %</b>', font: { size: 26, color: c2Theme(selection.tema).text } }] };
|
||||
return { status: 'supported', figure, legend: strata.map((s, i) => ({ label: s.label, color: categorias[i].color })), total, notes };
|
||||
const highlight: FigureHighlight = { groups: [], traces: [0], center: { annotation: 0 }, allLabel: labels[0],
|
||||
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: categorias[i].color, points: [{ trace: 0, index: i }],
|
||||
center: '<b>' + (numerador ? percentNumber(100 * values[i] / numerador) : '0') + ' %</b><br>' + escape(s.label) })) };
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
}
|
||||
figure.layout = { ...figure.layout, title };
|
||||
// Both groups, then the age groups in the shades of the first one.
|
||||
const legend = [...grupos.map(g => ({ label: g.etiqueta, color: g.color })),
|
||||
...strata.map((s, i) => ({ label: s.label, color: categorias[i].color }))];
|
||||
return { status: 'supported', figure, legend, total, notes };
|
||||
// Next to its group's button, a category only needs its age group.
|
||||
const highlight = donaHighlight(modelo, id => strata.find(s => id.endsWith(':' + s.id))?.label);
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
|
||||
// "Con EEG" -> "con EEG", to follow «pacientes».
|
||||
|
||||
@@ -59,7 +59,18 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({}, {status:503,statusText:'Failure'});
|
||||
expect(fixture.componentInstance.result().status).toBe('error');
|
||||
});
|
||||
it('TEA: dona de un periodo con ambos anillos y botones para resaltar grupos y categorías', () => {
|
||||
fixture.detectChanges(); dataRequest().flush(c2Fixture());
|
||||
const result = fixture.componentInstance.result();
|
||||
expect(result.status).toBe('ready');
|
||||
expect(result.hierarchy).toBeUndefined();
|
||||
expect(result.figure?.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
|
||||
expect(result.highlight?.groups.length).toBeGreaterThan(0);
|
||||
expect(result.highlight?.items.every(i => i.group)).toBe(true);
|
||||
});
|
||||
it('cambio de periodo cancela lectura, limpia selección y no expone snapshot previo', () => {
|
||||
// TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts).
|
||||
fixture.componentRef.setInput('dominio', 'cama');
|
||||
fixture.detectChanges(); const old = dataRequest();
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision:2,selection:{mode:'explicit',periodos:['2026-S1']} }); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true); const current = dataRequest(); expect(current.request.params.get('periodos')).toBe('2026-S1');
|
||||
|
||||
@@ -176,6 +176,8 @@ describe('navegación multiperiodo en el panel común', () => {
|
||||
expect(JSON.stringify(source)).toBe(before); http.expectNone(() => true);
|
||||
});
|
||||
it('un periodo no presenta navegación y una selección vacía es incompatible sin HTTP', () => {
|
||||
// TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts).
|
||||
fixture.componentRef.setInput('dominio', 'cama');
|
||||
apply([periods[0]]); dataRequest().flush(c2Fixture()); fixture.detectChanges();
|
||||
expect(buttons()).toHaveLength(0); expect(card().state.hierarchy).toBeTruthy();
|
||||
apply([], 2); fixture.detectChanges(); expect(panel().result().status).toBe('incompatible'); expect(buttons()).toHaveLength(0); http.expectNone(() => true);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, toggleHighlight } from './indicadores-highlight';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
|
||||
// A double donut like dona(): 0 centre, 1 groups, 2 categories.
|
||||
const figure: PlotlyFigure = { data: [
|
||||
{ type: 'pie', values: [1], text: ['<b>10</b><br>TOTAL'] },
|
||||
{ type: 'pie', values: [6, 4], marker: { colors: ['rgba(10, 20, 30, 1)', '#FF0000'] } },
|
||||
{ type: 'pie', values: [2, 4, 4], marker: { colors: ['#000000', '#111111', '#222222'] } },
|
||||
], layout: {} };
|
||||
const h: FigureHighlight = { traces: [1, 2], center: { trace: 0 }, allLabel: 'TOTAL',
|
||||
groups: [{ id: 'A', label: 'Grupo A', color: '#000000', points: [{ trace: 1, index: 0 }, { trace: 2, index: 0 }, { trace: 2, index: 1 }], center: 'A' },
|
||||
{ id: 'B', label: 'Grupo B', color: '#FF0000', points: [{ trace: 1, index: 1 }, { trace: 2, index: 2 }], center: 'B' }],
|
||||
items: [{ id: 'a1', label: 'A · 1', short: '1', color: '#000000', group: 'A', points: [{ trace: 2, index: 0 }], center: 'a1' },
|
||||
{ id: 'a2', label: 'A · 2', short: '2', color: '#111111', group: 'A', points: [{ trace: 2, index: 1 }] },
|
||||
{ id: 'b1', label: 'B · 1', short: '1', color: '#222222', group: 'B', points: [{ trace: 2, index: 2 }] }] };
|
||||
const colors = (f: PlotlyFigure, t: number) => (f.data[t]['marker'] as { colors: string[] }).colors;
|
||||
|
||||
describe('Botones que resaltan una parte de la figura', () => {
|
||||
it('sin selección deja la figura intacta', () => {
|
||||
expect(highlightFigure(figure, h, {})).toBe(figure);
|
||||
expect(highlightLabel(h, {})).toBe('TOTAL');
|
||||
});
|
||||
it('un grupo conserva su parte de ambos anillos y atenúa el resto, también colores rgba', () => {
|
||||
const f = highlightFigure(figure, h, { group: 'B' });
|
||||
expect(colors(f, 1)).toEqual(['rgba(10, 20, 30, 0.3)', '#FF0000']);
|
||||
expect(colors(f, 2)).toEqual(['rgba(0, 0, 0, 0.3)', 'rgba(17, 17, 17, 0.3)', '#222222']);
|
||||
expect(f.data[0]['text']).toEqual(['B']);
|
||||
expect(colors(figure, 2)).toEqual(['#000000', '#111111', '#222222']);
|
||||
});
|
||||
it('una categoría conserva su grupo en el anillo interior', () => {
|
||||
const f = highlightFigure(figure, h, { item: 'a1' });
|
||||
expect(colors(f, 1)).toEqual(['rgba(10, 20, 30, 1)', 'rgba(255, 0, 0, 0.3)']);
|
||||
expect(colors(f, 2)).toEqual(['#000000', 'rgba(17, 17, 17, 0.3)', 'rgba(34, 34, 34, 0.3)']);
|
||||
expect(f.data[0]['text']).toEqual(['a1']);
|
||||
});
|
||||
it('en barras atenúa con la opacidad de cada barra', () => {
|
||||
const bars: PlotlyFigure = { data: [{ type: 'bar', x: ['a', 'b', 'c'], y: [1, 2, 3], marker: { color: '#000000' } }], layout: {} };
|
||||
const hb: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todas', items: ['a', 'b', 'c'].map((id, i) => ({ id, label: id, color: '#000000', points: [{ trace: 0, index: i }] })) };
|
||||
expect((highlightFigure(bars, hb, { item: 'b' }).data[0]['marker'] as { opacity: number[] }).opacity).toEqual([.3, 1, .3]);
|
||||
});
|
||||
it('alterna como CaCu: repetir vuelve un paso y un grupo limita las categorías', () => {
|
||||
expect(toggleHighlight(h, {}, 'group', 'A')).toEqual({ group: 'A' });
|
||||
expect(toggleHighlight(h, { group: 'A' }, 'group', 'A')).toEqual({});
|
||||
expect(toggleHighlight(h, { group: 'A' }, 'item', 'a2')).toEqual({ group: 'A', item: 'a2' });
|
||||
expect(toggleHighlight(h, { group: 'A', item: 'a2' }, 'item', 'a2')).toEqual({ group: 'A' });
|
||||
expect(toggleHighlight(h, { group: 'A' }, 'item', 'b1')).toEqual({ group: 'A' });
|
||||
expect(toggleHighlight(h, {}, 'item', 'b1')).toEqual({ item: 'b1' });
|
||||
});
|
||||
it('un clic en el anillo exterior es la categoría; en el interior, el grupo', () => {
|
||||
expect(highlightAt(h, { trace: 2, index: 1 })).toEqual({ kind: 'item', id: 'a2' });
|
||||
expect(highlightAt(h, { trace: 1, index: 1 })).toEqual({ kind: 'group', id: 'B' });
|
||||
expect(highlightAt(h, { trace: 0, index: 0 })).toBeUndefined();
|
||||
});
|
||||
it('agrupa los botones en filas: cada grupo seguido de sus categorías', () => {
|
||||
expect(highlightRows(h).map(r => [r.group?.id, r.items.map(i => i.id)])).toEqual([['A', ['a1', 'a2']], ['B', ['b1']]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { Modelo } from './indicadores-eu7-escenario';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
|
||||
// Legend buttons that highlight one part of a figure, like CaCu's «Distribución de resultados
|
||||
// citológicos»: the chosen group or category keeps its colour and everything else fades.
|
||||
export interface HighlightPoint { trace: number; index: number; }
|
||||
export interface HighlightEntry {
|
||||
id: string; label: string; color: string;
|
||||
// Shorter label for the button when it sits next to its group's button.
|
||||
short?: string;
|
||||
// Only for categories: the group they belong to (its button narrows the categories on offer).
|
||||
group?: string;
|
||||
points: readonly HighlightPoint[];
|
||||
// Text for the centre of a donut while this entry is chosen.
|
||||
center?: string;
|
||||
}
|
||||
export interface FigureHighlight {
|
||||
groups: readonly HighlightEntry[];
|
||||
items: readonly HighlightEntry[];
|
||||
// Traces whose points fade when they are not part of the choice.
|
||||
traces: readonly number[];
|
||||
// Where a donut shows its centre text: a pie trace's single text, or a layout annotation.
|
||||
center?: { trace: number } | { annotation: number };
|
||||
// Name of the whole, for the status line.
|
||||
allLabel: string;
|
||||
}
|
||||
export interface HighlightSelection { group?: string; item?: string; }
|
||||
|
||||
const FADED = .3;
|
||||
// Accepts #RRGGBB and rgb()/rgba() (dona() already writes its colours as rgba).
|
||||
function rgba(color: string, alpha: number): string {
|
||||
const hex = /^#([0-9a-f]{6})$/i.exec(color);
|
||||
if (hex) {
|
||||
const [r, g, b] = [0, 2, 4].map(i => parseInt(hex[1].slice(i, i + 2), 16));
|
||||
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
||||
}
|
||||
const rgb = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i.exec(color);
|
||||
return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color;
|
||||
}
|
||||
export function highlightEntry(h: FigureHighlight, sel: HighlightSelection): HighlightEntry | undefined {
|
||||
return sel.item ? h.items.find(e => e.id === sel.item) : sel.group ? h.groups.find(e => e.id === sel.group) : undefined;
|
||||
}
|
||||
export function highlightLabel(h: FigureHighlight, sel: HighlightSelection): string {
|
||||
return highlightEntry(h, sel)?.label ?? h.allLabel;
|
||||
}
|
||||
// Same state machine as CaCu: choosing the chosen entry again goes back one step.
|
||||
export function toggleHighlight(h: FigureHighlight, sel: HighlightSelection, kind: 'group' | 'item', id: string): HighlightSelection {
|
||||
if (kind === 'group') return !h.groups.some(g => g.id === id) || sel.group === id ? {} : { group: id };
|
||||
const item = h.items.find(e => e.id === id);
|
||||
if (!item || (sel.group && item.group !== sel.group)) return sel;
|
||||
return sel.item === id ? (sel.group ? { group: sel.group } : {}) : { ...(sel.group ? { group: sel.group } : {}), item: id };
|
||||
}
|
||||
// The entry a click on the figure means: a category first, otherwise a group.
|
||||
export function highlightAt(h: FigureHighlight, point: HighlightPoint): { kind: 'group' | 'item'; id: string } | undefined {
|
||||
const hit = (e: HighlightEntry) => e.points.some(p => p.trace === point.trace && p.index === point.index);
|
||||
// A group also covers its categories' slices, so an outer slice hits both: the category wins.
|
||||
const item = h.items.find(hit);
|
||||
if (item) return { kind: 'item', id: item.id };
|
||||
const group = h.groups.find(hit);
|
||||
return group ? { kind: 'group', id: group.id } : undefined;
|
||||
}
|
||||
|
||||
export function highlightFigure(figure: PlotlyFigure, h: FigureHighlight, sel: HighlightSelection): PlotlyFigure {
|
||||
const entry = highlightEntry(h, sel);
|
||||
if (!entry) return figure;
|
||||
const keep = new Set(entry.points.map(p => p.trace + ':' + p.index));
|
||||
// A chosen category also keeps its group's slice of the inner ring (not its sibling categories).
|
||||
const group = entry.group ? h.groups.find(g => g.id === entry.group) : undefined;
|
||||
const own = new Set(entry.points.map(p => p.trace));
|
||||
group?.points.filter(p => !own.has(p.trace)).forEach(p => keep.add(p.trace + ':' + p.index));
|
||||
const data = figure.data.map((trace, t) => {
|
||||
if (!h.traces.includes(t)) return trace;
|
||||
const marker = (trace['marker'] ?? {}) as Record<string, unknown>;
|
||||
if (trace['type'] === 'pie') {
|
||||
const colors = (marker['colors'] as unknown[] | undefined) ?? [];
|
||||
return { ...trace, marker: { ...marker, colors: colors.map((c, i) => typeof c === 'string' && !keep.has(t + ':' + i) ? rgba(c, FADED) : c) } };
|
||||
}
|
||||
const count = Array.isArray(trace['x']) ? (trace['x'] as unknown[]).length : Array.isArray(trace['y']) ? (trace['y'] as unknown[]).length : 0;
|
||||
return { ...trace, marker: { ...marker, opacity: Array.from({ length: count }, (_, i) => keep.has(t + ':' + i) ? 1 : FADED) } };
|
||||
});
|
||||
let layout = figure.layout;
|
||||
if (entry.center !== undefined && h.center) {
|
||||
if ('trace' in h.center) {
|
||||
const t = h.center.trace;
|
||||
data[t] = { ...data[t], text: [entry.center] };
|
||||
} else {
|
||||
const annotations = [...((layout['annotations'] as Record<string, unknown>[] | undefined) ?? [])];
|
||||
if (annotations[h.center.annotation]) annotations[h.center.annotation] = { ...annotations[h.center.annotation], text: entry.center };
|
||||
layout = { ...layout, annotations };
|
||||
}
|
||||
}
|
||||
return { ...figure, data, layout };
|
||||
}
|
||||
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// Buttons for a figure drawn by dona() (traces: 0 centre, 1 groups, 2 categories). A group also
|
||||
// covers its categories' slices; the centre shows the count of the choice. `short` gives each
|
||||
// category's button label next to its group (by default, its full label).
|
||||
export function donaHighlight(m: Modelo, short: (id: string) => string | undefined = () => undefined): FigureHighlight {
|
||||
const centre = (n: number, label: string) => '<b>' + n.toLocaleString('es-MX') + '</b><br>' + escape(label);
|
||||
return { traces: [1, 2], center: { trace: 0 }, allLabel: 'TOTAL',
|
||||
groups: m.grupos.map((g, gi) => {
|
||||
const children = m.categorias.map((c, i) => ({ c, i })).filter(({ c }) => c.grupo === g.id);
|
||||
return { id: g.id, label: g.etiqueta, color: g.color,
|
||||
points: [{ trace: 1, index: gi }, ...children.map(({ i }) => ({ trace: 2, index: i }))],
|
||||
center: centre(children.reduce((n, { c }) => n + (m.celdas[c.id].n ?? 0), 0), g.etiqueta) };
|
||||
}),
|
||||
items: m.categorias.map((c, i) => ({ id: c.id, label: c.etiqueta, short: short(c.id), color: c.color, group: c.grupo,
|
||||
points: [{ trace: 2, index: i }], center: centre(m.celdas[c.id].n ?? 0, c.etiqueta) })) };
|
||||
}
|
||||
|
||||
// Rows of buttons: each group followed by its categories; categories without a group share one row.
|
||||
export function highlightRows(h: FigureHighlight): { group?: HighlightEntry; items: HighlightEntry[] }[] {
|
||||
const rows = h.groups.map(group => ({ group, items: h.items.filter(i => i.group === group.id) }));
|
||||
const loose = h.items.filter(i => !i.group || !h.groups.some(g => g.id === i.group));
|
||||
return loose.length ? [...rows, { items: loose }] : rows;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { C2Distribution } from './indicadores-c2-adapter';
|
||||
import { c2Color } from './indicadores-c2-palette';
|
||||
import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario';
|
||||
import { donaHighlight, FigureHighlight } from './indicadores-highlight';
|
||||
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||
|
||||
// TEA (mock): C2 distributions with groups are drawn like CaCu's «Distribución de resultados
|
||||
// citológicos», both rings at once with highlight buttons, instead of the drill-down donut.
|
||||
const average = (colors: string[]) => '#' + [1, 3, 5].map(i => Math.round(colors.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colors.length)
|
||||
.toString(16).padStart(2, '0')).join('').toUpperCase();
|
||||
const hex = (c: string | undefined, i: number) => { const v = c2Color(c, i); return /^#[0-9a-f]{6}$/i.test(v) ? v : c2Color(undefined, i); };
|
||||
|
||||
export function teaC2Donut(model: C2Distribution, tema: Tema, title: unknown): { figure: PlotlyFigure; highlight: FigureHighlight } | undefined {
|
||||
if (!model.parents.length || model.total === 0) return undefined;
|
||||
const categorias: Categoria[] = model.categories.map((c, i) => ({ id: c.id, etiqueta: c.label, color: hex(c.color, i), grupo: 'group:' + c.parentId }));
|
||||
// A group takes the average colour of its categories, as in CaCu.
|
||||
const grupos: Grupo[] = model.parents.map(p => ({ id: p.id, etiqueta: p.label, color: average(categorias.filter(c => c.grupo === p.id).map(c => c.color)) }));
|
||||
const celdas: Modelo['celdas'] = Object.fromEntries(model.categories.map(c => [c.id, { n: c.value, estado: 'Publicado' as const }]));
|
||||
const modelo: Modelo = { periodo: model.period, categorias, grupos, celdas, total: model.total, sinDato: { n: 0, estado: 'Publicado' },
|
||||
escenarios: [], vacio: false, notas: [...model.notes], sinDatoEtiqueta: '' };
|
||||
const figure = dona(modelo, {}, tema);
|
||||
const unit = model.unit.endsWith('s') ? model.unit : model.unit + 's';
|
||||
for (const trace of figure.data.slice(1)) trace['hovertemplate'] = '%{label}<br>%{customdata[0]} ' + unit + ', %{customdata[1]} % de ' + model.total + '<extra></extra>';
|
||||
figure.layout = { ...figure.layout, title };
|
||||
return { figure, highlight: donaHighlight(modelo) };
|
||||
}
|
||||
|
||||
// Buttons for the C2 bars: one per category (bar), and its group highlights all of its bars.
|
||||
export function c2BarsHighlight(model: C2Distribution): FigureHighlight {
|
||||
const items = model.categories.map((c, i) => ({ id: c.id, label: c.label, color: hex(c.color, i),
|
||||
group: c.parentId ? 'group:' + c.parentId : undefined, points: [{ trace: 0, index: i }] }));
|
||||
const groups = model.parents.map(p => {
|
||||
const children = items.filter(c => c.group === p.id);
|
||||
return { id: p.id, label: p.label, color: average(children.map(c => c.color)), points: children.flatMap(c => c.points) };
|
||||
});
|
||||
return { groups, items, traces: [0], allLabel: 'Todas las categorías' };
|
||||
}
|
||||
Reference in New Issue
Block a user