Files
WebApp/src/app/features/indicadores/indicadores-axis-labels.ts
T

192 lines
13 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 { PlotlyFigure } from './indicadores.models';
import { AxisLabelOptions } from './indicadores-visual-profile';
export interface CategoryLabel {
readonly axis: 'x' | 'y';
readonly abbreviated: string;
readonly original: string;
}
const graphemes = new Intl.Segmenter('es', { granularity: 'grapheme' });
const characters = (text: string) => [...graphemes.segment(text)].map(part => part.segment);
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function plainLabel(value: unknown): value is string {
return typeof value === 'string' && value.trim().length > 0
&& !/[<>]|&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);|%\{/i.test(value);
}
function temporalOrNumeric(value: string): boolean {
// Conservative: published years, dates, semester/month codes and numeric text.
return /(?:^|\D)\d{4}(?:\D|$)/u.test(value) || /^[\d\s.,+−\-/%:]+$/u.test(value)
|| /^(?:S[12]|T[1-4]|Q[1-4]|\d{1,2}[-/]\d{1,2})$/iu.test(value);
}
/** A collision falls back to the original; identical categories share one label. */
export function abbreviateCategories(values: readonly string[], limit: number, preferWords = true): Map<string, string> {
const originals = [...new Set(values)];
const labels = new Map(originals.map(value => {
if (temporalOrNumeric(value) || characters(value).length <= limit) return [value, value];
let prefix = characters(value).slice(0, limit - 1).join('');
if (preferWords && !/^\s/u.test(characters(value)[limit - 1] ?? '')) {
const boundary = prefix.search(/\s+\S*$/u);
if (boundary < 1) return [value, value]; // Do not split an indivisible word.
prefix = prefix.slice(0, boundary);
}
return [value, prefix.trimEnd() + '…'];
}));
const counts = new Map<string, number>();
for (const label of labels.values()) counts.set(label, (counts.get(label) ?? 0) + 1);
for (const [original, label] of labels) {
if ((counts.get(label) ?? 0) > 1 || (label !== original && labels.has(label))) labels.set(original, original);
}
return labels;
}
function templates(trace: Record<string, unknown>, coordinate: 'x' | 'y', size: number): string[] | undefined {
const template = trace['hovertemplate'];
const list = typeof template === 'string' ? Array<string>(size).fill(template)
: Array.isArray(template) && template.length === size ? template : undefined;
// Do not reconstruct default hovers, formatted coordinates, expressions, or
// templates whose category is in a different field. Preserve those axes.
return list?.every(text => typeof text === 'string' && text.includes(`%{${coordinate}}`)
&& !text.includes(`%{${coordinate}:`) && !text.includes(`%{${coordinate}|`)) ? list : undefined;
}
// Keep dense categories readable inside the existing keyboard-scrollable plot
// viewport. The minimum is independent of the measured host width, preventing
// ResizeObserver feedback when the host grows to this minimum.
export function categoryMinimumWidth(figure: PlotlyFigure): number | undefined {
const published = figure.layout['xaxis'];
const template = figure.layout['template'];
const templateLayout = record(template) && record(template['layout']) ? template['layout'] : {};
const axis = { ...(record(templateLayout['xaxis']) ? templateLayout['xaxis'] : {}), ...(record(published) ? published : {}) };
if ((published !== undefined && !record(published)) || (axis['type'] !== undefined && !['category', 'multicategory'].includes(String(axis['type'])))
|| figure.frames?.length || figure.layout['width'] !== undefined || figure.layout['autosize'] === false
|| ['annotations', 'shapes', 'images', 'sliders', 'updatemenus'].some(key => {
const value = figure.layout[key]; return value !== undefined && (!Array.isArray(value) || value.length > 0);
}) || Object.keys(figure.layout).some(key => /^[xy]axis\d+$/.test(key))
|| ['tickvals', 'ticktext', 'tickmode', 'dtick', 'tick0', 'range', 'matches', 'overlaying', 'ticklabelstep'].some(key => axis[key] !== undefined)
|| !figure.data.length) return undefined;
const multi = figure.data.some(trace => Array.isArray(trace['x']) && trace['x'].some(Array.isArray));
if ((multi && axis['type'] === 'category') || (!multi && axis['type'] === 'multicategory')) return undefined;
const positions: string[] = [];
for (const trace of figure.data) {
if (!['scatter', 'bar'].includes(String(trace['type'])) || trace['orientation'] === 'h'
|| ['transforms', 'xsrc', 'ysrc'].some(key => trace[key] !== undefined)
|| (trace['xaxis'] !== undefined && trace['xaxis'] !== 'x') || (trace['yaxis'] !== undefined && trace['yaxis'] !== 'y')
|| !Array.isArray(trace['x']) || !Array.isArray(trace['y'])) return undefined;
const x = trace['x'] as unknown[], y = trace['y'] as unknown[];
if (y.some(value => value !== null && typeof value !== 'number')) return undefined;
if (multi) {
if (trace['type'] !== 'bar' || x.length !== 2 || !x.every(Array.isArray)
|| x.some(level => level.length !== y.length) || !(x[0] as unknown[]).every(value => typeof value === 'string' && /^\d{4}-S[12]$/.test(value))
|| !(x[1] as unknown[]).every(plainLabel)) return undefined;
(x[0] as string[]).forEach((period, index) => positions.push(JSON.stringify([period, (x[1] as string[])[index]])));
} else {
if (x.length !== y.length || !x.every(plainLabel) || x.some(temporalOrNumeric)) return undefined;
positions.push(...x as string[]);
}
}
const count = new Set(positions).size;
if (count < 3) return undefined;
const font = record(figure.layout['font']) ? figure.layout['font'] : {};
const tickfont = record(axis['tickfont']) ? axis['tickfont'] : font;
const size = typeof tickfont['size'] === 'number' ? tickfont['size'] : 12;
const legend = record(figure.layout['legend']) ? figure.layout['legend'] : {};
const legendWidth = figure.layout['showlegend'] === false || legend['orientation'] === 'h' ? 0
: Math.max(0, ...figure.data.filter(trace => trace['showlegend'] !== false).map(trace =>
characters(String(trace['name'] ?? '')).length * 7 + 48));
const margin = record(figure.layout['margin']) ? figure.layout['margin'] : {};
return Math.ceil(count * Math.max(20, size * 1.8) + legendWidth
+ (typeof margin['l'] === 'number' ? margin['l'] : 80)
+ (typeof margin['r'] === 'number' ? margin['r'] : 80));
}
/** Mutates only the independent presentation clone supplied by figurePresentation. */
export function applyAxisLabels(figure: PlotlyFigure, options?: AxisLabelOptions, availableWidth?: number): CategoryLabel[] {
const result: CategoryLabel[] = [];
const limit = options?.maxCharacters ?? 22;
if (!options?.enabled || !Number.isInteger(limit) || limit < 8 || limit > 80 || figure.frames?.length
|| figure.layout['updatemenus'] !== undefined || figure.layout['sliders'] !== undefined) return result;
// Multiple/linked axes and subplots require an explicit mapping contract.
if (Object.keys(figure.layout).some(key => /^[xy]axis\d+$/.test(key))) return result;
for (const coordinate of ['x', 'y'] as const) {
const axisKey = `${coordinate}axis`, other = coordinate === 'x' ? 'y' : 'x';
const published = figure.layout[axisKey];
if (published !== undefined && !record(published)) continue;
const axis = record(published) ? published : {};
const templateLayout = record(figure.layout['template']) ? figure.layout['template']['layout'] : undefined;
const templateAxis = record(templateLayout) && record(templateLayout[axisKey]) ? templateLayout[axisKey] : {};
const effective = { ...templateAxis, ...axis };
if (['tickvals', 'ticktext', 'tickmode', 'labelalias', 'tickformat', 'tickprefix', 'ticksuffix', 'dtick', 'tick0',
'ticklabelstep', 'range', 'matches', 'overlaying', 'ticklabelindex'].some(key => effective[key] !== undefined)
|| effective['showticklabels'] === false) continue;
const traces = figure.data;
if (!traces.length || traces.some(trace => !['scatter', 'bar'].includes(String(trace['type']))
|| (trace[axisKey] !== undefined && trace[axisKey] !== coordinate)
|| ['transforms', 'hovertemplatesrc', `${coordinate}src`].some(key => trace[key] !== undefined)
|| !Array.isArray(trace[coordinate]) || !Array.isArray(trace[other])
|| (trace[other] as unknown[]).some(value => value !== null && typeof value !== 'number'))) continue;
const arrays = traces.map(trace => trace[coordinate] as unknown[]);
const fits = (values: readonly string[], count: number): boolean => {
if (coordinate !== 'x' || options.preserveWhenFits === false || !Number.isFinite(availableWidth) || !count) return false;
const margin = record(figure.layout['margin']) ? figure.layout['margin'] : {};
const font = record(effective['tickfont']) ? effective['tickfont']
: record(figure.layout['font']) ? figure.layout['font'] : {};
const fontSize = typeof font['size'] === 'number' ? font['size'] : 12;
const textWidth = (text: string) => characters(text).reduce((size, char) => size
+ fontSize * (/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Extended_Pictographic}]/u.test(char) ? 1.1 : 0.58), 0);
const legend = record(figure.layout['legend']) ? figure.layout['legend'] : {};
const legendSize = figure.layout['showlegend'] === false || legend['orientation'] === 'h' ? 0
: Math.max(0, ...traces.filter(trace => trace['showlegend'] !== false).map(trace =>
textWidth(String(trace['name'] ?? '')) + 40));
const width = availableWidth! - (typeof margin['l'] === 'number' ? margin['l'] : 80)
- (typeof margin['r'] === 'number' ? margin['r'] : 80) - legendSize;
// A conservative estimate with padding; no SVG measurements or font loads.
return values.every(value => textWidth(value) + 16 <= width / count);
};
const multi = arrays.some(values => values.some(Array.isArray));
if (multi) {
// Plotly 4.1.2 does not safely map tickvals/ticktext to both levels.
// Keep every published coordinate, grouping, period and hover unchanged.
if (coordinate !== 'x' || options.multicategory !== 'fit' || traces.some(trace => trace['type'] !== 'bar')
|| (effective['type'] !== undefined && effective['type'] !== 'multicategory')
|| arrays.some((levels, i) => levels.length !== 2 || !levels.every(Array.isArray)
|| (levels[0] as unknown[]).length !== (levels[1] as unknown[]).length
|| (levels[0] as unknown[]).length !== (traces[i][other] as unknown[]).length
|| !(levels[0] as unknown[]).every(value => typeof value === 'string' && /^\d{4}-S[12]$/.test(value))
|| !(levels[1] as unknown[]).every(plainLabel))
|| !arrays.some(levels => (levels[1] as string[]).some(value => characters(value).length > limit))) continue;
if (fits(arrays.flatMap(levels => levels[1] as string[]), Math.max(...arrays.map(levels => (levels[1] as string[]).length)))) continue;
const font = record(effective['tickfont']) ? effective['tickfont'] : {};
figure.layout[axisKey] = { ...axis, automargin: true,
tickfont: { ...font, size: Math.min(typeof font['size'] === 'number' ? font['size'] : 12, 11) } };
continue;
}
if ((effective['type'] !== undefined && effective['type'] !== 'category')
|| arrays.some((values, i) => values.length !== (traces[i][other] as unknown[]).length || !values.every(plainLabel))) continue;
const order = effective['categoryarray'];
if (order !== undefined && (!Array.isArray(order) || !order.every(plainLabel))) continue;
const values = [...new Set([...(Array.isArray(order) ? order as string[] : []), ...arrays.flat() as string[]])];
if (fits(values, values.length)) continue;
const labels = abbreviateCategories(values, limit, options.preferWords ?? true);
if (![...labels].some(([original, label]) => original !== label)) continue;
const hoverTemplates = traces.map((trace, i) => templates(trace, coordinate, arrays[i].length));
if (hoverTemplates.some(value => value === undefined)) continue;
// Only the bare coordinate token changes, per point. All statistical and
// suppression tokens/text remain exactly as published; no customdata added.
traces.forEach((trace, i) => {
trace['hovertemplate'] = hoverTemplates[i]!.map((template, j) => template.replaceAll(
`%{${coordinate}}`, () => (arrays[i][j] as string).replaceAll('&', '&amp;')));
});
figure.layout[axisKey] = { ...axis, type: 'category', tickmode: 'array', tickvals: values,
ticktext: values.map(value => labels.get(value)!), automargin: true,
...(effective['tickangle'] === undefined ? { tickangle: coordinate === 'x' ? -60 : 0 } : {}) };
for (const [original, abbreviated] of labels) {
if (original !== abbreviated) result.push({ axis: coordinate, original, abbreviated });
}
}
return result;
}