Files
WebApp/src/app/features/indicadores/indicadores.presentation.ts
T

162 lines
9.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { FigureSelection, PlotlyFigure } from './indicadores.models';
import { BASE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile';
import { applyAxisLabels, categoryMinimumWidth, CategoryLabel } from './indicadores-axis-labels';
export interface FigurePresentation {
figure: PlotlyFigure;
// Plain text, including original line breaks; never an HTML fragment.
footnotes: readonly string[];
categoryLabels: readonly CategoryLabel[];
minimumPlotWidth?: number;
}
const TEA_FOOTER_FIGURES = new Set(['fig_c1_grupos', 'fig_c1_puntos', 'fig_c2_apiladas', 'fig_c3r_caja']);
// Verified published families share the complete documentary footer geometry.
// Donut totals (paper 0.5, 0.5), data labels and callouts do not match it.
const DISTRIBUTION_FOOTER_FIGURES = new Set(['fig_c2_barras', 'fig_c2_donas', 'fig_c3r_caja']);
const FOOTER_KEYS = new Set(['text', 'xref', 'yref', 'x', 'y', 'xanchor', 'yanchor', 'align', 'showarrow', 'font']);
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function footerText(annotation: unknown, selection: FigureSelection): string | undefined {
const tea = selection.dominio === 'tea';
const verifiedFamily = tea
? TEA_FOOTER_FIGURES.has(selection.figura) || DISTRIBUTION_FOOTER_FIGURES.has(selection.figura)
: (selection.dominio === 'cacu' || selection.dominio === 'cama') && DISTRIBUTION_FOOTER_FIGURES.has(selection.figura);
if (!verifiedFamily || !record(annotation)
|| Object.keys(annotation).some(key => !FOOTER_KEYS.has(key))
|| annotation['xref'] !== 'paper' || annotation['yref'] !== 'paper'
|| annotation['x'] !== 0 || annotation['y'] !== -0.22
|| annotation['xanchor'] !== 'left' || annotation['yanchor'] !== 'top'
|| annotation['align'] !== 'left' || annotation['showarrow'] !== false
|| !record(annotation['font']) || annotation['font']['size'] !== 11
|| Object.keys(annotation['font']).some(key => !['size', 'color'].includes(key))
|| typeof annotation['text'] !== 'string') return undefined;
const text = annotation['text'].replace(/<br\s*\/?\s*>/gi, '\n');
// Rich markup, encoded markup, links and unknown formatting stay in Plotly.
if (!text.trim() || /[<>]|&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);/i.test(text)) return undefined;
// CaCu/CaMa publish plain documentary text in this exact exterior slot.
// No length threshold, keywords or indicator-name inference is involved.
if (!tea) return text;
// Retain UX-07B's additional TEA source/restriction guarantees.
const lines = text.split('\n');
if (lines.length < 3 || !lines[0].trim()
|| !/^Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: \d{4}-\d{2}-\d{2}$/.test(lines.at(-2)!)
|| lines.at(-1) !== 'Uso exclusivo de investigación. No usar para decisiones clínicas.') return undefined;
return text;
}
function applyVisualProfile(figure: PlotlyFigure, profile: FigureVisualProfile, availableWidth?: number) {
const layout = figure.layout;
if (profile.paperBackground !== undefined) layout['paper_bgcolor'] = profile.paperBackground;
if (profile.plotBackground !== undefined) layout['plot_bgcolor'] = profile.plotBackground;
if (profile.font) {
// A larger inherited legend/tick font can hide multicategory labels on
// narrow cards. Bound only the optional profile enlargement, not the source.
const narrowCategories = profile.axisLabels?.enabled && availableWidth !== undefined && availableWidth > 0 && availableWidth < 360
&& record(layout['xaxis']) && ['category', 'multicategory'].includes(String(layout['xaxis']['type']))
&& figure.data.every(trace => ['scatter', 'bar'].includes(String(trace['type'])));
layout['font'] = { ...(record(layout['font']) ? layout['font'] : {}), ...profile.font,
...(narrowCategories && profile.font.size !== undefined && profile.font.size > 12 ? { size: 12 } : {}) };
}
if (profile.margin) layout['margin'] = { ...(record(layout['margin']) ? layout['margin'] : {}), ...profile.margin };
if (profile.grid) {
for (const key of Object.keys(layout).filter(key => /^[xy]axis\d*$/.test(key))) {
const axis = layout[key];
if (!record(axis)) continue;
layout[key] = { ...axis,
...(profile.grid.color !== undefined ? { gridcolor: profile.grid.color } : {}),
...(profile.grid.visible !== undefined ? { showgrid: profile.grid.visible } : {}),
};
}
}
// Respect fixed-size figures and animated layouts. No width feedback loop.
if (profile.minimumHeight !== undefined && Number.isFinite(profile.minimumHeight) && profile.minimumHeight > 0
&& !figure.frames?.length && layout['autosize'] !== false && layout['width'] === undefined
&& (layout['height'] === undefined || typeof layout['height'] === 'number')) {
layout['height'] = Math.max(typeof layout['height'] === 'number' ? layout['height'] : 620, profile.minimumHeight);
}
}
function relaxFooterMargin(figure: PlotlyFigure) {
const layout = figure.layout, axis = layout['xaxis'], margin = layout['margin'];
const template = layout['template'];
const templateLayout = record(template) ? template['layout'] : undefined;
const templateAxis = record(templateLayout) ? templateLayout['xaxis'] : undefined;
const legend = layout['legend'];
// Only the known footer reserve on a single, automatic Cartesian axis.
// Multicategory ticks, lower legends and other paper objects keep their space.
if (!record(axis) || !record(margin) || margin['b'] !== 150
|| (axis['automargin'] !== true && !(record(templateAxis) && templateAxis['automargin'] === true))
|| axis['type'] === 'multicategory' || figure.data.some(trace => !['scatter', 'bar', 'box'].includes(String(trace['type']))
|| (Array.isArray(trace['x']) && trace['x'].some(Array.isArray)))
|| Object.keys(layout).some(key => /^[xy]axis[1-9]\d*$/.test(key))
|| ['shapes', 'images', 'sliders', 'updatemenus'].some(key => layout[key] !== undefined)
|| (record(legend) && (legend['orientation'] === 'h' || (typeof legend['y'] === 'number' && legend['y'] <= 0)))
|| layout['autosize'] === false || layout['width'] !== undefined || layout['height'] !== undefined) return;
layout['margin'] = { ...margin, b: 80 };
}
export function figureTitle(figure: PlotlyFigure, fallback: string): string {
const title = figure.layout['title'];
if (typeof title === 'string' && title.trim()) return title;
if (title && typeof title === 'object' && 'text' in title
&& typeof title.text === 'string' && title.text.trim()) return title.text;
return fallback;
}
// Adapt only the dashboard copy; HTTP figures and all observations stay intact.
export function figurePresentation(original: PlotlyFigure, selection: FigureSelection,
profile: FigureVisualProfile = BASE_VISUAL_PROFILE, availableWidth?: number): FigurePresentation {
const figure = structuredClone(original);
const title = figure.layout['title'];
figure.layout['title'] = title && typeof title === 'object' ? { ...title, text: '' } : { text: '' };
if ((selection.dominio === 'cacu' || selection.dominio === 'cama')
&& selection.figura === 'fig_c1_puntos' && selection.tipoPeriodo === 'mes'
&& figure.data.length > 0
&& figure.data.every(trace => trace['type'] === 'scatter' && trace['mode'] === 'markers'
&& Array.isArray(trace['x']) && trace['x'].length > 0
&& trace['x'].every(x => typeof x === 'string' && /^[0-9]{4}-(0[1-9]|1[0-2])$/.test(x)))) {
const periods = [...new Set(figure.data.flatMap(trace => trace['x'] as string[]))].sort();
figure.layout['xaxis'] = {
...(figure.layout['xaxis'] as Record<string, unknown> | undefined),
type: 'category', categoryorder: 'array', categoryarray: periods,
tickmode: 'array', tickvals: periods, ticktext: periods,
tickangle: 0, automargin: true,
};
}
const footnotes: string[] = [];
const annotations = figure.layout['annotations'];
// Frames may reintroduce annotations. Keep animated figures entirely in Plotly.
if (!figure.frames?.length && Array.isArray(annotations)) {
figure.layout['annotations'] = annotations.filter(annotation => {
const text = footerText(annotation, selection);
if (text === undefined) return true;
footnotes.push(text);
return false;
});
// Only the previously verified TEA reserve can be relaxed. Newly supported
// families keep their margins, legends, colorbars and fixed dimensions.
if (footnotes.length && selection.dominio === 'tea' && TEA_FOOTER_FIGURES.has(selection.figura)
&& (figure.layout['annotations'] as unknown[]).length === 0) relaxFooterMargin(figure);
}
applyVisualProfile(figure, profile, availableWidth);
const minimumPlotWidth = profile.axisLabels?.enabled && Number.isFinite(availableWidth) && availableWidth! > 0
&& selection.dominio === 'tea' && ['fig_c1_grupos', 'fig_c2_apiladas'].includes(selection.figura)
? categoryMinimumWidth(figure) : undefined;
const categoryLabels = applyAxisLabels(figure, profile.axisLabels, availableWidth);
if (minimumPlotWidth !== undefined && !categoryLabels.length
&& figure.data.every(trace => Array.isArray(trace['x']) && !trace['x'].some(Array.isArray))) {
figure.layout['xaxis'] = { ...(record(figure.layout['xaxis']) ? figure.layout['xaxis'] : {}),
type: 'category', tickmode: 'linear', dtick: 1, automargin: true };
}
return { figure, footnotes, categoryLabels, minimumPlotWidth };
}
// Compatibility for existing consumers that only need the Plotly copy.
export function presentationFigure(original: PlotlyFigure, selection: FigureSelection,
profile: FigureVisualProfile = BASE_VISUAL_PROFILE): PlotlyFigure {
return figurePresentation(original, selection, profile).figure;
}