Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Add color() parsing and serialization
  • Loading branch information
tiaanl committed Dec 14, 2022
commit 87629211286cb8d84e078c410b3b607c3f4f6a1e
135 changes: 132 additions & 3 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use std::f32::consts::PI;
use std::fmt;
use std::{f32::consts::PI, str::FromStr};

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

Expand Down Expand Up @@ -350,6 +350,81 @@ macro_rules! impl_lch_like {
impl_lch_like!(Lch, "lch");
impl_lch_like!(Oklch, "oklch");

#[derive(Clone, Copy, PartialEq, Debug)]
pub enum PredefinedColorSpace {
Srgb,
SrgbLinear,
DisplayP3,
A98Rgb,
ProphotoRgb,
Rec2020,
XyzD50,
XyzD65,
}

impl PredefinedColorSpace {
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",
}
}
}

#[cfg(feature = "serde")]
impl Serialize for PredefinedColorSpace {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_str().serialize(serializer)
}
}

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

#[derive(Clone, Copy, PartialEq, Debug)]
pub struct ColorFunction {
pub color_space: PredefinedColorSpace,
pub red: f32,
pub green: f32,
pub blue: f32,
pub alpha: f32,
}

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_str(" ")?;
self.red.to_css(dest)?;
dest.write_str(" ")?;
self.green.to_css(dest)?;
dest.write_str(" ")?;
self.blue.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 +445,8 @@ pub enum AbsoluteColor {
/// Specifies an Oklab color by Oklab Lightness, Chroma, and hue using
/// the OKLCH cylindrical coordinate model.
Oklch(Oklch),
/// Specified a sRGB based color with a predefined color space.
ColorFunction(ColorFunction),
}

impl AbsoluteColor {
Expand All @@ -381,6 +458,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 +474,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 +650,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 +864,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 +906,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 +1153,51 @@ 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 location = arguments.current_source_location();
let color_space = arguments.try_parse(|i| {
let ident = i.expect_ident()?;
Ok(match_ignore_ascii_case! {
ident,
"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-d65" => PredefinedColorSpace::XyzD65,
_ => return Err(location.new_unexpected_token_error(Token::Ident(ident.clone())))
})
})?;

let red = component_parser
.parse_number_or_percentage(arguments)?
.unit_value();
let green = component_parser
.parse_number_or_percentage(arguments)?
.unit_value();
let blue = component_parser
.parse_number_or_percentage(arguments)?
.unit_value();

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

Ok(Color::Absolute(AbsoluteColor::ColorFunction(
ColorFunction {
color_space,
red,
green,
blue,
alpha,
},
)))
}
3 changes: 3 additions & 0 deletions src/css-parsing-tests/color4_color_function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[
"color(srgb 1 1 1 / 0.5)", "color(srgb 1 1 1 / 0.5)"
]
16 changes: 16 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,18 @@ fn color4_lab_lch_oklab_oklch() {
)
}

#[test]
fn color4_color_function() {
run_color_tests(
include_str!("css-parsing-tests/color4_color_function.json"),
|c| {
c.ok()
.map(|v| v.to_css_string().to_json())
.unwrap_or(Value::Null)
},
)
}

#[test]
fn nth() {
run_json_tests(include_str!("css-parsing-tests/An+B.json"), |input| {
Expand Down Expand Up @@ -854,6 +866,7 @@ where
}
}

#[cfg(feature = "serde")]
impl ToJson for Color {
fn to_json(&self) -> Value {
match *self {
Expand All @@ -866,6 +879,9 @@ impl ToJson for Color {
AbsoluteColor::Lch(ref c) => json!([c.lightness, c.chroma, c.hue, c.alpha]),
AbsoluteColor::Oklab(ref c) => json!([c.lightness, c.a, c.b, c.alpha]),
AbsoluteColor::Oklch(ref c) => json!([c.lightness, c.chroma, c.hue, c.alpha]),
AbsoluteColor::ColorFunction(ref c) => {
json!([c.color_space, c.red, c.green, c.blue, c.alpha])
}
},
}
}
Expand Down