1use std::fmt;
5
6pub use crate::color::contrast_ratio;
7use crate::contract::CATEGORY;
8use crate::{Color, ResolvedTokens};
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum PairKind {
13 Text,
16 Ui,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum Level {
24 Normal,
26 High,
28}
29
30impl Level {
31 pub fn required(self, kind: PairKind) -> f32 {
33 match (kind, self) {
34 (PairKind::Text, Level::Normal) => 4.5,
35 (PairKind::Text, Level::High) => 7.0,
36 (PairKind::Ui, _) => 3.0,
37 }
38 }
39}
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub struct Pair {
44 pub foreground: &'static str,
45 pub background: &'static str,
46 pub kind: PairKind,
47}
48
49const fn text(foreground: &'static str, background: &'static str) -> Pair {
50 Pair {
51 foreground,
52 background,
53 kind: PairKind::Text,
54 }
55}
56
57const fn ui(foreground: &'static str, background: &'static str) -> Pair {
58 Pair {
59 foreground,
60 background,
61 kind: PairKind::Ui,
62 }
63}
64
65pub const PAIRS: &[Pair] = &[
69 text("text.default", "surface.canvas"),
71 text("text.default", "surface.panel"),
72 text("text.default", "surface.raised"),
73 text("text.default", "surface.hover"),
74 text("text.default", "surface.overlay"),
75 text("text.default", "surface.sunken"),
76 text("text.default", "selection"),
77 text("text.strong", "surface.panel"),
79 text("text.strong", "surface.hover"),
80 text("text.strong", "surface.active"),
81 text("text.muted", "surface.canvas"),
83 text("text.muted", "surface.panel"),
84 text("text.muted", "surface.raised"),
85 text("text.muted", "surface.overlay"),
86 text("text.muted", "surface.sunken"),
87 text("text-role.title.color", "surface.panel"),
89 text("text-role.title.color", "surface.raised"),
90 text("text-role.section.color", "surface.panel"),
91 text("text-role.section.color", "surface.raised"),
92 text("text-role.body.color", "surface.panel"),
93 text("text-role.body.color", "surface.raised"),
94 text("text-role.strong.color", "surface.panel"),
95 text("text-role.strong.color", "surface.raised"),
96 text("text-role.muted.color", "surface.panel"),
97 text("text-role.muted.color", "surface.raised"),
98 text("text-role.meta.color", "surface.panel"),
99 text("text-role.meta.color", "surface.raised"),
100 text("text.on-accent", "accent.default"),
102 text("text.on-accent", "accent.hover"),
103 text("accent.default", "surface.panel"),
104 text("danger", "surface.panel"),
106 text("danger", "surface.overlay"),
107 text("warning", "surface.panel"),
108 text("warning", "surface.overlay"),
109 text("success", "surface.panel"),
110 text("success", "surface.overlay"),
111 text("info", "surface.panel"),
112 text("info", "surface.overlay"),
113 text("palette.log.trace", "surface.canvas"),
115 text("palette.log.trace", "surface.panel"),
116 text("palette.log.debug", "surface.canvas"),
117 text("palette.log.debug", "surface.panel"),
118 text("palette.log.info", "surface.canvas"),
119 text("palette.log.info", "surface.panel"),
120 text("palette.log.warn", "surface.canvas"),
121 text("palette.log.warn", "surface.panel"),
122 text("palette.log.error", "surface.canvas"),
123 text("palette.log.error", "surface.panel"),
124 text("palette.log.critical", "surface.canvas"),
125 text("palette.log.critical", "surface.panel"),
126 text("button.rest.text", "button.rest.fill"),
128 text("button.tone.accent.text", "button.tone.accent.fill"),
130 text(
131 "button.tone.accent.hover.text",
132 "button.tone.accent.hover.fill",
133 ),
134 text("button.tone.info.text", "button.tone.info.fill"),
135 text("button.tone.success.text", "button.tone.success.fill"),
136 text("button.tone.warning.text", "button.tone.warning.fill"),
137 text("button.tone.danger.text", "button.tone.danger.fill"),
138 text("button.tone.record.text", "button.tone.record.fill"),
139 text("menu-item.rest.text", "menu-item.hover.fill"),
140 text("menu-item.tone.muted.text", "surface.overlay"),
141 text("toast.rest.text", "toast.rest.fill"),
142 text("tooltip.rest.text", "tooltip.rest.fill"),
143 text("field.rest.text", "field.rest.fill"),
144 text("field.rest.text", "field.tone.muted.fill"),
145 text("field.tone.muted.text", "field.rest.fill"),
146 text("field.tone.danger.border-color", "surface.panel"),
147 text("dialog-header.rest.text", "header-band.rest.fill"),
148 text("header-band.rest.text", "header-band.rest.fill"),
149 text("band-icon-button.rest.text", "header-band.rest.fill"),
150 text(
151 "command-palette-row.rest.text",
152 "command-palette-row.selected.fill",
153 ),
154 text("pill.rest.text", "pill.rest.fill"),
155 text("readout.rest.text", "readout.rest.fill"),
156 text("editor.line-number", "editor.gutter"),
158 text("editor.line-number-active", "editor.gutter"),
159 text("syntax.plain", "editor-frame.rest.fill"),
160 text("syntax.plain", "editor.current-line"),
161 text("syntax.plain", "editor.selection"),
162 text("syntax.keyword", "editor-frame.rest.fill"),
163 text("syntax.string", "editor-frame.rest.fill"),
164 text("syntax.number", "editor-frame.rest.fill"),
165 text("syntax.comment", "editor-frame.rest.fill"),
166 text("syntax.function", "editor-frame.rest.fill"),
167 text("syntax.type", "editor-frame.rest.fill"),
168 text("syntax.invalid", "editor-frame.rest.fill"),
169 ui("editor.cursor", "editor-frame.rest.fill"),
170 ui("editor.error", "editor.gutter"),
171 ui("editor.warning", "editor.gutter"),
172 ui("editor.breakpoint", "editor.gutter"),
173 text("terminal.foreground", "terminal-frame.rest.fill"),
175 text("terminal.foreground", "terminal.selection"),
176 ui("terminal.cursor", "terminal-frame.rest.fill"),
177 ui("cursor.fill", "cursor.outline"),
179 ui("border.strong", "surface.panel"),
181 ui("border.strong", "surface.raised"),
182 ui("border.strong", "surface.overlay"),
183 ui("focus.ring", "surface.panel"),
184 ui("focus.ring", "surface.raised"),
185 ui("focus.ring", "surface.overlay"),
186 ui("focus.ring", "surface.sunken"),
187 ui("accent.default", "surface.raised"),
188 ui("slider-fill.rest.fill", "slider.rest.fill"),
189 ui("progress-fill.rest.fill", "progress-bar.rest.fill"),
190 ui("slider-thumb.rest.fill", "slider.rest.fill"),
191 ui("field.tone.accent.border-color", "field.rest.fill"),
193 ui("field.tone.warning.border-color", "field.rest.fill"),
194 ui("field.tone.danger.border-color", "field.rest.fill"),
195 ui("field.tone.info.border-color", "field.rest.fill"),
196 ui("card.tone.accent.border-color", "surface.panel"),
198 ui("card.tone.info.border-color", "surface.panel"),
199 ui("card.tone.success.border-color", "surface.panel"),
200 ui("card.tone.warning.border-color", "surface.panel"),
201 ui("card.tone.danger.border-color", "surface.panel"),
202 ui("card.tone.record.border-color", "surface.panel"),
203 ui("toast.rest.border-color", "surface.panel"),
204 text("indicator-badge.rest.text", "indicator-badge.rest.fill"),
208 text(
209 "indicator-badge.rest.text",
210 "indicator-badge.tone.accent.fill",
211 ),
212 text(
213 "indicator-badge.rest.text",
214 "indicator-badge.tone.info.fill",
215 ),
216 text(
217 "indicator-badge.rest.text",
218 "indicator-badge.tone.success.fill",
219 ),
220 text(
221 "indicator-badge.rest.text",
222 "indicator-badge.tone.warning.fill",
223 ),
224 text(
225 "indicator-badge.rest.text",
226 "indicator-badge.tone.danger.fill",
227 ),
228 text(
229 "indicator-badge.rest.text",
230 "indicator-badge.tone.muted.fill",
231 ),
232 text(
233 "indicator-badge.rest.text",
234 "indicator-badge.tone.record.fill",
235 ),
236 ui("indicator-dot.tone.record.fill", "surface.panel"),
237 ui("indicator-dot.tone.record.fill", "surface.overlay"),
238 ui("indicator-dot.rest.border-color", "surface.panel"),
239 ui("indicator-dot.rest.border-color", "surface.overlay"),
240 ui("indicator-swatch.rest.border-color", "surface.panel"),
241 ui("indicator-swatch.rest.border-color", "surface.overlay"),
242 text("section-band.rest.text", "surface.panel"),
245 text("section-band.rest.text", "section-band.hover.fill"),
246 text("section-count.rest.text", "section-count.rest.fill"),
247 ui("section-disclosure.rest.text", "surface.panel"),
248 ui(
249 "indicator-dot.tone.accent.fill",
250 "indicator-outline.rest.ring-color",
251 ),
252 ui(
253 "indicator-dot.tone.danger.fill",
254 "indicator-outline.rest.ring-color",
255 ),
256 ui("rating-star.selected.fill", "surface.panel"),
261 ui("rating-star.selected.fill", "surface.raised"),
262 ui("rating-star.rest.border-color", "surface.panel"),
263 ui("rating-star.rest.border-color", "surface.raised"),
264 ui("rating-star-display.selected.fill", "surface.panel"),
265 ui("curve.line", "curve.background"),
267 ui("curve.point", "curve.background"),
268 ui("graph.node-selected", "graph.node"),
270 ui("graph.wire-hover.color", "graph.background"),
272 ui("graph.wire-selected.color", "graph.background"),
273 text("plot.rest.text", "plot.rest.fill"),
277 ui("plot-cursor.rest.fill", "plot.rest.fill"),
278 ui("plot-cursor.hover.fill", "plot.rest.fill"),
279 ui("palette.category.0", "surface.canvas"),
282 ui("palette.category.0", "surface.panel"),
283 ui("palette.category.0", "surface.raised"),
284 ui("palette.category.1", "surface.canvas"),
285 ui("palette.category.1", "surface.panel"),
286 ui("palette.category.1", "surface.raised"),
287 ui("palette.category.2", "surface.canvas"),
288 ui("palette.category.2", "surface.panel"),
289 ui("palette.category.2", "surface.raised"),
290 ui("palette.category.3", "surface.canvas"),
291 ui("palette.category.3", "surface.panel"),
292 ui("palette.category.3", "surface.raised"),
293 ui("palette.category.4", "surface.canvas"),
294 ui("palette.category.4", "surface.panel"),
295 ui("palette.category.4", "surface.raised"),
296 ui("palette.category.5", "surface.canvas"),
297 ui("palette.category.5", "surface.panel"),
298 ui("palette.category.5", "surface.raised"),
299 ui("palette.category.6", "surface.canvas"),
300 ui("palette.category.6", "surface.panel"),
301 ui("palette.category.6", "surface.raised"),
302 ui("palette.category.7", "surface.canvas"),
303 ui("palette.category.7", "surface.panel"),
304 ui("palette.category.7", "surface.raised"),
305 ui("palette.category.8", "surface.canvas"),
306 ui("palette.category.8", "surface.panel"),
307 ui("palette.category.8", "surface.raised"),
308 ui("palette.category.9", "surface.canvas"),
309 ui("palette.category.9", "surface.panel"),
310 ui("palette.category.9", "surface.raised"),
311 ui("palette.axis.x", "viewport.background"),
314 ui("palette.axis.y", "viewport.background"),
315 ui("palette.axis.z", "viewport.background"),
316];
317
318pub const OVER_IMAGES: &[Pair] = &[
323 text("viewport-label.rest.text", "viewport-label.rest.fill"),
325];
326
327pub fn over_image_ratio(tokens: &ResolvedTokens, pair: &Pair) -> Option<f32> {
331 let fg = tokens.color(pair.foreground)?;
332 let bg = tokens.color(pair.background)?;
333 Some(
334 [Color::BLACK, Color::WHITE]
335 .into_iter()
336 .map(|image| contrast_ratio(fg, bg.over(image)))
337 .fold(f32::INFINITY, f32::min),
338 )
339}
340
341#[derive(Clone, Debug, PartialEq)]
343pub struct Failure {
344 pub pair: Pair,
345 pub ratio: Option<f32>,
347 pub required: f32,
348}
349
350impl fmt::Display for Failure {
351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352 let Pair {
353 foreground,
354 background,
355 ..
356 } = self.pair;
357 match self.ratio {
358 Some(r) => write!(
359 f,
360 "{foreground} on {background}: {r:.2}:1, needs {}:1",
361 self.required
362 ),
363 None => write!(f, "{foreground} on {background}: not two colours"),
364 }
365 }
366}
367
368pub fn pair_ratio(tokens: &ResolvedTokens, pair: &Pair) -> Option<f32> {
370 Some(contrast_ratio(
371 tokens.color(pair.foreground)?,
372 tokens.color(pair.background)?,
373 ))
374}
375
376pub fn check(tokens: &ResolvedTokens, level: Level) -> Vec<Failure> {
379 let plain = PAIRS.iter().map(|pair| (pair, pair_ratio(tokens, pair)));
380 let over = OVER_IMAGES
381 .iter()
382 .map(|pair| (pair, over_image_ratio(tokens, pair)));
383 plain
384 .chain(over)
385 .filter_map(|(pair, ratio)| {
386 let required = level.required(pair.kind);
387 ratio.is_none_or(|r| r < required).then_some(Failure {
388 pair: *pair,
389 ratio,
390 required,
391 })
392 })
393 .collect()
394}
395
396#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
399pub enum Vision {
400 Normal,
402 Protanopia,
404 Deuteranopia,
406}
407
408impl Vision {
409 pub const ALL: [Vision; 3] = [Vision::Normal, Vision::Protanopia, Vision::Deuteranopia];
410
411 pub fn name(self) -> &'static str {
412 match self {
413 Vision::Normal => "normal vision",
414 Vision::Protanopia => "protanopia",
415 Vision::Deuteranopia => "deuteranopia",
416 }
417 }
418
419 pub fn simulate(self, c: Color) -> Color {
422 const PROTAN: [[f64; 3]; 3] = [
423 [0.152_286, 1.052_583, -0.204_868],
424 [0.114_503, 0.786_281, 0.099_216],
425 [-0.003_882, -0.048_116, 1.051_998],
426 ];
427 const DEUTAN: [[f64; 3]; 3] = [
428 [0.367_322, 0.860_646, -0.227_968],
429 [0.280_085, 0.672_501, 0.047_413],
430 [-0.011_820, 0.042_940, 0.968_881],
431 ];
432 let m = match self {
433 Vision::Normal => return c,
434 Vision::Protanopia => &PROTAN,
435 Vision::Deuteranopia => &DEUTAN,
436 };
437 let rgb = c.to_linear();
438 let row = |i: usize| {
439 (m[i][0] * rgb[0] + m[i][1] * rgb[1] + m[i][2] * rgb[2]).clamp(0.0, 1.0) as f32
440 };
441 Color::from_linear(row(0), row(1), row(2), c.a)
442 }
443}
444
445pub fn delta_e(a: Color, b: Color, vision: Vision) -> f32 {
450 let [l1, a1, b1] = vision.simulate(a).to_oklab();
451 let [l2, a2, b2] = vision.simulate(b).to_oklab();
452 (((l1 - l2).powi(2) + (a1 - a2).powi(2) + (b1 - b2).powi(2)).sqrt() * 100.0) as f32
453}
454
455pub const CATEGORY_ADJACENT: f32 = 15.0;
458pub const CATEGORY_ANY: f32 = 10.0;
461pub const CATEGORY_CVD_ADJACENT: f32 = 8.0;
464
465#[derive(Clone, Debug, PartialEq)]
467pub struct Separation {
468 pub slots: (usize, usize),
470 pub vision: Vision,
471 pub delta_e: Option<f32>,
474 pub required: f32,
475}
476
477impl fmt::Display for Separation {
478 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479 let (a, b) = self.slots;
480 match self.delta_e {
481 Some(d) => write!(
482 f,
483 "palette.category.{a} and .{b} ({}): ΔE {d:.1}, needs {}",
484 self.vision.name(),
485 self.required
486 ),
487 None => write!(f, "palette.category.{a} and .{b}: not two colours"),
488 }
489 }
490}
491
492pub fn check_category(tokens: &ResolvedTokens) -> Vec<Separation> {
498 let colors: Vec<Option<Color>> = CATEGORY.iter().map(|p| tokens.color(p)).collect();
499 let mut out = Vec::new();
500 for i in 0..colors.len() {
501 for j in i + 1..colors.len() {
502 let adjacent = j == i + 1;
503 for vision in Vision::ALL {
504 let required = match (vision, adjacent) {
505 (Vision::Normal, true) => CATEGORY_ADJACENT,
506 (Vision::Normal, false) => CATEGORY_ANY,
507 (_, true) => CATEGORY_CVD_ADJACENT,
508 (_, false) => continue,
509 };
510 let d = colors[i].zip(colors[j]).map(|(a, b)| delta_e(a, b, vision));
511 if d.is_none_or(|d| d < required) {
512 out.push(Separation {
513 slots: (i, j),
514 vision,
515 delta_e: d,
516 required,
517 });
518 }
519 }
520 }
521 }
522 out
523}