231 lines
18 KiB
TypeScript
231 lines
18 KiB
TypeScript
import { abbreviateCategories, categoryMinimumWidth } from './indicadores-axis-labels';
|
||
import { FigureSelection, PlotlyFigure } from './indicadores.models';
|
||
import { figurePresentation } from './indicadores.presentation';
|
||
import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile';
|
||
|
||
const selection: FigureSelection = { dominio: 'tea', indicador: 'synthetic', figura: 'fig_c1_grupos', tema: 'claro' };
|
||
const long = 'Fármaco de riesgo para el neurodesarrollo';
|
||
const hover = '2025-S1<br>%{x}<br>%{y:.1f}% (%{customdata[0]} de %{customdata[1]})<extra></extra>';
|
||
function source(): PlotlyFigure {
|
||
return { data: [{ type: 'scatter', mode: 'markers', x: [long, 'Otra'], y: [20, null],
|
||
customdata: [[2, 10], [null, 'SUPRIMIDO']], error_y: { array: [5, null] }, hovertemplate: hover,
|
||
future: { keep: true } }], layout: { xaxis: { type: 'category', categoryorder: 'array', categoryarray: [long, 'Otra'], future: 7 },
|
||
yaxis: { range: [0, 100] }, margin: { b: 150 }, annotations: [{ text: 'Nota desconocida', y: -0.3 }] },
|
||
config: { displaylogo: false }, future: { keep: [null, 0] } };
|
||
}
|
||
const present = (figure: PlotlyFigure) => figurePresentation(figure, selection, READABLE_VISUAL_PROFILE);
|
||
function freezeDeep(value: unknown) {
|
||
if (value && typeof value === 'object') { Object.values(value).forEach(freezeDeep); Object.freeze(value); }
|
||
}
|
||
|
||
describe('UX-07C etiquetas de ejes', () => {
|
||
it('UX-07D reserva espacio para las cinco áreas cortas sin perder ticks ni modificar observaciones', () => {
|
||
const figure: PlotlyFigure = { data: [{ type: 'bar', name: 'Desarrollo adecuado', x: ['Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo'], y: [20, null, 0, 40, 60] }],
|
||
layout: { xaxis: {}, margin: { l: 60, r: 30 } } };
|
||
const before = structuredClone(figure); freezeDeep(figure);
|
||
const result = figurePresentation(figure, { ...selection, figura: 'fig_c2_apiladas' }, READABLE_VISUAL_PROFILE, 253);
|
||
expect(result.minimumPlotWidth).toBeGreaterThan(253);
|
||
expect(result.figure.layout['xaxis']).toMatchObject({ type: 'category', tickmode: 'linear', dtick: 1, automargin: true });
|
||
expect(result.figure.data).toEqual(before.data); expect(figure).toEqual(before);
|
||
expect(figurePresentation(figure, selection, BASE_VISUAL_PROFILE, 253).minimumPlotWidth).toBeUndefined();
|
||
expect(figurePresentation(figure, { ...selection, dominio: 'cacu' }, READABLE_VISUAL_PROFILE, 253).minimumPlotWidth).toBeUndefined();
|
||
expect(figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, result.minimumPlotWidth).minimumPlotWidth).toBe(result.minimumPlotWidth);
|
||
});
|
||
it('UX-07D mantiene todos los pares semestre/área con un mínimo estable y sin ticks simples', () => {
|
||
const figure: PlotlyFigure = { data: [{ type: 'bar', x: [Array(5).fill('2025-S1').concat(Array(5).fill('2025-S2')),
|
||
['Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo', 'Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo']], y: Array(10).fill(null) }], layout: { xaxis: {} } };
|
||
const before = structuredClone(figure);
|
||
const result = figurePresentation(figure, { ...selection, figura: 'fig_c2_apiladas' }, READABLE_VISUAL_PROFILE, 253);
|
||
expect(result.minimumPlotWidth).toBeGreaterThan(253);
|
||
expect(result.figure.layout['xaxis']).toEqual({}); expect(result.figure.data).toEqual(before.data);
|
||
expect(figure).toEqual(before);
|
||
});
|
||
it('UX-07D no reserva ancho en estructuras desconocidas, ejes numéricos, notas sin reconocer o dimensiones fijas', () => {
|
||
const base: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: { xaxis: { type: 'category' } } };
|
||
for (const layout of [{ width: 700 }, { autosize: false }, { xaxis2: {} }, { annotations: [{ text: 'Advertencia desconocida' }] }, { xaxis: { type: 'date' } }, { template: { layout: { xaxis: { tickvals: ['A'] } } } }]) {
|
||
expect(categoryMinimumWidth({ ...base, layout: { ...base.layout, ...layout } })).toBeUndefined();
|
||
}
|
||
expect(categoryMinimumWidth({ ...base, data: [{ type: 'box', x: ['A', 'B', 'C'], y: [0, null, 20] }] })).toBeUndefined();
|
||
expect(categoryMinimumWidth({ ...base, frames: [{}] })).toBeUndefined();
|
||
});
|
||
it('deja las etiquetas cortas intactas y abrevia por palabras sólo las extensas', () => {
|
||
expect([...abbreviateCategories(['Corta', long], 22)]).toEqual([['Corta', 'Corta'], [long, 'Fármaco de riesgo…']]);
|
||
const result = present(source());
|
||
expect(result.figure.layout['xaxis']).toMatchObject({ tickvals: [long, 'Otra'], ticktext: ['Fármaco de riesgo…', 'Otra'],
|
||
categoryarray: [long, 'Otra'], categoryorder: 'array', future: 7, automargin: true });
|
||
expect(result.categoryLabels).toEqual([{ axis: 'x', original: long, abbreviated: 'Fármaco de riesgo…' }]);
|
||
});
|
||
it('sin etiquetas extensas no crea ticks ni cambia el hover', () => {
|
||
const figure = source(); figure.data[0]['x'] = ['Corta', 'Otra']; figure.layout['xaxis'] = { type: 'category' };
|
||
expect(present(figure).figure.data).toEqual(figure.data);
|
||
expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']);
|
||
expect(present(figure).categoryLabels).toEqual([]);
|
||
});
|
||
it('conserva etiquetas completas cuando hay ancho suficiente y abrevia al estrechar la misma figura', () => {
|
||
const figure = source(), before = structuredClone(figure);
|
||
const spacious = figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, 1400);
|
||
expect(spacious.categoryLabels).toEqual([]); expect(spacious.figure.data).toEqual(before.data);
|
||
expect(spacious.figure.layout['xaxis']).toEqual(before.layout['xaxis']);
|
||
expect(figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, 320).categoryLabels).toHaveLength(1);
|
||
expect(figurePresentation(figure, selection, { axisLabels: { enabled: true, preserveWhenFits: false } }, 1400).categoryLabels).toHaveLength(1);
|
||
expect(figure).toEqual(before);
|
||
});
|
||
it('acota la ampliación tipográfica opcional en tarjetas estrechas sin cambiar la fuente original ni el perfil amplio', () => {
|
||
const figure = source(); figure.layout['font'] = { size: 13, future: true };
|
||
const profile = { ...DEMO_VISUAL_PROFILE, ...READABLE_VISUAL_PROFILE };
|
||
expect(figurePresentation(figure, selection, profile, 270).figure.layout['font']).toMatchObject({ size: 12, future: true });
|
||
expect(figurePresentation(figure, selection, profile, 646).figure.layout['font']).toMatchObject({ size: 15 });
|
||
expect(figure.layout['font']).toEqual({ size: 13, future: true });
|
||
});
|
||
it('las colisiones y las abreviaciones iguales a otra categoría vuelven al original', () => {
|
||
const a = 'Fármaco de riesgo para el neurodesarrollo', b = 'Fármaco de riesgo para otra condición';
|
||
const labels = abbreviateCategories([a, b, 'Fármaco de riesgo…'], 22);
|
||
expect([...labels.values()]).toEqual([a, b, 'Fármaco de riesgo…']);
|
||
expect(new Set(labels.values()).size).toBe(labels.size);
|
||
});
|
||
it('deduplica la correspondencia sin retirar puntos duplicados', () => {
|
||
const figure = source(); figure.data[0]['x'] = [long, long];
|
||
const result = present(figure);
|
||
expect(result.categoryLabels).toHaveLength(1);
|
||
expect(result.figure.data[0]['x']).toEqual([long, long]);
|
||
expect((result.figure.layout['xaxis'] as Record<string, unknown>)['tickvals']).toEqual([long, 'Otra']);
|
||
});
|
||
it('conserva grafemas Unicode, acentos, símbolos y palabras indivisibles', () => {
|
||
const value = 'Área 👩🏽⚕️ y comunicación extensa';
|
||
expect(abbreviateCategories([value], 12).get(value)).toBe('Área 👩🏽⚕️ y…');
|
||
const word = 'Neurodesarrollosuperextenso';
|
||
expect(abbreviateCategories([word], 10).get(word)).toBe(word);
|
||
expect(abbreviateCategories([word], 10, false).get(word)).toBe('Neurodesa…');
|
||
const symbol = 'Área α ± lenguaje y comunicación';
|
||
expect(abbreviateCategories([symbol], 12).get(symbol)).toBe('Área α ±…');
|
||
});
|
||
it('preserva profundamente el original, datos, customdata, anotaciones, configuración y atributos desconocidos', () => {
|
||
const figure = source(), before = structuredClone(figure); freezeDeep(figure);
|
||
const result = present(figure);
|
||
expect(figure).toEqual(before);
|
||
const { hovertemplate: ignored, ...observations } = result.figure.data[0];
|
||
const { hovertemplate: originalHover, ...originalObservations } = before.data[0];
|
||
expect(observations).toEqual(originalObservations);
|
||
expect(result.figure.data[0]).not.toBe(figure.data[0]);
|
||
expect(result.figure.layout['annotations']).toEqual(before.layout['annotations']);
|
||
expect(result.figure.layout['margin']).toEqual(before.layout['margin']);
|
||
expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']);
|
||
});
|
||
it('restituye exclusivamente la categoría en hover y conserva porcentajes, intervalos y conteos', () => {
|
||
const figure = source(); figure.data[0]['hovertemplate'] = hover.replace('<extra>', '<br>IC %{error_y.array}<extra>');
|
||
const result = present(figure);
|
||
expect(result.figure.data[0]['hovertemplate']).toEqual([long, 'Otra'].map(label =>
|
||
(figure.data[0]['hovertemplate'] as string).replace('%{x}', label)));
|
||
expect(figure.data[0]['hovertemplate']).toContain('%{x}');
|
||
});
|
||
it('conserva símbolos de reemplazo y ampersands como texto literal en el hover', () => {
|
||
const figure = source(), label = 'Área $& y salud & comunicación extensa';
|
||
figure.data[0]['x'] = [label, 'Otra'];
|
||
expect((present(figure).figure.data[0]['hovertemplate'] as string[])[0]).toBe(hover.replace('%{x}', () => label.replaceAll('&', '&')));
|
||
});
|
||
it.each([NaN, 0, 7, 81, 20.5])('opciones inválidas conservan los ejes: %s', maxCharacters => {
|
||
const figure = source();
|
||
const result = figurePresentation(figure, selection, { axisLabels: { enabled: true, maxCharacters } });
|
||
expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]);
|
||
});
|
||
it('conserva plantillas por punto, hovertext, hoverinfo y contenido suprimido sin exponer valores', () => {
|
||
const figure = source(); figure.data[0]['hovertemplate'] = [hover, '%{x}<br>dato suprimido (conteo bajo)<extra></extra>'];
|
||
figure.data[0]['hovertext'] = ['Observación publicada', 'SUPRIMIDO']; figure.data[0]['hoverinfo'] = 'text';
|
||
const result = present(figure).figure.data[0];
|
||
expect((result['hovertemplate'] as string[])[1]).toBe('Otra<br>dato suprimido (conteo bajo)<extra></extra>');
|
||
expect((result['hovertemplate'] as string[])[1]).not.toMatch(/customdata|%\{y|20|0 %/);
|
||
expect(result['hovertext']).toEqual(figure.data[0]['hovertext']); expect(result['customdata']).toEqual(figure.data[0]['customdata']);
|
||
expect(result['hoverinfo']).toBe('text'); expect(result['y']).toEqual([20, null]);
|
||
});
|
||
it.each([undefined, '%{x:.2f}<br>%{y}', '%{customdata[0]}', ['%{x}'], ['%{x}', null]])('fallback de hover desconocido o incompatible: %j', template => {
|
||
const figure = source(); figure.data[0]['hovertemplate'] = template;
|
||
expect(present(figure).figure.data).toEqual(figure.data);
|
||
expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']);
|
||
expect(present(figure).categoryLabels).toEqual([]);
|
||
});
|
||
it.each(['linear', 'date', 'log', 'multicategory'])('no adapta un eje simple declarado %s', type => {
|
||
const figure = source(); figure.layout['xaxis'] = { type };
|
||
expect(present(figure).figure.data).toEqual(figure.data);
|
||
expect(present(figure).figure.layout['xaxis']).toEqual({ type });
|
||
});
|
||
it.each(['2025-01', '2025-S1', '2025-10-14T14:00:00', 'Primer semestre del año 2025', '1234567890123456789012345'])('no abrevia fechas, periodos ni texto numérico: %s', label => {
|
||
expect(abbreviateCategories([label], 8).get(label)).toBe(label);
|
||
});
|
||
it.each([{ ticktext: ['Alias'] }, { tickmode: 'auto' }, { labelalias: { [long]: 'Alias' } }, { range: [0, 2] },
|
||
{ showticklabels: false }, { tickprefix: 'Grupo: ' }, { matches: 'x2' }])('respeta ticks/semántica explícita del eje: %j', axis => {
|
||
const figure = source(); figure.layout['xaxis'] = { type: 'category', ...axis };
|
||
expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']);
|
||
});
|
||
it('respeta ticks heredados de una plantilla y una orientación publicada', () => {
|
||
const figure = source(); figure.layout['template'] = { layout: { xaxis: { ticktext: ['Alias'] } } };
|
||
expect(present(figure).categoryLabels).toEqual([]);
|
||
delete figure.layout['template']; (figure.layout['xaxis'] as Record<string, unknown>)['tickangle'] = 30;
|
||
expect(present(figure).figure.layout['xaxis']).toMatchObject({ tickangle: 30 });
|
||
});
|
||
it('soporta barras horizontales sin cambiar categorías Y ni valores X', () => {
|
||
const figure: PlotlyFigure = { data: [{ type: 'bar', orientation: 'h', y: [long], x: [0], customdata: [null],
|
||
hovertemplate: '%{y}<br>%{x:.1f}%<extra></extra>' }], layout: { yaxis: { type: 'category' } } };
|
||
const result = present(figure);
|
||
expect(result.figure.layout['yaxis']).toMatchObject({ ticktext: ['Fármaco de riesgo…'], tickvals: [long] });
|
||
expect(result.figure.data[0]['x']).toEqual([0]); expect(result.figure.data[0]['y']).toEqual([long]);
|
||
expect(result.figure.data[0]['hovertemplate']).toEqual([long + '<br>%{x:.1f}%<extra></extra>']);
|
||
});
|
||
it('multicategoría conserva niveles, periodos, agrupación, hover y reserva de margen', () => {
|
||
const figure = source(); figure.data[0]['type'] = 'bar'; figure.data[0]['x'] = [['2025-S1', '2025-S2'], [long, long]];
|
||
figure.layout['xaxis'] = { type: 'multicategory', future: true };
|
||
const result = present(figure);
|
||
expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]);
|
||
expect(result.figure.layout['xaxis']).toEqual({ type: 'multicategory', future: true, automargin: true, tickfont: { size: 11 } });
|
||
expect(result.figure.layout['margin']).toEqual(figure.layout['margin']);
|
||
const preserve = figurePresentation(figure, selection, { axisLabels: { enabled: true, multicategory: 'preserve' } });
|
||
expect(preserve.figure.layout['xaxis']).toEqual(figure.layout['xaxis']);
|
||
});
|
||
it.each([{ levels: [['2025-S1'], [long, long]] }, { levels: [['Grupo', 'Grupo'], [long, long]] },
|
||
{ levels: [['2025-S1', '2025-S2'], [long, long], ['a', 'b']] }])('preserva multicategorías no validadas: %j', ({ levels }) => {
|
||
const figure = source(); figure.data[0]['x'] = levels; figure.layout['xaxis'] = { type: 'multicategory' };
|
||
expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']);
|
||
expect(present(figure).figure.data).toEqual(figure.data);
|
||
});
|
||
it.each(['pie', 'box', 'heatmap', 'future'])('conserva familias incompatibles: %s', type => {
|
||
const figure = source(); figure.data[0]['type'] = type;
|
||
expect(present(figure).categoryLabels).toEqual([]); expect(present(figure).figure.data).toEqual(figure.data);
|
||
});
|
||
it('conserva frames/menús/subplots y no infiere identidades o HTML', () => {
|
||
for (const extra of [{ frames: [{ name: 'f', data: [{ x: [long] }], future: 3 }] },
|
||
{ layout: { ...source().layout, updatemenus: [] } }, { layout: { ...source().layout, xaxis2: {} } }]) {
|
||
const figure = { ...source(), ...extra }, before = structuredClone(figure);
|
||
expect(present(figure).figure.data).toEqual(before.data); expect(present(figure).figure.frames).toEqual(before.frames);
|
||
expect(present(figure).categoryLabels).toEqual([]);
|
||
}
|
||
for (const label of ['<b>Texto extenso publicado</b>', 'Área & texto extenso', 'Área %{customdata} muy extensa']) {
|
||
const figure = source(); figure.data[0]['x'] = [label, 'Otra'];
|
||
expect(present(figure).categoryLabels).toEqual([]);
|
||
}
|
||
});
|
||
it('revierte al perfil base desde el original y combina el perfil de demostración sin acumulación', () => {
|
||
const figure = source(), original = structuredClone(figure);
|
||
const compact = present(figure); compact.figure.data[0]['x'] = ['mutación del runtime'];
|
||
const restored = figurePresentation(figure, selection, BASE_VISUAL_PROFILE);
|
||
expect(restored.figure.data).toEqual(original.data); expect(restored.categoryLabels).toEqual([]);
|
||
expect(restored.figure.layout['xaxis']).toEqual(original.layout['xaxis']);
|
||
const demo = figurePresentation(figure, selection, { ...DEMO_VISUAL_PROFILE, ...READABLE_VISUAL_PROFILE });
|
||
expect(demo.figure.layout['paper_bgcolor']).toBe('#f2f7fc'); expect(demo.categoryLabels).toHaveLength(1);
|
||
expect(figure).toEqual(original);
|
||
});
|
||
it('extrae el pie TEA sin perder el mapa de categorías ni alterar anotaciones desconocidas', () => {
|
||
const figure = source(); figure.layout['annotations'] = [{
|
||
text: 'Nota sintética.<br>Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: 2025-08-01<br>Uso exclusivo de investigación. No usar para decisiones clínicas.',
|
||
xref: 'paper', yref: 'paper', x: 0, y: -0.22, xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 },
|
||
}];
|
||
const result = present(figure);
|
||
expect(result.footnotes).toHaveLength(1); expect(result.figure.layout['annotations']).toEqual([]);
|
||
expect(result.categoryLabels[0].original).toBe(long);
|
||
});
|
||
it.each(['cacu', 'cama'] as const)('mantiene la adaptación mensual %s con el perfil legible', dominio => {
|
||
const figure: PlotlyFigure = { data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01'], y: [null, 0], hovertemplate: hover }], layout: {} };
|
||
const result = figurePresentation(figure, { ...selection, dominio, figura: 'fig_c1_puntos', tipoPeriodo: 'mes' }, READABLE_VISUAL_PROFILE);
|
||
expect(result.figure.layout['xaxis']).toMatchObject({ categoryarray: ['2025-01', '2025-03'], ticktext: ['2025-01', '2025-03'] });
|
||
expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]);
|
||
});
|
||
});
|