Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 170 additions & 6 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use std::f32::consts::PI;
use std::fmt;
use std::str::FromStr;

use super::{BasicParseError, ParseError, Parser, ToCss, Token};

Expand Down Expand Up @@ -221,7 +222,7 @@ macro_rules! impl_lab_like {

#[cfg(feature = "serde")]
impl Serialize for $cls {
fn serialize<S>(&self, serializer: S) -> Result<serde::ser::Ok, serde::ser::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Expand All @@ -231,7 +232,7 @@ macro_rules! impl_lab_like {

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for $cls {
fn deserialize<D>(deserializer: D) -> Result<Self, serde::de::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Expand Down Expand Up @@ -309,7 +310,7 @@ macro_rules! impl_lch_like {

#[cfg(feature = "serde")]
impl Serialize for $cls {
fn serialize<S>(&self, serializer: S) -> Result<serde::ser::Ok, serde::ser::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Expand All @@ -319,7 +320,7 @@ macro_rules! impl_lch_like {

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for $cls {
fn deserialize<D>(deserializer: D) -> Result<Self, serde::de::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Expand Down Expand Up @@ -350,6 +351,122 @@ macro_rules! impl_lch_like {
impl_lch_like!(Lch, "lch");
impl_lch_like!(Oklch, "oklch");

/// A Predefined color space specified in:
/// https://w3c.github.io/csswg-drafts/css-color-4/#predefined
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum PredefinedColorSpace {
/// https://w3c.github.io/csswg-drafts/css-color-4/#predefined-sRGB
Srgb,
/// https://w3c.github.io/csswg-drafts/css-color-4/#predefined-sRGB-linear
SrgbLinear,
/// https://w3c.github.io/csswg-drafts/css-color-4/#predefined-display-p3
DisplayP3,
/// https://w3c.github.io/csswg-drafts/css-color-4/#predefined-a98-rgb
A98Rgb,
/// https://w3c.github.io/csswg-drafts/css-color-4/#predefined-prophoto-rgb
ProphotoRgb,
/// https://w3c.github.io/csswg-drafts/css-color-4/#predefined-rec2020
Rec2020,
/// https://w3c.github.io/csswg-drafts/css-color-4/#predefined-xyz
XyzD50,
/// https://w3c.github.io/csswg-drafts/css-color-4/#predefined-xyz
XyzD65,
}

impl PredefinedColorSpace {
/// Returns the string value of the predefined color space.
pub fn as_str(&self) -> &str {
match self {
PredefinedColorSpace::Srgb => "srgb",
PredefinedColorSpace::SrgbLinear => "srgb-linear",
PredefinedColorSpace::DisplayP3 => "display-p3",
PredefinedColorSpace::A98Rgb => "a98-rgb",
PredefinedColorSpace::ProphotoRgb => "prophoto-rgb",
PredefinedColorSpace::Rec2020 => "rec2020",
PredefinedColorSpace::XyzD50 => "xyz-d50",
PredefinedColorSpace::XyzD65 => "xyz-d65",
}
}
}

impl FromStr for PredefinedColorSpace {
type Err = ();

fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match_ignore_ascii_case! { s,
"srgb" => PredefinedColorSpace::Srgb,
"srgb-linear" => PredefinedColorSpace::SrgbLinear,
"display-p3" => PredefinedColorSpace::DisplayP3,
"a98-rgb" => PredefinedColorSpace::A98Rgb,
"prophoto-rgb" => PredefinedColorSpace::ProphotoRgb,
"rec2020" => PredefinedColorSpace::Rec2020,
"xyz-d50" => PredefinedColorSpace::XyzD50,
"xyz" | "xyz-d65" => PredefinedColorSpace::XyzD65,

_ => return Err(()),
})
}
}

impl ToCss for PredefinedColorSpace {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
dest.write_str(self.as_str())
}
}

/// A color specified by the color() function.
/// https://w3c.github.io/csswg-drafts/css-color-4/#color-function
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct ColorFunction {
/// The color space for this color.
pub color_space: PredefinedColorSpace,
/// The first component of the color. Either red or x.
pub c1: f32,
/// The second component of the color. Either green or y.
pub c2: f32,
/// The third component of the color. Either blue or z.
pub c3: f32,
/// The alpha component of the color.
pub alpha: f32,
}

impl ColorFunction {
/// Construct a new color function definition with the given color space and
/// color components.
pub fn new(color_space: PredefinedColorSpace, c1: f32, c2: f32, c3: f32, alpha: f32) -> Self {
Self {
color_space,
c1,
c2,
c3,
alpha,
}
}
}

impl ToCss for ColorFunction {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where
W: fmt::Write,
{
dest.write_str("color(")?;
self.color_space.to_css(dest)?;
dest.write_char(' ')?;
self.c1.to_css(dest)?;
dest.write_char(' ')?;
self.c2.to_css(dest)?;
dest.write_char(' ')?;
self.c3.to_css(dest)?;

serialize_alpha(dest, self.alpha, false)?;

dest.write_char(')')
}
}

/// An absolutely specified color.
/// https://w3c.github.io/csswg-drafts/css-color-4/#typedef-absolute-color-base
#[derive(Clone, Copy, PartialEq, Debug)]
Expand All @@ -370,6 +487,8 @@ pub enum AbsoluteColor {
/// Specifies an Oklab color by Oklab Lightness, Chroma, and hue using
/// the OKLCH cylindrical coordinate model.
Oklch(Oklch),
/// Specifies a color in a predefined color space.
ColorFunction(ColorFunction),
}

impl AbsoluteColor {
Expand All @@ -381,6 +500,7 @@ impl AbsoluteColor {
Self::Lch(c) => c.alpha,
Self::Oklab(c) => c.alpha,
Self::Oklch(c) => c.alpha,
Self::ColorFunction(c) => c.alpha,
}
}
}
Expand All @@ -396,6 +516,7 @@ impl ToCss for AbsoluteColor {
Self::Lch(lch) => lch.to_css(dest),
Self::Oklab(lab) => lab.to_css(dest),
Self::Oklch(lch) => lch.to_css(dest),
Self::ColorFunction(color_function) => color_function.to_css(dest),
}
}
}
Expand Down Expand Up @@ -571,7 +692,7 @@ impl Color {
Token::Function(ref name) => {
let name = name.clone();
return input.parse_nested_block(|arguments| {
parse_color_function(component_parser, &*name, arguments)
parse_color(component_parser, &*name, arguments)
});
}
_ => Err(()),
Expand Down Expand Up @@ -785,7 +906,7 @@ fn clamp_floor_256_f32(val: f32) -> u8 {
}

#[inline]
fn parse_color_function<'i, 't, ComponentParser>(
fn parse_color<'i, 't, ComponentParser>(
component_parser: &ComponentParser,
name: &str,
arguments: &mut Parser<'i, 't>,
Expand Down Expand Up @@ -827,6 +948,8 @@ where
Color::Absolute(AbsoluteColor::Oklch(Oklch::new(l.max(0.), c.max(0.), h, alpha)))
}),

"color" => parse_color_function(component_parser, arguments),

_ => return Err(arguments.new_unexpected_token_error(Token::Ident(name.to_owned().into()))),
}?;

Expand Down Expand Up @@ -1072,3 +1195,44 @@ where

Ok(into_color(lightness, chroma, hue, alpha))
}

#[inline]
fn parse_color_function<'i, 't, ComponentParser>(
component_parser: &ComponentParser,
arguments: &mut Parser<'i, 't>,
) -> Result<Color, ParseError<'i, ComponentParser::Error>>
where
ComponentParser: ColorComponentParser<'i>,
{
let color_space = {
let location = arguments.current_source_location();

let ident = arguments.expect_ident()?;
PredefinedColorSpace::from_str(ident)
.map_err(|_| location.new_unexpected_token_error(Token::Ident(ident.clone())))?
};

macro_rules! parse_component {
() => {{
component_parser
.parse_number_or_percentage(arguments)?
.unit_value()
}};
}

let c1 = parse_component!();
let c2 = parse_component!();
let c3 = parse_component!();

let alpha = parse_alpha(component_parser, arguments, false)?;

Ok(Color::Absolute(AbsoluteColor::ColorFunction(
ColorFunction {
color_space,
c1,
c2,
c3,
alpha,
},
)))
}
Loading