-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathutils.rs
More file actions
242 lines (233 loc) · 6.18 KB
/
utils.rs
File metadata and controls
242 lines (233 loc) · 6.18 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
use once_cell::sync::Lazy;
use oxc_allocator::{Allocator, CloneIn};
use oxc_ast::ast::{Expression, JSXAttributeValue, Statement};
use oxc_codegen::Codegen;
use oxc_parser::Parser;
use oxc_span::{SPAN, SourceType};
use oxc_syntax::operator::UnaryOperator;
use std::collections::HashSet;
/// Convert a value to a pixel value
pub fn convert_value(value: &str) -> String {
value
.parse::<f64>()
.map_or_else(|_| value.to_string(), |num| format!("{}px", num * 4.0))
}
pub fn expression_to_code(expression: &Expression) -> String {
let allocator = Allocator::default();
let mut parsed = Parser::new(&allocator, "", SourceType::d_ts()).parse();
parsed.program.body.insert(
0,
Statement::ExpressionStatement(
oxc_ast::AstBuilder::new(&allocator)
.alloc_expression_statement(SPAN, expression.clone_in(&allocator)),
),
);
let code = Codegen::new().build(&parsed.program).code;
code[0..code.len() - 2].to_string()
}
static SPECIAL_PROPERTIES: Lazy<HashSet<&str>> = Lazy::new(|| {
let mut set = HashSet::<&str>::new();
for prop in [
"style",
"className",
"role",
"ref",
"key",
"id",
"alt",
"type",
"src",
"children",
"placeholder",
"tabIndex",
"maxLength",
"minLength",
"disabled",
"readOnly",
"autoFocus",
"required",
"checked",
"defaultChecked",
"value",
"defaultValue",
"selected",
"multiple",
"accept",
"step",
"autoComplete",
"capture",
"form",
"formAction",
"formEncType",
"formMethod",
"formNoValidate",
"formTarget",
"list",
"max",
"min",
"name",
"pattern",
"size",
"challenge",
"keyType",
"keyParams",
"htmlFor",
"crossOrigin",
"fetchPriority",
"href",
"hrefLang",
"integrity",
"media",
"imageSrcSet",
"imageSizes",
"referrerPolicy",
"sizes",
"charSet",
"precedence",
"autoPlay",
"controls",
"controlsList",
"loop",
"mediaGroup",
"muted",
"playsInline",
"preload",
"content",
"httpEquiv",
"high",
"low",
"optimum",
"classID",
"data",
"useMap",
"wmode",
"reversed",
"start",
"label",
"async",
"defer",
"noModule",
"srcSet",
"scoped",
"align",
"bgcolor",
"cellPadding",
"cellSpacing",
"frame",
"rules",
"summary",
"cols",
"dirName",
"rows",
"wrap",
"colSpan",
"headers",
"rowSpan",
"scope",
"abbr",
"valign",
"dateTime",
"default",
"kind",
"srcLang",
"poster",
"disablePictureInPicture",
"disableRemotePlayback",
"download",
"target",
"rel",
"ping",
"coords",
"shape",
"isMap",
"longDesc",
"loading",
"decoding",
"importance",
"axis",
"char",
"charOff",
"span",
"noWrap",
"vSpace",
"hSpace",
"compact",
"scheme",
"indeterminate",
"defaultSelected",
"selectedIndex",
"selectedOptions",
] {
set.insert(prop);
}
set
});
pub fn is_special_property(name: &str) -> bool {
name.starts_with("on")
|| name.starts_with("data-")
|| name.starts_with("aria-")
|| SPECIAL_PROPERTIES.contains(name)
}
pub fn get_number_by_jsx_expression(expr: &JSXAttributeValue) -> Option<f64> {
match expr {
JSXAttributeValue::StringLiteral(sl) => get_number_by_literal_expression(
&Expression::StringLiteral(sl.clone_in(&Allocator::default())),
),
JSXAttributeValue::ExpressionContainer(ec) => {
get_number_by_literal_expression(ec.expression.to_expression())
}
_ => None,
}
}
pub fn get_number_by_literal_expression(expr: &Expression) -> Option<f64> {
match expr {
Expression::ParenthesizedExpression(parenthesized) => {
get_number_by_literal_expression(&parenthesized.expression)
}
Expression::NumericLiteral(num) => Some(num.value),
Expression::UnaryExpression(unary) => get_number_by_literal_expression(&unary.argument)
.and_then(|num| match unary.operator {
UnaryOperator::UnaryNegation => Some(-num),
UnaryOperator::UnaryPlus => Some(num),
_ => None,
}),
_ => None,
}
}
pub fn get_string_by_literal_expression(expr: &Expression) -> Option<String> {
get_number_by_literal_expression(expr)
.map(|num| num.to_string())
.or_else(|| match expr {
Expression::ParenthesizedExpression(parenthesized) => {
get_string_by_literal_expression(&parenthesized.expression)
}
Expression::StringLiteral(str) => Some(str.value.as_str().to_string()),
Expression::TemplateLiteral(tmp) => {
let mut collect = vec![];
for (idx, q) in tmp.quasis.iter().enumerate() {
collect.push(q.value.raw.to_string());
if idx < tmp.expressions.len() {
if let Some(value) = get_string_by_literal_expression(&tmp.expressions[idx])
{
collect.push(value);
} else {
return None;
}
}
}
Some(collect.join(""))
}
_ => None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_convert_value() {
assert_eq!(convert_value("1px"), "1px");
assert_eq!(convert_value("1%"), "1%");
assert_eq!(convert_value("foo"), "foo");
assert_eq!(convert_value("4"), "16px");
}
}