1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
mod color;
mod merge_blocks;
mod merge_m_n_p;
mod merge_media;
mod merge_shorthand;
mod transformer;

use crate::optimizations::color::optimize_color;
use crate::optimizations::merge_blocks::MergeBlocks;
use crate::optimizations::merge_m_n_p::Merge;
use crate::optimizations::merge_media::MergeMedia;
use crate::optimizations::merge_shorthand::MergeShortHand;
use crate::optimizations::transformer::{Transform, Transformer, TransformerParameterFn};
use crate::parsers::css_entity::parse_css;
use crate::structure::Value;
use derive_more::{From, Into};
use nom::lib::std::fmt::Debug;
use nom::lib::std::str::FromStr;
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;

/// Struct which stores all optimizations from css minify lib
pub struct Minifier {
    transformer: Transformer,
    merge_m_n_p: Merge,
    merge_shorthand: MergeShortHand,
    media: MergeMedia,
    blocks: MergeBlocks,
}

impl Minifier {
    /// Minify css input and return result with minified css string
    pub fn minify<'a>(&mut self, input: &'a str, level: Level) -> MResult<'a> {
        let mut result = parse_css(input)
            .map(|(_, blocks)| blocks)
            .map_err(MError::from);

        if level == Level::Three {
            result = result
                .map(|blocks| self.blocks.transform_many(blocks))
                .map(|blocks| self.media.transform_many(blocks))
        }

        if level >= Level::Two {
            result = result
                .map(|blocks| self.merge_m_n_p.transform_many(blocks))
                .map(|blocks| self.merge_shorthand.transform_many(blocks))
        }

        if level >= Level::One {
            result = result.map(|blocks| self.transformer.transform_many(blocks))
        }

        result.map(|blocks| blocks.to_string())
    }
}

impl Default for Minifier {
    fn default() -> Self {
        let mut transformer = Transformer::default();
        transformer.register_parameter(TransformerParameterFn::Value(Box::new(|value| {
            optimize_color(&value).into()
        })));
        transformer.register_parameter(TransformerParameterFn::Value(Box::new(|mut value| {
            if value.starts_with("0px") {
                value = format!("0{}", value.trim_start_matches("0px"))
            }
            if value.starts_with("0rem") {
                value = format!("0{}", value.trim_start_matches("0rem"))
            }
            if value.starts_with("0.") {
                value = format!(".{}", value.trim_start_matches("0."))
            }
            value
                .replace(" 0px", " 0")
                .replace(" 0rem", " 0")
                .replace(" 0.", " .")
                .replace(", ", ",")
                .replace(" !important", "!important")
        })));

        transformer.register_parameter(TransformerParameterFn::Name(Box::new(|name| {
            name.to_lowercase()
        })));

        let merge_m_n_p = Merge::default();
        let merge_shorthand = MergeShortHand::default();
        let media = MergeMedia::default();
        let blocks = MergeBlocks::default();

        Minifier {
            merge_m_n_p,
            merge_shorthand,
            transformer,
            media,
            blocks,
        }
    }
}

/// Transforming level
#[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Copy, Clone)]
pub enum Level {
    /// Disable transformer
    Zero = 0,
    /// Remove whitespaces, replace `0.` to `.` and others non dangerous optimizations
    /// It's default level
    One = 1,
    /// Level One + shortcuts (margins, paddings, backgrounds and etc)
    /// In mostly cases it's non dangerous optimizations, but be careful
    Two = 2,
    /// Level Two + merge @media and css blocks with equal screen/selectors
    /// It is a danger optimizations, because ordering of your css code may be changed
    Three = 3,
}

impl Default for Level {
    fn default() -> Self {
        Self::One
    }
}

impl FromStr for Level {
    type Err = ParseLevelError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "0" => Ok(Level::Zero),
            "1" => Ok(Level::One),
            "2" => Ok(Level::Two),
            "3" => Ok(Level::Three),
            _ => Err(ParseLevelError),
        }
    }
}

#[derive(Default, Copy, Clone)]
pub struct ParseLevelError;

impl Display for ParseLevelError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Input must be number from 0 to 3 values")
    }
}

impl Debug for ParseLevelError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParseLevelError")
            .field(
                "message",
                &"Input must be number from 0 to 3 values".to_string(),
            )
            .finish()
    }
}

impl Error for ParseLevelError {}

pub type MResult<'a> = Result<String, MError<'a>>;

#[derive(Debug, From, Into, PartialEq)]
pub struct MError<'a>(nom::Err<nom::error::Error<&'a str>>);

impl Display for MError<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Invalid css")
    }
}

impl<'a> Error for MError<'a> {}

#[inline]
pub(crate) fn if_some_has_important(input: Option<&Value>) -> bool {
    if let Some(input) = input {
        return input.ends_with("!important");
    }
    true
}

#[inline]
pub(crate) fn none_or_has_important(input: Option<&Value>) -> bool {
    if let Some(input) = input {
        return input.ends_with("!important");
    }
    false
}

#[cfg(test)]
mod test {
    use crate::optimizations::{Level, Minifier};

    #[test]
    fn test_minify() {
        assert_eq!(
            Minifier::default().minify(
                r#"
                #some_id, input {
                    padding: 5px 3px; /* Mega comment */
                    color: white;
                }
                
                
                /* this is are test id */
                #some_id_2, .class {
                    padding: 5px 4px; /* Mega comment */
                    Color: rgb(255, 255, 255);
                }
            "#,
                    Level::Three
            ),
            Ok("#some_id,input{color:white;padding:5px 3px}#some_id_2,.class{color:#fff;padding:5px 4px}".into())
        )
    }
}