Pick best contrast between black/white in theme::palette
This commit is contained in:
parent
ee86aea7f2
commit
72b975ec82
1 changed files with 16 additions and 8 deletions
|
|
@ -4,7 +4,7 @@ use crate::{color, Color};
|
|||
use once_cell::sync::Lazy;
|
||||
use palette::color_difference::Wcag21RelativeContrast;
|
||||
use palette::rgb::Rgb;
|
||||
use palette::{FromColor, Hsl, Lch, Mix};
|
||||
use palette::{FromColor, Hsl, Mix};
|
||||
|
||||
/// A color palette.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
|
|
@ -613,12 +613,17 @@ fn mix(a: Color, b: Color, factor: f32) -> Color {
|
|||
fn readable(background: Color, text: Color) -> Color {
|
||||
if is_readable(background, text) {
|
||||
text
|
||||
} else if to_lch(background).l < 70.0 {
|
||||
} else {
|
||||
let white_contrast = relative_contrast(background, Color::WHITE);
|
||||
let black_contrast = relative_contrast(background, Color::BLACK);
|
||||
|
||||
if white_contrast >= black_contrast {
|
||||
Color::WHITE
|
||||
} else {
|
||||
Color::BLACK
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_dark(color: Color) -> bool {
|
||||
to_hsl(color).lightness < 0.6
|
||||
|
|
@ -631,12 +636,15 @@ fn is_readable(a: Color, b: Color) -> bool {
|
|||
a_srgb.has_enhanced_contrast_text(b_srgb)
|
||||
}
|
||||
|
||||
fn to_hsl(color: Color) -> Hsl {
|
||||
Hsl::from_color(Rgb::from(color))
|
||||
fn relative_contrast(a: Color, b: Color) -> f32 {
|
||||
let a_srgb = Rgb::from(a);
|
||||
let b_srgb = Rgb::from(b);
|
||||
|
||||
a_srgb.relative_contrast(b_srgb)
|
||||
}
|
||||
|
||||
fn to_lch(color: Color) -> Lch {
|
||||
Lch::from_color(Rgb::from(color))
|
||||
fn to_hsl(color: Color) -> Hsl {
|
||||
Hsl::from_color(Rgb::from(color))
|
||||
}
|
||||
|
||||
fn from_hsl(hsl: Hsl) -> Color {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue