-
Notifications
You must be signed in to change notification settings - Fork 167
/
css.rs
218 lines (193 loc) · 6.14 KB
/
css.rs
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
216
217
218
/*
[parcel css] - A CSS parser, transformer, and minifier written in Rust.
https://github.com/parcel-bundler/parcel-css
MPL-2.0 License
! below code was copied from https://github.com/parcel-bundler/parcel-css/blob/510df4e2d825927115427b690d6706da395d2170/node/src/lib.rs, and removed node napi code
*/
use parcel_css::bundler::BundleErrorKind;
use parcel_css::css_modules::CssModuleExports;
use parcel_css::dependencies::Dependency;
use parcel_css::error::{Error, MinifyErrorKind, ParserError, PrinterErrorKind};
use parcel_css::stylesheet::{MinifyOptions, ParserOptions, PrinterOptions, PseudoClasses, StyleSheet};
use parcel_css::targets::Browsers;
use parcel_sourcemap::SourceMap;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct SourceMapJson<'a> {
version: u8,
mappings: String,
sources: &'a Vec<String>,
sources_content: &'a Vec<String>,
names: &'a Vec<String>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransformResult {
code: String,
map: Option<String>,
exports: Option<CssModuleExports>,
dependencies: Option<Vec<Dependency>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Config {
pub targets: Option<Browsers>,
pub minify: Option<bool>,
pub source_map: Option<bool>,
pub drafts: Option<Drafts>,
pub css_modules: Option<bool>,
pub analyze_dependencies: Option<bool>,
pub pseudo_classes: Option<OwnedPseudoClasses>,
pub unused_symbols: Option<HashSet<String>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OwnedPseudoClasses {
pub hover: Option<String>,
pub active: Option<String>,
pub focus: Option<String>,
pub focus_visible: Option<String>,
pub focus_within: Option<String>,
}
impl<'a> Into<PseudoClasses<'a>> for &'a OwnedPseudoClasses {
fn into(self) -> PseudoClasses<'a> {
PseudoClasses {
hover: self.hover.as_deref(),
active: self.active.as_deref(),
focus: self.focus.as_deref(),
focus_visible: self.focus_visible.as_deref(),
focus_within: self.focus_within.as_deref(),
}
}
}
#[derive(Serialize, Debug, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct Drafts {
#[serde(default)]
nesting: bool,
#[serde(default)]
custom_media: bool,
}
pub fn compile<'i>(filename: String, code: &'i str, config: &Config) -> Result<TransformResult, CompileError<'i>> {
let drafts = config.drafts.as_ref();
let mut stylesheet = StyleSheet::parse(
&filename,
&code,
ParserOptions {
nesting: matches!(drafts, Some(d) if d.nesting),
custom_media: matches!(drafts, Some(d) if d.custom_media),
css_modules: config.css_modules.unwrap_or(false),
source_index: 0,
},
)?;
stylesheet.minify(MinifyOptions {
targets: config.targets,
unused_symbols: config.unused_symbols.clone().unwrap_or_default(),
})?;
let mut source_map = if config.source_map.unwrap_or(false) {
let mut sm = SourceMap::new("/");
sm.add_source(&filename);
sm.set_source_content(0, code)?;
Some(sm)
} else {
None
};
let res = stylesheet.to_css(PrinterOptions {
minify: config.minify.unwrap_or(false),
source_map: source_map.as_mut(),
targets: config.targets,
analyze_dependencies: config.analyze_dependencies.unwrap_or(false),
pseudo_classes: config.pseudo_classes.as_ref().map(|p| p.into()),
})?;
let map = if let Some(mut source_map) = source_map {
Some(source_map_to_json(&mut source_map)?)
} else {
None
};
Ok(TransformResult {
code: res.code,
map,
exports: res.exports,
dependencies: res.dependencies,
})
}
#[inline]
fn source_map_to_json<'i>(source_map: &mut SourceMap) -> Result<String, CompileError<'i>> {
let mut vlq_output: Vec<u8> = Vec::new();
source_map.write_vlq(&mut vlq_output)?;
let sm = SourceMapJson {
version: 3,
mappings: unsafe { String::from_utf8_unchecked(vlq_output) },
sources: source_map.get_sources(),
sources_content: source_map.get_sources_content(),
names: source_map.get_names(),
};
Ok(serde_json::to_string(&sm).unwrap())
}
#[derive(Serialize, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AttrConfig {
pub code: String,
pub targets: Option<Browsers>,
pub minify: Option<bool>,
pub analyze_dependencies: Option<bool>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AttrResult {
code: String,
dependencies: Option<Vec<Dependency>>,
}
pub enum CompileError<'i> {
ParseError(Error<ParserError<'i>>),
MinifyError(Error<MinifyErrorKind>),
PrinterError(Error<PrinterErrorKind>),
SourceMapError(parcel_sourcemap::SourceMapError),
BundleError(Error<BundleErrorKind<'i>>),
}
impl<'i> CompileError<'i> {
fn reason(&self) -> String {
match self {
CompileError::ParseError(e) => e.kind.to_string(),
CompileError::MinifyError(err) => err.kind.to_string(),
CompileError::PrinterError(err) => err.kind.to_string(),
CompileError::BundleError(err) => err.kind.to_string(),
_ => "Unknown error".into(),
}
}
}
impl<'i> From<Error<ParserError<'i>>> for CompileError<'i> {
fn from(e: Error<ParserError<'i>>) -> CompileError<'i> {
CompileError::ParseError(e)
}
}
impl<'i> From<Error<MinifyErrorKind>> for CompileError<'i> {
fn from(err: Error<MinifyErrorKind>) -> CompileError<'i> {
CompileError::MinifyError(err)
}
}
impl<'i> From<Error<PrinterErrorKind>> for CompileError<'i> {
fn from(err: Error<PrinterErrorKind>) -> CompileError<'i> {
CompileError::PrinterError(err)
}
}
impl<'i> From<parcel_sourcemap::SourceMapError> for CompileError<'i> {
fn from(e: parcel_sourcemap::SourceMapError) -> CompileError<'i> {
CompileError::SourceMapError(e)
}
}
impl<'i> From<Error<BundleErrorKind<'i>>> for CompileError<'i> {
fn from(e: Error<BundleErrorKind<'i>>) -> CompileError<'i> {
CompileError::BundleError(e)
}
}
impl<'i> From<CompileError<'i>> for wasm_bindgen::JsValue {
fn from(e: CompileError) -> wasm_bindgen::JsValue {
match e {
CompileError::SourceMapError(e) => js_sys::Error::new(&e.to_string()).into(),
_ => js_sys::Error::new(&e.reason()).into(),
}
}
}