theme: Fix lighten, darken method. (#483)

Close #332
This commit is contained in:
Jason Lee 2024-12-10 17:35:44 +08:00 committed by GitHub
parent 9f0f05af2d
commit cf090923a7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 41 additions and 4 deletions

View file

@ -576,7 +576,11 @@ impl ButtonVariant {
let bg = match self {
ButtonVariant::Primary => cx.theme().primary_active,
ButtonVariant::Secondary | ButtonVariant::Outline | ButtonVariant::Ghost => {
cx.theme().secondary_active
if cx.theme().mode.is_dark() {
cx.theme().secondary.lighten(0.2).opacity(0.8)
} else {
cx.theme().secondary.darken(0.2).opacity(0.8)
}
}
ButtonVariant::Danger => cx.theme().destructive_active,
ButtonVariant::Link => cx.theme().transparent,
@ -605,7 +609,11 @@ impl ButtonVariant {
let bg = match self {
ButtonVariant::Primary => cx.theme().primary_active,
ButtonVariant::Secondary | ButtonVariant::Outline | ButtonVariant::Ghost => {
cx.theme().secondary_active
if cx.theme().mode.is_dark() {
cx.theme().secondary.lighten(0.2).opacity(0.8)
} else {
cx.theme().secondary.darken(0.2).opacity(0.8)
}
}
ButtonVariant::Danger => cx.theme().destructive_active,
ButtonVariant::Link => cx.theme().transparent,

View file

@ -119,15 +119,19 @@ impl Colorize for Hsla {
}
/// Return a new color with the lightness increased by the given factor.
///
/// factor range: 0.0 .. 1.0
fn lighten(&self, factor: f32) -> Hsla {
let l = self.l + (1.0 - self.l) * factor.clamp(0.0, 1.0).min(1.0);
let l = self.l * (1.0 + factor.clamp(0.0, 1.0));
Hsla { l, ..*self }
}
/// Return a new color with the darkness increased by the given factor.
///
/// factor range: 0.0 .. 1.0
fn darken(&self, factor: f32) -> Hsla {
let l = self.l * (1.0 - factor.clamp(0.0, 1.0).min(1.0));
let l = self.l * (1.0 - factor.clamp(0.0, 1.0));
Hsla { l, ..*self }
}
@ -544,3 +548,28 @@ impl ThemeMode {
matches!(self, Self::Dark)
}
}
#[cfg(test)]
mod tests {
use crate::theme::Colorize as _;
#[test]
fn test_lighten() {
let color = super::hsl(240.0, 5.0, 30.0);
let color = color.lighten(0.5);
assert_eq!(color.l, 0.45000002);
let color = color.lighten(0.5);
assert_eq!(color.l, 0.675);
let color = color.lighten(0.1);
assert_eq!(color.l, 0.7425);
}
#[test]
fn test_darken() {
let color = super::hsl(240.0, 5.0, 96.0);
let color = color.darken(0.5);
assert_eq!(color.l, 0.48);
let color = color.darken(0.5);
assert_eq!(color.l, 0.24);
}
}