Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add path parsing to BasicShape #868

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
29 changes: 21 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,14 @@ browserslist = ["browserslist-rs"]
bundler = ["dashmap", "sourcemap", "rayon"]
cli = ["atty", "clap", "serde_json", "browserslist", "jemallocator"]
grid = []
jsonschema = ["schemars", "serde", "parcel_selectors/jsonschema"]
jsonschema = ["schemars", "serde", "parcel_selectors/jsonschema", "oxvg_path/jsonschema"]
nodejs = ["dep:serde"]
serde = [
"dep:serde",
"smallvec/serde",
"cssparser/serde",
"parcel_selectors/serde",
"oxvg_path/serde",
"into_owned",
]
sourcemap = ["parcel_sourcemap"]
Expand Down Expand Up @@ -73,6 +74,7 @@ pathdiff = "0.2.1"
ahash = "0.8.7"
paste = "1.0.12"
indexmap = "2.2.6"
oxvg_path = "0.0.1-beta.4"
# CLI deps
atty = { version = "0.2", optional = true }
clap = { version = "3.0.6", features = ["derive"], optional = true }
Expand Down
12 changes: 12 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25010,6 +25010,18 @@ mod tests {
".foo { clip-path: polygon(evenodd, 50% 0%, 100% 50%, 50% 100%, 0% 50%); }",
".foo{clip-path:polygon(evenodd,50% 0%,100% 50%,50% 100%,0% 50%)}",
);
minify_test(
r#".foo { clip-path: path("M 0 0 L 0 10"); }"#,
r#".foo{clip-path:path("M0 0v10")}"#,
);
minify_test(
r#".foo { clip-path: path(nonzero, "M 0 0 L 10 20"); }"#,
r#".foo{clip-path:path("m0 0 10 20")}"#,
);
minify_test(
r#".foo { clip-path: path(evenodd, "M 0 0 L 10 20"); }"#,
r#".foo{clip-path:path(evenodd,"m0 0 10 20")}"#,
);
minify_test(
".foo { clip-path: padding-box circle(50px at 0 100px); }",
".foo{clip-path:circle(50px at 0 100px) padding-box}",
Expand Down
74 changes: 73 additions & 1 deletion src/values/shape.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! CSS shape values for masking and clipping.

use std::fmt::Write;

use super::length::LengthPercentage;
use super::position::Position;
use super::rect::Rect;
Expand All @@ -9,8 +11,9 @@ use crate::printer::Printer;
use crate::properties::border_radius::BorderRadius;
use crate::traits::{Parse, ToCss};
#[cfg(feature = "visitor")]
use crate::visitor::Visit;
use crate::visitor::{Visit, VisitTypes, Visitor};
use cssparser::*;
use oxvg_path;

/// A CSS [`<basic-shape>`](https://www.w3.org/TR/css-shapes-1/#basic-shape-functions) value.
#[derive(Debug, Clone, PartialEq)]
Expand All @@ -31,6 +34,8 @@ pub enum BasicShape {
Ellipse(Ellipse),
/// A polygon.
Polygon(Polygon),
/// A path.
Path(Path),
}

/// An [`inset()`](https://www.w3.org/TR/css-shapes-1/#funcdef-inset) rectangle shape.
Expand Down Expand Up @@ -124,6 +129,19 @@ pub struct Point {
y: LengthPercentage,
}

/// An SVG path within a `path()` shape.
///
/// See [Path](oxvg_path::Path).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
pub struct Path {
/// The fill rule used to determine the interior of the polygon.
pub fill_rule: FillRule,
/// The path data of each command in the path
pub path: oxvg_path::Path,
}

enum_property! {
/// A [`<fill-rule>`](https://www.w3.org/TR/css-shapes-1/#typedef-fill-rule) used to
/// determine the interior of a `polygon()` shape.
Expand Down Expand Up @@ -152,6 +170,7 @@ impl<'i> Parse<'i> for BasicShape {
"circle" => Ok(BasicShape::Circle(input.parse_nested_block(Circle::parse)?)),
"ellipse" => Ok(BasicShape::Ellipse(input.parse_nested_block(Ellipse::parse)?)),
"polygon" => Ok(BasicShape::Polygon(input.parse_nested_block(Polygon::parse)?)),
"path" => Ok(BasicShape::Path(input.parse_nested_block(Path::parse)?)),
_ => Err(location.new_unexpected_token_error(Token::Ident(f.clone()))),
}
}
Expand Down Expand Up @@ -233,6 +252,28 @@ impl<'i> Parse<'i> for Point {
}
}

impl<'i> Parse<'i> for Path {
fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
use oxvg_path::convert;

let fill_rule = input.try_parse(FillRule::parse);
if fill_rule.is_ok() {
input.expect_comma()?;
}

let string = input.expect_string()?.to_string();
let Ok(path) = oxvg_path::Path::parse(string) else {
return Err(input.new_custom_error(ParserError::InvalidValue));
};
let path = convert::run(&path, &convert::Options::default(), &convert::StyleInfo::conservative());

Ok(Path {
fill_rule: fill_rule.unwrap_or_default(),
path,
})
}
}

impl ToCss for BasicShape {
fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
where
Expand All @@ -259,6 +300,11 @@ impl ToCss for BasicShape {
poly.to_css(dest)?;
dest.write_char(')')
}
BasicShape::Path(path) => {
dest.write_str("path(")?;
path.to_css(dest)?;
dest.write_char(')')
}
}
}
}
Expand Down Expand Up @@ -359,3 +405,29 @@ impl ToCss for Point {
self.y.to_css(dest)
}
}

impl ToCss for Path {
fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
where
W: std::fmt::Write,
{
if self.fill_rule != FillRule::default() {
self.fill_rule.to_css(dest)?;
dest.delim(',', false)?;
}

dest.write_char('"')?;
write!(dest, "{}", self.path)?;
dest.write_char('"')?;
Ok(())
}
}

#[cfg(feature = "visitor")]
#[cfg_attr(docsrs, doc(cfg(feature = "visitor")))]
impl<'i, V: ?Sized + Visitor<'i, T>, T: Visit<'i, T, V>> Visit<'i, T, V> for Path {
const CHILD_TYPES: VisitTypes = VisitTypes::empty();
fn visit_children(&mut self, _: &mut V) -> Result<(), V::Error> {
Ok(())
}
}