diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs
index ef42eec957..d63e07c952 100644
--- a/crates/color/src/wcag.rs
+++ b/crates/color/src/wcag.rs
@@ -2,6 +2,7 @@
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
+//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum.
/// What the content in front is, which sets the ratio it needs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -87,6 +88,99 @@ pub fn ratio_text(ratio: f64) -> String {
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
}
+/// The lightnesses [`closest_passing`] tests on each side before it narrows down the first that
+/// passes.
+const LIGHTNESS_SAMPLES: usize = 16;
+/// The halvings [`closest_passing`] makes of the lightness step, which leave it within 1e-9.
+const LIGHTNESS_STEPS: usize = 32;
+/// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples,
+/// which leave it within 1e-7 of the step.
+const PEAK_STEPS: usize = 32;
+/// The halvings [`closest_passing`] makes of the chroma when sRGB cannot show it.
+const CHROMA_STEPS: usize = 24;
+
+/// The display sRGB of OKLCH lightness `l`, chroma `c` and the hue whose sine and cosine are `sc`,
+/// with the chroma lowered until the color fits in sRGB.
+fn oklch_in_gamut(l: f64, c: f64, (sin, cos): (f64, f64)) -> [f32; 3] {
+ let at = |c: f64| crate::libraries::oklab_to_srgb(l, c * cos, c * sin);
+ let fits = |rgb: &[f64; 3]| rgb.iter().all(|v| (-1e-6..=1.0 + 1e-6).contains(v));
+ let mut rgb = at(c);
+ if !fits(&rgb) {
+ let (mut lo, mut hi) = (0.0, c);
+ for _ in 0..CHROMA_STEPS {
+ let mid = (lo + hi) / 2.0;
+ if fits(&at(mid)) { lo = mid } else { hi = mid }
+ }
+ rgb = at(lo);
+ }
+ rgb.map(|v| v.clamp(0.0, 1.0) as f32)
+}
+
+/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a
+/// single peak between them. `f` is called 34 times.
+pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 {
+ let g = (5f64.sqrt() - 1.0) / 2.0;
+ let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo));
+ let (mut fa, mut fb) = (f(a), f(b));
+ for _ in 0..PEAK_STEPS {
+ if fa < fb {
+ (lo, a, fa) = (a, b, fb);
+ b = lo + g * (hi - lo);
+ fb = f(b);
+ } else {
+ (hi, b, fb) = (b, a, fa);
+ a = hi - g * (hi - lo);
+ fa = f(a);
+ }
+ }
+ if fa > fb { a } else { b }
+}
+
+/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue
+/// () with the lightness raised or lowered, whichever
+/// takes the smaller step, and the chroma lowered where sRGB cannot show it. Each side is tested at
+/// 16 even steps up to white or black, and the step before the first that passes is narrowed down.
+/// When no step passes, the highest ratio between the neighbors of the highest step is looked for,
+/// so a color that passes only in a narrow band between white and black (as under a Difference
+/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is
+/// bounded: at most 167 colors are tested.
+pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> {
+ let passes = |c: [f32; 3]| ratio(c) >= minimum;
+ let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
+ if passes(srgb) {
+ return Some(srgb);
+ }
+ let [l, a, b] = crate::libraries::srgb_to_oklab(srgb);
+ let (c, sc) = (a.hypot(b), b.atan2(a).sin_cos());
+ let mut best: Option<(f64, [f32; 3])> = None;
+ for end in [1.0, 0.0] {
+ let at = |t: f64| oklch_in_gamut(l + (end - l) * t, c, sc);
+ let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64;
+ let ratios: Vec = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect();
+ // `lo` fails and `hi` passes, the step before the first sample that passes.
+ let found = match ratios.iter().position(|r| *r >= minimum) {
+ Some(i) => Some((step(i), step(i + 1))),
+ None => {
+ // Every sample fails: look for a higher ratio around the highest one.
+ let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0;
+ let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES)));
+ let peak = peak_between(lo, hi, &|t| ratio(at(t)));
+ passes(at(peak)).then_some((lo, peak))
+ }
+ };
+ let Some((mut lo, mut hi)) = found else { continue };
+ for _ in 0..LIGHTNESS_STEPS {
+ let mid = (lo + hi) / 2.0;
+ if passes(at(mid)) { hi = mid } else { lo = mid }
+ }
+ let step = (end - l).abs() * hi;
+ if best.is_none_or(|(d, _)| step < d) {
+ best = Some((step, at(hi)));
+ }
+ }
+ best.map(|(_, c)| c)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -137,6 +231,66 @@ mod tests {
assert_eq!(Category::parse("NormalText"), None);
}
+ fn hue(srgb: [f32; 3]) -> f64 {
+ let [_, a, b] = crate::libraries::srgb_to_oklab(srgb);
+ b.atan2(a).to_degrees()
+ }
+
+ #[test]
+ fn the_closest_passing_color_keeps_the_hue_and_just_passes() {
+ let (fg, bg) = (hex("fdc96e"), hex("355f78"));
+ let fix = closest_passing(fg, 4.5, &|c| contrast_ratio(c, bg)).unwrap();
+ let r = contrast_ratio(fix, bg);
+ assert!((4.5..4.501).contains(&r), "{r}");
+ assert!((hue(fix) - hue(fg)).abs() < 1.0, "{} {}", hue(fix), hue(fg));
+ // A color lighter than the background gets lighter.
+ assert!(relative_luminance(fix) > relative_luminance(fg));
+ }
+
+ #[test]
+ fn the_closest_passing_gray_on_white_is_a_darker_gray() {
+ let white = [1.0; 3];
+ let fix = closest_passing(hex("777777"), 4.5, &|c| contrast_ratio(c, white)).unwrap();
+ let r = contrast_ratio(fix, white);
+ assert!((4.5..4.501).contains(&r), "{r}");
+ assert!((fix[0] - fix[1]).abs() < 1e-4 && (fix[1] - fix[2]).abs() < 1e-4, "{fix:?}");
+ }
+
+ #[test]
+ fn a_color_that_passes_only_between_white_and_black_is_found() {
+ // White drawn with Difference over mid gray: white and black both draw mid gray (1:1), and
+ // mid gray draws black, 5.3:1.
+ let gray = [0.5; 3];
+ let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
+ let fix = closest_passing([1.0; 3], 4.5, &|c| contrast_ratio(difference(c), gray)).unwrap();
+ let r = contrast_ratio(difference(fix), gray);
+ assert!((4.5..4.51).contains(&r), "{fix:?}: {r}");
+ assert!(fix[0] > 0.5, "the nearest side of mid gray from white: {fix:?}");
+ }
+
+ #[test]
+ fn a_narrow_band_between_the_samples_is_found() {
+ // Over #5A5A5A only colors within a few hundredths of it draw dark enough with Difference
+ // for 3:1 (black reaches 3.04:1), and no even step from white lands there.
+ let gray = hex("5a5a5a");
+ let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
+ let ratio = |c: [f32; 3]| contrast_ratio(difference(c), gray);
+ let fix = closest_passing([1.0; 3], 3.0, &ratio).unwrap();
+ let r = ratio(fix);
+ assert!((3.0..3.01).contains(&r), "{fix:?}: {r}");
+ }
+
+ #[test]
+ fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() {
+ let white = [1.0; 3];
+ assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3]));
+ assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None);
+ // Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches.
+ let mid = hex("777777");
+ assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None);
+ assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3]));
+ }
+
#[test]
fn half_opaque_black_over_white_is_mid_gray() {
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs
index e2bc50cdc5..2859e8751e 100644
--- a/crates/engine/src/cmd.rs
+++ b/crates/engine/src/cmd.rs
@@ -821,6 +821,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
+pub use colorcmds::{Backdrop, contrast_measure};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
pub use docmenu::guide_indexes;
diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs
index b1817784b6..b3f0a4e2fb 100644
--- a/crates/engine/src/cmd/colorcmds.rs
+++ b/crates/engine/src/cmd/colorcmds.rs
@@ -141,7 +141,7 @@ pub fn specs() -> Vec {
"Contrast",
[],
None,
- "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the background; the modes inside an object, group or layer that isolates its blending do not apply; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
+ "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the background; the modes inside an object, group or layer that isolates its blending do not apply; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it; null when the color already meets the level, or when no lightness of its hue does}",
always,
contrast
),
@@ -1000,7 +1000,160 @@ const BELOW_SIDE: f64 = 1.0;
/// The pixels per point [`color_below`] renders at.
const BELOW_SCALE: f64 = 4.0;
+/// What `color.contrast` measures a color against: the background, and how the color is drawn over
+/// it (its blend modes, its opacity and the translucent groups and layers around it). The Color
+/// Wheel panel's contrast lines measure many colors against one.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Backdrop {
+ /// The background in display sRGB.
+ against: [f32; 3],
+ /// The background in working RGB, rounded to 8 bits, as the answer writes it.
+ written: [u8; 3],
+ /// The blend modes the color is drawn with, innermost first.
+ modes: Vec,
+ /// The given opacity, which takes the place of the drawn ones.
+ opacity: Option,
+ /// Each translucent group or layer around the object, from the outermost in, with the color
+ /// outside it.
+ levels: Vec<(f32, [f32; 3])>,
+ /// The opacity the color is drawn with inside its object.
+ drawn: f32,
+ /// The color and amount a fill stains the picked object of a dynamic symbol instance with.
+ stain: Option<(Color, f32)>,
+}
+
+impl Backdrop {
+ /// `c` as the measured object draws it: the picked object of a dynamic symbol instance that a
+ /// fill stains mixes its solid color towards the stain.
+ pub fn drawn_color(&self, c: &Color) -> Color {
+ match self.stain {
+ Some((stain, amount)) => c.lerp(&stain, amount),
+ None => *c,
+ }
+ }
+
+ /// Display sRGB `shown`, drawn as the measured color is drawn, over the background.
+ pub fn front(&self, shown: [f32; 3]) -> [f32; 3] {
+ // Each blend mode, innermost first, replaces the color with its blend with the background
+ // where it covers it.
+ let blended = self.modes.iter().fold(shown, |c, m| vectorcraft_color::blend::blend_rgb(*m, self.against, c));
+ match self.opacity {
+ Some(o) => wcag::over(blended, o, self.against),
+ None => {
+ // A translucent group or layer draws the art inside it, the art behind the object
+ // included, over what is outside it: the color is drawn opaque through each such
+ // level from the outermost in, over the color read with that level hidden, then at
+ // the object's own opacity over the background.
+ let x = self.levels.iter().fold(blended, |x, (a, outside)| wcag::over(x, *a, *outside));
+ wcag::over(x, self.drawn, self.against)
+ }
+ }
+ }
+
+ /// The contrast ratio of display sRGB `shown`, drawn as the measured color is drawn, against
+ /// the background.
+ pub fn ratio(&self, shown: [f32; 3]) -> f64 {
+ wcag::contrast_ratio(self.front(shown), self.against)
+ }
+
+ /// The background as `#rrggbb` in working RGB, the form a color param takes.
+ pub fn against_hex(&self) -> String {
+ let [r, g, b] = self.written;
+ format!("#{r:02x}{g:02x}{b:02x}")
+ }
+}
+
+/// The display sRGB the canvas shows for `c` through `cms`: with a rich black Appearance of Black,
+/// 100 % K alone shows as black.
+fn shown_rgb(cms: &vectorcraft_color::cms::Cms, rich_black: bool, c: &Color) -> [f32; 3] {
+ match *c {
+ Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
+ _ => cms.display_rgb(c),
+ }
+}
+
+/// Display sRGB `srgb` as a color in the model of `like`, as a pick on the Color Wheel stores it:
+/// an RGB color in the working RGB space, a CMYK or Lab color converted with the color settings, a
+/// Gray color as gray.
+fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) -> Color {
+ let [r, g, b] = cms.srgb_to_rgb(srgb);
+ let rgb = Color::rgb(r, g, b);
+ match like {
+ Color::Rgb { .. } => rgb,
+ Color::Cmyk { .. } => {
+ let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent);
+ Color::cmyk(c, m, y, k)
+ }
+ Color::Lab { .. } => {
+ let l = cms.lab(&rgb);
+ Color::lab(l.l, l.a, l.b)
+ }
+ Color::Gray { .. } => keep_model(*like, rgb),
+ }
+}
+
+/// The closest color in the model of `color` whose contrast against `backdrop` meets `minimum`
+/// ([`wcag::closest_passing`]), checked as the canvas shows it once stored (a symbol's stain
+/// included). None when `color` already meets it, or when no lightness of its hue does.
+fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64, rich_black: bool) -> Option {
+ let cms = vectorcraft_color::cms::active();
+ let drawn = |c: &Color| shown_rgb(&cms, rich_black, &backdrop.drawn_color(c));
+ let ratio = |srgb: [f32; 3]| backdrop.ratio(drawn(&in_model_of(&cms, srgb, color)));
+ if backdrop.ratio(drawn(color)) >= minimum {
+ return None;
+ }
+ let fix = wcag::closest_passing(shown_rgb(&cms, rich_black, color), minimum, &ratio)?;
+ Some(in_model_of(&cms, fix, color))
+}
+
fn contrast(s: &mut Session, p: &Value) -> Result {
+ contrast_measure(s, p).map(|(answer, _)| answer)
+}
+
+/// `color.contrast`'s answer for params `p`, and what it measured the color against.
+pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> {
+ const C: &str = "color.contrast";
+ let category = match p.get("for") {
+ None | Some(Value::Null) => Category::NormalText,
+ Some(v) => {
+ let key = "for";
+ let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
+ v.as_str().and_then(Category::parse).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", ids.join(", "))))?
+ }
+ };
+ let (color, backdrop) = contrast_backdrop(s, p)?;
+ let rich_black = s.prefs.black_on_screen == "rich";
+ let ratio = backdrop.ratio(shown_rgb(&vectorcraft_color::cms::active(), rich_black, &backdrop.drawn_color(&color)));
+ let levels = |c: Category| {
+ let (aa, aaa) = c.passes(ratio);
+ match aaa {
+ Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
+ None => json!({ "aa": aa }),
+ }
+ };
+ let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum, rich_black) {
+ Some(c) => serde_json::to_value(c).unwrap_or(Value::Null),
+ None => Value::Null,
+ };
+ let fixes = match category.minimums() {
+ (aa, Some(aaa)) => json!({ "aa": fix(aa), "aaa": fix(aaa) }),
+ (aa, None) => json!({ "aa": fix(aa) }),
+ };
+ let answer = json!({
+ "ratio": ratio,
+ "against": backdrop.against_hex(),
+ "normalText": levels(Category::NormalText),
+ "largeText": levels(Category::LargeText),
+ "graphics": levels(Category::Graphics),
+ "for": category.id(),
+ "fix": fixes,
+ });
+ Ok((answer, backdrop))
+}
+
+/// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and
+/// what it measures it against.
+fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> {
const C: &str = "color.contrast";
check_numbers(p, &["opacity"], C)?;
let opacity = match p.get("opacity").and_then(Value::as_f64) {
@@ -1012,16 +1165,14 @@ fn contrast(s: &mut Session, p: &Value) -> Result {
None => None,
};
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
+ let given = p.get("color").is_some_and(|v| !v.is_null());
let (color, drawn, mode, around) = match p.get("color") {
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, 1.0, vec![], vec![]),
};
let rich_black = s.prefs.black_on_screen == "rich";
let cms = vectorcraft_color::cms::active();
- let shown = |c: &Color| match *c {
- Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
- _ => cms.display_rgb(c),
- };
+ let shown = |c: &Color| shown_rgb(&cms, rich_black, c);
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
let (against, written) = match p.get("against").filter(|_| !below) {
@@ -1037,43 +1188,19 @@ fn contrast(s: &mut Session, p: &Value) -> Result {
(shown, to_8bit(cms.srgb_to_rgb(shown)))
}
};
- // Each blend mode, innermost first, replaces the color with its blend with the background
- // where it covers it.
- let blended = mode.iter().fold(shown(&color), |c, m| vectorcraft_color::blend::blend_rgb(*m, against, c));
- let front = match opacity {
- Some(o) => wcag::over(blended, o, against),
- None => {
- // A translucent group or layer draws the art inside it, the art behind the object
- // included, over what is outside it: the color is drawn opaque through each such level
- // from the outermost in, over the color read with that level hidden, then at the
- // object's own opacity over the background.
- let mut x = blended;
- for (a, level) in around.iter().rev().filter(|(a, _)| *a < 1.0) {
- let outside = match level.filter(|_| below) {
- Some(id) => color_below(s, rich_black, Some(id)).map_err(|e| bad(C, e))?,
- None => against,
- };
- x = wcag::over(x, *a, outside);
- }
- wcag::over(x, drawn, against)
+ // Each translucent group or layer, from the outermost in, with the color read with it hidden.
+ let mut levels = vec![];
+ if opacity.is_none() {
+ for (a, level) in around.iter().rev().filter(|(a, _)| *a < 1.0) {
+ let outside = match level.filter(|_| below) {
+ Some(id) => color_below(s, rich_black, Some(id)).map_err(|e| bad(C, e))?,
+ None => against,
+ };
+ levels.push((*a, outside));
}
- };
- let ratio = wcag::contrast_ratio(front, against);
- let levels = |c: Category| {
- let (aa, aaa) = c.passes(ratio);
- match aaa {
- Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
- None => json!({ "aa": aa }),
- }
- };
- let [r, g, b] = written;
- Ok(json!({
- "ratio": ratio,
- "against": format!("#{r:02x}{g:02x}{b:02x}"),
- "normalText": levels(Category::NormalText),
- "largeText": levels(Category::LargeText),
- "graphics": levels(Category::Graphics),
- }))
+ }
+ let stain = if given { None } else { stain_of(s) };
+ Ok((color, Backdrop { against, written, modes: mode, opacity, levels, drawn, stain }))
}
/// The opacity of each object around the proxy's object that draws it, innermost first, with the
@@ -1134,7 +1261,7 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
}
let no_color = || "the active fill or stroke has no color: give `color`".to_string();
match if stroke { stroke_paint } else { fill } {
- Paint::Solid { color, .. } => Ok((stained(s, color), layer, mode, around)),
+ Paint::Solid { color, .. } => Ok((color, layer, mode, around)),
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
@@ -1186,19 +1313,18 @@ fn drawn_settings(s: &Session, n: &Node, item: Option, stroke: bool) -> s
Ok((opacity, drawn_modes(levels.collect()), around))
}
-/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
-/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
-/// `color` itself otherwise.
-fn stained(s: &Session, color: Color) -> Color {
- let stain = s.active().and_then(|st| {
- let sp = st.selection.symbol_part.as_ref()?;
- st.selected_symbol_part()?;
- vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
- });
- match stain {
- Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
- None => color,
+/// The color and amount a fill stains the picked object of a dynamic symbol instance with
+/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill), when
+/// such an object is picked and its proxy shows a solid color.
+fn stain_of(s: &Session) -> Option<(Color, f32)> {
+ let (fill, stroke) = s.proxy_paints();
+ if !matches!(if s.fill_active { fill } else { stroke }, Paint::Solid { .. }) {
+ return None;
}
+ let st = s.active()?;
+ let sp = st.selection.symbol_part.as_ref()?;
+ st.selected_symbol_part()?;
+ vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?).map(|(c, amount)| (c, amount.clamp(0.0, 1.0)))
}
/// The blend modes that apply to a color drawn through `levels` (each a blend mode and whether that
diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs
index 398dc24b88..20a8b9bcda 100644
--- a/crates/engine/src/tests/colorcontrast.rs
+++ b/crates/engine/src/tests/colorcontrast.rs
@@ -379,6 +379,14 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() {
let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap();
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}");
+ // The fix is the color to store: the stain mixes it half way to black again, and the result
+ // just meets AA against white.
+ let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap();
+ assert_eq!(r["normalText"]["aa"], false, "{r}");
+ let fix = fix_color(&r["fix"]["aa"]);
+ let drawn = fix.lerp(&vectorcraft_color::Color::BLACK, 0.5).to_rgb_uncalibrated();
+ let got = vectorcraft_color::wcag::contrast_ratio(drawn, [1.0; 3]);
+ assert!((4.5..4.51).contains(&got), "{fix:?} draws {drawn:?}: {got}");
}
#[test]
@@ -441,3 +449,79 @@ fn a_fill_of_none_has_no_color_to_measure() {
assert!(e.contains("has no color"), "{e}");
assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok());
}
+
+fn fix_color(v: &Value) -> vectorcraft_color::Color {
+ crate::cmd::color_value(v).unwrap_or_else(|| panic!("not a color: {v}"))
+}
+
+fn oklch_hue(c: &vectorcraft_color::Color) -> f64 {
+ let [_, a, b] = vectorcraft_color::libraries::to_oklab(c);
+ b.atan2(a).to_degrees()
+}
+
+#[test]
+fn a_failing_color_answers_the_closest_passing_color_of_its_hue() {
+ let mut s = Session::new();
+ let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap();
+ assert_eq!(r["for"], "normalText");
+ let aa = fix_color(&r["fix"]["aa"]);
+ let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
+ assert!((4.5..4.51).contains(&ratio(&back)), "{back}");
+ let want = oklch_hue(&vectorcraft_color::Color::from_hex("#fdc96e").unwrap());
+ assert!((oklch_hue(&aa) - want).abs() < 1.0, "{} {want}", oklch_hue(&aa));
+ assert!(matches!(aa, vectorcraft_color::Color::Rgb { .. }), "an RGB color answers RGB: {aa:?}");
+ // White on #355F78 is 6.87:1 and black 3.05:1, so no color reaches AAA's 7:1.
+ assert!(r["fix"]["aaa"].is_null(), "{r}");
+ let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
+ let aaa = s.execute("color.contrast", &json!({"color": large["fix"]["aaa"], "against": "#355f78"})).unwrap();
+ assert!((4.5..4.51).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}");
+}
+
+#[test]
+fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() {
+ let mut s = Session::new();
+ let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
+ assert_eq!(r["fix"], json!({"aa": null, "aaa": null}));
+ let g = s.execute("color.contrast", &json!({"color": "#cccccc", "against": "#ffffff", "for": "graphics"})).unwrap();
+ assert_eq!(g["for"], "graphics");
+ let fix = g["fix"].as_object().unwrap();
+ assert_eq!(fix.keys().collect::>(), ["aa"], "{g}");
+ let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap();
+ assert!((3.0..3.01).contains(&ratio(&back)), "{back}");
+ let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
+ assert!(large["fix"]["aa"].is_null(), "4.49:1 meets large text AA: {large}");
+ assert!(!large["fix"]["aaa"].is_null(), "{large}");
+}
+
+#[test]
+fn a_cmyk_color_answers_a_cmyk_fix() {
+ let mut s = Session::new();
+ let r = s.execute("color.contrast", &json!({"color": {"c": 0, "m": 40, "y": 70, "k": 20}, "against": "#355f78"})).unwrap();
+ assert_eq!(r["normalText"]["aa"], false, "{r}");
+ let fix = fix_color(&r["fix"]["aa"]);
+ assert!(matches!(fix, vectorcraft_color::Color::Cmyk { .. }), "{fix:?}");
+ let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
+ assert!(ratio(&back) >= 4.5, "{back}");
+}
+
+#[test]
+fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() {
+ let mut s = Session::new();
+ // #808080 at 50 % over white draws as a light gray: black at 50 % draws 0.5 gray, 3.98:1, which
+ // meets large text AA (3:1) but not AAA (4.5:1).
+ let p = json!({"color": "#808080", "against": "#ffffff", "opacity": 50, "for": "largeText"});
+ let r = s.execute("color.contrast", &p).unwrap();
+ assert_eq!(r["largeText"]["aa"], false, "{r}");
+ assert!(r["fix"]["aaa"].is_null(), "no gray at 50 % reaches 4.5:1: {r}");
+ let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff", "opacity": 50})).unwrap();
+ assert!((3.0..3.01).contains(&ratio(&back)), "{back}");
+}
+
+#[test]
+fn for_takes_only_the_three_categories() {
+ let mut s = Session::new();
+ for bad in [json!("NormalText"), json!("aa"), json!(1), json!(true)] {
+ let e = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "for": bad})).unwrap_err().to_string();
+ assert!(e.contains("`for` must be one of normalText, largeText, graphics"), "{e}");
+ }
+}
diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv
index 359972b26c..b78684086f 100644
--- a/crates/ui-egui/src/i18n/bg.tsv
+++ b/crates/ui-egui/src/i18n/bg.tsv
@@ -1477,6 +1477,7 @@ font-technology Variable Променливи
Fail Не покрива
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимален контраст по WCAG 2.2: нормален текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), голям текст AA 3:1 и AAA 4.5:1, графики и контроли AA 3:1 (1.4.11).
The background is read at the center of the selection. Фонът се отчита в центъра на селекцията.
+ The closest color that passes {level}: click to apply it. Най-близкият цвят, който покрива {level}: щракнете, за да го приложите.
Graphics Processor Графичен процесор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv
index a9d9bfe3c2..52513dddfb 100644
--- a/crates/ui-egui/src/i18n/bs.tsv
+++ b/crates/ui-egui/src/i18n/bs.tsv
@@ -1968,6 +1968,7 @@ digits Malayalam Malajalam
Fail Ne prolazi
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalni kontrast po WCAG 2.2: normalni tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), veliki tekst AA 3:1 i AAA 4.5:1, grafike i kontrole AA 3:1 (1.4.11).
The background is read at the center of the selection. Pozadina se očitava u sredini odabira.
+ The closest color that passes {level}: click to apply it. Najbliža boja koja zadovoljava {level}: kliknite da je primijenite.
Local Libraries Lokalne biblioteke
Add Content Dodaj sadržaj
Click to apply to the selected type Kliknite da primijenite na odabrani tekst
diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv
index 47559f16c1..7a64590644 100644
--- a/crates/ui-egui/src/i18n/ca.tsv
+++ b/crates/ui-egui/src/i18n/ca.tsv
@@ -1992,6 +1992,7 @@ digits Malayalam Malaiàlam
Fail No supera
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrast mínim de les WCAG 2.2: text normal AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), text gran AA 3:1 i AAA 4.5:1, gràfics i controls AA 3:1 (1.4.11).
The background is read at the center of the selection. El fons es llegeix al centre de la selecció.
+ The closest color that passes {level}: click to apply it. El color més proper que compleix {level}: feu clic per aplicar-lo.
Graphics Processor Processador gràfic
Graphics: {adapter} Gràfics: {adapter}
Gravity Gravetat
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 517c4732e4..e6c2295c24 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2041,6 +2041,7 @@ digits Malayalam Malajálamské
Fail Nevyhovuje
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimální kontrast podle WCAG 2.2: normální text AA 4.5:1 (1.4.3) a AAA 7:1 (1.4.6), velký text AA 3:1 a AAA 4.5:1, grafika a ovládací prvky AA 3:1 (1.4.11).
The background is read at the center of the selection. Pozadí se čte uprostřed výběru.
+ The closest color that passes {level}: click to apply it. Nejbližší barva, která splňuje {level}: kliknutím ji použijete.
Local Libraries Místní knihovny
Add Content Přidat obsah
Click to apply to the selected type Kliknutím použijete na vybraný text
diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv
index 3ab1d7eb08..c38325c433 100644
--- a/crates/ui-egui/src/i18n/da.tsv
+++ b/crates/ui-egui/src/i18n/da.tsv
@@ -4520,6 +4520,7 @@ digits Malayalam Malayalam
Fail Ikke bestået
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindstekontrast efter WCAG 2.2: normal tekst AA 4.5:1 (1.4.3) og AAA 7:1 (1.4.6), stor tekst AA 3:1 og AAA 4.5:1, grafik og kontrolelementer AA 3:1 (1.4.11).
The background is read at the center of the selection. Baggrunden aflæses i midten af markeringen.
+ The closest color that passes {level}: click to apply it. Den nærmeste farve, der består {level}: klik for at anvende den.
Local Libraries Lokale biblioteker
Add Content Tilføj indhold
Click to apply to the selected type Klik for at anvende på den markerede tekst
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index d9f7612aa8..8e3c8847e4 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -1527,6 +1527,7 @@ file-filter Templates Vorlagen
Fail Nicht bestanden
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindestkontrast nach WCAG 2.2: normaler Text AA 4.5:1 (1.4.3) und AAA 7:1 (1.4.6), großer Text AA 3:1 und AAA 4.5:1, Grafiken und Bedienelemente AA 3:1 (1.4.11).
The background is read at the center of the selection. Der Hintergrund wird in der Mitte der Auswahl gemessen.
+ The closest color that passes {level}: click to apply it. Die nächste Farbe, die {level} besteht: Klicken Sie, um sie anzuwenden.
Graphics Processor Grafikprozessor
Graphics: {adapter} Grafik: {adapter}
Gravity Schwerkraft
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index f476aa9b33..9b7b485a6f 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -1459,6 +1459,7 @@ font-technology Variable Μεταβλητές
Fail Αποτυχία
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Ελάχιστη αντίθεση κατά WCAG 2.2: κανονικό κείμενο AA 4.5:1 (1.4.3) και AAA 7:1 (1.4.6), μεγάλο κείμενο AA 3:1 και AAA 4.5:1, γραφικά και στοιχεία ελέγχου AA 3:1 (1.4.11).
The background is read at the center of the selection. Το φόντο διαβάζεται στο κέντρο της επιλογής.
+ The closest color that passes {level}: click to apply it. Το πλησιέστερο χρώμα που περνά το {level}: κάντε κλικ για να το εφαρμόσετε.
Graphics Processor Επεξεργαστής γραφικών
Graphics: {adapter} Γραφικά: {adapter}
Gravity Βαρύτητα
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index c0ced0baaa..78858b8cd4 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -1542,6 +1542,7 @@ font-technology Variable Variables
Fail No cumple
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo de WCAG 2.2: texto normal AA 4.5:1 (1.4.3) y AAA 7:1 (1.4.6), texto grande AA 3:1 y AAA 4.5:1, gráficos y controles AA 3:1 (1.4.11).
The background is read at the center of the selection. El fondo se lee en el centro de la selección.
+ The closest color that passes {level}: click to apply it. El color más cercano que cumple {level}: haga clic para aplicarlo.
Graphics Processor Procesador gráfico
Graphics: {adapter} Gráficos: {adapter}
Gravity Gravedad
diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv
index 018f984732..0f0a867295 100644
--- a/crates/ui-egui/src/i18n/fi.tsv
+++ b/crates/ui-egui/src/i18n/fi.tsv
@@ -2002,6 +2002,7 @@ digits Malayalam Malajalam
Fail Ei läpäise
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2:n vähimmäiskontrastit: tavallinen teksti AA 4.5:1 (1.4.3) ja AAA 7:1 (1.4.6), suuri teksti AA 3:1 ja AAA 4.5:1, grafiikka ja säätimet AA 3:1 (1.4.11).
The background is read at the center of the selection. Tausta luetaan valinnan keskeltä.
+ The closest color that passes {level}: click to apply it. Lähin väri, joka läpäisee tason {level}: käytä sitä napsauttamalla.
Local Libraries Paikalliset kirjastot
Add Content Lisää sisältöä
Click to apply to the selected type Käytä valittuun tekstiin napsauttamalla
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index eaac8d95b1..9cf5367489 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -1532,6 +1532,7 @@ font-technology Variable Variables
Fail Échec
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste minimal WCAG 2.2 : texte normal AA 4.5:1 (1.4.3) et AAA 7:1 (1.4.6), grand texte AA 3:1 et AAA 4.5:1, graphiques et commandes AA 3:1 (1.4.11).
The background is read at the center of the selection. L’arrière-plan est lu au centre de la sélection.
+ The closest color that passes {level}: click to apply it. La couleur la plus proche qui satisfait {level} : cliquez pour l’appliquer.
Graphics Processor Processeur graphique
Graphics: {adapter} Carte graphique : {adapter}
Gravity Gravité
diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv
index ee71f52157..54f5a79610 100644
--- a/crates/ui-egui/src/i18n/gu.tsv
+++ b/crates/ui-egui/src/i18n/gu.tsv
@@ -1616,6 +1616,7 @@
Fail નાપાસ
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 લઘુત્તમ કોન્ટ્રાસ્ટ: સામાન્ય ટેક્સ્ટ AA 4.5:1 (1.4.3) અને AAA 7:1 (1.4.6), મોટું ટેક્સ્ટ AA 3:1 અને AAA 4.5:1, ગ્રાફિક્સ અને નિયંત્રણો AA 3:1 (1.4.11).
The background is read at the center of the selection. પૃષ્ઠભૂમિ પસંદગીના કેન્દ્રમાં વાંચવામાં આવે છે.
+ The closest color that passes {level}: click to apply it. {level} પાસ કરતો સૌથી નજીકનો રંગ: તેને લાગુ કરવા ક્લિક કરો.
Graphics Processor ગ્રાફિક્સ પ્રોસેસર
Graphics: {adapter} ગ્રાફિક્સ: {adapter}
Gravity ગ્રેવિટી
diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv
index 6b62bda40f..cffebdc9b7 100644
--- a/crates/ui-egui/src/i18n/hi.tsv
+++ b/crates/ui-egui/src/i18n/hi.tsv
@@ -2208,6 +2208,7 @@ antiAlias Sharp शार्प
Fail फ़ेल
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 न्यूनतम कंट्रास्ट: सामान्य टेक्स्ट AA 4.5:1 (1.4.3) और AAA 7:1 (1.4.6), बड़ा टेक्स्ट AA 3:1 और AAA 4.5:1, ग्राफ़िक्स और कंट्रोल AA 3:1 (1.4.11)।
The background is read at the center of the selection. पृष्ठभूमि सिलेक्शन के केंद्र पर पढ़ी जाती है।
+ The closest color that passes {level}: click to apply it. {level} पास करने वाला सबसे नज़दीकी रंग: लागू करने के लिए क्लिक करें।
Graphics Processor ग्राफिक्स प्रोसेसर
Graphics: {adapter} ग्राफिक्स: {adapter}
Gravity ग्रेविटी
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index 1d24dba789..87b38dc4aa 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -1925,6 +1925,7 @@ file-filter Templates Sablonok
Fail Nem felel meg
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 szerinti minimális kontraszt: normál szöveg AA 4.5:1 (1.4.3) és AAA 7:1 (1.4.6), nagy szöveg AA 3:1 és AAA 4.5:1, grafikák és vezérlők AA 3:1 (1.4.11).
The background is read at the center of the selection. A háttér színét a kijelölés közepén olvassa le a program.
+ The closest color that passes {level}: click to apply it. A legközelebbi szín, amely megfelel a(z) {level} szintnek: kattintson az alkalmazásához.
Graphics Processor Grafikus processzor
Graphics: {adapter} Grafika: {adapter}
Gravity Gravitáció
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index af89105e27..b8e9a88359 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -1804,6 +1804,7 @@ digits Malayalam Malayalam
Fail Gagal
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Kontras minimum WCAG 2.2: teks normal AA 4.5:1 (1.4.3) dan AAA 7:1 (1.4.6), teks besar AA 3:1 dan AAA 4.5:1, grafis dan kontrol AA 3:1 (1.4.11).
The background is read at the center of the selection. Latar dibaca di tengah seleksi.
+ The closest color that passes {level}: click to apply it. Warna terdekat yang lolos {level}: klik untuk menerapkannya.
Local Libraries Pustaka lokal
Add Content Tambahkan konten
Click to apply to the selected type Klik untuk menerapkan ke teks terpilih
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index a902541e0b..52e3aeccb7 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -1561,6 +1561,7 @@ file-filter Templates Modelli
Fail Non superato
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrasto minimo WCAG 2.2: testo normale AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), testo grande AA 3:1 e AAA 4.5:1, grafica e controlli AA 3:1 (1.4.11).
The background is read at the center of the selection. Lo sfondo viene letto al centro della selezione.
+ The closest color that passes {level}: click to apply it. Il colore più vicino che soddisfa {level}: fai clic per applicarlo.
Graphics Processor Processore grafico
Graphics: {adapter} Scheda grafica: {adapter}
Gravity Gravità
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index f647393ade..0187ebacc2 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3987,6 +3987,7 @@ file-filter Templates テンプレート
Fail 不合格
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 の最小コントラスト:通常のテキスト AA 4.5:1 (1.4.3) と AAA 7:1 (1.4.6)、大きなテキスト AA 3:1 と AAA 4.5:1、グラフィックとコントロール AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景は選択範囲の中央で読み取ります。
+ The closest color that passes {level}: click to apply it. {level} を満たす最も近いカラー:クリックで適用します。
Greek & Cyrillic ギリシャ文字とキリル文字
Hex by Column 六角形 (列)
Hex by Row 六角形 (行)
diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv
index 8041133095..516a00d1ec 100644
--- a/crates/ui-egui/src/i18n/ka.tsv
+++ b/crates/ui-egui/src/i18n/ka.tsv
@@ -3869,6 +3869,7 @@ digits Malayalam მალაიალამური
Fail არ აკმაყოფილებს
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2-ის მინიმალური კონტრასტი: ჩვეულებრივი ტექსტი AA 4.5:1 (1.4.3) და AAA 7:1 (1.4.6), დიდი ტექსტი AA 3:1 და AAA 4.5:1, გრაფიკა და მართვის ელემენტები AA 3:1 (1.4.11).
The background is read at the center of the selection. ფონი იკითხება მონიშნულის ცენტრში.
+ The closest color that passes {level}: click to apply it. უახლოესი ფერი, რომელიც აკმაყოფილებს {level}-ს: დააწკაპუნეთ მის გამოსაყენებლად.
Local Libraries ლოკალური ბიბლიოთეკები
Add Content შიგთავსის დამატება
Click to apply to the selected type დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 9e890e2580..9402411a0d 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -3975,6 +3975,7 @@ file-filter Templates 템플릿
Fail 실패
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 최소 대비: 일반 텍스트 AA 4.5:1 (1.4.3) 및 AAA 7:1 (1.4.6), 큰 텍스트 AA 3:1 및 AAA 4.5:1, 그래픽과 컨트롤 AA 3:1 (1.4.11).
The background is read at the center of the selection. 배경은 선택 영역의 중앙에서 읽습니다.
+ The closest color that passes {level}: click to apply it. {level}을(를) 충족하는 가장 가까운 색상: 클릭하여 적용합니다.
Greek & Cyrillic 그리스어 및 키릴 문자
Hex by Column 열 기준 육각형
Hex by Row 행 기준 육각형
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index b63a05e26f..06559f4d4f 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -2414,6 +2414,7 @@ digits Malayalam Malayalam
Fail Niet geslaagd
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimumcontrast volgens WCAG 2.2: normale tekst AA 4.5:1 (1.4.3) en AAA 7:1 (1.4.6), grote tekst AA 3:1 en AAA 4.5:1, illustraties en bedieningselementen AA 3:1 (1.4.11).
The background is read at the center of the selection. De achtergrond wordt in het midden van de selectie gemeten.
+ The closest color that passes {level}: click to apply it. De dichtstbijzijnde kleur die aan {level} voldoet: klik om deze toe te passen.
Local Libraries Lokale bibliotheken
Add Content Inhoud toevoegen
Click to apply to the selected type Klik om toe te passen op de geselecteerde tekst
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index aeaa4a7bac..e703f9f206 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -1959,6 +1959,7 @@ digits Malayalam Malajalam
Fail Nie spełnia
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalny kontrast według WCAG 2.2: zwykły tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), duży tekst AA 3:1 i AAA 4.5:1, grafika i elementy sterujące AA 3:1 (1.4.11).
The background is read at the center of the selection. Tło jest odczytywane na środku zaznaczenia.
+ The closest color that passes {level}: click to apply it. Najbliższy kolor spełniający {level}: kliknij, aby go zastosować.
Local Libraries Biblioteki lokalne
Add Content Dodaj zawartość
Click to apply to the selected type Kliknij, aby zastosować do zaznaczonego tekstu
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 91820ab433..2a30fdb4d0 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -3684,6 +3684,7 @@ font-technology Variable Variáveis
Fail Reprovado
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo da WCAG 2.2: texto normal AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), texto grande AA 3:1 e AAA 4.5:1, gráficos e controles AA 3:1 (1.4.11).
The background is read at the center of the selection. O fundo é lido no centro da seleção.
+ The closest color that passes {level}: click to apply it. A cor mais próxima que atende a {level}: clique para aplicá-la.
Highlight Rows Destacar linhas
Highlight Variable Destacar variável
Sort Variables Ordenar variáveis
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 76a70a4fb6..7dd8cb1654 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -1552,6 +1552,7 @@ file-filter Templates Шаблоны
Fail Не соответствует
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимальный контраст по WCAG 2.2: обычный текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), крупный текст AA 3:1 и AAA 4.5:1, графика и элементы управления AA 3:1 (1.4.11).
The background is read at the center of the selection. Фон определяется в центре выделения.
+ The closest color that passes {level}: click to apply it. Ближайший цвет, соответствующий {level}: щёлкните, чтобы применить его.
Graphics Processor Графический процессор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv
index 37292b64ee..6e47263e1c 100644
--- a/crates/ui-egui/src/i18n/sv.tsv
+++ b/crates/ui-egui/src/i18n/sv.tsv
@@ -1495,6 +1495,7 @@ font-technology Variable Variabla
Fail Underkänd
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minsta kontrast enligt WCAG 2.2: normal text AA 4.5:1 (1.4.3) och AAA 7:1 (1.4.6), stor text AA 3:1 och AAA 4.5:1, grafik och kontroller AA 3:1 (1.4.11).
The background is read at the center of the selection. Bakgrunden läses i mitten av markeringen.
+ The closest color that passes {level}: click to apply it. Den närmaste färgen som klarar {level}: klicka för att använda den.
Graphics Processor Grafikprocessor
Graphics: {adapter} Grafik: {adapter}
Gravity Gravitation
diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv
index fd72402419..75c89b5a0d 100644
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@ -1453,6 +1453,7 @@ font-technology Variable Değişken
Fail Kaldı
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 en düşük kontrast: normal metin AA 4.5:1 (1.4.3) ve AAA 7:1 (1.4.6), büyük metin AA 3:1 ve AAA 4.5:1, grafikler ve denetimler AA 3:1 (1.4.11).
The background is read at the center of the selection. Arka plan seçimin ortasında okunur.
+ The closest color that passes {level}: click to apply it. {level} düzeyini karşılayan en yakın renk: uygulamak için tıklayın.
Graphics Processor Grafik İşlemcisi
Graphics: {adapter} Grafik: {adapter}
Gravity Yerçekimi
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index eedbd4ca26..e46c5e9175 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -1555,6 +1555,7 @@ file-filter Templates Шаблони
Fail Не відповідає
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Мінімальний контраст за WCAG 2.2: звичайний текст AA 4.5:1 (1.4.3) і AAA 7:1 (1.4.6), великий текст AA 3:1 і AAA 4.5:1, графіка й елементи керування AA 3:1 (1.4.11).
The background is read at the center of the selection. Фон визначається в центрі виділення.
+ The closest color that passes {level}: click to apply it. Найближчий колір, що відповідає {level}: клацніть, щоб застосувати його.
Graphics Processor Графічний процесор
Graphics: {adapter} Графіка: {adapter}
Gravity Гравітація
diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv
index 4816d2ebaa..03793d07d4 100644
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@ -1785,6 +1785,7 @@ file-filter Templates Mẫu
Fail Không đạt
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Độ tương phản tối thiểu theo WCAG 2.2: văn bản thường AA 4.5:1 (1.4.3) và AAA 7:1 (1.4.6), văn bản lớn AA 3:1 và AAA 4.5:1, đồ họa và điều khiển AA 3:1 (1.4.11).
The background is read at the center of the selection. Nền được đọc tại tâm vùng chọn.
+ The closest color that passes {level}: click to apply it. Màu gần nhất đạt {level}: bấm để áp dụng.
Graphics Processor Bộ xử lý đồ họa
Graphics: {adapter} Đồ họa: {adapter}
Gravity Trọng lực
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 3049598865..a9ebbfc8b3 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -1490,6 +1490,7 @@ file-filter Templates 模板
Fail 未通过
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低对比度:普通文本 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大号文本 AA 3:1 和 AAA 4.5:1,图形和控件 AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景在所选对象的中心读取。
+ The closest color that passes {level}: click to apply it. 符合 {level} 的最接近颜色:单击即可应用。
Gravity 重力
Grays 灰度级数
Grays and Neutrals 灰色和中性色
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 17e10e55f3..7b28293be5 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -1525,6 +1525,7 @@ file-filter Templates 範本
Fail 未通過
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低對比度:一般文字 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大型文字 AA 3:1 和 AAA 4.5:1,圖形和控制項 AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景在選取範圍的中心讀取。
+ The closest color that passes {level}: click to apply it. 符合 {level} 的最接近顏色:按一下即可套用。
Graphics Processor 圖形處理器
Graphics: {adapter} 圖形:{adapter}
Gravity 重力
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 31dc6307c6..214ecdb392 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -786,6 +786,8 @@ mod tests_color_wheel_box;
#[cfg(test)]
mod tests_color_wheel_contrast;
#[cfg(test)]
+mod tests_color_wheel_contrast_lines;
+#[cfg(test)]
mod tests_constrain;
#[cfg(test)]
mod tests_css_properties;
diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs
index 5bc807f4bb..38cfaf1bc0 100644
--- a/crates/ui-egui/src/panels/color_wheel.rs
+++ b/crates/ui-egui/src/panels/color_wheel.rs
@@ -16,14 +16,20 @@
//! () of the color against the color drawn
//! behind the selection, or against a color pinned with Contrast Background › Current Color, and
//! whether it meets AA and AAA for the category picked under Contrast For (`color.contrast`).
+//! The wheel's square and the box's field then draw lines where the color picked there would meet
+//! AA and AAA (AAA dashed), and when the color fails, a chip in the row offers the closest color
+//! that passes, the one `color.contrast` answers as `fix`.
-use egui::{Ui, UiBuilder, vec2};
+use std::collections::HashMap;
+
+use egui::{Color32, Rect, Stroke, Ui, UiBuilder, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::cms::{self, Cms};
use vectorcraft_color::wcag::{self, Category};
use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb};
use vectorcraft_doc::{ColorMode, NodeId};
+use vectorcraft_engine::cmd::{Backdrop, contrast_measure};
use super::color::{Target, apply, wheel_target};
use super::{color_json, pstate, set_pstate};
@@ -273,15 +279,19 @@ fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) {
/// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with
/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks,
-/// and its phase.
-fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> {
+/// and its phase, and the field's rect.
+fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> (Option<([f32; 3], Live)>, Rect) {
let (z, x, y) = box_pos(ch, hsb);
let mut pick = None;
+ let mut field_rect = Rect::NOTHING;
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = STRIP_GAP;
let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size);
let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb));
- if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) {
+ let picked = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at);
+ // The field is the first thing in the row.
+ field_rect = Rect::from_min_size(ui.min_rect().min, field);
+ if let (Some((x, y)), phase) = picked {
pick = Some((box_pick(ch, z, x, y, hsb), phase));
}
// The hue strip shows the whole spectrum; the others change only their own component.
@@ -294,7 +304,7 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) ->
_ => {}
}
});
- pick
+ (pick, field_rect)
}
/// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored.
@@ -313,9 +323,217 @@ type BehindKey = (u64, u64, Vec, Option>, String, Under);
/// What the contrast row's answer depends on: the background, the active proxy's paint (with nothing
/// selected it is the default for new art, which no revision counts), the document, its revision,
/// the selection and its picked symbol object, the proxy, the appearance item, the selected
-/// gradient stop and freeform point, the on-screen Appearance of Black and the color settings.
+/// gradient stop and freeform point, the on-screen Appearance of Black, the color settings and the
+/// Contrast For category, which the closest passing colors are for.
pub(super) type RatioKey =
- (String, String, Option<(u64, u64)>, Vec, Option>, bool, Option, Option, Option, String, Under);
+ (String, String, Option<(u64, u64)>, Vec, Option>, bool, Option, Option, Option, String, Under, Category);
+
+/// Panel state: what the contrast row's answer was measured against, with its [`RatioKey`].
+const BACKDROP: &str = "color-wheel-backdrop";
+/// Panel state: the contrast lines of the square or the field, with the [`LinesKey`] they were
+/// found for.
+pub(super) const LINES: &str = "color-wheel-lines";
+/// What the contrast lines depend on: what the color is measured against, the category, the field
+/// (the view, the channel and the component the field holds fixed) with the model a pick there
+/// stores, and the color settings.
+pub(super) type LinesKey = (Backdrop, Category, String, Under);
+/// Per minimum of the category (AA, then AAA where it has one), the lines in field coordinates.
+pub(super) type Lines = Vec>>;
+
+/// The columns and rows at which [`contrast_lines`] samples a field.
+const LINE_SAMPLES: usize = 32;
+/// The halvings that place a line on the edge between two samples.
+const LINE_STEPS: usize = 10;
+
+/// A point of a field: x across, y down, 0 to 1 each.
+type FieldPoint = (f32, f32);
+
+/// The passing bands found between the samples of one column or row: where each peaks along it, and
+/// its two crossings.
+type Bands = Vec<(f32, FieldPoint, FieldPoint)>;
+
+/// Where the contrast `ratio_at` a field point crosses each of `minimums`: per minimum, polylines in
+/// field coordinates. The field is sampled on a 33 × 33 grid, and each cell whose corners fall on
+/// both sides gets a segment between the crossings on its edges, placed by bisection (marching
+/// squares; a cell with two opposite corners passing is split by its center). Around a failing
+/// sample higher than its neighbors in a column or a row, the highest ratio is looked for, so a
+/// passing band narrower than the samples gets its two edges too, joined from column to column or
+/// from row to row. Segments that share an end are joined into one polyline.
+pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64]) -> Lines {
+ let n = LINE_SAMPLES;
+ let at = |i: usize| i as f32 / n as f32;
+ // `grid[i][j]` is column i (x) and row j (y).
+ let grid: Vec> = (0..=n).map(|i| (0..=n).map(|j| ratio_at(at(i), at(j))).collect()).collect();
+ let r = |i: usize, j: usize| grid.get(i).and_then(|c| c.get(j)).copied().unwrap_or(f64::NAN);
+ minimums
+ .iter()
+ .map(|&min| {
+ let pass = |p: FieldPoint| ratio_at(p.0, p.1) >= min;
+ // The crossing between `p`, on the side `above` says, and `q`.
+ let cross = |p: FieldPoint, q: FieldPoint, above: bool| {
+ let lerp = |t: f32| (p.0 + (q.0 - p.0) * t, p.1 + (q.1 - p.1) * t);
+ let (mut lo, mut hi) = (0.0, 1.0);
+ for _ in 0..LINE_STEPS {
+ let mid = (lo + hi) / 2.0;
+ if pass(lerp(mid)) == above { lo = mid } else { hi = mid }
+ }
+ lerp((lo + hi) / 2.0)
+ };
+ let mut edges: HashMap<(usize, usize, bool), Option> = HashMap::new();
+ // The crossing on the edge from sample (i, j) across (`across`) or down.
+ let mut edge = |i: usize, j: usize, across: bool| {
+ *edges.entry((i, j, across)).or_insert_with(|| {
+ let (i2, j2) = if across { (i + 1, j) } else { (i, j + 1) };
+ let (a, b) = (r(i, j) >= min, r(i2, j2) >= min);
+ (a != b).then(|| cross((at(i), at(j)), (at(i2), at(j2)), a))
+ })
+ };
+ let mut segments: Vec<[FieldPoint; 2]> = vec![];
+ for i in 0..n {
+ for j in 0..n {
+ let (top, right, bottom, left) = (edge(i, j, true), edge(i + 1, j, false), edge(i, j + 1, true), edge(i, j, false));
+ match (top, right, bottom, left) {
+ (Some(t), Some(rt), Some(b), Some(l)) => {
+ // Opposite corners pass: the center says which pair of them it joins.
+ let half = 0.5 / n as f32;
+ if pass((at(i) + half, at(j) + half)) == (r(i, j) >= min) {
+ segments.extend([[t, rt], [b, l]]);
+ } else {
+ segments.extend([[t, l], [rt, b]]);
+ }
+ }
+ _ => {
+ let found: Vec = [top, right, bottom, left].into_iter().flatten().collect();
+ if let &[p, q] = found.as_slice() {
+ segments.push([p, q]);
+ }
+ }
+ }
+ }
+ }
+ // Bands narrower than the samples, along each column and then each row.
+ for across in [false, true] {
+ let point = |k: usize, t: f32| if across { (t, at(k)) } else { (at(k), t) };
+ let value = |k: usize, s: usize| if across { r(s, k) } else { r(k, s) };
+ let bands: Vec = (0..=n)
+ .map(|k| {
+ let mut found = vec![];
+ for s in 0..=n {
+ let (before, after) = (s.saturating_sub(1), (s + 1).min(n));
+ let v = value(k, s);
+ if v >= min || v < value(k, before) || (after != s && v <= value(k, after)) {
+ continue;
+ }
+ let peak = wcag::peak_between(f64::from(at(before)), f64::from(at(after)), &|t| {
+ let p = point(k, t as f32);
+ ratio_at(p.0, p.1)
+ }) as f32;
+ if pass(point(k, peak)) {
+ found.push((
+ peak,
+ cross(point(k, at(before)), point(k, peak), false),
+ cross(point(k, peak), point(k, at(after)), true),
+ ));
+ }
+ }
+ found
+ })
+ .collect();
+ for pair in bands.windows(2) {
+ let [this, next] = pair else { continue };
+ for (peak, a, b) in this {
+ if let Some((_, c, d)) = next.iter().find(|(p, ..)| (p - peak).abs() <= 1.5 / n as f32) {
+ segments.extend([[*a, *c], [*b, *d]]);
+ }
+ }
+ }
+ }
+ chain(segments)
+ })
+ .collect()
+}
+
+/// `segments` joined end to end into polylines where they share an end.
+fn chain(segments: Vec<[FieldPoint; 2]>) -> Vec> {
+ let key = |p: FieldPoint| (p.0.to_bits(), p.1.to_bits());
+ let mut ends: HashMap<(u32, u32), Vec> = HashMap::new();
+ for (s, seg) in segments.iter().enumerate() {
+ for p in seg {
+ ends.entry(key(*p)).or_default().push(s);
+ }
+ }
+ let mut used = vec![false; segments.len()];
+ let mut lines = vec![];
+ for (start, [a, b]) in segments.iter().enumerate() {
+ if used.get(start).copied().unwrap_or(true) {
+ continue;
+ }
+ if let Some(u) = used.get_mut(start) {
+ *u = true;
+ }
+ let mut line = std::collections::VecDeque::from([*a, *b]);
+ for back in [true, false] {
+ loop {
+ let end = if back { line.back() } else { line.front() };
+ let Some(end) = end.copied() else { break };
+ let next = ends.get(&key(end)).and_then(|ss| ss.iter().copied().find(|s| !used.get(*s).copied().unwrap_or(true)));
+ let Some((s, [p, q])) = next.and_then(|s| segments.get(s).map(|seg| (s, *seg))) else { break };
+ if let Some(u) = used.get_mut(s) {
+ *u = true;
+ }
+ let other = if key(p) == key(end) { q } else { p };
+ if back { line.push_back(other) } else { line.push_front(other) }
+ }
+ }
+ lines.push(line.into_iter().collect());
+ }
+ lines
+}
+
+/// The contrast lines of the wheel's square or the box's field on HSB `hsb`, kept per [`LinesKey`]:
+/// where a pick there, stored as the wheel stores it in place of `tgt`'s color, meets each minimum
+/// of the chosen category against `backdrop`.
+fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, hsb: [f32; 3], cmyk_doc: bool) -> Lines {
+ let set = &app.ui.color_wheel;
+ let (category, view, ch) = (set.contrast_for, set.view, set.channel);
+ let was = replaced(app, tgt, false);
+ // The component the field holds fixed: the box's strip value, or the wheel's hue.
+ let fixed = if view == View::Box { box_pos(ch, hsb).0 } else { hsb[0] };
+ let field = format!("{view:?} {ch:?} {fixed} {:?} {cmyk_doc}", was.map(|c| c.model()));
+ let key: LinesKey = (backdrop.clone(), category, field, under());
+ if let Some((k, lines)) = pstate::