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

minify selectors #696

Open
wants to merge 1 commit 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions selectors/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use cssparser::{Parser as CssParser, ToCss, Token};
use precomputed_hash::PrecomputedHash;
use smallvec::{smallvec, SmallVec};
use std::borrow::Borrow;
use std::collections::HashSet;
use std::fmt::{self, Debug};
use std::iter::Rev;
use std::slice;
Expand Down Expand Up @@ -540,6 +541,28 @@ impl<'i, Impl: SelectorImpl<'i>> SelectorList<'i, Impl> {
}
}

pub fn minify(&mut self) {
self
.0
.iter()
.enumerate()
.fold(
(HashSet::with_capacity(self.0.len()), Vec::with_capacity(self.0.len())),
|(mut seen, mut to_remove), (i, selector)| {
if !seen.insert(selector.to_css_string()) {
to_remove.push(i);
}
(seen, to_remove)
},
)
.1
.into_iter()
.rev()
.for_each(|i| {
self.0.remove(i);
});
}

/// Creates a new SelectorList.
pub fn new(v: SmallVec<[Selector<'i, Impl>; 1]>) -> Self {
SelectorList(v)
Expand Down
12 changes: 12 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8872,6 +8872,18 @@ mod tests {

#[test]
fn test_merge_rules() {
test(
r#"
.foo, .bar, .foo {
color: red;
}
"#,
indoc! {r#"
.foo, .bar {
color: red;
}
"#},
);
test(
r#"
.foo {
Expand Down
2 changes: 2 additions & 0 deletions src/rules/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ impl<'i, T: Clone> StyleRule<'i, T> {
context: &mut MinifyContext<'_, 'i>,
parent_is_unused: bool,
) -> Result<bool, MinifyError> {
self.selectors.minify();

let mut unused = false;
if !context.unused_symbols.is_empty() {
if is_unused(&mut self.selectors.0.iter(), &context.unused_symbols, parent_is_unused) {
Expand Down