296 lines
22 KiB
TypeScript
296 lines
22 KiB
TypeScript
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||
import { C2_PALETTE, c2Color, c2Theme, tonoDe } from './indicadores-c2-palette';
|
||
import { Celda, wilson } from './indicadores-confirmacion-citologia';
|
||
import { percentNumber, shareText } from './indicadores-format';
|
||
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||
|
||
// CaMa's histopathological result by BI-RADS (cama_histopatologia_birads): a C2 stratified by `birads`, one
|
||
// patient per period. This module turns the published matrix into what the view draws; it owns no HTTP and no
|
||
// drawing library, so another source of the same matrix (for example a MeasureReport adapter) only has to
|
||
// produce the same payload. The selection of units stays in the backend; here nothing is added, inferred or
|
||
// completed: a stratum or a cell that is not published is "No disponible", never zero, and a suppressed cell
|
||
// is "Suprimido". A total is only drawn over a complete matrix.
|
||
export const ID_HISTOPATOLOGIA = ID_HISTOPATOLOGIA_CAMA;
|
||
export const ESTRATO_BIRADS = 'birads';
|
||
// The six strata of the contract, in the order they are published. BIRADS_4 is a row of its own and is never
|
||
// split among 4A/4B/4C nor added to them.
|
||
export const ESTRATOS_BIRADS = ['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'] as const;
|
||
const ETIQUETA_ESTRATO: Readonly<Record<string, string>> = {
|
||
BIRADS_4: 'BI-RADS 4 sin subtipo', BIRADS_4A: 'BI-RADS 4A', BIRADS_4B: 'BI-RADS 4B', BIRADS_4C: 'BI-RADS 4C', BIRADS_5: 'BI-RADS 5', BIRADS_6: 'BI-RADS 6',
|
||
};
|
||
// The categories with a biopsy result: their sum is the denominator of every rate. NO_MALIGNO holds the first two
|
||
// and MALIGNO the last two, as the catalog says.
|
||
export const CON_RESULTADO = ['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR'] as const;
|
||
const OBLIGATORIAS: readonly string[] = ['BENIGNO', 'IN_SITU', 'INVASOR'];
|
||
// Reported apart, outside the denominator and the donut: no biopsy reported at the cut-off, and a biopsy without grade.
|
||
export const APARTE = [
|
||
{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia reportada' },
|
||
{ id: 'SIN_DATO', etiqueta: 'Sin dato' },
|
||
] as const;
|
||
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<Record<string, string>> = {
|
||
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<Record<string, string>> = { 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[]; }
|
||
export interface FilaBirads {
|
||
id: string; etiqueta: string;
|
||
// The four categories with a result.
|
||
celdas: Record<string, Celda>;
|
||
// SIN_BIOPSIA and SIN_DATO, when the catalog publishes them.
|
||
aparte: Record<string, Celda>;
|
||
// Patients of the stratum, as the response publishes them.
|
||
total: Celda;
|
||
// Patients with a biopsy result: the denominator. Null while any of the four cells is unknown.
|
||
den: number | null; estado: Celda['estado'];
|
||
}
|
||
export interface ModeloHistopatologia {
|
||
periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string;
|
||
filas: FilaBirads[]; totales: Record<string, number | null>; conResultado: number | null;
|
||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
|
||
}
|
||
export interface SeleccionHistopatologia { grupo: string; categoria?: string; }
|
||
export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||
export class HistopatologiaIncompatible extends Error {}
|
||
|
||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||
const texto = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0;
|
||
const fail = (message: string): never => { throw new HistopatologiaIncompatible(message); };
|
||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
|
||
// A label inside a sentence: «Lesión de riesgo (B3)» reads «lesión de riesgo (B3)», keeping the code's capitals.
|
||
const enFrase = (v: string) => v.charAt(0).toLowerCase() + v.slice(1);
|
||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||
|
||
// 0 is a published count; a suppressed cell has no count; a cell the response does not carry is not available.
|
||
function celda(fila?: Record<string, unknown>): Celda {
|
||
if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' };
|
||
return typeof fila?.['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 && fila['suprimido'] === 0
|
||
? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' };
|
||
}
|
||
const suma = (celdas: Celda[]): number | null => celdas.some(c => c.n === null) ? null : celdas.reduce((s, c) => s + c.n!, 0);
|
||
const estadoDe = (celdas: Celda[]): Celda['estado'] =>
|
||
celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||
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('');
|
||
}
|
||
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. */
|
||
export function periodosHistopatologia(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
||
if (datos.id !== ID_HISTOPATOLOGIA || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_BIRADS
|
||
|| !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length
|
||
|| datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|
||
|| (solicitados && datos.periodos.some(p => !solicitados.includes(p)))
|
||
|| datos.filas.some(f => !registro(f) || !datos.periodos.includes(f['periodo'] as string))) {
|
||
return fail('Los datos no corresponden a la histopatología por BI-RADS o al periodo aplicado.');
|
||
}
|
||
return solicitados ? solicitados.filter(p => datos.periodos.includes(p)) : [...datos.periodos].sort();
|
||
}
|
||
|
||
/** One stratified /datos payload -> the matrix of a single period. */
|
||
export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): ModeloHistopatologia {
|
||
periodosHistopatologia(datos, datos.tipo_periodo);
|
||
const cats = datos['categorias'], nombres = datos['grupos_de_categoria'];
|
||
if (!registro(cats) || !registro(nombres)) return fail('Catálogo de categorías incompleto.');
|
||
// A category the view does not know would change the denominator without anyone noticing.
|
||
const conocidas: readonly string[] = [...CON_RESULTADO, ...APARTE_IDS];
|
||
// The risk lesion (B3) is only published by a source that has it: the others have to be there.
|
||
if (Object.keys(cats).some(id => !conocidas.includes(id)) || OBLIGATORIAS.some(id => !Object.hasOwn(cats, id))) {
|
||
return fail('El catálogo no publica las categorías esperadas de la biopsia.');
|
||
}
|
||
const curso = { frio: 0, calido: 0, neutro: 0 };
|
||
const categorias: Categoria[] = CON_RESULTADO.filter(id => Object.hasOwn(cats, id)).map(id => {
|
||
const c = cats[id];
|
||
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']) === '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 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;
|
||
const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => {
|
||
const c = cats[a.id];
|
||
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
|
||
});
|
||
|
||
const indice = new Map<string, Record<string, unknown>>();
|
||
for (const row of datos.filas.filter(f => f['periodo'] === periodo)) {
|
||
const c = row['categoria'], e = row['estrato'];
|
||
if (!esTotal(row['grupo']) || typeof e !== 'string' || !(ESTRATOS_BIRADS as readonly string[]).includes(e) || typeof c !== 'string' || !conocidas.includes(c)
|
||
|| ![0, 1].includes(row['suprimido'] as number)) return fail('Fila de histopatología inválida.');
|
||
const key = JSON.stringify([e, c]);
|
||
if (indice.has(key)) return fail('Filas de histopatología duplicadas.');
|
||
indice.set(key, row);
|
||
}
|
||
const publicados = datos['valores_estrato'];
|
||
if (publicados !== undefined && (!Array.isArray(publicados) || !publicados.every(v => typeof v === 'string' && (ESTRATOS_BIRADS as readonly string[]).includes(v)))) {
|
||
return fail('Estratos de BI-RADS inválidos.');
|
||
}
|
||
const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {};
|
||
const totalesPublicados = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : [];
|
||
if (!totalesPublicados.every(registro)) return fail('Totales de BI-RADS inválidos.');
|
||
const totalesDelPeriodo = (totalesPublicados as Record<string, unknown>[]).filter(t => t['periodo'] === periodo);
|
||
if (totalesDelPeriodo.some(t => !esTotal(t['grupo']) || typeof t['estrato'] !== 'string' || !(ESTRATOS_BIRADS as readonly string[]).includes(t['estrato'])
|
||
|| ![0, 1].includes(t['suprimido'] as number))) return fail('Totales de BI-RADS inválidos.');
|
||
|
||
const filas: FilaBirads[] = ESTRATOS_BIRADS.map(id => {
|
||
const rotulo = texto(etiquetas[id]) ? etiquetas[id] : ETIQUETA_ESTRATO[id];
|
||
// A stratum the response does not publish has cells that are not available: it is never read as zero patients.
|
||
const celdas = Object.fromEntries(categorias.map(c => [c.id, celda(indice.get(JSON.stringify([id, c.id])))]));
|
||
const otras = Object.fromEntries(aparte.map(a => [a.id, celda(indice.get(JSON.stringify([id, a.id])))]));
|
||
const total = celda(totalesDelPeriodo.find(t => t['estrato'] === id));
|
||
const valores = Object.values(celdas);
|
||
// The published total of a stratum has to be the sum of its cells, when both are known.
|
||
const todas = [...valores, ...Object.values(otras)];
|
||
if (total.n !== null && todas.every(c => c.n !== null) && suma(todas) !== total.n) return fail('El total de ' + rotulo + ' no coincide con la suma de sus celdas.');
|
||
// A suppressed published total suppresses the row, whatever its cells say.
|
||
return { id, etiqueta: rotulo, celdas, aparte: otras, total,
|
||
den: total.estado === 'Suprimido' ? null : suma(valores), estado: total.estado === 'Suprimido' ? 'Suprimido' : estadoDe(valores) };
|
||
});
|
||
// The donut and its total need the six strata complete: a partial sum would be a different, unpublished figure.
|
||
const porCategoria = Object.fromEntries(categorias.map(c => [c.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[c.id]))]));
|
||
return { periodo, categorias, grupos, base, filas, totales: porCategoria,
|
||
conResultado: suma(categorias.map(c => ({ n: porCategoria[c.id], estado: 'Publicado' as const }))),
|
||
aparte, vacio: indice.size === 0 && !totalesDelPeriodo.length, notas: [...new Set(datos.notas ?? [])] };
|
||
}
|
||
|
||
export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; }
|
||
export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] {
|
||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? [];
|
||
}
|
||
export function seleccionEtiqueta(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string {
|
||
return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta;
|
||
}
|
||
/** A group selects the group; a category selects it and a second click returns to its group; the centre returns to the base. */
|
||
export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistopatologia, traza: string, indice: number): SeleccionHistopatologia {
|
||
if (traza === 'centro') return seleccionBase(m);
|
||
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
|
||
if (traza !== 'categorias') return sel;
|
||
const c = m.categorias[indice];
|
||
if (!c) return sel;
|
||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||
}
|
||
/** The axis title says what the rate reads. */
|
||
export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string {
|
||
if (!sel.categoria && sel.grupo === m.base) return 'Pacientes con resultado maligno entre las que tienen resultado de biopsia';
|
||
if (!sel.categoria) return 'Pacientes con resultado no maligno entre las que tienen resultado de biopsia';
|
||
return 'Proporción con resultado ' + enFrase(seleccionEtiqueta(m, sel));
|
||
}
|
||
/** Per BI-RADS stratum: the selected categories over the patients with a biopsy result. No biopsy and no data never enter. */
|
||
export function tasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): Tasa[] {
|
||
const ids = seleccionadas(m, sel);
|
||
return m.filas.map(fila => {
|
||
if (fila.den === null || fila.den === 0) return { fila, k: null, valor: null, bajo: null, alto: null };
|
||
const k = ids.reduce((s, c) => s + fila.celdas[c].n!, 0);
|
||
const [bajo, alto] = wilson(k, fila.den);
|
||
return { fila, k, valor: 100 * k / fila.den, bajo, alto };
|
||
});
|
||
}
|
||
export function estadoTasa(t: Tasa): string {
|
||
return t.fila.den === 0 ? 'Sin pacientes con resultado de biopsia' : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
|
||
}
|
||
/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */
|
||
export function rangoTasas(valores: Tasa[]): [number, number] {
|
||
const visibles = valores.filter(t => t.bajo !== null && t.alto !== null);
|
||
if (!visibles.length) return [0, 100];
|
||
const min = Math.min(...visibles.map(t => t.bajo!)), max = Math.max(...visibles.map(t => t.alto!));
|
||
return [Math.max(0, Math.floor((min - 5) / 5) * 5), Math.min(100, Math.ceil((max + 5) / 5) * 5)];
|
||
}
|
||
|
||
/** Rates on the left: one point and horizontal Wilson interval per BI-RADS stratum, one trace always. */
|
||
// `estrecho`: a phone-width plot, where the labels wrap and the axis keeps only what fits.
|
||
export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema, estrecho = false): PlotlyFigure {
|
||
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: 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}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||
}], layout: {
|
||
autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||
// The labels of the categories size their own margin, so the plot keeps its width on a narrow screen.
|
||
margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 },
|
||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true,
|
||
...(estrecho ? { tickmode: 'array', tickvals: y, ticktext: y.map(v => v.replace(' sin subtipo', '<br>sin subtipo')) } : {}) },
|
||
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true,
|
||
title: { text: estrecho ? 'Porcentaje' : 'Porcentaje con resultado ' + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } },
|
||
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
|
||
font: { size: estrecho ? 11 : 12, color: p.text },
|
||
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||
}, config: { displayModeBar: false } };
|
||
}
|
||
|
||
/** 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;
|
||
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
|
||
const interior = m.grupos.map(g => g.categorias.reduce((s, c) => s + m.totales[c]!, 0));
|
||
const exterior = m.categorias.map(c => m.totales[c.id]!);
|
||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes con resultado, %{customdata[1]}<extra></extra>' };
|
||
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: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside',
|
||
text: [`<b>${miles(k)}</b><br>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) + '<extra></extra>' },
|
||
{ ...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 => 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 => 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 } };
|
||
}
|