encre_css/selector/mod.rs
1//! Define the structures used to parse scanned classes.
2//!
3//! ## Discover what is possible to do with classes by learning some vocabulary
4//!
5//! <style>
6//! .with-hints {
7//! font-family: sans-serif;
8//! overflow: visible !important;
9//! height: 3rem;
10//! font-size: 1rem;
11//! }
12//!
13//! .with-hints > b > span:nth-child(even) {
14//! padding: 0 0.35rem;
15//! }
16//!
17//! .with-hints > b > span:nth-child(odd) {
18//! position: relative;
19//! text-decoration: underline;
20//! text-underline-offset: 6px;
21//! }
22//!
23//! .with-hints span:nth-child(odd)::after {
24//! content: counter(hints);
25//! position: absolute;
26//! bottom: -1.75rem;
27//! left: 50%;
28//! transform: translateX(-50%);
29//! font-size: 0.7rem;
30//! border: 2px solid currentColor;
31//! border-radius: 50%;
32//! width: 1.1rem;
33//! height: 1.1rem;
34//! display: flex;
35//! justify-content: center;
36//! align-items: center;
37//! counter-increment: hints;
38//! }
39//! </style>
40//!
41//! <p class="with-hints" style="counter-reset: hints; margin-top: 2rem;"><b><span>hover:xl</span><span>:</span><span>bg</span><span>-</span><span>red-500</span></b></p>
42//!
43//! 1. The **[variants](crate::selector::Variant)** (used to add pseudo-selectors, pseudo-elements, pseudo classes, media queries), in this case
44//! the class will be applied only on a screen larger than 1280px (see [`BUILTIN_SCREENS`]) and
45//! if hovered;
46//! 2. The **namespace** (basically the name of the plugin), in this case `bg` for changing the background;
47//! 3. The **[modifier](crate::selector::Modifier)** (used to clarify the CSS needed to be generated), in this case the
48//! background color will become `rgb(239 68 68)` (see [`BUILTIN_COLORS`]).
49//!
50//! <p class="with-hints" style="margin-top: 3rem;"><b><span style="counter-set: hints 3;">[&>*]</span><span>:</span><span style="counter-set: hints 4;">[@supports_(display:flex)]</span><span>:</span><span style="counter-set: hints 1;">flex</span><span>-</span><span style="counter-set: hints 5;">[2_2_10%]</span></b></p>
51//!
52//! 4. The **arbitrary variant** (used to modify the class generated), in this case the class
53//! will be `.\[\&\>\*]\:flex-\[2_2_10\%\]>*`.
54//!
55//! 5. Another **arbitrary variant** (with another syntax used to add [at rules](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule)),
56//! in this case the rule will become `@supports (display:flex) { <rule content> }` (spaces need to be replaced with underscores in arbitrary
57//! variants).
58//!
59//! 6. The **[arbitrary value](crate::selector::Modifier::Arbitrary)**
60//! (used to specify a value not included in your design system), in this case the background
61//! color will become `2 2 10%` (spaces need to be replaced with underscores in arbitrary
62//! values).
63//!
64//! <p class="with-hints" style="margin-top: 3rem;"><b><span>[mask-type:luminance]</span></b></p>
65//!
66//! 7. The **arbitrary CSS property** (used to use a CSS property not supported by `encre-css`), in
67//! this case the rule content will be `.\[mask-type\:luminance\] { mask-type: luminance; }`.
68//!
69//! <p class="with-hints" style="margin-top: 3rem;"><b><span>dark:(text-white,bg-gray-500)</span></b></p>
70//!
71//! 8. The **variant group** (used to group together several classes conditionally enabled by the
72//! same variant), in this case the class will be expanded to `dark:text-white` and
73//! `dark:bg-gray-500`.
74//!
75//! <p class="with-hints" style="margin-top: 3rem;"><b><span>(hover,focus-visible):bg-blue-400</span></b></p>
76//!
77//! 9. The **variant group without any namespace or modifier** (used to group together several classes conditionally enabled by the
78//! same variant but sharing the same modifier), in this case the class will be expanded to `hover:bg-blue-400` and
79//! `focus-visible:bg-blue-400`.
80//!
81//! As you can see, by default variants are separated by `:`, modifiers by `-` (the dash after the
82//! first modifier can be omitted, e.g. `m1` instead of `m-1`), arbitrary values/variants are surrounded by `[]` and variant
83//! groups are surrounded by `()`.
84//!
85//! [`BUILTIN_SCREENS`]: crate::config::BUILTIN_SCREENS
86//! [`BUILTIN_COLORS`]: crate::config::BUILTIN_COLORS
87pub(crate) mod parser;
88
89use crate::plugins::Plugin;
90
91use std::{borrow::Cow, cmp::Ordering};
92
93pub(crate) use parser::parse;
94
95/// The modifier is the rest of the selector after the namespace, it is used to clarify the
96/// CSS needed to be generated.
97#[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Ord)]
98pub enum Modifier<'a> {
99 /// A builtin static modifier (e.g. `bg-red-500`).
100 Builtin {
101 /// Whether the value is negative (e.g. `-translate-2` is negative).
102 is_negative: bool,
103
104 /// The inner value of the modifier.
105 value: &'a str,
106 },
107
108 /// A dynamic modifier capable of automatically generating a rule from a CSS value
109 /// (e.g. `bg-[rgb(12_12_12)]`).
110 ///
111 /// All underscores in the value will be replaced by spaces except in `url()`, if you really
112 /// want to keep one of them, you can prefix it with a backslash `\_` and it will be used as
113 /// is.
114 ///
115 /// Sometimes the value is ambiguous, for example `bg-[var(--foo)]` can be handled by either
116 /// the [`background color`](crate::plugins::background::background_color) or the
117 /// [`background size`](crate::plugins::background::background_size) utility. In this case,
118 /// you need to provide a [CSS type](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Types)
119 /// hint (see the list of hints below) before the arbitrary value. For example
120 /// `bg-[length:var(--foo)]` will generate `background-size: var(--foo);` (using the
121 /// [`background size`](crate::plugins::background::background_size) utility).
122 ///
123 /// List of all type hints:
124 /// - `color`
125 /// - `length`
126 /// - `line-width`
127 /// - `image`
128 /// - `url`
129 /// - `position`
130 /// - `percentage`
131 /// - `number`
132 /// - `generic-name`
133 /// - `family-name`
134 /// - `absolute-size`
135 /// - `relative-size`
136 /// - `shadow`
137 Arbitrary {
138 /// The rest of the modifier without the arbitrary value (e.g. `bg` in `bg-[rgb(12_12_12)]`).
139 prefix: &'a str,
140
141 /// The type hint needed for ambiguous values.
142 hint: &'a str,
143
144 /// The inner value of the modifier.
145 ///
146 /// All escaped characters (prefixed by a backslash) are already unescaped.
147 value: Cow<'a, str>,
148 },
149}
150
151/// A selector variant.
152#[derive(Debug, Clone, Eq)]
153pub struct Variant<'a> {
154 pub(crate) order: usize,
155 pub(crate) prefixed: bool,
156 pub(crate) template: Cow<'a, str>,
157}
158
159impl<'a> Variant<'a> {
160 pub(crate) const fn new_const(counter: &mut usize, template: &'static str) -> Self {
161 *counter += 1;
162
163 Self {
164 order: *counter - 1,
165 prefixed: false,
166 template: Cow::Borrowed(template),
167 }
168 }
169
170 /// Create a new variant.
171 ///
172 /// The order is used to decide where the generated class having this variant will be placed in
173 /// the generated CSS. [`Config::last_variant_order`] can be used to insert a variant after all
174 /// the others.
175 ///
176 /// The template is a string which defines how the class will be modified. If it starts with `@`,
177 /// a CSS block will wrap the inner class (like media queries), otherwise just the class name will
178 /// be modified.
179 ///
180 /// The template should contain `&` which will be replaced by the complete class name.
181 ///
182 /// # Example
183 ///
184 /// ```
185 /// use encre_css::{Config, selector::Variant};
186 /// use std::borrow::Cow;
187 ///
188 /// let mut config = Config::default();
189 /// config.register_variant(
190 /// "headings",
191 /// // Insert the classes having this variant after all the other variants
192 /// Variant::new(config.last_variant_order(), "& :where(h1, h2, h3, h4, h5, h6)")
193 /// );
194 ///
195 /// let generated = encre_css::generate(
196 /// ["headings:text-gray-700"],
197 /// &config,
198 /// );
199 ///
200 /// assert!(generated.ends_with(".headings\\:text-gray-700 :where(h1, h2, h3, h4, h5, h6) {
201 /// color: oklch(37.3% .034 259.733);
202 /// }"));
203 /// ```
204 ///
205 /// [`Config::last_variant_order`]: crate::Config::last_variant_order
206 pub fn new<T: Into<Cow<'a, str>>>(order: usize, template: T) -> Self {
207 Self {
208 order,
209 prefixed: false,
210 template: template.into(),
211 }
212 }
213
214 /// Defines a prefixed variant which is composed of a prefix and an arbitrary value which will
215 /// be inserted into the variant template.
216 ///
217 /// A prefixed variant can have `{}` in its template which will be replaced by the arbitrary
218 /// value.
219 ///
220 /// # Example
221 ///
222 /// ```
223 /// use encre_css::{Config, selector::Variant};
224 /// use std::borrow::Cow;
225 ///
226 /// let mut config = Config::default();
227 /// config.register_variant(
228 /// "media",
229 /// // Insert the classes having this variant after all the other variants
230 /// Variant::new(config.last_variant_order(), "@media {}").with_prefixed()
231 /// );
232 ///
233 /// let generated = encre_css::generate(
234 /// ["media-[print]:flex"],
235 /// &config,
236 /// );
237 ///
238 /// assert!(generated.ends_with(r"@media print {
239 /// .media-\[print\]\:flex {
240 /// display: flex;
241 /// }
242 /// }"));
243 /// ```
244 #[must_use]
245 pub const fn with_prefixed(mut self) -> Self {
246 self.prefixed = true;
247 self
248 }
249}
250
251impl PartialEq for Variant<'_> {
252 fn eq(&self, other: &Self) -> bool {
253 // Does not test order because it can change
254 self.template == other.template
255 }
256}
257
258/// A parsed selector, aka a utility class, containing the variants, the namespace and the modifier.
259///
260/// See [`crate::selector`] for more information.
261#[derive(Clone, Debug)]
262pub(crate) struct Selector<'a> {
263 pub(crate) layer: i8,
264 pub(crate) order: usize,
265 pub(crate) full: &'a str,
266 pub(crate) modifier: Modifier<'a>,
267 pub(crate) variants: Vec<Variant<'a>>,
268 pub(crate) is_important: bool,
269 pub(crate) plugin: &'static (dyn Plugin + Sync + Send),
270}
271
272impl PartialEq for Selector<'_> {
273 fn eq(&self, other: &Self) -> bool {
274 // Does not test order because it can change
275 self.full == other.full
276 && self.modifier == other.modifier
277 && self.variants == other.variants
278 && self.is_important == other.is_important
279 && self.layer == other.layer
280 }
281}
282
283impl Eq for Selector<'_> {}
284
285impl PartialOrd for Selector<'_> {
286 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
287 Some(self.cmp(other))
288 }
289}
290
291impl Ord for Selector<'_> {
292 fn cmp(&self, other: &Self) -> Ordering {
293 // We need to check the order as well as the strict egality because the PartialEq
294 // implementation for Selector does not check if two selectors have the same plugin which
295 // can lead two selectors having the same modifier to be recognized as the same although
296 // they use different plugins
297 if self.order == other.order && self == other {
298 return Ordering::Equal;
299 }
300
301 self.layer.cmp(&other.layer).then_with(|| {
302 if self.variants.is_empty() && !other.variants.is_empty() {
303 Ordering::Less
304 } else if !self.variants.is_empty() && other.variants.is_empty() {
305 Ordering::Greater
306 } else if !self.variants.is_empty() && !other.variants.is_empty() {
307 let mut compared = None;
308
309 // Compare variants in the lexicographic order
310 for variant_i in 0..self.variants.len() {
311 if variant_i >= other.variants.len() {
312 compared = Some(Ordering::Greater);
313 break;
314 }
315
316 let res = self
317 .variants
318 .get(variant_i)
319 .as_ref()
320 .unwrap()
321 .order
322 .cmp(&other.variants.get(variant_i).unwrap().order);
323
324 if res != Ordering::Equal {
325 compared = Some(res);
326 break;
327 }
328 }
329
330 compared.unwrap_or(Ordering::Less).then_with(|| {
331 self.order.cmp(&other.order).then_with(|| {
332 self.full
333 .cmp(other.full)
334 .then_with(|| self.modifier.cmp(&other.modifier))
335 })
336 })
337 } else {
338 self.order.cmp(&other.order).then_with(|| {
339 self.full
340 .cmp(other.full)
341 .then_with(|| self.modifier.cmp(&other.modifier))
342 })
343 }
344 })
345 }
346}
347
348#[cfg(test)]
349mod tests {
350 use crate::{config::Config, selector::parse};
351
352 use std::collections::BTreeSet;
353
354 #[test]
355 fn sorting_test() {
356 let config = Config::default();
357
358 let selectors1 = parse(
359 "lg:bg-red-500",
360 None,
361 None,
362 &config,
363 &config.get_derived_variants(),
364 );
365 let selectors2 = parse(
366 "bg-red-500",
367 None,
368 None,
369 &config,
370 &config.get_derived_variants(),
371 );
372
373 let mut selectors = BTreeSet::new();
374 selectors.insert(selectors1[0].as_ref().unwrap());
375 selectors.insert(selectors2[0].as_ref().unwrap());
376
377 let mut iter = selectors.iter();
378 assert!(
379 iter.next().unwrap().full == "bg-red-500"
380 && iter.next().unwrap().full == "lg:bg-red-500"
381 );
382 }
383
384 #[test]
385 fn layers_test() {
386 let config = Config::default();
387
388 let selectors1 = parse(
389 "lg:bg-red-500",
390 None,
391 None,
392 &config,
393 &config.get_derived_variants(),
394 );
395 let mut selectors2 = parse(
396 "bg-red-500",
397 None,
398 None,
399 &config,
400 &config.get_derived_variants(),
401 );
402 selectors2[0].as_mut().unwrap().layer = 42;
403
404 let mut selectors = BTreeSet::new();
405 selectors.insert(selectors1[0].as_ref().unwrap());
406 selectors.insert(selectors2[0].as_ref().unwrap());
407
408 let mut iter = selectors.iter();
409 assert!(
410 iter.next().unwrap().full == "lg:bg-red-500"
411 && iter.next().unwrap().full == "bg-red-500"
412 );
413 }
414}