From 3f22d5683a03f0bc7006744b04a50b4bc38f2918 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Wed, 6 Aug 2025 05:55:33 +0200 Subject: [PATCH] Expose `relative_luminance` as part of `Color` --- core/src/color.rs | 7 +++++++ core/src/theme/palette.rs | 10 ++-------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/core/src/color.rs b/core/src/color.rs index 65a47781..ad60592a 100644 --- a/core/src/color.rs +++ b/core/src/color.rs @@ -195,6 +195,13 @@ impl Color { ..self } } + + /// Returns the relative luminance of the [`Color`]. + /// https://www.w3.org/TR/WCAG21/#dfn-relative-luminance + pub fn relative_luminance(self) -> f32 { + let linear = self.into_linear(); + 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2] + } } impl From<[f32; 3]> for Color { diff --git a/core/src/theme/palette.rs b/core/src/theme/palette.rs index 08a80a26..77189730 100644 --- a/core/src/theme/palette.rs +++ b/core/src/theme/palette.rs @@ -716,17 +716,11 @@ fn is_readable(a: Color, b: Color) -> bool { // https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio fn relative_contrast(a: Color, b: Color) -> f32 { - let lum_a = relative_luminance(a); - let lum_b = relative_luminance(b); + let lum_a = a.relative_luminance(); + let lum_b = b.relative_luminance(); (lum_a.max(lum_b) + 0.05) / (lum_a.min(lum_b) + 0.05) } -// https://www.w3.org/TR/WCAG21/#dfn-relative-luminance -fn relative_luminance(color: Color) -> f32 { - let linear = color.into_linear(); - 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2] -} - // https://en.wikipedia.org/wiki/Oklab_color_space#Conversions_between_color_spaces fn to_oklch(color: Color) -> Oklch { let [r, g, b, alpha] = color.into_linear();