Skip to main content

nsh_core/tailwind/
mod.rs

1//! Tailwind CSS classes (`class="flex-row gap-4 p-4 bg-white dark:bg-zinc-900"`),
2//! resolved in Rust: each distinct class string is parsed once into rules
3//! (cached), and applied to a node's style whenever its variants may have
4//! changed (appearance, window width, press / hover / focus, group
5//! states). JS only passes the string.
6//!
7//! Utilities later in the string win over earlier ones, so components can
8//! take a `class` prop and append it (no `tailwind-merge`). Variant
9//! utilities apply after plain ones, ordered by Tailwind's variant order
10//! (`hover:` before `active:`, breakpoints ascending, `dark:` last).
11//!
12//! Each class string is parsed once into rules, cached in an LRU of up to
13//! 4096 strings, with what the rules depend on (appearance, window width and
14//! height, direction, the node's own states, a group's states, sibling
15//! position, reduce motion, the `data-*` attributes it or a group shows): the core
16//! (`core/classes.rs`) resolves a node again only when one of those changes. Interaction states are reported by the platforms
17//! only for the bits a node's classes read (`MountItem::TrackStates`), and
18//! `focus-within` propagates to ancestors in the core. A node's style is the
19//! default, then its class rules, then its inline `style` replayed on top
20//! (`Op::SetStyle` carries a `StylePatch` besides the merged `Style`). The
21//! theme is Tailwind 4's (the palette converted from OKLCH to sRGB) extended
22//! by `nsh.json` `"tailwind"`, compiled into the bundle as
23//! `nsh:tailwind-theme` and pushed as a root prop at startup.
24
25pub(crate) mod palette;
26mod theme;
27mod utilities;
28
29use std::{rc::Rc, sync::Arc};
30
31use rustc_hash::FxHashMap;
32
33pub use self::theme::{Theme, ThemeError};
34pub(crate) use self::utilities::{Decl, Len, Part, PropDecl};
35use self::{theme::ClassTokens, utilities::Parts};
36use crate::{
37    geometry::{Points, Size},
38    props::PointerEvents,
39    style::{Color, EllipsizeMode, PropertyValue, Style, TextShadow},
40};
41
42/// Interaction states a class can depend on (`active:`, `hover:`, ...).
43pub mod state {
44    /// The view is pressed (`active:`).
45    pub const PRESSED: u16 = 1;
46    /// A pointer is over the view (`hover:`).
47    pub const HOVERED: u16 = 2;
48    /// The input has focus (`focus:`).
49    pub const FOCUSED: u16 = 4;
50    /// The view is disabled (`disabled:`).
51    pub const DISABLED: u16 = 8;
52    /// The view or a descendant has focus (`focus-within:`).
53    pub const FOCUS_WITHIN: u16 = 16;
54    /// The view is selected (`selected:`): its
55    /// `accessibilityState.selected`, a `Button`'s `selected`. Set by the
56    /// core, never reported by the platform.
57    pub const SELECTED: u16 = 32;
58    /// The view is checked (`checked:`): its `accessibilityState.checked`
59    /// (a checkbox, a switch, a radio; not when mixed). Set by the core,
60    /// never reported by the platform.
61    pub const CHECKED: u16 = 64;
62    /// The view is indeterminate (`indeterminate:`): its
63    /// `accessibilityState.checked` is mixed (a checkbox that is neither
64    /// checked nor unchecked, as CSS's `:indeterminate`). Set by the core,
65    /// never reported by the platform.
66    pub const INDETERMINATE: u16 = 128;
67    /// The view's popup, menu or section is open (`aria-expanded:`): its
68    /// `accessibilityState.expanded`, which `Popover` and `Menu` set on
69    /// their trigger. Set by the core, never reported by the platform.
70    pub const EXPANDED: u16 = 256;
71    /// The view is a toggle button that is on (`aria-pressed:`): its
72    /// `accessibilityState.pressed` is `true` (not mixed). Not
73    /// [`PRESSED`], a press in progress (`active:`). Set by the core,
74    /// never reported by the platform.
75    pub const ARIA_PRESSED: u16 = 512;
76    /// The view is busy (`aria-busy:`): its `accessibilityState.busy`.
77    /// Set by the core, never reported by the platform.
78    pub const BUSY: u16 = 1024;
79    /// The view has the keyboard focus and shows it (`focus-visible:`):
80    /// the keyboard moved it there, or it is an input that edits, as CSS's
81    /// `:focus-visible`. Set by the core from [`FOCUSED`] and the surface's
82    /// input modality (`Core::set_input_modality`), never reported by the
83    /// platform.
84    pub const FOCUS_VISIBLE: u16 = 2048;
85    /// The view's content does not pass the app's checks
86    /// (`aria-invalid:`): its `accessibilityState.invalid`. Set by the
87    /// core, never reported by the platform.
88    pub const INVALID: u16 = 4096;
89    /// States that style a pointer or focus interaction.
90    pub(super) const INTERACTION: u16 = PRESSED | HOVERED | FOCUSED | FOCUS_WITHIN | FOCUS_VISIBLE;
91    /// The states the core sets from the accessibility state, which the
92    /// platforms never report.
93    pub(crate) const ACCESSIBILITY: u16 =
94        SELECTED | CHECKED | INDETERMINATE | EXPANDED | ARIA_PRESSED | BUSY | INVALID;
95}
96
97/// The view's place among its siblings (`first:`, `odd:`, ...).
98pub mod position {
99    /// The first child.
100    pub const FIRST: u8 = 1;
101    /// The last child.
102    pub const LAST: u8 = 2;
103    /// An odd child (1st, 3rd, ...).
104    pub const ODD: u8 = 4;
105    /// An even child.
106    pub const EVEN: u8 = 8;
107    /// The only child.
108    pub const ONLY: u8 = 16;
109}
110
111/// What resolved classes depend on, so the core knows when to resolve
112/// them again.
113pub mod deps {
114    /// Light or dark appearance.
115    pub const DARK: u16 = 1;
116    /// The window width (breakpoints, `w-screen`).
117    pub const WIDTH: u16 = 2;
118    /// The window's orientation or height (`landscape:`, `h-screen`).
119    pub const HEIGHT: u16 = 4;
120    /// The layout direction.
121    pub const RTL: u16 = 8;
122    /// The view's own interaction states.
123    pub const STATE: u16 = 16;
124    /// The states of an ancestor `group`.
125    pub const GROUP: u16 = 32;
126    /// The position among siblings.
127    pub const POSITION: u16 = 64;
128    /// The reduce-motion setting.
129    pub const MOTION: u16 = 128;
130    /// The component theme's tokens (`bg-primary`): parsed again when they
131    /// change.
132    pub const THEME: u16 = 256;
133    /// The text color it inherits (CSS's `currentColor`: a border, an
134    /// outline or a ring without a color of its own).
135    pub const CURRENT_COLOR: u16 = 512;
136    /// The advance of its font's `0` (CSS's `ch`: `max-w-prose`).
137    pub const CH: u16 = 1024;
138    /// The view's own `data-*` attributes (`data-range-start:`); a group's
139    /// are [`GROUP`].
140    pub const DATA: u16 = 2048;
141    /// The pointer's precision and the terminal (`pointer-fine:`,
142    /// `pointer-coarse:`, `terminal:`).
143    pub const DEVICE: u16 = 4096;
144    /// The platform (`ios:`, `android:`, `web:`).
145    pub const PLATFORM: u16 = 8192;
146}
147
148/// CSS's `ch` where no font is known ([`ClassList::apply`]): half a `rem`,
149/// so `max-w-prose` is 520 points there.
150pub(crate) const DEFAULT_CH: f32 = 8.0;
151
152/// What CSS's `currentColor` is for a node: its own text color (its
153/// inline style's, else its classes'), else the one it inherits, else
154/// black, React Native's default.
155#[derive(Debug, Clone, Copy, Default, PartialEq)]
156pub(crate) struct CurrentColor {
157    /// The text color the node inherits.
158    pub(crate) inherited: Option<Color>,
159    /// The color its inline style sets.
160    pub(crate) inline: Option<Color>,
161}
162
163/// The platform classes run on (`ios:`, `android:`, `web:`).
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
165pub enum Platform {
166    /// iOS and Mac Catalyst.
167    #[default]
168    Ios,
169    /// Android.
170    Android,
171    /// A web browser.
172    Web,
173}
174
175/// How precise the primary pointer is (`pointer-fine:`, `pointer-coarse:`),
176/// as CSS's `pointer` media feature.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
178pub enum Pointer {
179    /// A finger on a touch screen.
180    #[default]
181    Coarse,
182    /// A mouse or a trackpad: desktop behavior (a desktop OS, a desktop
183    /// browser, a terminal).
184    Fine,
185}
186
187/// The environment variants depend on, set by the engine.
188#[derive(Debug, Clone, Copy, PartialEq, Default)]
189pub struct ClassEnvironment {
190    /// Dark appearance.
191    pub dark: bool,
192    /// The platform.
193    pub platform: Platform,
194    /// The user asked for less motion.
195    pub reduce_motion: bool,
196    /// The primary pointer's precision.
197    pub pointer: Pointer,
198    /// Drawn in a terminal (`terminal:`).
199    pub terminal: bool,
200}
201
202/// What a node's classes are matched against: the core builds it per
203/// node; tools resolve classes outside a tree with one of their own.
204pub struct Context<'a> {
205    /// The appearance, platform and motion setting.
206    pub env: ClassEnvironment,
207    /// The window (root view) size.
208    pub window: Size<Points>,
209    /// Right-to-left layout.
210    pub rtl: bool,
211    /// [`state`] bits of the node.
212    pub states: u16,
213    /// [`position`] bits of the node.
214    pub position: u8,
215    /// [`state`] bits of the nearest ancestor group with this name (`""`
216    /// for unnamed groups).
217    pub group: &'a dyn Fn(&str) -> u16,
218}
219
220/// Whether the node (`None`) or the nearest ancestor group with this name
221/// (`Some`, `""` for unnamed groups) has the boolean `data-*` attribute
222/// named (without `data-`): `data-range-start:`, `group-data-range-start:`.
223/// Components set them on their parts (`Interactive::project_data`); only
224/// the core has them, so they stay out of the public [`Context`].
225pub(crate) type Data<'a> = &'a dyn Fn(Option<&str>, &str) -> bool;
226
227/// No `data-*` attribute: what classes resolved outside a tree see.
228pub(crate) fn no_data(_: Option<&str>, _: &str) -> bool {
229    false
230}
231
232/// Conditions of one rule (all must hold).
233#[derive(Debug, Clone, Default, PartialEq)]
234pub(crate) struct Condition {
235    dark: Option<bool>,
236    min_width: Option<f32>,
237    max_width: Option<f32>,
238    landscape: Option<bool>,
239    platform: Option<Platform>,
240    rtl: Option<bool>,
241    reduce_motion: Option<bool>,
242    pointer: Option<Pointer>,
243    terminal: Option<bool>,
244    /// Required [`state`] bits.
245    states: u16,
246    /// [`state`] bits that must be off (`enabled:`).
247    not_states: u16,
248    /// A group name and its required states.
249    group: Option<(Box<str>, u16)>,
250    /// `data-*` attributes the node must have (`data-<name>:`), by name.
251    data: Vec<Box<str>>,
252    /// `data-*` attributes the group of [`Condition::group`] must have
253    /// (`group-data-<name>:`).
254    group_data: Vec<Box<str>>,
255    /// Allowed [`position`] bits (any of them).
256    position: u8,
257    /// Applies to an input's placeholder.
258    placeholder: bool,
259    /// Applies to the selection (and caret) of an input or selectable text.
260    selection: bool,
261}
262
263impl Condition {
264    fn matches(&self, cx: &Context<'_>, data: Data<'_>) -> bool {
265        if self.dark.is_some_and(|d| d != cx.env.dark)
266            || self.platform.is_some_and(|p| p != cx.env.platform)
267            || self.pointer.is_some_and(|p| p != cx.env.pointer)
268            || self.terminal.is_some_and(|t| t != cx.env.terminal)
269            || self.rtl.is_some_and(|r| r != cx.rtl)
270            || self
271                .reduce_motion
272                .is_some_and(|r| r != cx.env.reduce_motion)
273            || self.min_width.is_some_and(|w| cx.window.width.0 < w)
274            || self.max_width.is_some_and(|w| cx.window.width.0 >= w)
275            || self
276                .landscape
277                .is_some_and(|l| l != (cx.window.width > cx.window.height))
278            || cx.states & self.states != self.states
279            || cx.states & self.not_states != 0
280        {
281            return false;
282        }
283        if self.position != 0 && cx.position & self.position == 0 {
284            return false;
285        }
286        if !self.data.iter().all(|d| data(None, d)) {
287            return false;
288        }
289        if let Some((name, states)) = &self.group
290            && ((cx.group)(name) & states != *states
291                || !self.group_data.iter().all(|d| data(Some(name), d)))
292        {
293            return false;
294        }
295        true
296    }
297
298    /// Applies to a pseudo-element (`placeholder:`, `selection:`): only
299    /// its color is read.
300    fn pseudo(&self) -> bool {
301        self.placeholder || self.selection
302    }
303
304    /// The color a pseudo-element rule's `decls` give it: the placeholder's
305    /// text color (`placeholder:text-*`), the selection's background, its
306    /// highlight (`selection:bg-*`). `None`: the rule sets something else,
307    /// which NSH has no native counterpart for.
308    fn pseudo_color(&self, decls: &[Decl]) -> Option<Color> {
309        match decls {
310            [decl] if self.placeholder => decl.text_color(),
311            [decl] if self.selection => decl.background_color(),
312            _ => None,
313        }
314    }
315
316    /// Applies only while the view (or its group) is pressed, hovered or
317    /// focused: press feedback.
318    fn interactive(&self) -> bool {
319        self.states & state::INTERACTION != 0
320            || self
321                .group
322                .as_ref()
323                .is_some_and(|(_, states)| states & state::INTERACTION != 0)
324    }
325
326    fn deps(&self) -> u16 {
327        let mut d = 0;
328        if self.dark.is_some() {
329            d |= deps::DARK;
330        }
331        if self.min_width.is_some() || self.max_width.is_some() {
332            d |= deps::WIDTH;
333        }
334        if self.landscape.is_some() {
335            d |= deps::WIDTH | deps::HEIGHT;
336        }
337        if self.rtl.is_some() {
338            d |= deps::RTL;
339        }
340        if self.reduce_motion.is_some() {
341            d |= deps::MOTION;
342        }
343        if self.pointer.is_some() || self.terminal.is_some() {
344            d |= deps::DEVICE;
345        }
346        if self.platform.is_some() {
347            d |= deps::PLATFORM;
348        }
349        if self.states != 0 || self.not_states != 0 {
350            d |= deps::STATE;
351        }
352        if self.group.is_some() {
353            d |= deps::GROUP;
354        }
355        if !self.data.is_empty() {
356            d |= deps::DATA;
357        }
358        if self.position != 0 {
359            d |= deps::POSITION;
360        }
361        d
362    }
363}
364
365#[derive(Debug, Clone, PartialEq)]
366pub(crate) struct Rule {
367    cond: Condition,
368    decls: Rc<[Decl]>,
369    /// Variant order: plain utilities first, then by Tailwind's order.
370    rank: Rank,
371    /// `!`: applied after everything else.
372    important: bool,
373    /// Names theme tokens ([`deps::THEME`]).
374    theme: bool,
375}
376
377/// One variant's place in Tailwind's variant order (Tailwind sorts the
378/// variants it registers, the compound ones by their inner variant and
379/// then by their modifier, the breakpoints by unit and then by value).
380#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
381pub(crate) struct Key {
382    /// The variant's (or for `group-*` the group's) place.
383    order: u16,
384    /// A breakpoint's unit (its index in [`BREAKPOINT_UNITS`]).
385    unit: u8,
386    /// A breakpoint's value (thousandths, negated for `max-*`), or a
387    /// group's inner variant.
388    value: i64,
389    /// A group's name (`group-hover/item`), `None` unnamed; a `data-*`
390    /// attribute's ([`Key::data`]).
391    name: Option<Box<str>>,
392}
393
394impl Key {
395    const fn new(order: u16) -> Self {
396        Self {
397            order,
398            unit: 0,
399            value: 0,
400            name: None,
401        }
402    }
403
404    /// `data-<name>:`'s place: [`rank::DATA`], then by name.
405    fn data(name: &str) -> Self {
406        Self {
407            name: Some(name.into()),
408            ..Self::new(rank::DATA)
409        }
410    }
411}
412
413/// Breakpoint units as Tailwind orders them: by their name.
414const BREAKPOINT_UNITS: [&str; 4] = ["", "pt", "px", "rem"];
415
416/// Where a rule's variants put it: Tailwind sorts rules by the bit set of
417/// their variants' places, so the highest variant decides, then the next
418/// highest, and a rule with one more variant comes later. Plain
419/// utilities have none and come first.
420#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
421pub(crate) struct Rank(Vec<Key>);
422
423impl Rank {
424    /// Adds `key`, keeping the keys highest first.
425    pub(crate) fn add(&mut self, key: Key) {
426        if let Err(i) = self.0.binary_search_by(|k| key.cmp(k)) {
427            self.0.insert(i, key);
428        }
429    }
430
431    /// The group variant of `inner` (a [`rank`] key) on group `name`.
432    pub(crate) fn add_group(&mut self, inner: &Key, name: &str) {
433        self.add(Key {
434            order: rank::GROUP,
435            unit: 0,
436            value: inner.order.into(),
437            name: (!name.is_empty()).then(|| name.into()),
438        });
439    }
440}
441
442impl From<Key> for Rank {
443    fn from(key: Key) -> Self {
444        Rank(vec![key])
445    }
446}
447
448/// The places of the variants (Tailwind's order, as [`variant`] gives
449/// them).
450pub(crate) mod rank {
451    use super::Key;
452
453    /// `group-*`: before the pseudo-elements and `first:` ... `even:`.
454    pub(crate) const GROUP: u16 = 1;
455    pub(crate) const SELECTION: Key = Key::new(10);
456    pub(crate) const PLACEHOLDER: Key = Key::new(11);
457    pub(crate) const FIRST: Key = Key::new(20);
458    pub(crate) const LAST: Key = Key::new(21);
459    pub(crate) const ONLY: Key = Key::new(22);
460    pub(crate) const ODD: Key = Key::new(23);
461    pub(crate) const EVEN: Key = Key::new(24);
462    pub(crate) const CHECKED: Key = Key::new(30);
463    pub(crate) const INDETERMINATE: Key = Key::new(31);
464    /// NSH's (Tailwind has `aria-selected:`).
465    pub(crate) const SELECTED: Key = Key::new(32);
466    pub(crate) const FOCUS_WITHIN: Key = Key::new(33);
467    pub(crate) const HOVER: Key = Key::new(34);
468    pub(crate) const FOCUS: Key = Key::new(35);
469    pub(crate) const FOCUS_VISIBLE: Key = Key::new(36);
470    pub(crate) const ACTIVE: Key = Key::new(37);
471    pub(crate) const ENABLED: Key = Key::new(38);
472    pub(crate) const DISABLED: Key = Key::new(39);
473    /// Tailwind's `aria-*` variants come after the pseudo-classes, in the
474    /// order of their names.
475    pub(crate) const ARIA_BUSY: Key = Key::new(40);
476    pub(crate) const ARIA_CHECKED: Key = Key::new(41);
477    pub(crate) const EXPANDED: Key = Key::new(42);
478    pub(crate) const ARIA_INVALID: Key = Key::new(43);
479    pub(crate) const ARIA_PRESSED: Key = Key::new(44);
480    pub(crate) const ARIA_SELECTED: Key = Key::new(45);
481    /// `data-*`, after `aria-*` as Tailwind registers them, in the order
482    /// of their names ([`Key::data`]).
483    pub(crate) const DATA: u16 = 46;
484    pub(crate) const MOTION_SAFE: Key = Key::new(47);
485    pub(crate) const MOTION_REDUCE: Key = Key::new(48);
486    /// `max-*` breakpoints, widest first.
487    pub(crate) const MAX: u16 = 50;
488    /// Breakpoints and `min-*`, narrowest first.
489    pub(crate) const MIN: u16 = 51;
490    pub(crate) const PORTRAIT: Key = Key::new(60);
491    pub(crate) const LANDSCAPE: Key = Key::new(61);
492    pub(crate) const LTR: Key = Key::new(62);
493    pub(crate) const RTL: Key = Key::new(63);
494    pub(crate) const DARK: Key = Key::new(64);
495    /// Tailwind's pointer variants, after `dark:` as it registers them.
496    pub(crate) const POINTER_COARSE: Key = Key::new(65);
497    pub(crate) const POINTER_FINE: Key = Key::new(66);
498    /// NSH's platform variants, after Tailwind's.
499    pub(crate) const IOS: Key = Key::new(70);
500    pub(crate) const ANDROID: Key = Key::new(71);
501    pub(crate) const WEB: Key = Key::new(72);
502    pub(crate) const TERMINAL: Key = Key::new(73);
503}
504
505impl Rule {
506    /// A rule applying `decls` while the node is in all of [`state`]
507    /// `states`, ordered by `rank`.
508    pub(crate) fn new(states: u16, rank: impl Into<Rank>, decls: Vec<Decl>) -> Self {
509        Self {
510            cond: Condition {
511                states,
512                ..Condition::default()
513            },
514            decls: Rc::from(decls),
515            rank: rank.into(),
516            important: false,
517            theme: false,
518        }
519    }
520
521    /// A state style (`activeStyle`, ...): `decls` while the node is in
522    /// `states` (and, unless `disabled`, not disabled), applied over the
523    /// inline style as `!` utilities are, ordered by `rank`.
524    pub(crate) fn state_style(
525        states: u16,
526        rank: impl Into<Rank>,
527        decls: Vec<crate::StyleDecl>,
528    ) -> Self {
529        // A style's defaults and its `currentColor` are the classes' own
530        // kinds, applied before the rules and read with the text color.
531        let decls = decls
532            .into_iter()
533            .map(|d| match d {
534                crate::StyleDecl::Default(key, value) => Decl::Default(key, value),
535                crate::StyleDecl::CurrentColor(key) => Decl::CurrentColor(key),
536                d => Decl::Style(d),
537            })
538            .collect();
539        let mut rule = Self::new(states, rank, decls);
540        if states & state::DISABLED == 0 {
541            rule.cond.not_states = state::DISABLED;
542        }
543        rule.important = true;
544        rule
545    }
546
547    /// [`Rule::new`], also requiring the nearest ancestor group `group`
548    /// (`""`: unnamed) in its states, and dark appearance when `dark`.
549    pub(crate) fn with(
550        states: u16,
551        group: Option<(&str, u16)>,
552        dark: bool,
553        rank: Rank,
554        decls: Vec<Decl>,
555    ) -> Self {
556        let mut rule = Self::new(states, rank, decls);
557        rule.cond.group = group.map(|(name, states)| (name.into(), states));
558        rule.cond.dark = dark.then_some(true);
559        rule
560    }
561}
562
563/// Node properties classes and styles set: those that are not layout or
564/// drawing (the core takes them from the style, [`crate::Style`]'s
565/// `numberOfLines`, `textOverflow`, `userSelect` and `pointerEvents`, and from
566/// the classes for the rest).
567#[derive(Debug, Clone, Default, PartialEq)]
568pub struct ClassProps {
569    /// `numberOfLines` (`line-clamp-*`, `truncate`); `Some(0)` removes a clamp.
570    pub number_of_lines: Option<u32>,
571    /// `textOverflow` (`text-ellipsis`, `text-clip`, `truncate`).
572    pub ellipsize: Option<EllipsizeMode>,
573    /// `whitespace-nowrap`, `text-nowrap`, `truncate`: lines never wrap.
574    /// Inherited, as CSS's `white-space`: a view's reaches the texts in it.
575    pub no_wrap: Option<bool>,
576    /// `text-pretty`: lines wrap, and a last line of a word or two takes
577    /// words from the lines above. Set with [`Self::no_wrap`].
578    pub pretty: bool,
579    /// `pointerEvents` (`pointer-events-none` / `-auto`).
580    pub pointer_events: Option<PointerEvents>,
581    /// `userSelect` (`select-none` / `select-text`; `auto`: none). A
582    /// view's reach the texts in it that say none, as CSS's `user-select:
583    /// auto` takes its parent's.
584    pub selectable: Option<bool>,
585    /// `placeholder:text-*` (inputs).
586    pub placeholder_color: Option<Color>,
587    /// `selection:bg-*`: the highlight of a selection (inputs, selectable
588    /// texts).
589    pub selection_color: Option<Color>,
590    /// `caret-*` (inputs).
591    pub caret_color: Option<Color>,
592    /// `text-shadow-*` layers beyond the first (drawn as one shadow).
593    pub text_shadows: Option<Vec<TextShadow>>,
594    /// `space-x-*` / `space-y-*`: margins the view gives its children.
595    pub space: Option<Space>,
596}
597
598/// `space-x-*` / `space-y-*` (and `-reverse`): the margins a view gives
599/// each of its children but the last, as Tailwind CSS's `:where(& >
600/// :not(:last-child))`: under the child's own margins, which win.
601#[derive(Debug, Clone, Default, PartialEq)]
602#[non_exhaustive]
603pub struct Space {
604    /// `space-x-*`: the end margin (`margin-inline-end`; the start one
605    /// with `space-x-reverse`).
606    pub x: Option<PropertyValue>,
607    /// `space-y-*`: the bottom margin (`margin-block-end`; the top one
608    /// with `space-y-reverse`).
609    pub y: Option<PropertyValue>,
610    /// `space-x-reverse`.
611    pub reverse_x: bool,
612    /// `space-y-reverse`.
613    pub reverse_y: bool,
614    /// The horizontal margins override normal child declarations.
615    pub important_x: bool,
616    /// The vertical margins override normal child declarations.
617    pub important_y: bool,
618}
619
620impl Space {
621    /// The margins of a child laid out in direction `rtl`: Tailwind's
622    /// `margin-inline-end`, the right side left to right and the left side
623    /// right to left (the start side when reversed).
624    pub(crate) fn apply(&self, style: &mut Style, important: bool, rtl: bool) {
625        use crate::style::StyleKey as K;
626        if let Some(v) = &self.x
627            && self.important_x == important
628        {
629            let (end, start) = if rtl {
630                (K::MarginLeft, K::MarginRight)
631            } else {
632                (K::MarginRight, K::MarginLeft)
633            };
634            let (key, other) = if self.reverse_x {
635                (start, end)
636            } else {
637                (end, start)
638            };
639            let _ = style.set_key(other, crate::style::StyleValue::Number(0.0));
640            let _ = style.apply_value(key, v);
641        }
642        if let Some(v) = &self.y
643            && self.important_y == important
644        {
645            let key = if self.reverse_y {
646                K::MarginTop
647            } else {
648                K::MarginBottom
649            };
650            let other = if self.reverse_y {
651                K::MarginBottom
652            } else {
653                K::MarginTop
654            };
655            let _ = style.set_key(other, crate::style::StyleValue::Number(0.0));
656            let _ = style.apply_value(key, v);
657        }
658    }
659}
660
661/// Precomputed rule capabilities on [`ClassList`], maintained by [`ClassList::add`]
662/// so [`ClassList::apply_with_current`] skips unnecessary passes and `Parts` allocations.
663mod rule_flags {
664    pub(super) const DEFAULTS: u8 = 1 << 0;
665    pub(super) const PSEUDO: u8 = 1 << 1;
666    pub(super) const PARTS: u8 = 1 << 2;
667    pub(super) const INTERACTIVE_BG: u8 = 1 << 3;
668}
669
670/// A parsed class string.
671#[derive(Debug, Clone, Default, PartialEq)]
672pub struct ClassList {
673    rules: Vec<Rule>,
674    /// [`deps`] bits.
675    deps: u16,
676    /// [`state`] bits the platform must report for this view.
677    tracked: u16,
678    /// [`rule_flags`] bits summarizing declarations and pseudo rules.
679    flags: u8,
680    /// The view is a `group` (`""`) or named groups (`group/item`).
681    groups: Vec<Box<str>>,
682    /// Classes that are not known utilities.
683    unknown: Vec<Box<str>>,
684}
685
686/// Interaction states do not match a disabled view.
687fn normalized(mut rule: Rule) -> Rule {
688    if rule.cond.states & state::INTERACTION != 0 {
689        rule.cond.not_states |= state::DISABLED;
690    }
691    rule
692}
693
694impl ClassList {
695    /// [`deps`] bits.
696    #[inline]
697    pub fn deps(&self) -> u16 {
698        self.deps
699    }
700
701    /// [`state`] bits whose changes the platform must report.
702    #[inline]
703    pub fn tracked_states(&self) -> u16 {
704        self.tracked
705    }
706
707    /// Group names this view defines (`""`: an unnamed `group`).
708    pub fn groups(&self) -> &[Box<str>] {
709        &self.groups
710    }
711
712    /// Classes that are not known utilities or variants.
713    pub fn unknown(&self) -> &[Box<str>] {
714        &self.unknown
715    }
716
717    /// Whether nothing applies.
718    pub fn is_empty(&self) -> bool {
719        self.rules.is_empty()
720    }
721
722    /// Applies the rules matching `cx` to `style` and `props`, then
723    /// `inline` (the node's inline style, which only `!` utilities win
724    /// over). `currentColor` (a border without a color) is the node's own
725    /// text color, else black.
726    pub fn apply(
727        &self,
728        cx: &Context<'_>,
729        theme: &Theme,
730        style: &mut Style,
731        props: &mut ClassProps,
732        inline: impl FnOnce(&mut Style),
733    ) {
734        self.apply_with(
735            cx,
736            &no_data,
737            theme,
738            CurrentColor::default(),
739            DEFAULT_CH,
740            style,
741            props,
742            inline,
743        );
744    }
745
746    /// [`ClassList::apply`] in a tree, where `current` says what the
747    /// node's `currentColor` comes from and `ch` is its font's `0` advance.
748    #[allow(clippy::too_many_arguments)]
749    pub(crate) fn apply_with(
750        &self,
751        cx: &Context<'_>,
752        data: Data<'_>,
753        theme: &Theme,
754        current: CurrentColor,
755        ch: f32,
756        style: &mut Style,
757        props: &mut ClassProps,
758        inline: impl FnOnce(&mut Style),
759    ) {
760        self.apply_with_current(cx, data, theme, current, None, ch, style, props, inline);
761    }
762
763    /// [`ClassList::apply_with`] taking a precomputed `resolved_current` when
764    /// the caller already resolved `current_color` for an inline style.
765    #[allow(clippy::too_many_arguments)]
766    pub(crate) fn apply_with_current(
767        &self,
768        cx: &Context<'_>,
769        data: Data<'_>,
770        theme: &Theme,
771        current: CurrentColor,
772        resolved_current: Option<Color>,
773        ch: f32,
774        style: &mut Style,
775        props: &mut ClassProps,
776        inline: impl FnOnce(&mut Style),
777    ) {
778        let mut parts = (self.flags & rule_flags::PARTS != 0).then(Parts::default);
779        let mut important = false;
780        let current = if self.deps & deps::CURRENT_COLOR != 0 {
781            resolved_current.unwrap_or_else(|| self.current_color(cx, data, current))
782        } else {
783            Color::BLACK
784        };
785        if let Some(p) = parts.as_mut() {
786            p.current = current;
787            p.ch = ch;
788        }
789        if self.flags & rule_flags::DEFAULTS != 0 {
790            for rule in &self.rules {
791                if rule.cond.pseudo() || !rule.cond.matches(cx, data) {
792                    continue;
793                }
794                for decl in rule.decls.iter() {
795                    match decl {
796                        Decl::Default(key, value) => {
797                            let _ = style.apply_value(*key, value);
798                        }
799                        Decl::CurrentColor(key) => style.set_color(*key, current),
800                        _ => {}
801                    }
802                }
803            }
804        }
805        // A background color of an interaction state (`active:bg-*`) hides
806        // the gradients unless that state sets one too: drawn over the
807        // color, they would hide the feedback (CSS would keep them).
808        let track_interactive_bg = self.flags & rule_flags::INTERACTIVE_BG != 0;
809        let mut state_background = false;
810        let mut state_image = false;
811        for rule in &self.rules {
812            if rule.cond.pseudo() || !rule.cond.matches(cx, data) {
813                continue;
814            }
815            important |= rule.important;
816            for decl in rule.decls.iter() {
817                decl.apply(
818                    cx.env.dark,
819                    rule.important,
820                    current,
821                    ch,
822                    style,
823                    props,
824                    parts.as_mut(),
825                );
826            }
827            if track_interactive_bg {
828                let background = rule.decls.iter().any(Decl::sets_background_color);
829                if rule.cond.interactive() {
830                    if background {
831                        state_background = true;
832                        state_image = false;
833                    }
834                    state_image |= rule.decls.iter().any(Decl::sets_background_image);
835                } else if background {
836                    // A later rule's color (`dark:bg-*`) is not feedback.
837                    state_background = false;
838                }
839            }
840        }
841        let state_color = if state_background {
842            style.view.background_color
843        } else {
844            Color::TRANSPARENT
845        };
846        if self.flags & rule_flags::PSEUDO != 0 {
847            // `placeholder:` and `selection:` rules only carry a color.
848            for rule in self.rules.iter().filter(|r| r.cond.pseudo()) {
849                if !rule.cond.matches(cx, data) {
850                    continue;
851                }
852                if let Some(c) = rule.cond.pseudo_color(&rule.decls) {
853                    if rule.cond.placeholder {
854                        props.placeholder_color = Some(c);
855                    } else {
856                        props.selection_color = Some(c);
857                    }
858                }
859            }
860        }
861        if let Some(p) = parts.as_ref()
862            && p.touched != 0
863        {
864            p.finish(style, props, theme, cx.window, p.touched);
865        }
866        inline(style);
867        if self.deps & deps::CURRENT_COLOR != 0 {
868            // What the classes set to `currentColor` inside a value.
869            style.apply_current_color(current);
870        }
871        if important {
872            // `!` utilities win over the inline style too, as in CSS. The
873            // parts keep every rule's values (a `!scale-*` still composes
874            // with a plain `translate-*`); only the groups the important
875            // rules touch are written again.
876            if let Some(p) = parts.as_mut() {
877                p.touched = 0;
878                p.transform_parts = 0;
879                p.screen.clear();
880            }
881            for rule in self
882                .rules
883                .iter()
884                .filter(|r| r.important && !r.cond.pseudo())
885            {
886                if rule.cond.matches(cx, data) {
887                    for decl in rule.decls.iter() {
888                        decl.apply(
889                            cx.env.dark,
890                            rule.important,
891                            current,
892                            ch,
893                            style,
894                            props,
895                            parts.as_mut(),
896                        );
897                    }
898                }
899            }
900            if let Some(p) = parts.as_ref()
901                && p.touched != 0
902            {
903                p.finish(style, props, theme, cx.window, p.touched);
904            }
905            if self.deps & deps::CURRENT_COLOR != 0 {
906                style.apply_current_color(current);
907            }
908        }
909        // Unless the inline style replaced the state's color.
910        if state_background && !state_image && style.view.background_color == state_color {
911            style.view.clear_background_images();
912        }
913    }
914}
915
916impl ClassList {
917    /// CSS's `currentColor` of a node with these classes in `cx`: the text
918    /// color of its `!` classes, its inline style, its classes, else the
919    /// one it inherits, else black.
920    pub(crate) fn current_color(
921        &self,
922        cx: &Context<'_>,
923        data: Data<'_>,
924        current: CurrentColor,
925    ) -> Color {
926        let [plain, important] = self.text_colors(cx, data);
927        important
928            .or(current.inline)
929            .or(plain)
930            .or(current.inherited)
931            .unwrap_or(Color::BLACK)
932    }
933
934    /// The text colors the rules matching `cx` set: the plain ones' and
935    /// the `!` ones' (which win over the inline style).
936    fn text_colors(&self, cx: &Context<'_>, data: Data<'_>) -> [Option<Color>; 2] {
937        let mut out = [None; 2];
938        for rule in &self.rules {
939            if rule.cond.pseudo() || !rule.cond.matches(cx, data) {
940                continue;
941            }
942            for decl in rule.decls.iter() {
943                if let Some(c) = decl.sets_text_color(cx.env.dark) {
944                    out[usize::from(rule.important)] = c;
945                }
946            }
947        }
948        out
949    }
950
951    /// The rules of a Rust component's styles (already in order), on a
952    /// view that is the groups `groups` (`""`: unnamed).
953    pub(crate) fn from_rules(rules: Vec<Rule>, groups: Vec<Box<str>>) -> Self {
954        let mut list = ClassList::default();
955        for rule in rules {
956            list.add(rule);
957        }
958        if !groups.is_empty() {
959            list.tracked |= state::PRESSED | state::HOVERED | state::FOCUS_WITHIN;
960            list.groups = groups;
961        }
962        list.rules
963            .sort_by(|a, b| (a.important, &a.rank).cmp(&(b.important, &b.rank)));
964        list
965    }
966
967    fn add(&mut self, rule: Rule) {
968        let rule = normalized(rule);
969        self.deps |= rule.cond.deps();
970        self.tracked |= rule.cond.states & !(state::DISABLED | state::ACCESSIBILITY);
971        if rule.cond.states & state::FOCUS_WITHIN != 0 {
972            self.tracked |= state::FOCUS_WITHIN;
973        }
974        let pseudo = rule.cond.pseudo();
975        if pseudo {
976            self.flags |= rule_flags::PSEUDO;
977        }
978        let interactive = !pseudo && rule.cond.interactive();
979        for d in rule.decls.iter() {
980            self.deps |= d.deps();
981            if !pseudo {
982                if d.is_default() {
983                    self.flags |= rule_flags::DEFAULTS;
984                }
985                if d.needs_parts() {
986                    self.flags |= rule_flags::PARTS;
987                }
988                if interactive && d.sets_background_color() {
989                    self.flags |= rule_flags::INTERACTIVE_BG;
990                }
991            }
992        }
993        if rule.theme {
994            self.deps |= deps::THEME;
995        }
996        self.rules.push(rule);
997    }
998
999    /// `self`, then `over`: at equal rank `over`'s rules win (the app's
1000    /// classes on a Rust component).
1001    pub(crate) fn merged(&self, over: &ClassList) -> ClassList {
1002        let mut list = self.clone();
1003        for rule in &over.rules {
1004            list.add(rule.clone());
1005        }
1006        list.groups.extend(over.groups.iter().cloned());
1007        list.unknown.extend(over.unknown.iter().cloned());
1008        list.tracked |= over.tracked;
1009        list.rules
1010            .sort_by(|a, b| (a.important, &a.rank).cmp(&(b.important, &b.rank)));
1011        list
1012    }
1013}
1014
1015/// The greatest number of parsed class tokens kept before the cache is cleared.
1016const TOKEN_CACHE: usize = 4096;
1017
1018/// Parsed class tokens shared by class strings of one engine.
1019#[derive(Debug, Default)]
1020struct TokenCache {
1021    entries: FxHashMap<Box<str>, Option<Token>>,
1022}
1023
1024impl TokenCache {
1025    fn parse(&mut self, theme: &Theme, token: &str) -> Option<Token> {
1026        if let Some(parsed) = self.entries.get(token) {
1027            return parsed.clone();
1028        }
1029        let parsed = parse_token(theme, token);
1030        if self.entries.len() >= TOKEN_CACHE {
1031            self.entries.clear();
1032        }
1033        self.entries.insert(token.into(), parsed.clone());
1034        parsed
1035    }
1036
1037    /// Token values changed under the same names: entries that cannot
1038    /// substitute them are still valid. Unknown entries are not: they may
1039    /// be substitutions whose old values did not parse.
1040    fn retain_token_independent(&mut self) {
1041        self.entries.retain(|_, parsed| {
1042            matches!(
1043                parsed,
1044                Some(Token::Rule(_) | Token::Group(_) | Token::Ignored)
1045            )
1046        });
1047    }
1048}
1049
1050/// The class cache and theme of one engine.
1051#[derive(Debug, Default)]
1052pub struct Tailwind {
1053    theme: Theme,
1054    cache: FxHashMap<Box<str>, std::rc::Rc<ClassList>>,
1055    token_cache: TokenCache,
1056}
1057
1058impl Tailwind {
1059    /// Classes with the default theme.
1060    pub fn new() -> Self {
1061        Self::default()
1062    }
1063
1064    /// Replaces the theme (cached classes are parsed again); the tokens
1065    /// stay.
1066    pub fn set_theme(&mut self, mut theme: Theme) {
1067        theme.share_tokens(&self.theme);
1068        self.theme = theme;
1069        self.cache.clear();
1070        self.token_cache.entries.clear();
1071    }
1072
1073    /// Takes design tokens `theme`. Returns which classes
1074    /// to resolve again: none ([`None`]) when the tokens did not change,
1075    /// those that name tokens ([`deps::THEME`]) when only their values
1076    /// did, else all (`u16::MAX`: unknown classes may name new ones).
1077    pub(crate) fn set_tokens(&mut self, theme: &crate::element::Tokens) -> Option<u16> {
1078        let tokens = ClassTokens::new(theme);
1079        let current = self.theme.tokens();
1080        if *current == tokens {
1081            return None;
1082        }
1083        let changed = if current.same_names(&tokens) {
1084            self.cache.retain(|_, list| list.deps & deps::THEME == 0);
1085            self.token_cache.retain_token_independent();
1086            deps::THEME
1087        } else {
1088            self.cache.clear();
1089            self.token_cache.entries.clear();
1090            u16::MAX
1091        };
1092        self.theme.replace_tokens(Arc::new(tokens));
1093        Some(changed)
1094    }
1095
1096    /// The theme.
1097    pub fn theme(&self) -> &Theme {
1098        &self.theme
1099    }
1100
1101    /// The parsed form of `classes` (cached by string).
1102    pub fn classes(&mut self, classes: &str) -> std::rc::Rc<ClassList> {
1103        self.get(classes).0
1104    }
1105
1106    /// Like [`Tailwind::classes`], and whether `classes` was parsed just
1107    /// now (to report its unknown classes once).
1108    pub fn get(&mut self, classes: &str) -> (std::rc::Rc<ClassList>, bool) {
1109        if let Some(c) = self.cache.get(classes) {
1110            return (c.clone(), false);
1111        }
1112        let parsed = std::rc::Rc::new(parse_with_cache(
1113            &self.theme,
1114            classes,
1115            &mut self.token_cache,
1116        ));
1117        // Class strings are static in practice; a bound keeps generated
1118        // ones (`w-[${n}px]`) from growing the cache forever.
1119        if self.cache.len() >= 4096 {
1120            self.cache.clear();
1121        }
1122        self.cache.insert(classes.into(), parsed.clone());
1123        (parsed, true)
1124    }
1125}
1126
1127/// Parses a class string.
1128pub fn parse(theme: &Theme, classes: &str) -> ClassList {
1129    parse_tokens(classes, |token| parse_token(theme, token))
1130}
1131
1132/// [`parse`] with its tokens shared through `cache`.
1133fn parse_with_cache(theme: &Theme, classes: &str, cache: &mut TokenCache) -> ClassList {
1134    parse_tokens(classes, |token| cache.parse(theme, token))
1135}
1136
1137fn parse_tokens(classes: &str, mut parse_token: impl FnMut(&str) -> Option<Token>) -> ClassList {
1138    let mut list = ClassList::default();
1139    for token in classes.split_ascii_whitespace() {
1140        match parse_token(token) {
1141            Some(Token::Rule(rule)) => list.add(rule),
1142            Some(Token::Themed(rule, dark)) => {
1143                list.add(rule);
1144                if let Some(dark) = dark {
1145                    list.add(*dark);
1146                }
1147            }
1148            Some(Token::Group(name)) => {
1149                list.tracked |= state::PRESSED | state::HOVERED | state::FOCUS_WITHIN;
1150                list.groups.push(name);
1151            }
1152            Some(Token::Ignored) => {}
1153            Some(Token::UnknownThemed) => {
1154                list.deps |= deps::THEME;
1155                list.unknown.push(token.into());
1156            }
1157            None => list.unknown.push(token.into()),
1158        }
1159    }
1160    // Stable: equal ranks keep the order of the string.
1161    list.rules
1162        .sort_by(|a, b| (a.important, &a.rank).cmp(&(b.important, &b.rank)));
1163    list
1164}
1165
1166#[derive(Debug, Clone)]
1167enum Token {
1168    Rule(Rule),
1169    /// A utility naming theme tokens: one rule, or one per appearance.
1170    Themed(Rule, Option<Box<Rule>>),
1171    Group(Box<str>),
1172    /// Accepted, but has no effect natively (`antialiased`; [`ignored`]).
1173    Ignored,
1174    /// A utility naming theme tokens whose substituted values do not parse.
1175    UnknownThemed,
1176}
1177
1178/// `token` split at `:` outside brackets: an iterator over its variants,
1179/// then the utility.
1180struct VariantSplit<'a> {
1181    utility: &'a str,
1182    variants: Variants<'a>,
1183    has_variants: bool,
1184}
1185
1186struct Variants<'a> {
1187    rest: &'a str,
1188    done: bool,
1189}
1190
1191impl<'a> Iterator for Variants<'a> {
1192    type Item = &'a str;
1193
1194    fn next(&mut self) -> Option<Self::Item> {
1195        if self.done {
1196            return None;
1197        }
1198        let mut depth = 0i32;
1199        for (i, b) in self.rest.bytes().enumerate() {
1200            match b {
1201                b'[' | b'(' => depth += 1,
1202                b']' | b')' => depth -= 1,
1203                b':' if depth == 0 => {
1204                    let part = &self.rest[..i];
1205                    self.rest = &self.rest[i + 1..];
1206                    return Some(part);
1207                }
1208                _ => {}
1209            }
1210        }
1211        self.done = true;
1212        Some(self.rest)
1213    }
1214}
1215
1216/// Splits `token` at `:` outside brackets, without collecting the parts.
1217fn split_variants(token: &str) -> VariantSplit<'_> {
1218    let mut depth = 0i32;
1219    let mut utility_start = 0;
1220    for (i, b) in token.bytes().enumerate() {
1221        match b {
1222            b'[' | b'(' => depth += 1,
1223            b']' | b')' => depth -= 1,
1224            b':' if depth == 0 => utility_start = i + 1,
1225            _ => {}
1226        }
1227    }
1228    let has_variants = utility_start != 0;
1229    let variants = if has_variants {
1230        &token[..utility_start - 1]
1231    } else {
1232        ""
1233    };
1234    VariantSplit {
1235        utility: &token[utility_start..],
1236        variants: Variants {
1237            rest: variants,
1238            done: !has_variants,
1239        },
1240        has_variants,
1241    }
1242}
1243
1244fn parse_token(theme: &Theme, token: &str) -> Option<Token> {
1245    let split = split_variants(token);
1246    let mut utility = split.utility;
1247    // `!p-4` (v3) or `p-4!` (v4): important.
1248    let mut important = false;
1249    if let Some(u) = utility.strip_prefix('!') {
1250        utility = u;
1251        important = true;
1252    } else if let Some(u) = utility.strip_suffix('!') {
1253        utility = u;
1254        important = true;
1255    }
1256    if !split.has_variants {
1257        if utility == "group" {
1258            return Some(Token::Group("".into()));
1259        }
1260        if let Some(name) = utility.strip_prefix("group/") {
1261            return Some(Token::Group(name.into()));
1262        }
1263    }
1264    let mut cond = Condition::default();
1265    let mut rank = Rank::default();
1266    for v in split.variants {
1267        rank.add(variant(theme, v, &mut cond)?);
1268    }
1269    if ignored(utility) {
1270        return Some(Token::Ignored);
1271    }
1272    if theme.tokens().replaces(utility) {
1273        return themed(theme, cond, rank, important, utility);
1274    }
1275    let Some(decls) = utilities::parse(theme, utility) else {
1276        return themed(theme, cond, rank, important, utility);
1277    };
1278    if cond.pseudo() && cond.pseudo_color(&decls).is_none() {
1279        return None;
1280    }
1281    Some(Token::Rule(Rule {
1282        cond,
1283        decls: Rc::from(decls),
1284        rank,
1285        important,
1286        theme: false,
1287    }))
1288}
1289
1290/// Utilities whose CSS is a rendering hint or what every native view
1291/// already is: accepted, and they do nothing (`box-border` is preflight's
1292/// `box-sizing`, NSH's only one).
1293fn ignored(utility: &str) -> bool {
1294    matches!(
1295        utility,
1296        "antialiased"
1297            | "subpixel-antialiased"
1298            | "isolation-auto"
1299            | "appearance-none"
1300            | "appearance-auto"
1301            | "will-change-auto"
1302            | "will-change-scroll"
1303            | "will-change-contents"
1304            | "will-change-transform"
1305    ) || utility
1306        .strip_prefix("will-change-[")
1307        .is_some_and(|v| v.len() > 1 && v.ends_with(']'))
1308}
1309
1310/// `utility` naming theme tokens (`bg-primary`, `rounded-(--radius)`):
1311/// parsed with their light and their dark values; two rules of the same
1312/// rank when those differ, so later utilities still win in both.
1313fn themed(
1314    theme: &Theme,
1315    cond: Condition,
1316    rank: Rank,
1317    important: bool,
1318    utility: &str,
1319) -> Option<Token> {
1320    let tokens = theme.tokens();
1321    let pseudo = Condition {
1322        placeholder: cond.placeholder,
1323        selection: cond.selection,
1324        ..Condition::default()
1325    };
1326    // Substituting is what makes the utility theme-dependent; whether the
1327    // value then parses decides only if it is a rule or an unknown class.
1328    let dark_only = cond.dark == Some(true);
1329    let light_substitution = if dark_only {
1330        None
1331    } else {
1332        tokens.substitute(utility, false)
1333    };
1334    let dark_substitution = tokens.substitute(utility, true);
1335    if light_substitution.is_none() && dark_substitution.is_none() {
1336        return None;
1337    }
1338    let parse = |substituted: Option<String>| {
1339        let decls = utilities::parse(theme, &substituted?)?;
1340        (!pseudo.pseudo() || pseudo.pseudo_color(&decls).is_some()).then_some(decls)
1341    };
1342    let rule = |cond: Condition, decls: Vec<Decl>| Rule {
1343        cond,
1344        decls: Rc::from(decls),
1345        rank: rank.clone(),
1346        important,
1347        theme: true,
1348    };
1349    // `dark:bg-primary` only needs the dark values.
1350    if dark_only {
1351        return Some(match parse(dark_substitution) {
1352            Some(decls) => Token::Themed(rule(cond, decls), None),
1353            None => Token::UnknownThemed,
1354        });
1355    }
1356    let (Some(light), Some(dark)) = (parse(light_substitution), parse(dark_substitution)) else {
1357        return Some(Token::UnknownThemed);
1358    };
1359    if light == dark {
1360        return Some(Token::Themed(rule(cond, light), None));
1361    }
1362    let mut dark_cond = cond.clone();
1363    dark_cond.dark = Some(true);
1364    let mut light_cond = cond;
1365    light_cond.dark = Some(false);
1366    Some(Token::Themed(
1367        rule(light_cond, light),
1368        Some(Box::new(rule(dark_cond, dark))),
1369    ))
1370}
1371
1372/// Whether `name` names a boolean `data-*` attribute (`data-<name>:`):
1373/// lower case letters, digits and `-`. Tailwind's `data-[state=open]:`,
1374/// an attribute's value, is not supported.
1375fn data_name(name: &str) -> bool {
1376    !name.is_empty()
1377        && name
1378            .bytes()
1379            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
1380}
1381
1382/// Applies variant `v` to `cond`; returns its place in Tailwind's order.
1383fn variant(theme: &Theme, v: &str, cond: &mut Condition) -> Option<Key> {
1384    use state::*;
1385    let states = |cond: &mut Condition, s: u16| {
1386        cond.states |= s;
1387    };
1388    // Tailwind registers `group-*` first, then the pseudo-elements, then
1389    // the structural pseudo-classes: later ones win over earlier ones.
1390    Some(match v {
1391        "selection" => {
1392            cond.selection = true;
1393            rank::SELECTION
1394        }
1395        "placeholder" => {
1396            cond.placeholder = true;
1397            rank::PLACEHOLDER
1398        }
1399        "first" => {
1400            cond.position |= position::FIRST;
1401            rank::FIRST
1402        }
1403        "last" => {
1404            cond.position |= position::LAST;
1405            rank::LAST
1406        }
1407        "only" => {
1408            cond.position |= position::ONLY;
1409            rank::ONLY
1410        }
1411        "odd" => {
1412            cond.position |= position::ODD;
1413            rank::ODD
1414        }
1415        "even" => {
1416            cond.position |= position::EVEN;
1417            rank::EVEN
1418        }
1419        "checked" => {
1420            states(cond, CHECKED);
1421            rank::CHECKED
1422        }
1423        "indeterminate" => {
1424            states(cond, INDETERMINATE);
1425            rank::INDETERMINATE
1426        }
1427        "selected" => {
1428            states(cond, SELECTED);
1429            rank::SELECTED
1430        }
1431        "focus-within" => {
1432            states(cond, FOCUS_WITHIN);
1433            rank::FOCUS_WITHIN
1434        }
1435        "hover" => {
1436            states(cond, HOVERED);
1437            rank::HOVER
1438        }
1439        "focus" => {
1440            states(cond, FOCUSED);
1441            rank::FOCUS
1442        }
1443        "focus-visible" => {
1444            states(cond, FOCUS_VISIBLE);
1445            rank::FOCUS_VISIBLE
1446        }
1447        "active" => {
1448            states(cond, PRESSED);
1449            rank::ACTIVE
1450        }
1451        "enabled" => {
1452            cond.not_states |= DISABLED;
1453            rank::ENABLED
1454        }
1455        "disabled" => {
1456            states(cond, DISABLED);
1457            rank::DISABLED
1458        }
1459        "aria-busy" => {
1460            states(cond, BUSY);
1461            rank::ARIA_BUSY
1462        }
1463        "aria-checked" => {
1464            states(cond, CHECKED);
1465            rank::ARIA_CHECKED
1466        }
1467        "aria-expanded" => {
1468            states(cond, EXPANDED);
1469            rank::EXPANDED
1470        }
1471        "aria-invalid" => {
1472            states(cond, INVALID);
1473            rank::ARIA_INVALID
1474        }
1475        "aria-pressed" => {
1476            states(cond, ARIA_PRESSED);
1477            rank::ARIA_PRESSED
1478        }
1479        "aria-selected" => {
1480            states(cond, SELECTED);
1481            rank::ARIA_SELECTED
1482        }
1483        "motion-safe" => {
1484            cond.reduce_motion = Some(false);
1485            rank::MOTION_SAFE
1486        }
1487        "motion-reduce" => {
1488            cond.reduce_motion = Some(true);
1489            rank::MOTION_REDUCE
1490        }
1491        "portrait" => {
1492            cond.landscape = Some(false);
1493            rank::PORTRAIT
1494        }
1495        "landscape" => {
1496            cond.landscape = Some(true);
1497            rank::LANDSCAPE
1498        }
1499        "ltr" => {
1500            cond.rtl = Some(false);
1501            rank::LTR
1502        }
1503        "rtl" => {
1504            cond.rtl = Some(true);
1505            rank::RTL
1506        }
1507        "dark" => {
1508            cond.dark = Some(true);
1509            rank::DARK
1510        }
1511        "ios" => {
1512            cond.platform = Some(Platform::Ios);
1513            rank::IOS
1514        }
1515        "android" => {
1516            cond.platform = Some(Platform::Android);
1517            rank::ANDROID
1518        }
1519        "web" => {
1520            cond.platform = Some(Platform::Web);
1521            rank::WEB
1522        }
1523        "pointer-coarse" => {
1524            cond.pointer = Some(Pointer::Coarse);
1525            rank::POINTER_COARSE
1526        }
1527        "pointer-fine" => {
1528            cond.pointer = Some(Pointer::Fine);
1529            rank::POINTER_FINE
1530        }
1531        "terminal" => {
1532            cond.terminal = Some(true);
1533            rank::TERMINAL
1534        }
1535        v => {
1536            // `data-range-start`: Tailwind 4's boolean form, `[data-range-start]`.
1537            if let Some(name) = v.strip_prefix("data-").filter(|n| data_name(n)) {
1538                if !cond.data.iter().any(|d| **d == *name) {
1539                    cond.data.push(name.into());
1540                }
1541                return Some(Key::data(name));
1542            }
1543            if let Some(rest) = v.strip_prefix("group-") {
1544                // `group-hover`, `group-hover/item`.
1545                let (s, name) = match rest.split_once('/') {
1546                    Some((s, n)) => (s, n),
1547                    None => (rest, ""),
1548                };
1549                if let Some(data) = s.strip_prefix("data-").filter(|n| data_name(n)) {
1550                    let entry = cond.group.get_or_insert_with(|| (name.into(), 0));
1551                    if *entry.0 != *name {
1552                        return None;
1553                    }
1554                    if !cond.group_data.iter().any(|d| **d == *data) {
1555                        cond.group_data.push(data.into());
1556                    }
1557                    let mut group = Rank::default();
1558                    group.add_group(&Key::data(data), name);
1559                    return group.0.pop();
1560                }
1561                let (bit, inner) = match s {
1562                    "hover" => (HOVERED, rank::HOVER),
1563                    "active" => (PRESSED, rank::ACTIVE),
1564                    "focus" => (FOCUSED, rank::FOCUS),
1565                    "focus-visible" => (FOCUS_VISIBLE, rank::FOCUS_VISIBLE),
1566                    "focus-within" => (FOCUS_WITHIN, rank::FOCUS_WITHIN),
1567                    "disabled" => (DISABLED, rank::DISABLED),
1568                    "selected" => (SELECTED, rank::SELECTED),
1569                    "checked" => (CHECKED, rank::CHECKED),
1570                    "indeterminate" => (INDETERMINATE, rank::INDETERMINATE),
1571                    "aria-busy" => (BUSY, rank::ARIA_BUSY),
1572                    "aria-checked" => (CHECKED, rank::ARIA_CHECKED),
1573                    "aria-expanded" => (EXPANDED, rank::EXPANDED),
1574                    "aria-invalid" => (INVALID, rank::ARIA_INVALID),
1575                    "aria-pressed" => (ARIA_PRESSED, rank::ARIA_PRESSED),
1576                    "aria-selected" => (SELECTED, rank::ARIA_SELECTED),
1577                    _ => return None,
1578                };
1579                let entry = cond.group.get_or_insert_with(|| (name.into(), 0));
1580                if *entry.0 != *name {
1581                    return None;
1582                }
1583                entry.1 |= bit;
1584                let mut group = Rank::default();
1585                group.add_group(&inner, name);
1586                return group.0.pop();
1587            }
1588            // Breakpoints: `md:`, `max-md:`, `min-[600px]:`, `max-[600px]:`.
1589            let (max, name) = match v.strip_prefix("max-") {
1590                Some(n) => (true, n),
1591                None => (false, v.strip_prefix("min-").unwrap_or(v)),
1592            };
1593            // Tailwind orders breakpoints by their unit's name, then by
1594            // their value (`max-*` widest first).
1595            let (width, unit, value) =
1596                match name.strip_prefix('[').and_then(|n| n.strip_suffix(']')) {
1597                    Some(arbitrary) => {
1598                        let arbitrary = arbitrary.trim();
1599                        let digits = arbitrary
1600                            .find(|c: char| !(c.is_ascii_digit() || c == '.'))
1601                            .unwrap_or(arbitrary.len());
1602                        let unit = BREAKPOINT_UNITS
1603                            .iter()
1604                            .position(|u| *u == &arbitrary[digits..])?;
1605                        let value = crate::css::number(&arbitrary[..digits])?;
1606                        (crate::css::length(arbitrary)?, unit, value)
1607                    }
1608                    None => {
1609                        let b = theme.breakpoints.iter().find(|b| *b.0 == *name)?;
1610                        match b.2 {
1611                            true => (b.1, 3, b.1 / theme.rem),
1612                            false => (b.1, 2, b.1),
1613                        }
1614                    }
1615                };
1616            let thousandths = (f64::from(value) * 1000.0).round() as i64;
1617            let key = |order, value| Key {
1618                order,
1619                unit: unit as u8,
1620                value,
1621                name: None,
1622            };
1623            if max {
1624                cond.max_width = Some(cond.max_width.map_or(width, |w| w.min(width)));
1625                key(rank::MAX, -thousandths)
1626            } else {
1627                cond.min_width = Some(cond.min_width.map_or(width, |w| w.max(width)));
1628                key(rank::MIN, thousandths)
1629            }
1630        }
1631    })
1632}
1633
1634#[cfg(test)]
1635mod tests;