mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Color Wheel: the box and the wheel mark the contrast lines and offer the closest passing color
With Show Contrast on, the wheel's square and the box's field draw where
the color picked there meets AA (solid) and AAA (dashed) for the chosen
category, each as a white line over a black one. The field is sampled on
a 33 by 33 grid and each crossing is placed by bisection, so a line can
run across the field or up it; a passing band narrower than the samples
is found by looking for the highest ratio around a failing sample higher
than its neighbors.
When the color fails AA, or meets AA and fails AAA, a chip at the end of
the contrast row shows the closest color that passes that level, and a
click applies it. The chip keeps its space while hidden, so the row does
not move as a drag crosses a line. Screen readers read it as a button.
color.contrast takes `for` (normalText, largeText or graphics) and
answers `for` and `fix: {aa, aaa}` (no aaa for graphics): for each level,
the closest color that meets it when drawn the same way (blend modes,
opacity, translucent groups and layers, the stain of a picked symbol
object), in the model of the measured color, or null when the color
already meets it or no lightness of its hue does. The search keeps the
OKLCH hue, raises or lowers the lightness, whichever takes the smaller
step, lowers the chroma where sRGB cannot show it, and tests at most 167
colors.
Part of #978
This commit is contained in:
1 parent
8b9ef3813d
commit
cc5d3b5537
38 files changed
+946
-87
No files matched your search
@@ -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
|
||||
/// (<https://bottosson.github.io/posts/oklab/>) 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<f64> = (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]);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -141,7 +141,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<BlendMode>,
|
||||
/// The given opacity, which takes the place of the drawn ones.
|
||||
opacity: Option<f32>,
|
||||
/// 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<Color> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
(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<usize>, 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
|
||||
|
||||
@@ -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::<Vec<_>>(), ["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}");
|
||||
}
|
||||
}
|
||||
@@ -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 Гравитация
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 Βαρύτητα
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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é
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 ગ્રેવિટી
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
@@ -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 ग्रेविटी
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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ó
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
@@ -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à
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 六角形 (行)
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 행 기준 육각형
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 Гравитация
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 Гравітація
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 205 and column 5.
|
@@ -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 灰色和中性色
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 重力
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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;
|
||||
|
||||
@@ -16,14 +16,20 @@
|
||||
//! (<https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio>) 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<NodeId>, Option<Vec<u32>>, 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<NodeId>, Option<Vec<u32>>, bool, Option<usize>, Option<usize>, Option<usize>, String, Under);
|
||||
(String, String, Option<(u64, u64)>, Vec<NodeId>, Option<Vec<u32>>, bool, Option<usize>, Option<usize>, Option<usize>, 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<Vec<Vec<(f32, f32)>>>;
|
||||
|
||||
/// 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<Vec<f64>> = (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<FieldPoint>> = 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<FieldPoint> = [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<Bands> = (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<Vec<FieldPoint>> {
|
||||
let key = |p: FieldPoint| (p.0.to_bits(), p.1.to_bits());
|
||||
let mut ends: HashMap<(u32, u32), Vec<usize>> = 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::<Option<(LinesKey, Lines)>>(ui.ctx(), LINES)
|
||||
&& k == key
|
||||
{
|
||||
return lines;
|
||||
}
|
||||
let cms = cms::active();
|
||||
let at = |x: f32, y: f32| if view == View::Box { box_pick(ch, fixed, x, y, hsb) } else { [hsb[0], x, 1.0 - y] };
|
||||
let ratio_at = |x: f32, y: f32| backdrop.ratio(cms.display_rgb(&backdrop.drawn_color(&stored(&cms, at(x, y), was.as_ref(), cmyk_doc))));
|
||||
let (aa, aaa) = category.minimums();
|
||||
let minimums: Vec<f64> = std::iter::once(aa).chain(aaa).collect();
|
||||
let lines = contrast_lines(&ratio_at, &minimums);
|
||||
set_pstate(ui.ctx(), LINES, Some((key, lines.clone())));
|
||||
lines
|
||||
}
|
||||
|
||||
/// Draw `lines` (from [`contrast_lines`]) over the field in `rect`: AA solid and AAA dashed, each
|
||||
/// a light line over a dark one, as the field's marker is drawn.
|
||||
fn draw_contrast_lines(ui: &Ui, rect: Rect, lines: &Lines) {
|
||||
let painter = ui.painter().with_clip_rect(rect);
|
||||
let at = |(x, y): &(f32, f32)| egui::pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height());
|
||||
for (level, polylines) in lines.iter().enumerate() {
|
||||
for line in polylines {
|
||||
let points: Vec<egui::Pos2> = line.iter().map(at).collect();
|
||||
for stroke in [Stroke::new(3.0, Color32::BLACK), Stroke::new(1.0, Color32::WHITE)] {
|
||||
if level == 0 {
|
||||
painter.add(egui::Shape::line(points.clone(), stroke));
|
||||
} else {
|
||||
painter.extend(egui::Shape::dashed_line(&points, stroke, 4.0, 3.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The active color settings and profiles generation, which change how a color displays without
|
||||
/// a document revision (Edit › Color Settings, a document's assigned profiles).
|
||||
@@ -357,17 +575,24 @@ fn background(app: &mut VectorcraftApp, ui: &Ui) -> Option<Color> {
|
||||
Color::from_hex(&hex?)
|
||||
}
|
||||
|
||||
/// The contrast row: the background's chip, the ratio cut off at two decimals and the AA and AAA
|
||||
/// results for the chosen category; a dash when there is no background or no color to measure.
|
||||
/// Without a pinned background the row asks `color.contrast` for the color behind the selection
|
||||
/// (`against: "below"`), also during an interaction, so translucent groups and layers count as the
|
||||
/// command counts them; the chip then shows the background in the answer, else the pinned color or
|
||||
/// the one kept by [`background`].
|
||||
fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
/// The contrast row's measurement: the background it was measured against, `color.contrast`'s
|
||||
/// answer for the chosen category, and what the lines measure picks against.
|
||||
struct Measured {
|
||||
against: Option<Color>,
|
||||
answer: Option<Value>,
|
||||
backdrop: Option<Backdrop>,
|
||||
}
|
||||
|
||||
/// Measure the active color for the contrast row and the lines. Without a pinned background it
|
||||
/// asks `color.contrast` for the color behind the selection (`against: "below"`), also during an
|
||||
/// interaction, so translucent groups and layers count as the command counts them. The answer is
|
||||
/// kept per [`RatioKey`].
|
||||
fn measure(app: &mut VectorcraftApp, ui: &Ui) -> Measured {
|
||||
let category = app.ui.color_wheel.contrast_for;
|
||||
let pinned = app.ui.color_wheel.contrast_background.is_some();
|
||||
let against = background(app, ui);
|
||||
let sampled = !pinned;
|
||||
let mut backdrop = None;
|
||||
let answer = against.as_ref().and_then(|bg| {
|
||||
let st = app.session.active();
|
||||
let key: RatioKey = (
|
||||
@@ -382,27 +607,51 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
app.session.selected_freeform_point(),
|
||||
app.session.prefs.black_on_screen.clone(),
|
||||
under(),
|
||||
category,
|
||||
);
|
||||
match pstate::<Option<(RatioKey, Option<Value>)>>(ui.ctx(), RATIO) {
|
||||
Some((k, r)) if k == key => r,
|
||||
let kept = pstate::<Option<(RatioKey, Option<Value>)>>(ui.ctx(), RATIO);
|
||||
let kept_backdrop = pstate::<Option<(RatioKey, Option<Backdrop>)>>(ui.ctx(), BACKDROP);
|
||||
match (kept, kept_backdrop) {
|
||||
(Some((k, r)), Some((kb, b))) if k == key && kb == key => {
|
||||
backdrop = b;
|
||||
r
|
||||
}
|
||||
_ => {
|
||||
let against = if sampled { json!("below") } else { color_json(bg) };
|
||||
let r = app.session.execute("color.contrast", &json!({ "against": against })).ok();
|
||||
set_pstate(ui.ctx(), RATIO, Some((key, r.clone())));
|
||||
let m = contrast_measure(&app.session, &json!({ "against": against, "for": category.id() })).ok();
|
||||
let (r, b) = m.map_or((None, None), |(r, b)| (Some(r), Some(b)));
|
||||
set_pstate(ui.ctx(), RATIO, Some((key.clone(), r.clone())));
|
||||
set_pstate(ui.ctx(), BACKDROP, Some((key, b.clone())));
|
||||
backdrop = b;
|
||||
r
|
||||
}
|
||||
}
|
||||
});
|
||||
Measured { against, answer, backdrop }
|
||||
}
|
||||
|
||||
/// The contrast row: the background's chip, the ratio cut off at two decimals, the AA and AAA
|
||||
/// results for the chosen category, and a chip of the closest color that passes the first level the
|
||||
/// color fails; a dash when there is no background or no color to measure. Without a pinned
|
||||
/// background the first chip shows the background in the answer, else the pinned color or the one
|
||||
/// kept by [`background`]. The fix chip keeps its space while hidden. Returns the fix color when its
|
||||
/// chip is clicked.
|
||||
fn contrast_row(app: &VectorcraftApp, ui: &mut Ui, m: &Measured) -> Option<Color> {
|
||||
let category = app.ui.color_wheel.contrast_for;
|
||||
let pinned = app.ui.color_wheel.contrast_background.is_some();
|
||||
let sampled = !pinned;
|
||||
let (against, answer) = (m.against, m.answer.as_ref());
|
||||
let mut clicked = None;
|
||||
let resp = ui
|
||||
.horizontal(|ui| {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::hover());
|
||||
// The chip shows the background the ratio was measured against.
|
||||
let measured = answer.as_ref().filter(|_| sampled).and_then(|r| r["against"].as_str()).and_then(Color::from_hex);
|
||||
let measured = answer.filter(|_| sampled).and_then(|r| r["against"].as_str()).and_then(Color::from_hex);
|
||||
match measured.or(against) {
|
||||
Some(c) => widgets::swatch_tile(ui, rect, &Paint::solid(c), false, false),
|
||||
None => widgets::swatch_tile(ui, rect, &Paint::None, false, false),
|
||||
}
|
||||
let Some(ratio) = answer.as_ref().and_then(|r| r["ratio"].as_f64()) else {
|
||||
let Some(ratio) = answer.and_then(|r| r["ratio"].as_f64()) else {
|
||||
ui.label("—");
|
||||
return;
|
||||
};
|
||||
@@ -413,6 +662,7 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if let Some(aaa) = aaa {
|
||||
ui.label(format!("AAA {}", result(aaa)));
|
||||
}
|
||||
clicked = fix_chip(ui, answer, aa, aaa);
|
||||
})
|
||||
.response;
|
||||
let mut tip = tl!(
|
||||
@@ -424,6 +674,35 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
tip.push_str(tl!("The background is read at the center of the selection."));
|
||||
}
|
||||
resp.on_hover_text(tip);
|
||||
clicked
|
||||
}
|
||||
|
||||
/// The fix chip at the end of the contrast row: the closest color that passes AA when the color
|
||||
/// fails AA (`aa`), else AAA when it fails AAA (`aaa`), from `color.contrast`'s `fix`. Its space is
|
||||
/// kept while there is none, so the row does not move as a drag crosses a line. Returns the color
|
||||
/// when the chip is clicked or activated.
|
||||
fn fix_chip(ui: &mut Ui, answer: Option<&Value>, aa: bool, aaa: Option<bool>) -> Option<Color> {
|
||||
let level = if !aa {
|
||||
Some(("aa", "AA"))
|
||||
} else if aaa == Some(false) {
|
||||
Some(("aaa", "AAA"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let fix = level.and_then(|(key, name)| {
|
||||
let v = answer?.get("fix")?.get(key)?;
|
||||
serde_json::from_value::<Color>(v.clone()).ok().map(|c| (c, name))
|
||||
});
|
||||
let Some((color, name)) = fix else {
|
||||
ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::hover());
|
||||
return None;
|
||||
};
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::click());
|
||||
widgets::swatch_tile(ui, rect, &Paint::solid(color), false, false);
|
||||
let label = crate::i18n::fmt(tl!("The closest color that passes {level}: click to apply it."), &[("level", name)]);
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &label));
|
||||
let resp = resp.on_hover_text(&label);
|
||||
resp.clicked().then_some(color)
|
||||
}
|
||||
|
||||
/// What the HSB picked last belongs to: the document, the selected objects or text characters,
|
||||
@@ -528,7 +807,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
(c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)),
|
||||
};
|
||||
let marked = color.is_some();
|
||||
let measured = app.ui.color_wheel.contrast.then(|| measure(app, ui));
|
||||
let mut pick: Option<([f32; 3], Live)> = None;
|
||||
let mut field_rect = Rect::NOTHING;
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(44.0);
|
||||
@@ -536,11 +817,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
let size = ui.available_width().min(MAX_WHEEL);
|
||||
if app.ui.color_wheel.view == View::Box {
|
||||
pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size);
|
||||
(pick, field_rect) = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size);
|
||||
return;
|
||||
}
|
||||
let ring = widgets::hue_ring(ui, "color-wheel-ring", tl!("Hue ring"), size, hsb[0], marked);
|
||||
let square = widgets::ring_square(ring.rect);
|
||||
field_rect = square;
|
||||
let mut field_ui = ui.new_child(UiBuilder::new().id_salt("color-wheel-square").max_rect(square));
|
||||
let axes =
|
||||
[FieldAxis { name: tl!("Saturation"), units: 100.0, suffix: "%" }, FieldAxis { name: tl!("Brightness"), units: 100.0, suffix: "%" }];
|
||||
@@ -562,12 +844,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
pick = Some(([hsb[0], x, 1.0 - y], field_phase));
|
||||
}
|
||||
});
|
||||
if app.ui.color_wheel.contrast {
|
||||
contrast_row(app, ui);
|
||||
let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk);
|
||||
if let Some(m) = &measured {
|
||||
if let Some(backdrop) = &m.backdrop {
|
||||
let lines = lines_for(app, ui, backdrop, &tgt, hsb, cmyk_doc);
|
||||
draw_contrast_lines(ui, field_rect, &lines);
|
||||
}
|
||||
if let Some(c) = contrast_row(app, ui, m) {
|
||||
apply(app, &tgt, c, Live::Released, false);
|
||||
}
|
||||
}
|
||||
let Some((hsb, phase)) = pick else { return };
|
||||
let behind = super::alt_held(ui);
|
||||
let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk);
|
||||
let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc);
|
||||
apply(app, &tgt, c, phase, behind);
|
||||
if !behind {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! The Color Wheel panel's contrast lines on the box's field and the wheel's square, and the chip of
|
||||
//! the closest passing color in the contrast row, drawn headless.
|
||||
|
||||
use egui::vec2;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint, cms, hsb_to_rgb};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::color_wheel::{LINES, Lines, LinesKey, box_pick, show};
|
||||
use super::pstate;
|
||||
use crate::VectorcraftApp;
|
||||
use crate::dialogs::color_picker::Channel;
|
||||
|
||||
/// An app with a selected rectangle filled with #FDC96E, the contrast row shown against a pinned
|
||||
/// #355F78 (4.4963:1, just under AA for normal text), and `view` with `channel`.
|
||||
fn app(view: &str, channel: &str) -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#fdc96e"})).unwrap();
|
||||
app.run("ui.colorWheel", json!({"contrast": true, "contrastBackground": "#355f78", "view": view, "channel": channel})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> {
|
||||
let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state(
|
||||
|ui, app: &mut VectorcraftApp| {
|
||||
show(app, ui);
|
||||
// The height the panel took, for the test that checks nothing moves.
|
||||
let h = ui.min_rect().height();
|
||||
ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique("panel-height"), h));
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(2);
|
||||
h
|
||||
}
|
||||
|
||||
fn lines(h: &Harness<'static, VectorcraftApp>) -> Lines {
|
||||
pstate::<Option<(LinesKey, Lines)>>(&h.ctx, LINES).expect("the field's contrast lines were found").1
|
||||
}
|
||||
|
||||
/// Whether the color picked at field point (x, y) meets AA for normal text against #355F78, as
|
||||
/// `color.contrast` answers it; `hsb_at` maps the point to the HSB the field picks there.
|
||||
fn passes_aa(h: &mut Harness<'static, VectorcraftApp>, hsb_at: &dyn Fn(f32, f32) -> [f32; 3], (x, y): (f32, f32)) -> bool {
|
||||
let [r, g, b] = hsb_to_rgb(hsb_at(x, y));
|
||||
let r = h.state_mut().session.execute("color.contrast", &json!({"color": [r, g, b], "against": "#355f78"})).unwrap();
|
||||
r["normalText"]["aa"].as_bool().unwrap()
|
||||
}
|
||||
|
||||
/// The middle point of the longest AA line, and the points a little above and below it.
|
||||
fn either_side(lines: &Lines) -> [(f32, f32); 2] {
|
||||
let aa = lines.first().expect("an AA level");
|
||||
let line = aa.iter().max_by_key(|l| l.len()).expect("an AA line");
|
||||
let (x, y) = line[line.len() / 2];
|
||||
[(x, (y - 0.04).max(0.0)), (x, (y + 0.04).min(1.0))]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_box_marks_where_its_colors_meet_aa() {
|
||||
let mut h = harness(app("box", "hue"));
|
||||
let lines = lines(&h);
|
||||
assert_eq!(lines.len(), 2, "AA and AAA for normal text");
|
||||
let hsb = vectorcraft_color::rgb_to_hsb(cms::active().display_rgb(&Color::from_hex("#fdc96e").unwrap()));
|
||||
let z = super::color_wheel::box_pos(Channel::Hue, hsb).0;
|
||||
let at = move |x: f32, y: f32| box_pick(Channel::Hue, z, x, y, hsb);
|
||||
let [above, below] = either_side(&lines);
|
||||
let (a, b) = (passes_aa(&mut h, &at, above), passes_aa(&mut h, &at, below));
|
||||
assert_ne!(a, b, "the points either side of the line fall on either side of AA");
|
||||
// Against a dark background the lighter colors, at the top, pass.
|
||||
assert!(a && !b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wheels_square_marks_where_its_colors_meet_aa() {
|
||||
let mut h = harness(app("wheel", "hue"));
|
||||
let lines = lines(&h);
|
||||
let hsb = vectorcraft_color::rgb_to_hsb(cms::active().display_rgb(&Color::from_hex("#fdc96e").unwrap()));
|
||||
let at = move |x: f32, y: f32| [hsb[0], x, 1.0 - y];
|
||||
let [above, below] = either_side(&lines);
|
||||
assert!(passes_aa(&mut h, &at, above) && !passes_aa(&mut h, &at, below));
|
||||
}
|
||||
|
||||
/// White with Difference over a pinned #757575: in the gray box (saturation 0) only grays within a
|
||||
/// few hundredths of #757575 draw dark enough for AA, a band narrower than the samples.
|
||||
#[test]
|
||||
fn a_band_narrower_than_the_samples_gets_its_lines() {
|
||||
let mut app = app("box", "saturation");
|
||||
app.run("paint.setFill", json!({"color": "#ffffff"})).unwrap();
|
||||
app.run("transparency.set", json!({"blend": "difference"})).unwrap();
|
||||
app.run("ui.colorWheel", json!({"contrastBackground": "#757575"})).unwrap();
|
||||
let mut h = harness(app);
|
||||
let lines = lines(&h);
|
||||
let aa = lines.first().expect("an AA level");
|
||||
assert!(aa.len() >= 2, "a line on each side of the band: {aa:?}");
|
||||
h.state_mut().run("paint.setFill", json!({"color": "#757575"})).unwrap();
|
||||
let r = h.state_mut().session.execute("color.contrast", &json!({"against": "#757575"})).unwrap();
|
||||
assert!(r["normalText"]["aa"] == true, "#757575 draws black and passes: {r}");
|
||||
}
|
||||
|
||||
/// Multiply over a pinned #FF0000 keeps only the red of a pick, so in the blue box (red across)
|
||||
/// the contrast changes across and not up: the AA line runs top to bottom.
|
||||
#[test]
|
||||
fn a_line_that_runs_up_the_field_is_found() {
|
||||
let mut app = app("box", "blue");
|
||||
app.run("transparency.set", json!({"blend": "multiply"})).unwrap();
|
||||
app.run("ui.colorWheel", json!({"contrastBackground": "#ff0000"})).unwrap();
|
||||
let h = harness(app);
|
||||
let lines = lines(&h);
|
||||
let line = lines.first().and_then(|aa| aa.iter().max_by_key(|l| l.len())).expect("an AA line");
|
||||
let (xs, ys): (Vec<f32>, Vec<f32>) = line.iter().copied().unzip();
|
||||
let spread = |v: &[f32]| v.iter().copied().fold(f32::NEG_INFINITY, f32::max) - v.iter().copied().fold(f32::INFINITY, f32::min);
|
||||
assert!(spread(&ys) > 0.9 && spread(&xs) < 0.05, "{line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphics_have_one_line() {
|
||||
let mut app = app("box", "saturation");
|
||||
app.run("ui.colorWheel", json!({"contrastFor": "graphics"})).unwrap();
|
||||
let h = harness(app);
|
||||
assert_eq!(lines(&h).len(), 1, "graphics have AA only");
|
||||
}
|
||||
|
||||
const CHIP: &str = "The closest color that passes AA: click to apply it.";
|
||||
|
||||
#[test]
|
||||
fn the_chip_applies_the_fix_color_answers() {
|
||||
let mut h = harness(app("wheel", "hue"));
|
||||
let want = h.state_mut().session.execute("color.contrast", &json!({"against": "#355f78"})).unwrap();
|
||||
let fix: Color = serde_json::from_value(want["fix"]["aa"].clone()).unwrap();
|
||||
h.get_by_label(CHIP).click();
|
||||
h.run_steps(2);
|
||||
match h.state().session.proxy_paints().0 {
|
||||
Paint::Solid { color, .. } => assert_eq!(color, fix),
|
||||
other => panic!("the fill is {other:?}"),
|
||||
}
|
||||
assert!(h.query_by_label(CHIP).is_none(), "the color now passes AA: no chip");
|
||||
assert!(h.query_by_label("AA Pass").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_chip_offers_aaa_once_aa_passes_and_nothing_once_both_pass() {
|
||||
let mut app = app("wheel", "hue");
|
||||
app.run("ui.colorWheel", json!({"contrastFor": "largeText"})).unwrap();
|
||||
let h = harness(app);
|
||||
assert!(h.query_by_label(CHIP).is_none(), "4.49:1 meets large text AA");
|
||||
assert!(h.query_by_label("The closest color that passes AAA: click to apply it.").is_some());
|
||||
let mut app = self::app("wheel", "hue");
|
||||
app.run("paint.setFill", json!({"color": "#ffffff"})).unwrap();
|
||||
app.run("ui.colorWheel", json!({"contrastFor": "largeText"})).unwrap();
|
||||
let h = harness(app);
|
||||
assert!(h.query_by_label_contains("The closest color that passes").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_panel_keeps_its_height_when_the_chip_goes() {
|
||||
let height = |fill: &str| {
|
||||
let mut app = app("box", "hue");
|
||||
app.run("paint.setFill", json!({"color": fill})).unwrap();
|
||||
let h = harness(app);
|
||||
h.ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("panel-height"))).expect("a height")
|
||||
};
|
||||
// #FDC96E fails AA and shows the chip; #FFFFFF passes both levels and hides it.
|
||||
assert_eq!(height("#fdc96e"), height("#ffffff"));
|
||||
}
|
||||
@@ -234,11 +234,12 @@ its variation grid; the panel draws the same grid. `ui.colorGuideOptions` opens
|
||||
as `ui.color_guide` (`variation`, `steps`, `amount`). Save Colors as Swatches runs `swatch.new {colors: [...]}`
|
||||
(one swatch per colour, one undo step).
|
||||
|
||||
Color Wheel contrast: `color.contrast {color?, against?, opacity?}` answers the WCAG 2 contrast ratio of the active
|
||||
proxy's color against the color drawn behind the selection (`against: "below"`, the default) or against a given color,
|
||||
with the AA and AAA results for normal text, large text and graphics (docs/mcp.md). The Color Wheel panel's Show
|
||||
Contrast row shows the same answer for the category picked under Contrast For; `ui.colorWheel {contrast?, contrastFor?,
|
||||
contrastBackground?}` sets the row, its category and a pinned background, and `ui.inspect` reports them as
|
||||
Color Wheel contrast: `color.contrast {color?, against?, opacity?, for?}` answers the WCAG 2 contrast ratio of the
|
||||
active proxy's color against the color drawn behind the selection (`against: "below"`, the default) or against a given
|
||||
color, with the AA and AAA results for normal text, large text and graphics, and as `fix` the closest color of the same
|
||||
hue that meets each level of the category `for` names (docs/mcp.md). The Color Wheel panel's Show Contrast row shows
|
||||
the same answer for the category picked under Contrast For, with a chip of the fix color; `ui.colorWheel {contrast?,
|
||||
contrastFor?, contrastBackground?}` sets the row, its category and a pinned background, and `ui.inspect` reports them as
|
||||
`ui.color_wheel`.
|
||||
|
||||
Color Guide Limit to Library: `ui.colorGuideLimit {library}` (a swatch library id or name, `"document"` for the
|
||||
|
||||
+11
-3
@@ -658,7 +658,10 @@ the list return an error and change nothing. `{"contrast": true}` shows Show Con
|
||||
box, `contrastFor` (`normalText`, `largeText` or `graphics`) picks the category its AA and AAA results are for, and
|
||||
`contrastBackground` (a color, or `null` for the color behind the selection) pins the background it measures against,
|
||||
as `color.contrast` below answers it. The command returns `{view, channel, contrast, contrastFor,
|
||||
contrastBackground}`, and the settings are kept with the preferences.
|
||||
contrastBackground}`, and the settings are kept with the preferences. With the row shown, the wheel's square and the
|
||||
box's field draw lines where the color picked there meets AA (solid) and AAA (dashed) for the category, and when the
|
||||
color fails a level, a chip at the end of the row shows `color.contrast`'s `fix` for the first level it fails; a click
|
||||
applies it.
|
||||
|
||||
In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's
|
||||
screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop
|
||||
@@ -1065,7 +1068,7 @@ panel's Limit to Library does (`ui.colorGuideLimit`); Recolor Artwork's `limitTo
|
||||
that is not a string, such as `5`, names no library and gets the same error as an unknown name; `null` or `""` sets no
|
||||
limit.
|
||||
|
||||
`color.contrast {color?, against?, opacity?}` answers the WCAG 2 contrast ratio
|
||||
`color.contrast {color?, against?, opacity?, for?}` answers the WCAG 2 contrast ratio
|
||||
([definition](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio)) of a color against a background, from 1 to 21, and
|
||||
whether it meets AA and AAA for normal text (4.5:1 and 7:1), large text (3:1 and 4.5:1) and graphics (3:1, AA only):
|
||||
`{ratio, against, normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}`. The results compare the unrounded
|
||||
@@ -1087,7 +1090,12 @@ selected objects that draw one color with different blend modes, or at different
|
||||
`"below"`, also in different translucent groups or layers), where hidden objects do not count; and a proxy of None, a
|
||||
pattern or a hidden row without `color`. `against` in the answer is the background as a working RGB `#rrggbb`, the form
|
||||
`against` takes; the sampled background is rounded to 8 bits, so giving it back answers the same ratio. Headless MCP
|
||||
answers it too.
|
||||
answers it too. The answer also has `for` (the category `for` names: `normalText`, the default, `largeText` or
|
||||
`graphics`) and `fix: {aa, aaa}` (no `aaa` for graphics): for each level of that category, the closest color that
|
||||
meets it when drawn the same way, in the model of the measured color, as the Color Wheel stores a pick. The search
|
||||
keeps the color's [OKLCH](https://bottosson.github.io/posts/oklab/) hue, raises or lowers its lightness, whichever
|
||||
takes the smaller step, and lowers its chroma where sRGB cannot show it. A level is `null` when the color already meets
|
||||
it, or when no lightness of the hue does (white on `#355f78` is 6.87:1, so no color meets 7:1 there).
|
||||
|
||||
Color Themes (local only: no online service) keeps five-colour themes in the preferences. `colorTheme.save
|
||||
{colors: [...]}` saves up to five colours as they are, `colorTheme.save {color, rule}` saves the five-colour theme a
|
||||
|
||||
@@ -1651,7 +1651,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel.
|
||||
- **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given.
|
||||
- **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged.
|
||||
The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics. `color.contrast` answers the same for agents.
|
||||
The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics. `color.contrast` answers the same for agents. With the row shown, the wheel's square and the box's field draw the AA and AAA lines, and a chip in the row offers the closest color of the same hue that passes, which `color.contrast` answers as `fix`.
|
||||
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
|
||||
Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode").
|
||||
Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`.
|
||||
|
||||
Reference in new issue
Block a user