diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index b4f1518..3fe56b0 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -37,7 +37,7 @@ :host(.methodology-expanded) .figure-card { grid-row: auto; } .figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; } .state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; } -.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; } +.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b7d251; --mat-sys-outline: #a1aabd; } .figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; } @media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } } diff --git a/src/app/features/indicadores/indicadores-c1-alteraciones.ts b/src/app/features/indicadores/indicadores-c1-alteraciones.ts index 8f95020..6687df9 100644 --- a/src/app/features/indicadores/indicadores-c1-alteraciones.ts +++ b/src/app/features/indicadores/indicadores-c1-alteraciones.ts @@ -18,7 +18,7 @@ export function c1AlterationCapability(contract: string, representation: string) const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0; const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); -// The any-alteration bar keeps the red of the event; each alteration takes its own colour. +// The any-alteration bar uses the second series colour; each alteration takes its own colour. const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]]; const color = (i: number) => COLORS[i % COLORS.length]; diff --git a/src/app/features/indicadores/indicadores-c1-donut.ts b/src/app/features/indicadores/indicadores-c1-donut.ts index db83d2a..3a64965 100644 --- a/src/app/features/indicadores/indicadores-c1-donut.ts +++ b/src/app/features/indicadores/indicadores-c1-donut.ts @@ -21,7 +21,7 @@ const EVENT_LABELS: Readonly> = { M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'], M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'], }; -// Green for the event, red for its complement; age groups get lighter shades. +// Olive for the event, the next series colour for its complement; age groups keep their own colours. const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const; // One colour per age group, the same in the donut (M21) and the bars (M22). const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length]; diff --git a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts index 76fb1b6..c36c164 100644 --- a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts +++ b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts @@ -1,5 +1,5 @@ import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter'; -import { c2Color, C2_PALETTE } from './indicadores-c2-palette'; +import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette'; import { c2Fixture } from './indicadores-c2-adapter.testing'; import { FigureSelection } from './indicadores.models'; import { donutFixture } from './indicadores-donut-drilldown.testing'; @@ -43,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => { const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final); const legend = donutLegend(final), view = donutSimpleView(final); expect(legend).toEqual([ - { label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' }, + { label: 'A', color: C2_PALETTE.series[0] }, { label: 'B', color: C2_PALETTE.series[1] }, { label: 'C', color: C2_PALETTE.series[2] }, ]); expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } }); expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] }); @@ -158,15 +158,18 @@ describe('C2: datos publicados a Plotly', () => { }); describe('paleta C2 institucional y semántica', () => { - it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => { + it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => { const data = c2Fixture(); (data['categorias'] as Record>)['A']['color'] = '#D98E4A'; const figure = supported(data, { ...selection, tema }).figure; - expect((figure.data[0]['marker'] as Record)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']); + expect((figure.data[0]['marker'] as Record)['colors']).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]); + expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]); expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background); expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text }); expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2'); - expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A'); - expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778'); + expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]); + expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]); + expect(c2Color('#D98E4A', 0)).toBe('#D98E4A'); + expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]); expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined(); }); it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => { diff --git a/src/app/features/indicadores/indicadores-c2-adapter.ts b/src/app/features/indicadores/indicadores-c2-adapter.ts index f2fb5eb..d555baa 100644 --- a/src/app/features/indicadores/indicadores-c2-adapter.ts +++ b/src/app/features/indicadores/indicadores-c2-adapter.ts @@ -1,6 +1,6 @@ import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models'; import { DonutHierarchy } from './indicadores-donut-drilldown'; -import { c2Color, c2Theme } from './indicadores-c2-palette'; +import { c2Theme, groupBase, seriesColors } from './indicadores-c2-palette'; export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; } // Normalized presentation nodes and a selection path are independent of Plotly. @@ -81,7 +81,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))]; const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] }; const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label); - const colors = categories.map((c, i) => c2Color(c.color, i)); + const colors = seriesColors(categories.map(c => c.color)); const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined; const layout: Record = { title: { text: model.title + ', ' + period }, autosize: true, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 }, @@ -109,7 +109,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re hovertemplate: '%{label}
%{value} ' + model.unit + '
%{percent} de los ' + total + ' ' + model.unit + ' publicados' }]; if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label), values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)), - marker: { colors: parents.map((_, i) => c2Color(undefined, i)), line: { color: theme.outline, width: 0.7 } }, + marker: { colors: parents.map((_, i) => groupBase(i)), line: { color: theme.outline, width: 0.7 } }, hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } }); } const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0 diff --git a/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts b/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts index bd0220c..c2ac2c0 100644 --- a/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts +++ b/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts @@ -19,7 +19,9 @@ describe('selección local segura de barras generales C2', () => { it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => { const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source }); const view = c2GeneralSelection(source, data, selection, local)!; - expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } }); + const marker = source.data[0]['marker'] as { color: string[] }, labels = source.data[0]['y'] as string[]; + expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], + marker: { color: ['B', 'C'].map(label => marker.color[labels.indexOf(label)]) } }); expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] }); expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' }); expect(view.context).toContain('G2, 2025-S2'); diff --git a/src/app/features/indicadores/indicadores-c2-palette.spec.ts b/src/app/features/indicadores/indicadores-c2-palette.spec.ts new file mode 100644 index 0000000..1db8031 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c2-palette.spec.ts @@ -0,0 +1,53 @@ +import { C2_PALETTE, groupBase, institutionalize, isHarmoniousColor, paintByGroup, recolorFigure } from './indicadores-c2-palette'; + +describe('paleta del logo ISSSTELEON', () => { + it('combina varios matices del logo y del verde azulado, sin repetir el mismo color', () => { + expect(new Set(C2_PALETTE.series).size).toBe(C2_PALETTE.series.length); + for (const color of C2_PALETTE.series) expect(isHarmoniousColor(color)).toBe(true); + expect(institutionalize(['#a8c243'])).toEqual(['#a8c243']); + expect(C2_PALETTE.series[0]).not.toBe(C2_PALETTE.series[1]); + }); + + it('reemplaza mezclas de partido por entradas distintas y conserva el gris de sin dato', () => { + const [azul, rojo, naranja, amarillo, guinda, sinDato, edad] = institutionalize([ + '#0044CC', '#C41E3A', '#FF6B00', '#FFD100', '#7A2E0E', '#C9CDD2', '#2F6DB3', + ]); + expect([azul, rojo, naranja, amarillo, guinda]).toEqual(C2_PALETTE.series.slice(0, 5)); + expect(edad).toBe('#2F6DB3'); + expect(sinDato).toBe('#C9CDD2'); + }); + + it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => { + const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']); + expect(new Set(colors.slice(0, 3)).size).toBe(3); + expect(colors[3]).toBe(groupBase(1)); + expect(colors[0]).not.toBe(colors[3]); + expect(groupBase(0)).toBe(C2_PALETTE.series[0]); + }); + + it('pinta la tinta categórica, deja una escala continua y no toca texto ni fondo', () => { + const figure = recolorFigure({ + data: [{ + type: 'scatter', marker: { color: '#B55A1F' }, error_x: { color: 'rgba(0,68,204,0.4)' }, line: { color: '#C9CDD2' }, + colorscale: [[0, '#0d0887'], [0.5, '#ed7953'], [1, '#f0f921']], + }], + layout: { font: { color: '#081839' }, paper_bgcolor: '#FFFFFF', colorway: ['#EF553B', '#636efa'] }, + }); + expect((figure.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.series[0]); + expect(figure.data[0]['error_x']).toMatchObject({ color: expect.stringMatching(/^rgba\(\d+,\d+,\d+,0\.4\)$/) }); + expect((figure.data[0]['error_x'] as { color: string }).color).not.toContain('0,68,204'); + expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2'); + const scale = figure.data[0]['colorscale'] as [number, string][]; + expect(scale.map(stop => stop[0])).toEqual([0, 0.5, 1]); + expect(scale[0][1]).not.toBe('#0d0887'); + expect(scale[0][1]).not.toBe(scale[1][1]); + expect(figure.layout['font']).toEqual({ color: '#081839' }); + expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF'); + expect(figure.layout['colorway']).toEqual(C2_PALETTE.series.slice(2, 4)); + expect(new Set([ + (figure.data[0]['marker'] as { color: string }).color, + ...(figure.layout['colorway'] as string[]), + ]).size).toBe(3); + expect(recolorFigure(figure)).toBe(figure); + }); +}); diff --git a/src/app/features/indicadores/indicadores-c2-palette.ts b/src/app/features/indicadores/indicadores-c2-palette.ts index f3c310e..61f71a1 100644 --- a/src/app/features/indicadores/indicadores-c2-palette.ts +++ b/src/app/features/indicadores/indicadores-c2-palette.ts @@ -1,11 +1,16 @@ -import { Tema } from './indicadores.models'; +import { PlotlyFigure, Tema } from './indicadores.models'; -// Matches src/styles.scss: interface tokens are the source of these candidates, -// not a certified brand guide. Published semantic colours always take priority. +// Categorical palette anchored on the logo lime (#a8c243) and the theme teal (#5f9ea0). +// Neighboring entries differ in hue so series stay distinct, and none is a party colour: +// no royal blue, red, orange, yellow or guinda. Neutrals stay neutral. +// Sequential fills (heatmaps) use SCALE, from pale lime to deep teal. export const C2_PALETTE = Object.freeze({ - // ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness. - series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']), - // Age groups of the EEG indicators (M21, M22), which avoid the green and red of the rest. + series: Object.freeze([ + '#5c7014', '#0e7568', '#6a6448', '#3d6b38', + '#5a6170', '#3a5a48', '#3e5c6a', '#4a5a38', + ]), + scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']), + // Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose. edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']), states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }), // line: the green for thin marks; the brand green itself is too light to read as a line on white. @@ -13,6 +18,206 @@ export const C2_PALETTE = Object.freeze({ oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }), }); export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; } -export function c2Color(published: string | undefined, index: number): string { - return published ?? C2_PALETTE.series[index % C2_PALETTE.series.length]; +const ageKeys = new Set(C2_PALETTE.edades.map(color => parseColor(color)?.key).filter((key): key is string => !!key)); +export function isAgeColor(color: string): boolean { + const key = parseColor(color)?.key; + return !!key && ageKeys.has(key); +} +export function c2Color(published: string | undefined, index: number): string { + // A published swatch stays. The series only fills a category that arrived without one. + if (published && (/^#[0-9a-f]{6}$/i.test(published) || isAgeColor(published))) return published; + return C2_PALETTE.series[index % C2_PALETTE.series.length]; +} + +/** One base hue per group, then lighter and darker steps so siblings stay related but distinct. */ +export function paintByGroup(groups: readonly string[]): string[] { + const order = [...new Set(groups)]; + const counts = new Map(order.map(id => [id, groups.filter(g => g === id).length])); + const stairs = new Map(order.map((id, i) => [id, steps(C2_PALETTE.series[i % C2_PALETTE.series.length], counts.get(id)!)])); + const cursor = new Map(); + return groups.map(id => { + const index = cursor.get(id) ?? 0; + cursor.set(id, index + 1); + return stairs.get(id)![index]; + }); +} +export function groupBase(index: number): string { + return C2_PALETTE.series[index % C2_PALETTE.series.length]; +} + +/** Replace inharmonious hues. Same source colour keeps the same slot; grays and palette hues stay. */ +export function institutionalize(colors: readonly string[]): string[] { + const parsed = colors.map(parseColor); + const foreign: string[] = []; + const seen = new Set(); + for (const item of parsed) { + if (!item || item.kind !== 'foreign' || ageKeys.has(item.key) || seen.has(item.key)) continue; + seen.add(item.key); + foreign.push(item.key); + } + const assigned = new Map(foreign.map((key, i) => [key, C2_PALETTE.series[i % C2_PALETTE.series.length]])); + return colors.map((color, i) => { + const item = parsed[i]; + const next = item && assigned.get(item.key); + return item && next ? formatAs(item, next) : color; + }); +} + +/** Keep a published colour; only a missing one takes the next series entry. */ +export function seriesColors(published: readonly (string | undefined)[]): string[] { + return published.map((color, index) => c2Color(color, index)); +} + +const NAMED: Record = { + black: [0, 0, 0], white: [255, 255, 255], gray: [128, 128, 128], grey: [128, 128, 128], silver: [192, 192, 192], + red: [255, 0, 0], blue: [0, 0, 255], green: [0, 128, 0], orange: [255, 165, 0], yellow: [255, 255, 0], + purple: [128, 0, 128], brown: [165, 42, 42], pink: [255, 192, 203], cyan: [0, 255, 255], magenta: [255, 0, 255], + gold: [255, 215, 0], navy: [0, 0, 128], teal: [0, 128, 128], maroon: [128, 0, 0], lime: [0, 255, 0], olive: [128, 128, 0], +}; +interface Parsed { r: number; g: number; b: number; a: number; key: string; hue: number; sat: number; lum: number; kind: 'neutral' | 'harmonious' | 'foreign'; explicitAlpha: boolean; } +function parseColor(input: string): Parsed | undefined { + const text = input.trim(); + let r = 0, g = 0, b = 0, a = 1, explicitAlpha = false; + const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text); + const rgb = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(text); + if (hex) { + const raw = hex[1].length === 3 ? hex[1].split('').map(c => c + c).join('') : hex[1]; + r = parseInt(raw.slice(0, 2), 16); g = parseInt(raw.slice(2, 4), 16); b = parseInt(raw.slice(4, 6), 16); + } else if (rgb) { + r = Number(rgb[1]); g = Number(rgb[2]); b = Number(rgb[3]); + if (rgb[4] !== undefined) { a = Number(rgb[4]); explicitAlpha = true; } + if ([r, g, b].some(v => v > 255) || !Number.isFinite(a)) return undefined; + } else if (NAMED[text.toLowerCase()]) { + [r, g, b] = NAMED[text.toLowerCase()]; + } else return undefined; + const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min; + const sat = max === 0 ? 0 : d / max; + let hue = 0; + if (d !== 0) { + if (max === r) hue = ((g - b) / d) % 6; + else if (max === g) hue = (b - r) / d + 2; + else hue = (r - g) / d + 4; + hue *= 60; if (hue < 0) hue += 360; + } + const lum = luminance({ r, g, b }); + const neutral = sat < 0.18; + const harmonious = !neutral && ( + (hue >= 64 && hue <= 188 && sat >= 0.22) + || (hue > 188 && hue <= 230 && sat <= 0.5) + || (hue >= 40 && hue < 64 && sat <= 0.42)); + return { r, g, b, a, key: `${r},${g},${b}`, hue, sat, lum, explicitAlpha, kind: neutral ? 'neutral' : harmonious ? 'harmonious' : 'foreign' }; +} +function steps(base: string, count: number): string[] { + if (count <= 1) return [base]; + return Array.from({ length: count }, (_, i) => { + const t = i / (count - 1); + if (t < 0.5) return mixHex(base, [0, 0, 0], (0.5 - t) * 0.5); + return mixHex(base, [255, 255, 255], (t - 0.5) * 0.22); + }); +} +function mixHex(base: string, toward: [number, number, number], amount: number): string { + const item = parseColor(base)!; + const channel = (from: number, to: number) => Math.round(from + (to - from) * amount); + return '#' + [channel(item.r, toward[0]), channel(item.g, toward[1]), channel(item.b, toward[2])] + .map(v => v.toString(16).padStart(2, '0')).join(''); +} +function sampleScale(t: number): string { + const stops = C2_PALETTE.scale; + const scaled = Math.min(1, Math.max(0, t)) * (stops.length - 1); + const index = Math.min(stops.length - 2, Math.floor(scaled)); + const item = parseColor(stops[index])!, next = parseColor(stops[index + 1])!; + return mixHex(stops[index], [next.r, next.g, next.b], scaled - index); +} +function luminance(input: { r: number; g: number; b: number } | Parsed): number { + const c = [input.r, input.g, input.b].map(v => v / 255).map(v => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4); + return c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722; +} +function formatAs(original: Parsed, hex: string): string { + if (!original.explicitAlpha) return hex; + const item = parseColor(hex)!; + const alpha = Number(original.a.toFixed(3)); + return `rgba(${item.r},${item.g},${item.b},${alpha})`; +} +export function isNeutralColor(color: string): boolean { return parseColor(color)?.kind === 'neutral'; } +export function isHarmoniousColor(color: string): boolean { return parseColor(color)?.kind === 'harmonious'; } + +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +function collectStrings(value: unknown, into: string[]) { + if (typeof value === 'string') into.push(value); + else if (Array.isArray(value)) { + if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') into.push(value[1]); + else value.forEach(item => collectStrings(item, into)); + } +} +function mapColors(value: unknown, lookup: Map): unknown { + if (typeof value === 'string') return lookup.get(value) ?? value; + if (Array.isArray(value)) { + if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') return [value[0], lookup.get(value[1]) ?? value[1]]; + return value.map(item => mapColors(item, lookup)); + } + return value; +} +function paintTrace(trace: Record, lookup: Map) { + if (record(trace['marker'])) { + const marker = { ...trace['marker'] }; + if ('color' in marker) marker['color'] = mapColors(marker['color'], lookup); + if ('colors' in marker) marker['colors'] = mapColors(marker['colors'], lookup); + if (record(marker['line']) && 'color' in marker['line']) marker['line'] = { ...marker['line'], color: mapColors(marker['line']['color'], lookup) }; + trace['marker'] = marker; + } + if (record(trace['line']) && 'color' in trace['line']) trace['line'] = { ...trace['line'], color: mapColors(trace['line']['color'], lookup) }; + if (typeof trace['fillcolor'] === 'string') trace['fillcolor'] = lookup.get(trace['fillcolor']) ?? trace['fillcolor']; + for (const key of ['error_x', 'error_y']) { + if (record(trace[key]) && 'color' in (trace[key] as Record)) { + trace[key] = { ...(trace[key] as Record), color: mapColors((trace[key] as Record)['color'], lookup) }; + } + } + if (Array.isArray(trace['colorscale'])) trace['colorscale'] = sequentialScale(trace['colorscale']); +} +function sequentialScale(stops: unknown[]): unknown[] { + return stops.map(stop => { + if (!Array.isArray(stop) || typeof stop[0] !== 'number' || typeof stop[1] !== 'string') return stop; + return [stop[0], sampleScale(stop[0])]; + }); +} +function scalePending(figure: PlotlyFigure): boolean { + return traceList(figure).some(trace => Array.isArray(trace['colorscale']) + && JSON.stringify(sequentialScale(trace['colorscale'] as unknown[])) !== JSON.stringify(trace['colorscale'])); +} +function traceList(host: { data?: unknown; frames?: unknown }): Record[] { + const traces = Array.isArray(host.data) ? host.data.filter(record) : []; + if (Array.isArray(host.frames)) { + for (const frame of host.frames) { + if (record(frame) && Array.isArray(frame['data'])) traces.push(...frame['data'].filter(record)); + } + } + return traces; +} +function gather(figure: PlotlyFigure): string[] { + const found: string[] = []; + for (const trace of traceList(figure)) { + const marker = record(trace['marker']) ? trace['marker'] : undefined; + collectStrings(marker?.['color'], found); collectStrings(marker?.['colors'], found); + collectStrings(record(marker?.['line']) ? marker['line']['color'] : undefined, found); + collectStrings(record(trace['line']) ? trace['line']['color'] : undefined, found); + collectStrings(trace['fillcolor'], found); + collectStrings(record(trace['error_x']) ? trace['error_x']['color'] : undefined, found); + collectStrings(record(trace['error_y']) ? trace['error_y']['color'] : undefined, found); + } + if (Array.isArray(figure.layout['colorway'])) collectStrings(figure.layout['colorway'], found); + return found; +} + +/** Data ink of a published figure, without touching text, grid or background. */ +export function recolorFigure(figure: T): T { + const collected = gather(figure); + const painted = institutionalize(collected); + if (painted.every((color, i) => color === collected[i]) && !scalePending(figure)) return figure; + const lookup = new Map(collected.map((color, i) => [color, painted[i]])); + const copy = structuredClone(figure); + for (const trace of traceList(copy)) paintTrace(trace, lookup); + if (Array.isArray(copy.layout['colorway'])) copy.layout['colorway'] = mapColors(copy.layout['colorway'], lookup); + return copy; } diff --git a/src/app/features/indicadores/indicadores-confirmacion-citologia.ts b/src/app/features/indicadores/indicadores-confirmacion-citologia.ts index db80358..21c768f 100644 --- a/src/app/features/indicadores/indicadores-confirmacion-citologia.ts +++ b/src/app/features/indicadores/indicadores-confirmacion-citologia.ts @@ -1,5 +1,5 @@ import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; -import { c2Theme } from './indicadores-c2-palette'; +import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette'; import { percentNumber, shareText } from './indicadores-format'; // Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia): @@ -69,10 +69,6 @@ function suma(celdas: Celda[]): number | null { function estado(celdas: Celda[]): Celda['estado'] { return 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(''); -} function rgba(hex: string, alfa: number): string { const v = parseInt(hex.slice(1), 16); return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; @@ -101,15 +97,21 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode const c = cats[a.id]; return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta }; }); - const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => { + const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => { if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color']))) || typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.'); return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] }; }); + const conColor = gradosCrudos.filter(g => g.color !== COLOR_RESPALDO); + const colores = paintByGroup(conColor.map(g => g.grupo)); + const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]])); + const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color })); + const ordenGrupos = [...new Set(conColor.map(g => g.grupo))]; const grupos = [...new Set(grados.map(g => g.grupo))].map(id => { - // Off-catalogue grades share the group but not its colour. - const propios = grados.filter(g => g.grupo === id), publicados = propios.filter(g => g.color !== COLOR_RESPALDO); - return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)), + // Off-catalogue grades keep the neutral fallback and do not take the group hue. + const propios = grados.filter(g => g.grupo === id); + const indice = ordenGrupos.indexOf(id); + return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: indice < 0 ? COLOR_RESPALDO : groupBase(indice), grados: propios.map(g => g.id) }; }); // The base view is the group of LIEAG ("LIEAG o más"): the true positives. diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts index aca81aa..c37d5de 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts @@ -1,5 +1,5 @@ import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; -import { c2Theme } from './indicadores-c2-palette'; +import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette'; import { percentNumber, shareText } from './indicadores-format'; // Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts. @@ -39,10 +39,6 @@ function estado(celdas: Celda[]): Escenario['estado'] { return 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(''); -} function rgba(hex: string, alfa: number): string { const v = parseInt(hex.slice(1), 16); return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; @@ -128,9 +124,10 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.'); // Missing rows remain unavailable. Catalog order is used only for the accessible // list of missing categories; a partial distribution is never drawn as a donut. - const categorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity)); - const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], - color: promedio(categorias.filter(c => c.grupo === id).map(c => c.color)) })); + const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity)); + const colores = paintByGroup(baseCategorias.map(c => c.grupo)); + const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] })); + const grupos = [...new Set(categorias.map(c => c.grupo))].map((id, i) => ({ id, etiqueta: nombres[id], color: groupBase(i) })); const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))])); const totals = porEscenario['totales_estrato']; if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.'); diff --git a/src/app/features/indicadores/indicadores-stratified.ts b/src/app/features/indicadores/indicadores-stratified.ts index a245dc2..bb645af 100644 --- a/src/app/features/indicadores/indicadores-stratified.ts +++ b/src/app/features/indicadores/indicadores-stratified.ts @@ -1,6 +1,6 @@ import { DimensionEstrato, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { DonutSelection } from './indicadores-donut-drilldown'; -import { c2Color, c2Theme } from './indicadores-c2-palette'; +import { c2Theme, seriesColors } from './indicadores-c2-palette'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); @@ -43,6 +43,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas'); const cells: StratifiedCell[] = []; const theme = c2Theme(tema); + const palette = seriesColors(categories.map(([, c]) => c.color)); const figure: PlotlyFigure = { data: strata.map((s, series) => { const selected = categories.map(([id, c]) => { const row = rows.get(JSON.stringify([id, s])); @@ -52,7 +53,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato return value; }); return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)), - marker: { color: categories.map(([, c], i) => c2Color(c.color, i)), pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } }, + marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } }, hovertemplate: '%{y}
%{x}%{fullData.name}' }; }), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true, height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,