import { PlotlyFigure, Tema } from './indicadores.models'; // Logo lime plus the analogous and complementary hues chosen for the charts. // Cool greens, teal and blue are the normal side. Rose, violet and purple are the abnormal side. // Neutrals stay neutral. Sequential fills run from pale lime to deep teal. const OWNED = new Set(); function own(hex: string): string { OWNED.add(hex.toLowerCase()); return hex; } export const C2_PALETTE = Object.freeze({ frios: Object.freeze([own('#A8C243'), own('#69C242'), own('#42C25C'), own('#42C29C'), own('#4269C2')]), calidos: Object.freeze([own('#C24269'), own('#9C42C2'), own('#5C42C2'), own('#C2429C'), own('#8E2F62'), own('#7A3496')]), series: Object.freeze([ '#A8C243', '#42C29C', '#C24269', '#9C42C2', '#69C242', '#5C42C2', '#42C25C', '#4269C2', ]), 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. claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }), oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }), }); export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; } 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); } /** Orange, tan and coffee. Age gold and the palette's own stone are not included. */ function isCoffeeParsed(item: Parsed | undefined): boolean { if (!item || item.kind === 'neutral' || ageKeys.has(item.key)) return false; return item.hue >= 8 && item.hue <= 46 && item.sat >= 0.28; } export function isCoffeeColor(color: string): boolean { return isCoffeeParsed(parseColor(color)); } export type Tono = 'frio' | 'calido' | 'neutro'; /** Metadata id: cool for normal groups, warm for abnormal ones. Unknown ids stay neutral. */ export function tonoDe(clave: string | undefined | null): Tono { if (!clave) return 'neutro'; const id = clave.normalize('NFD').replace(/\p{M}/gu, '').toUpperCase().replace(/[^A-Z0-9]+/g, '_'); if (id.includes('SIN_DATO') || id.includes('SIN_BIOPSIA')) return 'neutro'; if (id.includes('NO_METAST') || id.includes('SIN_METAST') || id.includes('NO_ANORMAL') || id.includes('NO_MALIG') || id.includes('BENIGN') || id.includes('NO_ALTER')) return 'frio'; if (id.includes('METAST') || id.includes('CARCINOMA') || id.includes('ANORMAL') || id.includes('MALIG') || id.includes('INVAS') || id.includes('IN_SITU') || id.includes('LIEAG') || id.includes('ALTER')) return 'calido'; if (/^(B4|B4A|B4B|B4C|B5|B6)$/.test(id) || /^BIRADS_[456]/.test(id)) return 'calido'; return 'neutro'; } function poolDe(tono: Tono): readonly string[] { if (tono === 'calido') return C2_PALETTE.calidos; if (tono === 'frio') return C2_PALETTE.frios; return C2_PALETTE.series; } export function c2Color(published: string | undefined, index: number, tono: Tono = 'neutro'): string { // Coffee takes the cool or warm pool when the category metadata says which. Other published colours stay. if (published && isAgeColor(published)) return published; if (published && isNeutralColor(published)) return published; const pool = poolDe(tono); if (published && isCoffeeColor(published)) return pool[index % pool.length]; if (published && /^#[0-9a-f]{6}$/i.test(published)) return published; return pool[index % pool.length]; } /** One base per group: cool if the id is normal, warm if it is abnormal, then steps so siblings differ. */ export function basesPorGrupo(groups: readonly string[]): ReadonlyMap { const seen = { frio: 0, calido: 0, neutro: 0 }; const base = new Map(); for (const id of [...new Set(groups)]) { const tono = tonoDe(id); const pool = poolDe(tono); base.set(id, pool[seen[tono] % pool.length]); seen[tono] += 1; } return base; } export function paintByGroup(groups: readonly string[]): string[] { const bases = basesPorGrupo(groups); const counts = new Map([...bases.keys()].map(id => [id, groups.filter(g => g === id).length])); const stairs = new Map([...bases].map(([id, color]) => [id, steps(color, 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 || !isCoffeeParsed(item) || 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; }); } /** Coffee published colours take the cool or warm pool of their metadata id. */ export function seriesColors(published: readonly (string | undefined)[], claves?: readonly (string | undefined)[]): string[] { const seen = { frio: 0, calido: 0, neutro: 0 }; return published.map((color, index) => { const tono = tonoDe(claves?.[index]); const slot = tono === 'neutro' ? index : seen[tono]++; return c2Color(color, slot, tono); }); } 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 swatch = '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join(''); const harmonious = OWNED.has(swatch) || (!neutral && ( (hue >= 64 && hue <= 175 && sat >= 0.22) || (hue >= 200 && hue <= 320 && sat >= 0.22) || (hue >= 320 && hue < 356 && sat >= 0.28 && sat <= 0.78) || (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; }