NGU-Web/src/lib/color.ts
Zaldimmar de17da7dc8 Accessibility: reader view and full palette swaps; version v1.12.1-accessibility
- Reading mode is now a reader view (ReaderView.tsx): the page renders
  hidden and its headings, paragraphs, links and described pictures
  are written out in one column, with no header, backdrop or footer.
- Color blind modes swap all three color families (teal, green,
  amber); palette hexes in components and CSS are now
  var(--pal-<family>-<shade>) so the modes reach them.
- CLAUDE.md and docs/updating-data-in-code.md describe both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 16:10:57 -05:00

174 lines
8.4 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
COLOR
Two helpers for colors that arrive as data (a page's accent, an
event's or region's color), so they work with the theme tokens
in index.css as well as with hex.
withAlpha(color, 20) is that color at 20% opacity, for tints and
borders. It replaces `${color}33`, which only works on hex.
accentText(color) is that color as text: itself in light mode,
mixed halfway to white in dark mode (--accent-text-mix), so an
accent picked for a white page still reads on a dark one.
═══════════════════════════════════════════════════════════════ */
export const withAlpha = (color: string, percent: number): string =>
`color-mix(in srgb, ${color} ${percent}%, transparent)`
export const accentText = (color: string): string =>
`color-mix(in srgb, ${color} var(--accent-text-mix), #ffffff)`
/* Text for on top of a color that arrives as data: white or deep
ink, whichever has more contrast (WCAG), so a pale color an admin
picks still gets readable text. Anything that isn't #rrggbb (a
CSS variable, say) gets white, which suits the site's own dark
accents. */
export function readableOn(color: string): string {
const hex = /^#([0-9a-f]{6})$/i.exec(color ?? '')?.[1]
if (!hex) return '#ffffff'
const channel = (i: number) => {
const c = parseInt(hex.slice(i, i + 2), 16) / 255
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
}
const lum = 0.2126 * channel(0) + 0.7152 * channel(2) + 0.0722 * channel(4)
const INK_LUM = 0.0041 // #001011
const onWhite = 1.05 / (lum + 0.05)
const onInk = (lum + 0.05) / (INK_LUM + 0.05)
return onWhite >= onInk ? '#ffffff' : '#001011'
}
/* ── The palette ─────────────────────────────────────────────────
The site's 16 colors: four families, each [main, darkest, light,
lightest]. The theme tokens above are chosen from these; so is
anything drawn from the palette as data (a person's initials
tile, the page background, the admin home's sections). Each main
shade reads as text on white and takes white text on it (5:1 or
better); the darkest are for text, the light and lightest for
fills behind text. */
/* As stored and sent: never swapped for a color blind mode. For
colors that are saved or leave the site (the newsletter's picks);
anything drawn on a public page uses PALETTE, below. */
export const STORED_PALETTE = {
teal: ['#00748a', '#003a45', '#5cd3e6', '#d6f5fa'],
green: ['#4a7431', '#23361a', '#9cc47c', '#e6f0dd'],
amber: ['#8f5b00', '#4a2e00', '#f0bd4f', '#fdf1d6'],
ink: ['#3b5456', '#001011', '#a3b8b9', '#f5f9f8'],
}
/* ── Color blind modes (AccessibilityPanel.tsx) ──────────────────
<html data-vision> is set before the first paint (index.html)
and a change reloads the page, so it's read once here.
Every color on the site is one of three color families (teal,
green, amber) or the gray ink. Seen with protanopia or
deuteranopia, colors fall on one blue to yellow line plus light
and dark; with tritanopia, on a red to cyan one. Three families at
one darkness can't all stay apart there, so each mode replaces all
three, at hues and darknesses picked by simulating the type (the
Machado 2009 matrices) to keep every pair, and each from the ink,
far apart for it and for typical vision too. The closest pair of
main or light shades, in CIELAB distance, goes from 11.4 to 27.9
(protanopia), 19.5 to 24.7 (deuteranopia) and 6.4 to 21.1
(tritanopia). Contrast holds: main shades 5.3:1 or more on white
and under white text, light shades 9:1 or more under ink, so the
theme tokens drawn from them (index.css) still read in both modes.
Each family keeps its role (teal is still the buttons and links).
A color an admin picked off the palette snaps to the nearest
palette shade first, so two picked colors can't land on one
confusable pair. Monochrome is a grayscale filter instead
(index.css). The same values for CSS are the --pal-* variables
in index.css. */
export const VISIONS = [
{ id: 'protanopia', label: 'Protanopia (red weak)' },
{ id: 'deuteranopia', label: 'Deuteranopia (green weak)' },
{ id: 'tritanopia', label: 'Tritanopia (blue weak)' },
{ id: 'monochrome', label: 'Monochrome' },
] as const
const SWAPS: Record<string, Partial<Record<keyof typeof STORED_PALETTE, string[]>>> = {
protanopia: {
teal: ['#167c16', '#0b3c0b', '#55ca55', '#e3f5e3'],
green: ['#921a92', '#5b105b', '#e09ce0', '#f9edf9'],
amber: ['#603911', '#482a0d', '#d7ab7f', '#f7efe7'],
},
deuteranopia: {
teal: ['#3939dc', '#1b1b9b', '#aeaee6', '#f0f0fa'],
green: ['#11602b', '#0b3c1b', '#51c979', '#e1f5e7'],
amber: ['#627214', '#30370a', '#a7bd3b', '#eff3db'],
},
tritanopia: {
teal: ['#167a59', '#0a3b2a', '#4bc79e', '#e1f5ee'],
green: ['#a31d33', '#661220', '#e2a2ac', '#f9eef0'],
amber: ['#6f6f14', '#353509', '#b9b93a', '#f2f2d8'],
},
}
const vision = typeof document === 'undefined' ? undefined : document.documentElement.dataset.vision
const swaps = vision ? SWAPS[vision] : undefined
const SHADES = Object.entries(STORED_PALETTE).flatMap(([family, shades]) =>
shades.map((hex, i) => ({ hex, swapped: swaps?.[family as keyof typeof STORED_PALETTE]?.[i] ?? hex })),
)
const rgb = (hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16))
/* A #rrggbb color as the current color blind mode shows it: the
palette's swap, or an off-palette color snapped to the nearest
palette shade first. Anything else (a CSS variable, no mode)
comes back as it was. */
export function visionColor(color: string): string {
if (!swaps || !/^#[0-9a-f]{6}$/i.test(color)) return color
const [r, g, b] = rgb(color.toLowerCase())
let best = SHADES[0]
let bestDistance = Infinity
for (const shade of SHADES) {
const [sr, sg, sb] = rgb(shade.hex)
// Weighted RGB ("redmean"), close enough to pick a neighbor.
const mean = (r + sr) / 2
const distance = (2 + mean / 256) * (r - sr) ** 2 + 4 * (g - sg) ** 2 + (2 + (255 - mean) / 256) * (b - sb) ** 2
if (distance < bestDistance) [best, bestDistance] = [shade, distance]
}
return best.swapped
}
export const PALETTE = Object.fromEntries(
Object.entries(STORED_PALETTE).map(([family, shades]) => [family, shades.map(visionColor)]),
) as { [K in keyof typeof STORED_PALETTE]: string[] }
/* Fills that take the page's ink text (#001011, 9:1 or better) and
fills that take white text (5:1 or better), for things colored
from the palette by data, like an initials tile. */
export const PALETTE_LIGHT = ['#d6f5fa', '#e6f0dd', '#fdf1d6', '#f0bd4f', '#9cc47c', '#5cd3e6'].map(visionColor)
export const PALETTE_DARK = ['#003a45', '#23361a', '#4a2e00', '#00748a', '#4a7431', '#8f5b00', '#3b5456'].map(visionColor)
/* ── The site's accents ──────────────────────────────────────────
BRAND is the teal every page uses as its accent; it's the button
token, so the admin's palette (Site settings → Colors) reaches it.
ACCENTS are the other section colors a page may give a band: the
palette's dark shades, all readable as text on its light ones
(7:1 or better). Use these rather than a new hex. */
export const BRAND = 'var(--color-action)'
export const ACCENTS = {
teal: BRAND,
deep: visionColor('#003a45'),
green: visionColor('#4a7431'),
amber: visionColor('#8f5b00'),
}
/* A palette fill for something colored by its name, like the
initials tile of a person with no photo: the same name always gets
the same fill, and each fill comes with its readable text (ink on
the light ones, white on the dark ones). */
const NAMED_FILLS = [
...PALETTE_LIGHT.map((background) => ({ background, color: '#001011' })),
...PALETTE_DARK.map((background) => ({ background, color: '#ffffff' })),
]
export function paletteFill(name: string): { background: string; color: string } {
let hash = 0
for (const char of name.trim().toLowerCase()) hash = (hash * 31 + char.charCodeAt(0)) >>> 0
return NAMED_FILLS[hash % NAMED_FILLS.length]
}