lexical_ui/
set_dom_style.rs1use crate::json::array_index;
7use crate::selection_deletion::is_js_whitespace;
8
9pub fn js_trim(s: &str) -> &str {
12 s.trim_matches(is_js_whitespace)
13}
14
15#[derive(Clone, Debug, Default, PartialEq, Eq)]
20pub struct StyleObject {
21 entries: Vec<(String, String)>,
22}
23
24impl StyleObject {
25 pub fn new() -> Self {
26 Self::default()
27 }
28
29 pub fn len(&self) -> usize {
30 self.entries.len()
31 }
32
33 pub fn is_empty(&self) -> bool {
34 self.entries.is_empty()
35 }
36
37 pub fn get(&self, key: &str) -> Option<&str> {
38 self.entries
39 .iter()
40 .find(|(k, _)| k == key)
41 .map(|(_, v)| v.as_str())
42 }
43
44 pub fn contains_key(&self, key: &str) -> bool {
45 self.get(key).is_some()
46 }
47
48 pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
50 let key = key.into();
51 let value = value.into();
52 if let Some(entry) = self.entries.iter_mut().find(|(k, _)| *k == key) {
53 entry.1 = value;
54 return;
55 }
56 let at = match array_index(&key) {
57 Some(index) => self
58 .entries
59 .iter()
60 .position(|(k, _)| array_index(k).is_none_or(|i| i > index))
61 .unwrap_or(self.entries.len()),
62 None => self.entries.len(),
63 };
64 self.entries.insert(at, (key, value));
65 }
66
67 pub fn remove(&mut self, key: &str) -> Option<String> {
69 let index = self.entries.iter().position(|(k, _)| k == key)?;
70 Some(self.entries.remove(index).1)
71 }
72
73 pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
74 self.entries.iter().map(|(k, v)| (k.as_str(), v.as_str()))
75 }
76
77 pub fn keys(&self) -> impl Iterator<Item = &str> {
78 self.entries.iter().map(|(k, _)| k.as_str())
79 }
80}
81
82impl IntoIterator for StyleObject {
83 type Item = (String, String);
84 type IntoIter = std::vec::IntoIter<(String, String)>;
85
86 fn into_iter(self) -> Self::IntoIter {
87 self.entries.into_iter()
88 }
89}
90
91impl<K: Into<String>, V: Into<String>> FromIterator<(K, V)> for StyleObject {
92 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
93 let mut styles = StyleObject::new();
94 for (k, v) in iter {
95 styles.insert(k, v);
96 }
97 styles
98 }
99}
100
101pub fn get_style_object_from_css(css: &str) -> StyleObject {
105 css_declarations(css).into_iter().collect()
106}
107
108pub(crate) fn css_declarations(css: &str) -> Vec<(String, String)> {
111 let mut styles = Vec::new();
112 if css.is_empty() {
113 return styles;
114 }
115 let bytes = css.as_bytes();
118 let length = bytes.len();
119 let mut current_property = String::new();
120 let mut current_value = String::new();
121 let mut current_quote: Option<u8> = None;
122 let mut in_comment = false;
123 let mut is_escaped = false;
124 let mut is_parsing_value = false;
125 let mut parenthesis_depth = 0usize;
126 let mut chunk_start: Option<usize> = None;
128
129 let commit = |property: &str, value: &str, styles: &mut Vec<(String, String)>| {
130 let property = js_trim(property);
131 let value = js_trim(value);
132 if !property.is_empty() && !value.is_empty() {
133 styles.push((property.to_owned(), value.to_owned()));
134 }
135 };
136
137 let mut i = 0;
138 while i < length {
139 let char = bytes[i];
140 let next = bytes.get(i + 1).copied();
141 if in_comment {
142 if char == b'*' && next == Some(b'/') {
143 in_comment = false;
144 i += 1;
145 }
146 i += 1;
147 continue;
148 }
149 if is_escaped {
150 chunk_start.get_or_insert(i);
151 is_escaped = false;
152 i += 1;
153 continue;
154 }
155 if let Some(quote) = current_quote {
156 chunk_start.get_or_insert(i);
157 if char == b'\\' {
158 is_escaped = true;
159 } else if char == quote {
160 current_quote = None;
161 }
162 i += 1;
163 continue;
164 }
165 if char == b'/' && next == Some(b'*') {
166 if let Some(start) = chunk_start.take() {
168 if is_parsing_value {
169 current_value.push_str(&css[start..i]);
170 } else {
171 current_property.push_str(&css[start..i]);
172 }
173 }
174 in_comment = true;
175 i += 2;
176 continue;
177 }
178 match char {
179 b'"' | b'\'' => {
180 chunk_start.get_or_insert(i);
181 current_quote = Some(char);
182 }
183 b'(' => {
184 chunk_start.get_or_insert(i);
185 parenthesis_depth += 1;
186 }
187 b')' => {
188 chunk_start.get_or_insert(i);
189 parenthesis_depth = parenthesis_depth.saturating_sub(1);
190 }
191 b':' if !is_parsing_value && parenthesis_depth == 0 => {
192 if let Some(start) = chunk_start.take() {
194 current_property.push_str(&css[start..i]);
195 }
196 is_parsing_value = true;
197 }
198 b';' if parenthesis_depth == 0 => {
199 if let Some(start) = chunk_start.take() {
200 if is_parsing_value {
201 current_value.push_str(&css[start..i]);
202 } else {
203 current_property.push_str(&css[start..i]);
204 }
205 }
206 commit(¤t_property, ¤t_value, &mut styles);
207 current_property.clear();
208 current_value.clear();
209 is_parsing_value = false;
210 }
211 _ => {
212 chunk_start.get_or_insert(i);
213 }
214 }
215 i += 1;
216 }
217 if let Some(start) = chunk_start {
218 if is_parsing_value {
219 current_value.push_str(&css[start..]);
220 } else {
221 current_property.push_str(&css[start..]);
222 }
223 }
224 commit(¤t_property, ¤t_value, &mut styles);
225 styles
226}
227
228#[cfg(feature = "html")]
229mod dom_style {
230 use super::{StyleObject, get_style_object_from_css, js_trim};
231 use crate::dom::CssStyle;
232
233 const IMPORTANT_FLAG: &str = "!important";
234
235 fn set_dom_style_property(dom_style: &CssStyle, property: &str, value: &str) {
238 let trimmed = value.trim_end_matches(crate::selection_deletion::is_js_whitespace);
239 let n = trimmed.len();
240 let flag_start = n.checked_sub(IMPORTANT_FLAG.len());
241 let has_important = flag_start.is_some_and(|start| {
242 trimmed.is_char_boundary(start) && trimmed[start..].to_lowercase() == IMPORTANT_FLAG
243 });
244 match flag_start {
245 Some(start) if has_important => {
246 dom_style.set_property(property, js_trim(&trimmed[..start]), "important");
247 }
248 _ => dom_style.set_property(property, value, ""),
249 }
250 }
251
252 pub fn set_dom_style_object<'a>(
255 dom_style: &CssStyle,
256 style_object: impl IntoIterator<Item = (&'a str, Option<&'a str>)>,
257 ) {
258 for (property, value) in style_object {
259 match value {
260 None => {
261 dom_style.remove_property(property);
262 }
263 Some(value) => set_dom_style_property(dom_style, property, value),
264 }
265 }
266 }
267
268 pub fn set_dom_style_from_css(dom_style: &CssStyle, css_text: &str, prev_css_text: &str) {
271 if css_text == prev_css_text {
272 return;
273 }
274 let mut prev_css: StyleObject = get_style_object_from_css(prev_css_text);
275 let next_css = get_style_object_from_css(css_text);
276 for (property, value) in next_css.iter() {
277 prev_css.remove(property);
278 set_dom_style_property(dom_style, property, value);
279 }
280 for property in prev_css.keys() {
281 dom_style.remove_property(property);
282 }
283 }
284}
285
286#[cfg(feature = "html")]
287pub use dom_style::{set_dom_style_from_css, set_dom_style_object};
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292
293 #[test]
294 fn style_objects_follow_js_property_order() {
295 let styles = get_style_object_from_css("b: 1; 2: x; a: 2; 1: y; b: 3");
298 let entries: Vec<(&str, &str)> = styles.iter().collect();
299 assert_eq!(entries, [("1", "y"), ("2", "x"), ("b", "3"), ("a", "2")]);
300 }
301
302 #[test]
303 fn delimiters_in_quotes_parentheses_and_comments() {
304 let styles = get_style_object_from_css(
307 r#"content: "a;b:c"; /* x: y; */ background: url(a;b) ;font : 'q\'' "#,
308 );
309 let entries: Vec<(&str, &str)> = styles.iter().collect();
310 assert_eq!(
311 entries,
312 [
313 ("content", r#""a;b:c""#),
314 ("background", "url(a;b)"),
315 ("font", r"'q\''"),
316 ]
317 );
318 }
319}