Skip to main content

nsh_core/core/
classes.rs

1//! Tailwind classes on nodes: resolving them into styles (with the inline
2//! `style` applied on top) and resolving them again when what they depend
3//! on changes: the appearance, the window size, the layout direction, the
4//! node's interaction states, its group's states or its sibling position.
5//! A sibling-position change restyles, in one pass over the parent's
6//! children (`positions_changed`), only those whose position bits moved:
7//! once per parent before the next flush (`flush_positions`), however many
8//! children joined or left, so mounting a long list styles each row once.
9//! Ordinary restyling takes the position its node was last styled at while
10//! its parent's children did not move since (`known_position`).
11
12use super::{Core, Key, Kind, NO_KEY, Positional, dirty, disabling_changes};
13use crate::{
14    element::JsEvent,
15    geometry::{Points, Size},
16    mount::MountItem,
17    ops::{EventKind, EventPayload, NodeId, ResizeMode},
18    platform::{Appearance, ColorScheme, InputModality},
19    props::PointerEvents,
20    style::{Color, PaintStyle, Style, StylePatch, TextStyle, VerticalAlign, ViewStyle},
21    tailwind::{
22        ClassEnvironment, ClassList, ClassProps, Context, Pointer, Rule, Theme, deps, position,
23        rank, state,
24    },
25    text::TextEngine,
26};
27
28/// Maximum entries kept in [`Core::resolved_styles`] before clearing.
29pub(super) const RESOLVED_STYLE_CACHE: usize = 4096;
30
31/// Cache key for [`Core::resolved_styles`], normalized to the dependency bits of `ClassList`.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub(super) struct ResolvedKey {
34    classes: usize,
35    states: u16,
36    position: u8,
37    flags: u8,
38    width: u32,
39    height: u32,
40    inherited_color: u32,
41}
42
43impl ResolvedKey {
44    fn new(
45        classes: &ClassList,
46        env: &ClassEnvironment,
47        viewport: Size<Points>,
48        rtl: bool,
49        states: u16,
50        position: u8,
51        inherited_color: Option<Color>,
52    ) -> Self {
53        let deps = classes.deps();
54        let has_current = deps & deps::CURRENT_COLOR != 0;
55        let flags = u8::from(rtl)
56            | (u8::from(deps & deps::DARK != 0 && env.dark) << 1)
57            | (u8::from(deps & deps::MOTION != 0 && env.reduce_motion) << 2)
58            | (u8::from(deps & deps::DEVICE != 0 && env.pointer == Pointer::Fine) << 3)
59            | (u8::from(deps & deps::DEVICE != 0 && env.terminal) << 4)
60            | (u8::from(has_current && inherited_color.is_some()) << 5);
61        Self {
62            classes: std::ptr::from_ref(classes) as usize,
63            states: if deps & deps::STATE != 0 { states } else { 0 },
64            position: if deps & deps::POSITION != 0 {
65                position
66            } else {
67                0
68            },
69            flags,
70            width: if deps & deps::WIDTH != 0 {
71                viewport.width.0.to_bits()
72            } else {
73                0
74            },
75            height: if deps & deps::HEIGHT != 0 {
76                viewport.height.0.to_bits()
77            } else {
78                0
79            },
80            inherited_color: if has_current {
81                inherited_color.map_or(0, |c| c.0)
82            } else {
83                0
84            },
85        }
86    }
87}
88
89/// Cached resolved style fields ready to apply via [`Core::apply_resolved_style`].
90pub(super) struct ResolvedClassStyle {
91    /// The classes resolved: kept so that [`ResolvedKey::classes`], their
92    /// address, names no other list while the entry is cached.
93    pub(super) classes: std::rc::Rc<ClassList>,
94    pub(super) layout: std::rc::Rc<taffy::Style>,
95    pub(super) view: Option<std::rc::Rc<ViewStyle>>,
96    pub(super) text: Option<std::rc::Rc<TextStyle>>,
97    pub(super) paint: Option<std::rc::Rc<PaintStyle>>,
98    pub(super) props: Option<std::rc::Rc<ClassProps>>,
99    pub(super) sticky: Option<taffy::Rect<taffy::LengthPercentageAuto>>,
100    pub(super) object_fit: Option<ResizeMode>,
101    pub(super) perspective: Option<Points>,
102    pub(super) z_index: i32,
103    pub(super) vertical_align: VerticalAlign,
104    pub(super) wants_fixed: bool,
105    pub(super) rtl: bool,
106    pub(super) has_logical: bool,
107}
108
109/// The text color an inline style sets (`color`).
110fn inline_color(patch: &StylePatch) -> Option<Color> {
111    patch.decls().iter().rev().find_map(|d| match d {
112        crate::style::StyleDecl::Set(crate::style::StyleKey::Color, value) => Some(match value {
113            crate::style::PropertyValue::Color(c) => *c,
114            _ => None,
115        }),
116        _ => None,
117    })?
118}
119
120/// The states the platform reports ([`Core::set_states`]).
121const REPORTED: u16 = state::PRESSED | state::HOVERED | state::FOCUSED;
122
123/// The states the platform reports whatever a view tracks
124/// ([`crate::input::reported_states`]): never forgotten when its tracking
125/// changes.
126const ALWAYS_REPORTED: u16 = state::FOCUSED;
127
128/// The states a view is in for a moment, by the user's hand: a terminal
129/// lays a view out as it rests, without them (`Node::resting_fill`).
130const INTERACTION: u16 =
131    state::PRESSED | state::HOVERED | state::FOCUSED | state::FOCUS_VISIBLE | state::FOCUS_WITHIN;
132
133/// The `class` and `classList` props as set.
134#[derive(Debug, Default)]
135pub(super) struct ClassNames {
136    class: Box<str>,
137    list: Vec<Box<str>>,
138}
139
140/// A styled part of a node, besides the node itself: a state style
141/// (`activeStyle`, ...) or a part of a page or list.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub(super) enum Part {
144    /// `activeStyle`.
145    Active,
146    /// `hoverStyle`.
147    Hover,
148    /// `focusStyle`.
149    Focus,
150    /// `disabledStyle`.
151    Disabled,
152    /// `selectedStyle`.
153    Selected,
154    /// `checkedStyle`.
155    Checked,
156    /// `indeterminateStyle`.
157    Indeterminate,
158    /// `expandedStyle`.
159    Expanded,
160    /// `pressedStyle`.
161    Pressed,
162    /// `focusWithinStyle`.
163    FocusWithin,
164    /// `focusVisibleStyle`.
165    FocusVisible,
166    /// A page's `headerStyle` / `headerClass`.
167    Header,
168    /// A list's `contentClass`.
169    Content,
170}
171
172impl Part {
173    /// The state bits and rank of a state style.
174    fn state(self) -> Option<(u16, crate::tailwind::Key)> {
175        Some(match self {
176            Part::Active => (state::PRESSED, rank::ACTIVE),
177            Part::Hover => (state::HOVERED, rank::HOVER),
178            Part::Focus => (state::FOCUSED, rank::FOCUS),
179            Part::Disabled => (state::DISABLED, rank::DISABLED),
180            Part::Selected => (state::SELECTED, rank::SELECTED),
181            Part::Checked => (state::CHECKED, rank::CHECKED),
182            Part::Indeterminate => (state::INDETERMINATE, rank::INDETERMINATE),
183            Part::Expanded => (state::EXPANDED, rank::EXPANDED),
184            Part::Pressed => (state::ARIA_PRESSED, rank::ARIA_PRESSED),
185            Part::FocusWithin => (state::FOCUS_WITHIN, rank::FOCUS_WITHIN),
186            Part::FocusVisible => (state::FOCUS_VISIBLE, rank::FOCUS_VISIBLE),
187            _ => return None,
188        })
189    }
190}
191
192/// What only some nodes have ([`super::Node`]'s `parts`).
193#[derive(Debug, Default)]
194pub(super) struct NodeParts {
195    /// The classes as set, before the state styles are merged in.
196    base: Option<std::rc::Rc<ClassList>>,
197    /// The state styles, by [`Part`] (the first eleven).
198    states: [Option<std::rc::Rc<StylePatch>>; 11],
199    /// The state styles as rules (none without any).
200    state_rules: Option<std::rc::Rc<ClassList>>,
201    /// The inline styles of the other parts.
202    styles: Vec<(Part, std::rc::Rc<StylePatch>)>,
203    /// The classes of the other parts.
204    classes: Vec<(Part, std::rc::Rc<ClassList>)>,
205    /// The names a part's classes were set by (`headerClass`,
206    /// `contentClass`; a typed list has none): they are parsed again when
207    /// the theme or the design tokens they read change.
208    class_names: Vec<(Part, Box<str>)>,
209    /// The group whose press it shows as a part (`Prop::ProjectedActive`).
210    active_group: Option<&'static str>,
211    /// It was last styled with that group's press.
212    group_pressed: bool,
213}
214
215impl NodeParts {
216    /// The group whose press it shows as a part.
217    pub(super) fn active_group(&self) -> Option<&'static str> {
218        self.active_group
219    }
220}
221
222/// The [`state`] bits an element is in by its accessibility state `s`:
223/// selected, checked (true), indeterminate (checked mixed), expanded,
224/// pressed (true: a toggle button that is on), busy and invalid.
225pub(super) fn accessibility_states(s: &crate::AccessibilityState) -> u16 {
226    use crate::Checked;
227    let mut states = 0;
228    if s.selected {
229        states |= state::SELECTED;
230    }
231    match s.checked {
232        Some(Checked::True) => states |= state::CHECKED,
233        Some(Checked::Mixed) => states |= state::INDETERMINATE,
234        _ => {}
235    }
236    if s.expanded == Some(true) {
237        states |= state::EXPANDED;
238    }
239    if s.pressed == Some(Checked::True) {
240        states |= state::ARIA_PRESSED;
241    }
242    if s.busy {
243        states |= state::BUSY;
244    }
245    if s.invalid {
246        states |= state::INVALID;
247    }
248    states
249}
250
251/// The state style parts, by their index in [`NodeParts::states`].
252const STATE_PARTS: [Part; 11] = [
253    Part::Active,
254    Part::Hover,
255    Part::Focus,
256    Part::Disabled,
257    Part::Selected,
258    Part::Checked,
259    Part::Indeterminate,
260    Part::Expanded,
261    Part::Pressed,
262    Part::FocusWithin,
263    Part::FocusVisible,
264];
265
266impl<M: TextEngine> Core<M> {
267    /// Sets the environment class variants depend on (`dark:`, `ios:`,
268    /// `motion-reduce:`): nodes whose classes depend on it are styled again.
269    pub fn set_class_environment(&mut self, mut env: ClassEnvironment) {
270        self.system_dark = env.dark;
271        env.dark = self.shown_dark();
272        self.apply_class_environment(env);
273    }
274
275    /// Dark appearance as shown: the app's, else the system's.
276    pub(super) fn shown_dark(&self) -> bool {
277        let system = if self.system_dark {
278            ColorScheme::Dark
279        } else {
280            ColorScheme::Light
281        };
282        self.appearance.resolve(system) == ColorScheme::Dark
283    }
284
285    /// The appearance the app asks for (`nsh.json` `"appearance"`, TS
286    /// `setColorScheme`, [`crate::element::set_color_scheme`]): what
287    /// `dark:` variants and the components' theme follow in place of the
288    /// system's; the platform applies it to its own controls
289    /// ([`MountItem::Appearance`]).
290    pub fn set_appearance(&mut self, appearance: Appearance) {
291        if self.appearance == appearance {
292            return;
293        }
294        self.appearance = appearance;
295        self.mount.push(MountItem::Appearance { appearance });
296        let dark = self.shown_dark();
297        let mut env = self.class_env;
298        env.dark = dark;
299        self.apply_class_environment(env);
300        let mut environment = self.components.environment;
301        environment.dark = dark;
302        self.apply_environment(environment);
303    }
304
305    fn apply_class_environment(&mut self, env: ClassEnvironment) {
306        if self.class_env == env {
307            return;
308        }
309        let changed = (if env.dark != self.class_env.dark { deps::DARK } else { 0 })
310            | (if env.reduce_motion != self.class_env.reduce_motion { deps::MOTION } else { 0 })
311            | (if env.pointer != self.class_env.pointer || env.terminal != self.class_env.terminal {
312                deps::DEVICE
313            } else {
314                0
315            })
316            // `ios:` / `android:` never change at run time, but a new
317            // platform must reach classes resolved before it was known.
318            | (if env.platform != self.class_env.platform { deps::PLATFORM } else { 0 });
319        if env.platform != self.class_env.platform {
320            self.resolved_styles.clear();
321        }
322        self.class_env = env;
323        if env.reduce_motion {
324            self.clear_pressed_impulses();
325        }
326        self.restyle_where(changed);
327        self.parts_restyled();
328    }
329
330    /// The platform reports interaction states of view `id` (`active:`,
331    /// `hover:`, `focus:`): state bits for the states it
332    /// tracks ([`MountItem::TrackStates`]), and `FOCUSED` whatever it
333    /// tracks ([`crate::input::reported_states`]); see
334    /// [`crate::tailwind::state`].
335    pub fn set_states(&mut self, id: NodeId, states: u16) {
336        let Ok(key) = self.key(id) else { return };
337        self.set_node_states(key, states);
338    }
339
340    /// Reports the interaction states of view `id` after a short completed
341    /// press, holding `state::PRESSED` for `hold` so same-turn tap-to-click
342    /// releases still render `:active` feedback before settling to `states`.
343    /// Any subsequent state report for `id` (including a new press or
344    /// cancellation) supersedes the pending release.
345    pub fn release_states_after(&mut self, id: NodeId, states: u16, hold: std::time::Duration) {
346        let Ok(key) = self.key(id) else { return };
347        self.pressed_impulses.retain(|&(k, _, _)| k != key);
348        if self.class_env.reduce_motion
349            || hold.is_zero()
350            || crate::time::manual()
351            || states & state::PRESSED != 0
352            || self.press_cancelled(key)
353        {
354            self.set_node_states(key, states);
355            return;
356        }
357        self.set_node_states(key, states | state::PRESSED);
358        if self.nodes[key as usize].states & state::PRESSED != 0 {
359            self.pressed_impulses
360                .push((key, id, crate::time::now() + hold));
361        }
362    }
363
364    /// Earliest deadline at which a short press's held `PRESSED` state ends.
365    pub fn next_state_timer(&self) -> Option<crate::time::Instant> {
366        self.pressed_impulses.iter().map(|&(_, _, due)| due).min()
367    }
368
369    /// Releases any short-press `PRESSED` impulses due by `now`; returns
370    /// whether any state changed.
371    pub fn expire_state_timers(&mut self, now: crate::time::Instant) -> bool {
372        if self.pressed_impulses.iter().all(|&(_, _, due)| due > now) {
373            return false;
374        }
375        let mut due = Vec::new();
376        self.pressed_impulses.retain(|&(k, id, at)| {
377            if at <= now {
378                due.push((k, id));
379                false
380            } else {
381                true
382            }
383        });
384        let mut changed = false;
385        for (key, id) in due {
386            let Some(current) = self
387                .nodes
388                .get(key as usize)
389                .filter(|n| n.id == id)
390                .map(|n| n.states & REPORTED)
391            else {
392                continue;
393            };
394            if current & state::PRESSED != 0 {
395                let before = self.nodes[key as usize].states;
396                self.set_node_states(key, current & !state::PRESSED);
397                changed |= self.nodes[key as usize].states != before;
398            }
399        }
400        changed
401    }
402
403    fn clear_pressed_impulses(&mut self) {
404        let pending = std::mem::take(&mut self.pressed_impulses);
405        for (key, id, _) in pending {
406            if let Some(current) = self
407                .nodes
408                .get(key as usize)
409                .filter(|n| n.id == id)
410                .map(|n| n.states & REPORTED)
411                && current & state::PRESSED != 0
412            {
413                self.set_node_states(key, current & !state::PRESSED);
414            }
415        }
416    }
417
418    /// [`Self::set_states`] by key.
419    fn set_node_states(&mut self, key: Key, states: u16) {
420        if states & state::PRESSED != 0 || self.press_cancelled(key) {
421            self.pressed_impulses.retain(|&(k, _, _)| k != key);
422        }
423        let id = self.nodes[key as usize].id;
424        let impulse_held = self
425            .pressed_impulses
426            .iter()
427            .any(|&(k, imp_id, _)| k == key && imp_id == id);
428        let held = self.held_pressed() == Some(key) || impulse_held;
429        let node = &mut self.nodes[key as usize];
430        let mut new = node.states & !REPORTED | states & REPORTED;
431        if held {
432            new |= state::PRESSED;
433        }
434        if !held && self.press_cancelled(key) {
435            new &= !state::PRESSED;
436        }
437        let node = &mut self.nodes[key as usize];
438        if new == node.states {
439            return;
440        }
441        let focus_changed = (new ^ node.states) & state::FOCUSED != 0;
442        node.states = new;
443        self.states_changed(key);
444        if focus_changed {
445            self.focus_reported(key, new & state::FOCUSED != 0);
446        }
447    }
448
449    /// A span of a text heard the pointer come or go, or a press go in or
450    /// out (`kind`): its hover and press states, which no view reports
451    /// for it.
452    pub(super) fn span_state(&mut self, id: NodeId, kind: crate::ops::EventKind) {
453        use crate::ops::EventKind;
454        let (bit, on) = match kind {
455            EventKind::MouseEnter => (state::HOVERED, true),
456            EventKind::MouseLeave => (state::HOVERED, false),
457            EventKind::PressDown => (state::PRESSED, true),
458            EventKind::PressUp => (state::PRESSED, false),
459            _ => return,
460        };
461        let Ok(key) = self.key(id) else { return };
462        let tracked = self.nodes[key as usize]
463            .classes
464            .as_ref()
465            .map_or(0, |c| c.tracked_states());
466        if tracked & bit == 0 || !self.is_text_span(key) {
467            return;
468        }
469        let node = &mut self.nodes[key as usize];
470        let new = if on {
471            node.states | bit
472        } else {
473            node.states & !bit
474        };
475        if new != node.states {
476            node.states = new;
477            self.states_changed(key);
478        }
479    }
480
481    /// View `key` took (or lost) the keyboard focus. A surface has one: a
482    /// view taking it is the focus whether or not the one before reported
483    /// losing it yet, and a view losing it that is not the focus changes
484    /// nothing. The chain is worked out in the next commit round, once for
485    /// all the reports before it, so a move reported as a blur then a
486    /// focus leaves the views both chains share as they were; a blur no
487    /// focus follows in that round waits for the next display frame
488    /// (`blur_held`), so the focus arriving in a later message is still
489    /// the same move. The root
490    /// view taking it (macOS's first responder when no view has it) is no
491    /// focus.
492    fn focus_reported(&mut self, key: Key, focused: bool) {
493        let id = self.nodes[key as usize].id;
494        if focused {
495            self.focus = (key != self.root).then_some((key, id));
496            self.focus_visible = self.focus_shows(key);
497            // The focus a dialog gave its first control as it opened: no
498            // hint for it (`Core::modal_focus_given`).
499            let given_by_modal = self.modal_focus_given.take() == Some(id);
500            self.focus_by_keyboard = self.focus_shows_hints()
501                && self.modality == Some(InputModality::Keyboard)
502                && !self.restoring_modal_focus
503                && !given_by_modal;
504            // A popup a pointer opened gave it back (`pointer_focus_back`):
505            // still the pointer's, whatever closed the popup.
506            let given_back = self.pointer_focus_back.take() == Some(id);
507            self.focus_by_pointer = given_back || self.modality == Some(InputModality::Pointer);
508            self.blur_held = false;
509        } else if self.focus == Some((key, id)) {
510            self.focus = None;
511            self.blur_held = true;
512        } else {
513            return;
514        }
515        self.focus_moved = true;
516    }
517
518    /// The platform reports what the user gave the surface input with
519    /// last ([`InputModality`]), before the focus moves it causes: a key
520    /// typed while the focus does not show makes it show, as browsers
521    /// do. A pointer leaves a focus that shows as it is: only a move of
522    /// the focus decides again ([`Self::focus_shows`]). A hint the focus
523    /// shows is decided only as the focus moves
524    /// ([`Self::keyboard_moves_focus`]): a key typed after a press shows
525    /// the focus, never the hint of the view it is on.
526    pub fn set_input_modality(&mut self, modality: InputModality) {
527        self.restoring_modal_focus = false;
528        self.modal_focus_given = None;
529        self.modality = Some(modality);
530        if modality == InputModality::Keyboard && self.focus.is_some() && !self.focus_visible {
531            self.focus_visible = true;
532            self.focus_visible_moved = true;
533        }
534    }
535
536    /// Whether the focus coming to `key` shows (`focus-visible:`), the
537    /// one rule every platform follows, after CSS's `:focus-visible`: an
538    /// input that edits always shows it (it takes typing), any other view
539    /// when the keyboard moved the focus ([`Self::keyboard_moves_focus`]).
540    pub(super) fn focus_shows(&self, key: Key) -> bool {
541        let node = &self.nodes[key as usize];
542        let edits = node.kind == Kind::Input
543            && node
544                .input
545                .as_ref()
546                .is_some_and(|input| input.config.editable);
547        edits || self.keyboard_moves_focus()
548    }
549
550    /// Whether the focus moving now is the keyboard's, by the surface's
551    /// last input: unless that was a pointer, so the keyboard's moves
552    /// count (Tab, a group's arrows, a shortcut) and so does a move the
553    /// app makes (`focus()`, a calendar or a dialog moving it as it opens)
554    /// after a key, while a press, a tap or a move after one do not.
555    /// Before any input it counts, as a browser's `autofocus` shows its
556    /// focus. `focus-visible:` ([`Self::focus_shows`]) follows it; the
557    /// hints the focus shows (`Core::focus_hints`) ask for a key first
558    /// and a platform whose tooltips follow the focus
559    /// ([`Self::focus_shows_hints`]).
560    /// Whether the focus the keyboard moves shows the hint of the anchor
561    /// it comes to (`Core::focus_by_keyboard`). Not on macOS and iOS:
562    /// AppKit's `toolTip` and UIKit's `UIToolTipInteraction` show only
563    /// for the pointer resting on a view, never for Full Keyboard Access
564    /// or a hardware keyboard's focus. Elsewhere it does, as WinUI's
565    /// `ToolTipService` shows a tooltip for the keyboard's focus and the
566    /// WAI-ARIA tooltip pattern for a focus on its trigger. Even there a
567    /// focus before any input (an `autoFocus` at launch) shows none: the
568    /// user moved nothing.
569    fn focus_shows_hints(&self) -> bool {
570        !matches!(
571            self.components.environment.os,
572            crate::platform::Os::MacOs | crate::platform::Os::Ios
573        )
574    }
575
576    fn keyboard_moves_focus(&self) -> bool {
577        self.modality != Some(InputModality::Pointer)
578    }
579
580    /// Puts `FOCUS_VISIBLE` on the focus while it shows and takes it off
581    /// the view that had it: one view changes, the rest are not touched.
582    pub(super) fn update_focus_visible(&mut self) {
583        let alive = |this: &Self, (k, id): (Key, NodeId)| {
584            this.nodes.get(k as usize).is_some_and(|n| n.id == id)
585        };
586        let target = self.focus.filter(|&f| self.focus_visible && alive(self, f));
587        if target == self.focus_visible_on {
588            return;
589        }
590        let flipped = target.is_some() != self.focus_visible_on.is_some();
591        if let Some(old) = self.focus_visible_on.take()
592            && alive(self, old)
593        {
594            let node = &mut self.nodes[old.0 as usize];
595            if node.states & state::FOCUS_VISIBLE != 0 {
596                node.states &= !state::FOCUS_VISIBLE;
597                self.states_changed(old.0);
598            }
599        }
600        if let Some((k, _)) = target {
601            let node = &mut self.nodes[k as usize];
602            if node.states & state::FOCUS_VISIBLE == 0 {
603                node.states |= state::FOCUS_VISIBLE;
604                self.states_changed(k);
605            }
606        }
607        self.focus_visible_on = target;
608        if flipped {
609            self.restyle_projected_focus();
610        }
611    }
612
613    /// The states `key` is styled by: its own, those it shows as a part
614    /// of a control and a hover a component passes on to it, with
615    /// `FOCUS_VISIBLE` on a part projected focused while the focus shows.
616    /// Virtual focus is projected while its control has the focus, so on
617    /// its rows `focus:` is the cursor and `focus-visible:` the cursor the
618    /// keyboard is on.
619    pub(super) fn styled_states(&self, key: Key) -> u16 {
620        let node = &self.nodes[key as usize];
621        let passed = if node.passed_hover { state::HOVERED } else { 0 };
622        let mut states = node.states | node.projected | passed;
623        if let Some(group) = node.parts.as_ref().and_then(|p| p.active_group) {
624            states |= self.group_states(key, group) & state::PRESSED;
625        }
626        if node.projected & state::FOCUSED != 0 && self.focus_visible_on.is_some() {
627            states | state::FOCUS_VISIBLE
628        } else {
629            states
630        }
631    }
632
633    /// Restyles the parts projected focused: the focus started or stopped
634    /// showing. Those released since are dropped.
635    fn restyle_projected_focus(&mut self) {
636        let mut parts = std::mem::take(&mut self.projected_focus);
637        parts.retain(|&(k, id)| {
638            self.nodes
639                .get(k as usize)
640                .is_some_and(|n| n.id == id && n.projected & state::FOCUSED != 0)
641        });
642        for &(k, _) in &parts {
643            self.states_changed(k);
644        }
645        self.projected_focus = parts;
646    }
647
648    /// Puts `focus-within` on the focus and the views around it, and takes
649    /// it off the views it left (those first, then the new ones): the old
650    /// chain and the new one are walked, nothing else, and the views on
651    /// both are not touched. The views around are the parents in the core's tree,
652    /// where an overlay is its parent's child (whatever root view shows
653    /// it), so the focus in a popup is within the view the popup's overlay
654    /// is in, as in a React portal.
655    pub(super) fn update_focus_within(&mut self) {
656        self.focus_moved = false;
657        self.blur_held = false;
658        let focus = self
659            .focus
660            .filter(|&(k, id)| self.nodes.get(k as usize).is_some_and(|n| n.id == id));
661        if focus.is_none() {
662            self.focus = None;
663        }
664        let mut chain = std::mem::take(&mut self.focus_scratch);
665        chain.clear();
666        if let Some((mut k, _)) = focus {
667            while k != NO_KEY {
668                let node = &self.nodes[k as usize];
669                chain.push((k, node.id));
670                k = node.parent;
671            }
672        }
673        if chain == self.focus_chain {
674            self.focus_scratch = chain;
675            return;
676        }
677        let old = std::mem::replace(&mut self.focus_chain, chain);
678        for &(k, id) in &old {
679            if self.focus_chain.contains(&(k, id)) {
680                continue;
681            }
682            // A view released since (its key perhaps another's now).
683            let Some(node) = self.nodes.get_mut(k as usize).filter(|n| n.id == id) else {
684                continue;
685            };
686            if node.states & state::FOCUS_WITHIN != 0 {
687                node.states &= !state::FOCUS_WITHIN;
688                let hears = node.events.contains(EventKind::FocusOut);
689                self.states_changed(k);
690                if hears {
691                    self.events
692                        .push(JsEvent::Event(id, EventKind::FocusOut, EventPayload::None));
693                }
694            }
695        }
696        for i in 0..self.focus_chain.len() {
697            let k = self.focus_chain[i].0;
698            let node = &mut self.nodes[k as usize];
699            if node.states & state::FOCUS_WITHIN == 0 {
700                node.states |= state::FOCUS_WITHIN;
701                let (id, hears) = (node.id, node.events.contains(EventKind::FocusIn));
702                self.states_changed(k);
703                if hears {
704                    self.events
705                        .push(JsEvent::Event(id, EventKind::FocusIn, EventPayload::None));
706                }
707            }
708        }
709        self.focus_scratch = old;
710        self.focus_within_changed = true;
711    }
712
713    /// Whether the keyboard focus is on view `id` or a view inside it
714    /// (`focus-within`; an overlay is inside the view the app put it in).
715    pub(super) fn has_focus_within(&self, id: NodeId) -> bool {
716        self.key(id)
717            .is_ok_and(|k| self.nodes[k as usize].states & state::FOCUS_WITHIN != 0)
718    }
719
720    /// The node whose pressed state the touch responder holds.
721    fn held_pressed(&self) -> Option<Key> {
722        self.components
723            .touch
724            .pressed
725            .and_then(|id| self.key(id).ok())
726    }
727
728    /// Holds the `active:` (and `group-active:`) state on the components'
729    /// touch responder `id` until its touches end (`None`): a drag that
730    /// leaves its view, which the platform stops reporting as pressed,
731    /// keeps it pressed, as CSS's `:active` holds until the button is
732    /// released. The one held before is released.
733    pub(super) fn hold_pressed(&mut self, id: Option<NodeId>) {
734        let before = self.held_pressed();
735        self.components.touch.pressed = id;
736        if let Some(key) = before {
737            let prev_id = self.nodes[key as usize].id;
738            let impulse_held = self
739                .pressed_impulses
740                .iter()
741                .any(|&(k, imp_id, _)| k == key && imp_id == prev_id);
742            if !impulse_held {
743                let node = &mut self.nodes[key as usize];
744                if node.states & state::PRESSED != 0 {
745                    node.states &= !state::PRESSED;
746                    self.states_changed(key);
747                }
748            }
749        }
750        if let Some(key) = self.held_pressed() {
751            let node = &mut self.nodes[key as usize];
752            if node.states & state::PRESSED == 0 {
753                node.states |= state::PRESSED;
754                self.states_changed(key);
755            }
756        }
757    }
758
759    /// `disabled` on a host element: the `disabled:` variant.
760    pub(super) fn set_disabled(&mut self, key: Key, disabled: bool) {
761        let node = &mut self.nodes[key as usize];
762        let before = node.states;
763        if disabled {
764            node.states |= state::DISABLED;
765        } else {
766            node.states &= !state::DISABLED;
767        }
768        if node.states != before {
769            if disabling_changes(node.events) {
770                self.mark(key, dirty::EVENTS);
771            }
772            // Its accessibility state says it.
773            self.mark(key, dirty::VIEW_PROPS);
774            self.states_changed(key);
775        }
776    }
777
778    /// Restyles `key` if its classes read its states, and the nodes inside
779    /// it that read its group states.
780    pub(super) fn states_changed(&mut self, key: Key) {
781        let Some(classes) = self.nodes[key as usize].classes.clone() else {
782            return;
783        };
784        if classes.deps() & deps::STATE != 0 {
785            self.restyle(key);
786        }
787        if !classes.groups().is_empty() {
788            self.restyle_subtree(key, deps::GROUP);
789        }
790    }
791
792    /// The states `key`'s accessibility state puts it in
793    /// ([`accessibility_states`]): the `selected:`, `checked:`,
794    /// `indeterminate:` and `aria-*:` variants.
795    pub(super) fn set_accessibility_states(&mut self, key: Key, states: u16) {
796        let node = &mut self.nodes[key as usize];
797        let now = (node.states & !state::ACCESSIBILITY) | states;
798        if node.states != now {
799            node.states = now;
800            self.states_changed(key);
801        }
802    }
803
804    /// The states `key` shows as a part of a control: its classes and
805    /// state styles read them, its events and accessibility do not.
806    pub(super) fn set_projected_states(&mut self, key: Key, states: u16) {
807        let node = &mut self.nodes[key as usize];
808        if node.projected != states {
809            let focus_changed = (node.projected ^ states) & state::FOCUSED != 0;
810            node.projected = states;
811            let id = node.id;
812            if self.mount_projected && node.created {
813                self.mount.push(MountItem::ProjectStates { id, states });
814            }
815            if focus_changed {
816                // The key's entry before, and those released since, go.
817                let nodes = &self.nodes;
818                self.projected_focus
819                    .retain(|&(k, i)| k != key && nodes.get(k as usize).is_some_and(|n| n.id == i));
820                if states & state::FOCUSED != 0 {
821                    self.projected_focus.push((key, id));
822                }
823            }
824            self.states_changed(key);
825        }
826    }
827
828    /// The group whose press `key` shows as a part of a control
829    /// (`Prop::ProjectedActive`).
830    pub(super) fn set_projected_active(&mut self, key: Key, group: Option<&'static str>) {
831        let node = &mut self.nodes[key as usize];
832        if node.parts.as_ref().and_then(|p| p.active_group) == group {
833            return;
834        }
835        let base = node.classes.clone();
836        let parts = node.parts.get_or_insert_with(|| {
837            Box::new(NodeParts {
838                base,
839                ..NodeParts::default()
840            })
841        });
842        parts.active_group = group;
843        parts.group_pressed = false;
844        self.states_changed(key);
845    }
846
847    /// A group around part `key` that shows its press changed its states:
848    /// restyled when the press it shows came or went.
849    fn group_press_changed(&mut self, key: Key) {
850        let Some(group) = self.nodes[key as usize]
851            .parts
852            .as_ref()
853            .and_then(|p| p.active_group)
854        else {
855            return;
856        };
857        let pressed = self.group_states(key, group) & state::PRESSED != 0;
858        let node = &mut self.nodes[key as usize];
859        let parts = node.parts.as_mut().expect("a part with its group");
860        if parts.group_pressed == pressed {
861            return;
862        }
863        parts.group_pressed = pressed;
864        if !node
865            .classes
866            .as_ref()
867            .is_some_and(|c| c.deps() & deps::STATE != 0)
868        {
869            return;
870        }
871        self.restyle(key);
872    }
873
874    /// The `data-*` attributes `key` shows as a part of a component
875    /// (`Prop::ProjectedData`): its `data-*:` classes read them, and the
876    /// `group-data-*:` classes inside it when it is a group. A node whose
877    /// classes read none sends nothing.
878    pub(super) fn set_projected_data(&mut self, key: Key, data: Box<[&'static str]>) {
879        let node = &mut self.nodes[key as usize];
880        if node.data == data {
881            return;
882        }
883        node.data = data;
884        let Some(classes) = node.classes.clone() else {
885            return;
886        };
887        if classes.deps() & deps::DATA != 0 {
888            self.restyle(key);
889        }
890        if !classes.groups().is_empty() {
891            self.restyle_subtree(key, deps::GROUP);
892        }
893    }
894
895    /// The steps of its parent's perspective that `key`'s transform starts
896    /// with as mounted ([`Self::mounted_view_style`]): 5, or 0 without one.
897    /// Only a view that turns out of its plane (`rotateX`, `rotateY`) shows
898    /// a perspective; a flat one stays as it is.
899    pub(super) fn perspective_steps(&self, key: Key) -> u8 {
900        let node = &self.nodes[key as usize];
901        let has = node.parent != NO_KEY
902            && !node.inline
903            && self.nodes[node.parent as usize].child_perspective.is_some()
904            && node.view_style.transform.ops().iter().any(|op| {
905                matches!(
906                    op.kind,
907                    crate::transform::TransformKind::RotateX
908                        | crate::transform::TransformKind::RotateY
909                )
910            });
911        if has { 5 } else { 0 }
912    }
913
914    /// The view style of `key` as platforms take it: fractional
915    /// translations resolved, its parent's perspective composed in.
916    pub(super) fn mounted_view_style(&self, key: Key) -> Box<ViewStyle> {
917        let node = &self.nodes[key as usize];
918        let mut style = node.mounted_view_style();
919        if self.focus_ring_clipped(key, &style) {
920            super::focus_ring::draw_inside(&mut style);
921        }
922        let parent = node.parent;
923        if parent == NO_KEY || node.inline {
924            return style;
925        }
926        let parent = &self.nodes[parent as usize];
927        let Some(distance) = parent
928            .child_perspective
929            .filter(|_| self.perspective_steps(key) > 0)
930        else {
931            return style;
932        };
933        // CSS: the parent's perspective, around its center, applies to the
934        // child's plane: `translate(-d) perspective() translate(d)` before
935        // its own transform, `d` its origin's distance from that center.
936        let size = |s: Size<Points>| if s.width.is_nan() { Size::default() } else { s };
937        let (own, parent_size) = (size(node.frame.size), size(parent.frame.size));
938        let origin = if node.frame.size.width.is_nan() {
939            crate::geometry::Point::default()
940        } else {
941            node.frame.origin
942        };
943        let (offset, _) = style.transform_origin.offset(own);
944        let dx = origin.x.0 + own.width.0 / 2.0 + offset.x.0 - parent_size.width.0 / 2.0;
945        let dy = origin.y.0 + own.height.0 / 2.0 + offset.y.0 - parent_size.height.0 / 2.0;
946        use crate::transform::{Transform, TransformKind as T};
947        let mut composed = Transform::IDENTITY;
948        for (kind, value) in [
949            (T::TranslateX, -dx),
950            (T::TranslateY, -dy),
951            (T::Perspective, distance.0),
952            (T::TranslateX, dx),
953            (T::TranslateY, dy),
954        ] {
955            let _ = composed.push(kind, value);
956        }
957        for op in style.transform.ops() {
958            let _ = composed.push(op.kind, op.value);
959        }
960        style.transform = composed;
961        style
962    }
963
964    /// Sets the inline style of `key`'s `part` (`None`: removes it).
965    pub(super) fn set_part_style(
966        &mut self,
967        key: Key,
968        part: Part,
969        patch: Option<std::rc::Rc<StylePatch>>,
970    ) {
971        let node = &mut self.nodes[key as usize];
972        let base = node.classes.clone();
973        let parts = node.parts.get_or_insert_with(|| {
974            Box::new(NodeParts {
975                base,
976                ..NodeParts::default()
977            })
978        });
979        let patch = patch.filter(|p| !p.is_empty());
980        match part.state() {
981            Some(_) => {
982                let slot = &mut parts.states[part as usize];
983                if *slot == patch {
984                    return;
985                }
986                *slot = patch;
987                let rules: Vec<Rule> = parts
988                    .states
989                    .iter()
990                    .enumerate()
991                    .filter_map(|(i, p)| {
992                        let p = p.as_ref()?;
993                        let (states, rank) = STATE_PARTS[i].state()?;
994                        Some(Rule::state_style(states, rank, p.decls().to_vec()))
995                    })
996                    .collect();
997                parts.state_rules = (!rules.is_empty())
998                    .then(|| std::rc::Rc::new(ClassList::from_rules(rules, Vec::new())));
999                let base = parts.base.clone();
1000                self.set_class_list(key, base);
1001            }
1002            None => {
1003                let at = parts.styles.iter().position(|(p, _)| *p == part);
1004                match (at, patch) {
1005                    (Some(i), Some(p)) => parts.styles[i].1 = p,
1006                    (Some(i), None) => {
1007                        parts.styles.remove(i);
1008                    }
1009                    (None, Some(p)) => parts.styles.push((part, p)),
1010                    (None, None) => return,
1011                }
1012                self.part_changed(key, part);
1013            }
1014        }
1015    }
1016
1017    /// Sets the classes of `key`'s `part` (a page's header, a list's
1018    /// content).
1019    pub(super) fn set_part_class(&mut self, key: Key, part: Part, names: &str) {
1020        let classes = (!names.trim().is_empty()).then(|| self.tailwind.classes(names));
1021        let named = classes.is_some();
1022        self.set_part_class_list(key, part, classes);
1023        if named && let Some(parts) = self.nodes[key as usize].parts.as_deref_mut() {
1024            parts.class_names.push((part, names.into()));
1025        }
1026    }
1027
1028    /// Parses again the parts' classes set by name whose rules `reads`
1029    /// (the theme was replaced, or design tokens they name changed).
1030    fn part_classes_again(&mut self, reads: impl Fn(&ClassList) -> bool) {
1031        let named: Vec<(Key, Part, Box<str>)> = self
1032            .nodes
1033            .iter()
1034            .filter_map(|(k, n)| Some((k as Key, n.parts.as_deref()?)))
1035            .flat_map(|(k, p)| {
1036                let reads = &reads;
1037                p.class_names
1038                    .iter()
1039                    .filter(move |(part, _)| {
1040                        p.classes.iter().any(|(of, list)| of == part && reads(list))
1041                    })
1042                    .map(move |(part, names)| (k, *part, names.clone()))
1043            })
1044            .collect();
1045        for (key, part, names) in named {
1046            self.set_part_class(key, part, &names);
1047        }
1048    }
1049
1050    /// Sets `part`'s classes of `key` to `classes`, already parsed (typed
1051    /// styles lowered); none clears them.
1052    pub(super) fn set_part_class_list(
1053        &mut self,
1054        key: Key,
1055        part: Part,
1056        classes: Option<std::rc::Rc<ClassList>>,
1057    ) {
1058        let node = &mut self.nodes[key as usize];
1059        let base = node.classes.clone();
1060        let parts = node.parts.get_or_insert_with(|| {
1061            Box::new(NodeParts {
1062                base,
1063                ..NodeParts::default()
1064            })
1065        });
1066        parts.class_names.retain(|(p, _)| *p != part);
1067        let at = parts.classes.iter().position(|(p, _)| *p == part);
1068        match (at, classes) {
1069            (Some(i), Some(c)) => parts.classes[i].1 = c,
1070            (Some(i), None) => {
1071                parts.classes.remove(i);
1072            }
1073            (None, Some(c)) => parts.classes.push((part, c)),
1074            (None, None) => return,
1075        }
1076        self.part_changed(key, part);
1077    }
1078
1079    /// `part` of `key` changed: what shows it is sent again.
1080    fn part_changed(&mut self, key: Key, part: Part) {
1081        match part {
1082            Part::Header => {
1083                if self.nodes[key as usize].kind == Kind::Screen {
1084                    self.mark(key, dirty::SCREEN);
1085                }
1086            }
1087            Part::Content => {
1088                let content = self.list_content(key);
1089                if let Some(list) = self.nodes[key as usize].list.as_mut()
1090                    && list.set_class_content(content)
1091                {
1092                    self.needs_layout = true;
1093                }
1094            }
1095            _ => {}
1096        }
1097    }
1098
1099    /// The padding, gaps and cell alignment a list's `contentClass` sets.
1100    fn list_content(&self, key: Key) -> crate::ListContentStyle {
1101        let Some(style) = self.part_resolved(key, Part::Content) else {
1102            return crate::ListContentStyle::default();
1103        };
1104        let px = |l: taffy::LengthPercentage| match l.expand() {
1105            taffy::style::ExpandedLengthPercentage::Length(v) => crate::geometry::Points(v),
1106            _ => crate::geometry::Points::ZERO,
1107        };
1108        let p = &style.layout.padding;
1109        let align = style.layout.align_items;
1110        let align_items = (align == taffy::AlignItems::STRETCH
1111            || align == taffy::AlignItems::FLEX_START
1112            || align == taffy::AlignItems::CENTER
1113            || align == taffy::AlignItems::FLEX_END)
1114            .then_some(align);
1115        crate::ListContentStyle {
1116            padding: crate::EdgeInsets {
1117                top: px(p.top),
1118                right: px(p.right),
1119                bottom: px(p.bottom),
1120                left: px(p.left),
1121            },
1122            row_gap: px(style.layout.gap.height),
1123            column_gap: px(style.layout.gap.width),
1124            align_items,
1125        }
1126    }
1127
1128    /// The style of `key`'s `part`: its classes, then its inline style, as
1129    /// they resolve now; `None` when the part has neither.
1130    pub(super) fn part_resolved(&self, key: Key, part: Part) -> Option<Style> {
1131        let node = &self.nodes[key as usize];
1132        let parts = node.parts.as_deref()?;
1133        let classes = parts.classes.iter().find(|(p, _)| *p == part).map(|c| &c.1);
1134        let inline = parts.styles.iter().find(|(p, _)| *p == part).map(|s| &s.1);
1135        if classes.is_none() && inline.is_none() {
1136            return None;
1137        }
1138        let mut style = Style::default();
1139        let current = inline.and_then(|i| inline_color(i)).unwrap_or(Color::BLACK);
1140        if let Some(i) = inline {
1141            i.apply_defaults(&mut style, current);
1142        }
1143        let apply = |s: &mut Style| {
1144            if let Some(i) = inline {
1145                i.apply(s);
1146                s.apply_current_color(current);
1147            }
1148        };
1149        match classes {
1150            Some(classes) => {
1151                let group = |_: &str| 0;
1152                let cx = Context {
1153                    env: self.class_env,
1154                    window: self.class_window(),
1155                    rtl: node.rtl,
1156                    states: 0,
1157                    position: 0,
1158                    group: &group,
1159                };
1160                let mut props = ClassProps::default();
1161                classes.apply(&cx, self.tailwind.theme(), &mut style, &mut props, apply);
1162            }
1163            None => apply(&mut style),
1164        }
1165        Some(style)
1166    }
1167
1168    /// The parts whose classes resolve again when the environment changes
1169    /// (a header's `dark:` colors).
1170    fn parts_restyled(&mut self) {
1171        let keys: Vec<(Key, Part)> = self
1172            .nodes
1173            .iter()
1174            .filter_map(|(k, n)| Some((k as Key, n.parts.as_deref()?)))
1175            .flat_map(|(k, p)| p.classes.iter().map(move |(part, _)| (k, *part)))
1176            .collect();
1177        for (key, part) in keys {
1178            self.part_changed(key, part);
1179        }
1180    }
1181
1182    /// Sets `class` (`list == false`) or `classList` of `key`.
1183    pub(super) fn set_classes(
1184        &mut self,
1185        key: Key,
1186        names: Option<Box<str>>,
1187        list: Option<Vec<Box<str>>>,
1188    ) {
1189        let node = &mut self.nodes[key as usize];
1190        let current = node.class_names.get_or_insert_default();
1191        if let Some(n) = names {
1192            current.class = n;
1193        }
1194        if let Some(l) = list {
1195            current.list = l;
1196        }
1197        let (classes, fresh) = if current.list.is_empty() {
1198            if current.class.trim().is_empty() {
1199                (None, false)
1200            } else {
1201                let (classes, fresh) = self.tailwind.get(&current.class);
1202                (Some(classes), fresh)
1203            }
1204        } else {
1205            let mut combined = String::with_capacity(current.class.len() + 16 * current.list.len());
1206            combined.push_str(&current.class);
1207            for name in &current.list {
1208                combined.push(' ');
1209                combined.push_str(name);
1210            }
1211            if combined.trim().is_empty() {
1212                (None, false)
1213            } else {
1214                let (classes, fresh) = self.tailwind.get(&combined);
1215                (Some(classes), fresh)
1216            }
1217        };
1218        if fresh
1219            && let Some(c) = &classes
1220            && !c.unknown().is_empty()
1221        {
1222            log::warn!(
1223                "unknown classes: {}",
1224                c.unknown()
1225                    .iter()
1226                    .map(|s| &**s)
1227                    .collect::<Vec<_>>()
1228                    .join(" ")
1229            );
1230        }
1231        self.set_class_list(key, classes);
1232    }
1233
1234    /// Sets the resolved classes of `key` (a Rust component's styles go
1235    /// straight here).
1236    pub(super) fn set_class_list(&mut self, key: Key, classes: Option<std::rc::Rc<ClassList>>) {
1237        let state_rules = self.nodes[key as usize]
1238            .parts
1239            .as_deref_mut()
1240            .and_then(|parts| {
1241                parts.base = classes.clone();
1242                parts.state_rules.clone()
1243            });
1244        // The state styles go over the classes.
1245        let classes = if let Some(state_rules) = state_rules {
1246            self.merge_user(classes, Some(state_rules))
1247        } else {
1248            classes
1249        };
1250        let node = &mut self.nodes[key as usize];
1251        let unchanged = match (&node.classes, &classes) {
1252            (None, None) => true,
1253            (Some(a), Some(b)) => std::rc::Rc::ptr_eq(a, b),
1254            _ => false,
1255        };
1256        if unchanged {
1257            return;
1258        }
1259        let had_groups = node
1260            .classes
1261            .as_ref()
1262            .is_some_and(|c| !c.groups().is_empty());
1263        node.classes = classes;
1264        let has_groups = node
1265            .classes
1266            .as_ref()
1267            .is_some_and(|c| !c.groups().is_empty());
1268        self.update_tracking(key);
1269        self.restyle(key);
1270        if had_groups || has_groups {
1271            self.restyle_subtree(key, deps::GROUP);
1272        }
1273    }
1274
1275    /// How long the transitions of view `id` run, its delay included, with
1276    /// its styles now (a component waiting for its exit,
1277    /// [`crate::element::ElementRef::transition_time`]); zero for a view
1278    /// with none, or gone.
1279    pub(super) fn transition_time(&self, id: NodeId) -> std::time::Duration {
1280        let Ok(key) = self.key(id) else {
1281            return std::time::Duration::ZERO;
1282        };
1283        self.nodes[key as usize]
1284            .view_style
1285            .transition
1286            .filter(|t| t.properties.0 != 0)
1287            .map_or(std::time::Duration::ZERO, |t| {
1288                std::time::Duration::from_secs_f32((t.run_ms() + t.delay.max(0.0)) / 1000.0)
1289            })
1290    }
1291
1292    /// Replaces the theme: every class is resolved again.
1293    pub(super) fn set_tailwind_theme(&mut self, json: &str) {
1294        // A newer NSH's theme: what this one cannot read is left out, the
1295        // rest applies.
1296        let theme = match Theme::from_json_lenient(json) {
1297            Ok((theme, ignored)) => {
1298                for what in ignored {
1299                    log::warn!("tailwind theme: {what}, ignored");
1300                }
1301                theme
1302            }
1303            Err(e) => {
1304                log::warn!("tailwind theme: {e}");
1305                return;
1306            }
1307        };
1308        self.tailwind.set_theme(theme);
1309        self.resolved_styles.clear();
1310        self.components.merges.clear();
1311        let keys: Vec<Key> = self
1312            .nodes
1313            .iter()
1314            .filter(|(_, n)| n.class_names.is_some())
1315            .map(|(k, _)| k as Key)
1316            .collect();
1317        for key in keys {
1318            self.set_classes(key, None, None);
1319        }
1320        self.part_classes_again(|_| true);
1321    }
1322
1323    /// The design tokens changed: classes naming them
1324    /// (`bg-primary`) are resolved again, on nodes, on their parts (a
1325    /// page's header, a list's content) and on Rust components.
1326    pub(super) fn class_tokens_changed(&mut self) {
1327        let tokens = self.components.tokens.clone();
1328        let Some(changed) = self.tailwind.set_tokens(&tokens) else {
1329            return;
1330        };
1331        if changed == u16::MAX {
1332            self.resolved_styles.clear();
1333            self.components.merges.clear();
1334        } else {
1335            self.resolved_styles
1336                .retain(|_, entry| entry.classes.deps() & changed == 0);
1337            self.components
1338                .merges
1339                .retain(|_, [a, b, merged]| (a.deps() | b.deps() | merged.deps()) & changed == 0);
1340        }
1341        let reads = |c: &Option<std::rc::Rc<ClassList>>| {
1342            c.as_ref().is_some_and(|c| c.deps() & changed != 0)
1343        };
1344        let keys: Vec<Key> = self
1345            .nodes
1346            .iter()
1347            .filter(|(_, n)| n.class_names.is_some() && (changed == u16::MAX || reads(&n.classes)))
1348            .map(|(k, _)| k as Key)
1349            .collect();
1350        for key in keys {
1351            self.set_classes(key, None, None);
1352        }
1353        self.part_classes_again(|c| changed == u16::MAX || c.deps() & changed != 0);
1354        let hosts: Vec<NodeId> = self
1355            .components
1356            .instances
1357            .iter()
1358            .filter(|(_, inst)| {
1359                (!inst.class.is_empty() || !inst.class_list.is_empty())
1360                    && (changed == u16::MAX || reads(&inst.user))
1361            })
1362            .map(|(host, _)| *host)
1363            .collect();
1364        for host in hosts {
1365            self.update_user_class(host);
1366        }
1367        // The app's classes on the views' elements (`app_class`).
1368        let nodes: Vec<_> = self
1369            .components
1370            .app_classes
1371            .iter()
1372            .map(|(&id, entry)| (id, entry.clone()))
1373            .collect();
1374        for (id, (own, class, outer)) in nodes {
1375            let app = self.app_class_list(&class);
1376            let user = self.merge_user(Some(app), outer);
1377            let list = self.merge_user(own, user);
1378            if let Ok(key) = self.key(id) {
1379                self.set_class_list(key, list);
1380            }
1381        }
1382    }
1383
1384    /// Tells the platform which states of `key` to report.
1385    pub(super) fn update_tracking(&mut self, key: Key) {
1386        let node = &mut self.nodes[key as usize];
1387        // `focus-within` is the core's own (`update_focus_within`): the
1388        // platform reports only the states of the view itself.
1389        let tracked = node
1390            .classes
1391            .as_ref()
1392            .map_or(0, |c| c.tracked_states() & REPORTED);
1393        if tracked != node.tracked {
1394            node.tracked = tracked;
1395            // The platform stops reporting the states it no longer tracks,
1396            // and keeps the rest as they are: forget them here too, or a
1397            // state set before (a hover, a press) would outlive the pointer
1398            // and come back when the classes read it again. The focus it
1399            // reports always, so it stays.
1400            let kept = tracked | ALWAYS_REPORTED;
1401            let stale = node.states & REPORTED & !kept;
1402            let states = node.states & REPORTED & kept;
1403            if node.created {
1404                let id = node.id;
1405                self.mount.push(MountItem::TrackStates {
1406                    id,
1407                    states: tracked,
1408                });
1409            }
1410            if stale != 0 {
1411                if stale & state::PRESSED != 0 {
1412                    self.pressed_impulses.retain(|&(k, _, _)| k != key);
1413                }
1414                self.set_node_states(key, states);
1415            }
1416        }
1417    }
1418
1419    /// The tracking item of a view that was just created.
1420    pub(super) fn creation_tracking(&self, key: Key) -> Option<MountItem> {
1421        let node = &self.nodes[key as usize];
1422        (node.tracked != 0).then(|| MountItem::TrackStates {
1423            id: node.id,
1424            states: node.tracked,
1425        })
1426    }
1427
1428    /// The window size width and orientation variants (`md:`,
1429    /// `max-[900px]:`, `landscape:`) match against: the one `windowSize()`
1430    /// reports. Under the window model that is the app's primary window,
1431    /// not the hidden host's root view.
1432    pub(super) fn class_window(&self) -> crate::Size<crate::Points> {
1433        self.components.environment.window
1434    }
1435
1436    /// Restyles the nodes whose classes depend on any of `changed`.
1437    pub(super) fn restyle_where(&mut self, changed: u16) {
1438        if changed == 0 {
1439            return;
1440        }
1441        let keys: Vec<Key> = self
1442            .nodes
1443            .iter()
1444            .filter(|(_, n)| n.classes.as_ref().is_some_and(|c| c.deps() & changed != 0))
1445            .map(|(k, _)| k as Key)
1446            .collect();
1447        for key in keys {
1448            self.restyle(key);
1449        }
1450    }
1451
1452    /// Restyles the nodes inside `key` whose classes depend on `changed`.
1453    fn restyle_subtree(&mut self, key: Key, changed: u16) {
1454        let mut stack: Vec<Key> = self.nodes[key as usize].children.clone();
1455        while let Some(k) = stack.pop() {
1456            let node = &self.nodes[k as usize];
1457            stack.extend_from_slice(&node.children);
1458            let follows = changed & deps::GROUP != 0
1459                && node
1460                    .parts
1461                    .as_ref()
1462                    .is_some_and(|p| p.active_group.is_some());
1463            if node
1464                .classes
1465                .as_ref()
1466                .is_some_and(|c| c.deps() & changed != 0)
1467            {
1468                self.restyle(k);
1469            }
1470            if follows {
1471                self.group_press_changed(k);
1472            }
1473        }
1474    }
1475
1476    /// `key` joined `parent`, or left it (`parent` is where it was): the
1477    /// `group-*:` classes in it were resolved with the groups it had, which
1478    /// only matters while one of them, or of the new ones, is in a state (a
1479    /// disabled row, a pressed card). A leaf that reads no group skips the
1480    /// walk.
1481    pub(super) fn groups_changed(&mut self, key: Key, parent: Key) {
1482        let node = &self.nodes[key as usize];
1483        let reads = node
1484            .classes
1485            .as_ref()
1486            .is_some_and(|c| c.deps() & deps::GROUP != 0);
1487        if !reads && node.children.is_empty() {
1488            return;
1489        }
1490        let mut k = parent;
1491        loop {
1492            if k == NO_KEY {
1493                return;
1494            }
1495            let n = &self.nodes[k as usize];
1496            if (n.states | n.projected != 0 || n.passed_hover || !n.data.is_empty())
1497                && n.classes.as_ref().is_some_and(|c| !c.groups().is_empty())
1498            {
1499                break;
1500            }
1501            k = n.parent;
1502        }
1503        if reads {
1504            self.restyle(key);
1505        }
1506        self.restyle_subtree(key, deps::GROUP);
1507    }
1508
1509    /// `parent`'s children moved (one joined or left): their positions are
1510    /// looked at before the next flush, once ([`Core::flush_positions`]).
1511    pub(super) fn queue_positions(&mut self, parent: Key) {
1512        let node = &mut self.nodes[parent as usize];
1513        if !node.positional.has(Positional::QUEUED) {
1514            node.positional |= Positional::QUEUED;
1515            self.position_parents.push(parent);
1516        }
1517    }
1518
1519    /// Restyles the children whose position moved, of each parent queued
1520    /// since ([`Core::queue_positions`]).
1521    pub(super) fn flush_positions(&mut self) {
1522        if self.position_parents.is_empty() {
1523            return;
1524        }
1525        let mut parents = std::mem::take(&mut self.position_parents);
1526        for &parent in &parents {
1527            // A released key is vacant, or another node's: that one is
1528            // looked at only if it was queued itself.
1529            let Some(node) = self.nodes.get_mut(parent as usize) else {
1530                continue;
1531            };
1532            if node.positional.has(Positional::QUEUED) {
1533                node.positional.remove(Positional::QUEUED);
1534                self.positions_changed(parent);
1535            }
1536        }
1537        parents.clear();
1538        if self.position_parents.is_empty() {
1539            self.position_parents = parents;
1540        }
1541    }
1542
1543    /// `n` more siblings looked at for positions
1544    /// ([`super::components::Components::position_work`]).
1545    #[cfg(test)]
1546    fn positioning(&self, n: usize) {
1547        let work = &self.components.position_work;
1548        work.set(work.get() + n);
1549    }
1550
1551    #[cfg(not(test))]
1552    #[inline(always)]
1553    fn positioning(&self, _n: usize) {}
1554
1555    /// Restyles the children of `parent` that depend on their position.
1556    pub(super) fn positions_changed(&mut self, parent: Key) {
1557        if self.passes_position(parent) {
1558            // Its children take its own position, which theirs among
1559            // them do not change.
1560            let bits = self.known_position(parent);
1561            self.pass_to_children(parent, bits);
1562            return;
1563        }
1564        let children = self.nodes[parent as usize].children.clone();
1565        self.positioning(children.len());
1566        let count = children
1567            .iter()
1568            .filter(|&&c| self.is_element_child(c))
1569            .count();
1570        let mut next = 0;
1571        for c in children {
1572            let index = if self.is_element_child(c) {
1573                let index = next;
1574                next += 1;
1575                index
1576            } else {
1577                // Keep position_bits' fallback for a child that does not count.
1578                0
1579            };
1580            self.position_moved(c, Self::position_at(index, count));
1581        }
1582    }
1583
1584    /// Restyles `key`, now at position `bits`, if its classes read its
1585    /// position and it moved; a view passing its position on passes it.
1586    fn position_moved(&mut self, key: Key, bits: u8) {
1587        let node = &self.nodes[key as usize];
1588        // Only the children whose bits moved: an append restyles the old
1589        // last row and the new one, not every sibling.
1590        if node.position_used == bits {
1591            return;
1592        }
1593        if node.positional.has(Positional::PASS) {
1594            self.nodes[key as usize].position_used = bits;
1595            if self.nodes[key as usize]
1596                .positional
1597                .has(Positional::CHILDREN)
1598            {
1599                self.pass_to_children(key, bits);
1600            }
1601        }
1602        if self.nodes[key as usize]
1603            .classes
1604            .as_ref()
1605            .is_some_and(|c| c.deps() & deps::POSITION != 0)
1606        {
1607            self.restyle_at(key, Some(bits));
1608        }
1609    }
1610
1611    /// Gives `key`'s element children the position `bits`, its own.
1612    fn pass_to_children(&mut self, key: Key, bits: u8) {
1613        let children = self.nodes[key as usize].children.clone();
1614        self.positioning(children.len());
1615        for c in children {
1616            if self.is_element_child(c) {
1617                self.position_moved(c, bits);
1618            }
1619        }
1620    }
1621
1622    /// Whether `key`'s children take its position ([`Prop::PassPosition`]).
1623    ///
1624    /// [`Prop::PassPosition`]: crate::ops::Prop::PassPosition
1625    fn passes_position(&self, key: Key) -> bool {
1626        self.nodes[key as usize].positional.has(Positional::PASS)
1627    }
1628
1629    /// A child of `parent` reads its position: `parent` looks at its
1630    /// children's when they move, and so does each view whose position
1631    /// it passes on.
1632    pub(super) fn reads_positions(&mut self, parent: Key) {
1633        let mut k = parent;
1634        while k != NO_KEY {
1635            let node = &mut self.nodes[k as usize];
1636            node.positional |= Positional::CHILDREN;
1637            if !node.positional.has(Positional::PASS) {
1638                break;
1639            }
1640            k = node.parent;
1641        }
1642    }
1643
1644    /// Sets whether `key`'s children take its position among its
1645    /// siblings ([`Prop::PassPosition`]); those that read theirs are
1646    /// styled again.
1647    ///
1648    /// [`Prop::PassPosition`]: crate::ops::Prop::PassPosition
1649    pub(super) fn set_pass_position(&mut self, key: Key, pass: bool) {
1650        if self.passes_position(key) == pass {
1651            return;
1652        }
1653        let node = &mut self.nodes[key as usize];
1654        if pass {
1655            node.positional |= Positional::PASS;
1656        } else {
1657            node.positional.remove(Positional::PASS);
1658        }
1659        // Not yet known: counted again when asked for (`known_position`).
1660        node.position_used = 0;
1661        if node.positional.has(Positional::CHILDREN) {
1662            let parent = node.parent;
1663            if pass && parent != NO_KEY {
1664                self.reads_positions(parent);
1665            }
1666            self.queue_positions(key);
1667        }
1668    }
1669
1670    /// Whether `key`'s classes depend on the layout direction.
1671    pub(super) fn reads_direction(&self, key: Key) -> bool {
1672        self.nodes[key as usize]
1673            .classes
1674            .as_ref()
1675            .is_some_and(|c| c.deps() & deps::RTL != 0)
1676    }
1677
1678    /// [`position`] bits of `key`: those it was last styled at while its
1679    /// parent's children did not move since, so that restyling a row (its
1680    /// hover, its press) does not count its siblings; otherwise counted
1681    /// ([`Core::position_bits`]).
1682    fn known_position(&self, key: Key) -> u8 {
1683        let node = &self.nodes[key as usize];
1684        let parent = node.parent;
1685        if node.position_used != 0
1686            && parent != NO_KEY
1687            && !self.nodes[parent as usize]
1688                .positional
1689                .has(Positional::QUEUED)
1690        {
1691            return node.position_used;
1692        }
1693        self.position_bits(key)
1694    }
1695
1696    /// [`position`] bits of `key` among its parent's element children, or
1697    /// its parent's own when the parent passes its position on.
1698    fn position_bits(&self, key: Key) -> u8 {
1699        let parent = self.nodes[key as usize].parent;
1700        if parent == NO_KEY {
1701            return position::FIRST | position::LAST | position::ONLY | position::ODD;
1702        }
1703        if self.passes_position(parent) {
1704            return self.known_position(parent);
1705        }
1706        self.positioning(self.nodes[parent as usize].children.len());
1707        let siblings: Vec<Key> = self.nodes[parent as usize]
1708            .children
1709            .iter()
1710            .copied()
1711            .filter(|&c| self.is_element_child(c))
1712            .collect();
1713        let i = siblings.iter().position(|&c| c == key).unwrap_or(0);
1714        Self::position_at(i, siblings.len())
1715    }
1716
1717    fn position_at(i: usize, n: usize) -> u8 {
1718        let mut bits = if i.is_multiple_of(2) {
1719            position::ODD
1720        } else {
1721            position::EVEN
1722        };
1723        if i == 0 {
1724            bits |= position::FIRST;
1725        }
1726        if i + 1 == n {
1727            bits |= position::LAST;
1728        }
1729        if n == 1 {
1730            bits |= position::ONLY;
1731        }
1732        bits
1733    }
1734
1735    /// The states of the nearest ancestor of `key` that is group `name`.
1736    fn group_states(&self, key: Key, name: &str) -> u16 {
1737        let mut k = self.nodes[key as usize].parent;
1738        while k != NO_KEY {
1739            let node = &self.nodes[k as usize];
1740            if node
1741                .classes
1742                .as_ref()
1743                .is_some_and(|c| c.groups().iter().any(|g| **g == *name))
1744            {
1745                return self.styled_states(k);
1746            }
1747            k = node.parent;
1748        }
1749        0
1750    }
1751
1752    /// The `data-*` attributes of the nearest ancestor of `key` that is
1753    /// group `name`.
1754    fn group_data(&self, key: Key, name: &str) -> &[&'static str] {
1755        let mut k = self.nodes[key as usize].parent;
1756        while k != NO_KEY {
1757            let node = &self.nodes[k as usize];
1758            if node
1759                .classes
1760                .as_ref()
1761                .is_some_and(|c| c.groups().iter().any(|g| **g == *name))
1762            {
1763                return &node.data;
1764            }
1765            k = node.parent;
1766        }
1767        &[]
1768    }
1769
1770    /// The margins `key`'s parent gives it (`space-*`): it is an element
1771    /// child, and not the last.
1772    fn space_of(&self, key: Key) -> Option<&crate::tailwind::Space> {
1773        let node = &self.nodes[key as usize];
1774        let parent = node.parent;
1775        if parent == NO_KEY || node.inline {
1776            return None;
1777        }
1778        let space = self.nodes[parent as usize]
1779            .class_props
1780            .as_ref()?
1781            .space
1782            .as_ref()?;
1783        let last = self.nodes[parent as usize]
1784            .children
1785            .iter()
1786            .rev()
1787            .find(|&&c| self.is_element_child(c))?;
1788        (*last != key && self.is_element_child(key)).then_some(space)
1789    }
1790
1791    /// A child that counts among its siblings (`:last-child`, `first:`):
1792    /// not a raw text, a tooltip's overlay or a scroll view's built-in bar.
1793    fn is_element_child(&self, key: Key) -> bool {
1794        let node = &self.nodes[key as usize];
1795        node.kind != Kind::RawText && !node.decoration && !self.is_tooltip_overlay(key)
1796    }
1797
1798    /// `parent`'s children changed (`moved` joined it, or one left): the
1799    /// ones whose `space-*` margin that changes are styled again, the one
1800    /// that joined, and the last two, one of which was last before.
1801    pub(super) fn spacing_changed(&mut self, parent: Key, moved: Key) {
1802        let spacing = self.nodes[parent as usize]
1803            .class_props
1804            .as_ref()
1805            .is_some_and(|p| p.space.is_some());
1806        if !spacing && (moved == NO_KEY || !self.nodes[moved as usize].spaced) {
1807            return;
1808        }
1809        let mut keys = [moved, NO_KEY, NO_KEY];
1810        let mut elements = self.nodes[parent as usize]
1811            .children
1812            .iter()
1813            .rev()
1814            .filter(|&&c| self.is_element_child(c));
1815        keys[1] = elements.next().copied().unwrap_or(NO_KEY);
1816        keys[2] = elements.next().copied().unwrap_or(NO_KEY);
1817        for (i, k) in keys.into_iter().enumerate() {
1818            if k == NO_KEY || keys[..i].contains(&k) {
1819                continue;
1820            }
1821            let (now, was) = (self.space_of(k).is_some(), self.nodes[k as usize].spaced);
1822            // The one that moved may have left another `space-*` parent,
1823            // whose margin it still has.
1824            if now != was || i == 0 && now {
1825                self.restyle(k);
1826            }
1827        }
1828    }
1829
1830    /// Resolves `key`'s style from its classes and inline style.
1831    pub(super) fn restyle(&mut self, key: Key) {
1832        self.restyle_at(key, None);
1833    }
1834
1835    fn finish_restyle_metadata(&mut self, key: Key, pos: u8, positional: bool) {
1836        let node = &mut self.nodes[key as usize];
1837        node.spaced = false;
1838        node.color_used = node.inherited_color;
1839        let cleared_ch = node.reads_ch;
1840        node.reads_ch = false;
1841        node.resting_fill = None;
1842        node.position_used = if positional { pos } else { 0 };
1843        let parent = node.parent;
1844        if cleared_ch {
1845            self.ch_readers -= 1;
1846        }
1847        if positional {
1848            self.reads_positions(parent);
1849        }
1850    }
1851
1852    /// Resolves `key`'s classes through [`Core::resolved_styles`]. Returns
1853    /// `false` when more than the inputs of [`ResolvedKey`] decide its style
1854    /// (the root, an inline style, `direction`, insets, an input, `group-*`,
1855    /// `data-*`, `ch`, a `space-*` parent, a terminal box's resting fill under
1856    /// interaction): [`Self::restyle_at`] resolves it alone.
1857    fn try_resolve_cached(&mut self, key: Key, position: Option<u8>) -> bool {
1858        #[cfg(test)]
1859        if self.resolve_uncached {
1860            return false;
1861        }
1862        let node = &self.nodes[key as usize];
1863        if key == self.root
1864            || !node.inline_style.is_empty()
1865            || node.direction.is_some()
1866            || node.insets.is_some()
1867            || node.kind == Kind::Input
1868        {
1869            return false;
1870        }
1871        let Some(classes) = node.classes.clone() else {
1872            return false;
1873        };
1874        let d = classes.deps();
1875        if d & (deps::GROUP | deps::DATA | deps::CH) != 0 {
1876            return false;
1877        }
1878        if self.space_of(key).is_some() {
1879            return false;
1880        }
1881        let states = if d & deps::STATE != 0 {
1882            self.styled_states(key)
1883        } else {
1884            0
1885        };
1886        if self.layout.grid().is_some() && d & deps::STATE != 0 && states & INTERACTION != 0 {
1887            return false;
1888        }
1889        let pos = if d & deps::POSITION != 0 {
1890            position.unwrap_or_else(|| self.known_position(key))
1891        } else {
1892            0
1893        };
1894        let node = &self.nodes[key as usize];
1895        let positional = pos != 0 && node.parent != NO_KEY;
1896        let inherited_color = node.inherited_color;
1897        let rtl = self.resolved_rtl(key);
1898        let cache_key = ResolvedKey::new(
1899            &classes,
1900            &self.class_env,
1901            self.class_window(),
1902            rtl,
1903            states,
1904            pos,
1905            inherited_color,
1906        );
1907        let resolved = if let Some(cached) = self.resolved_styles.get(&cache_key) {
1908            cached.clone()
1909        } else {
1910            let group = |_: &str| 0;
1911            let cx = Context {
1912                env: self.class_env,
1913                window: self.class_window(),
1914                rtl,
1915                states,
1916                position: pos,
1917                group: &group,
1918            };
1919            let mut style = Style::default();
1920            let mut props = ClassProps::default();
1921            classes.apply_with_current(
1922                &cx,
1923                &crate::tailwind::no_data,
1924                self.tailwind.theme(),
1925                crate::tailwind::CurrentColor {
1926                    inherited: inherited_color,
1927                    inline: None,
1928                },
1929                None,
1930                crate::tailwind::DEFAULT_CH,
1931                &mut style,
1932                &mut props,
1933                |_| {},
1934            );
1935            style.node_props(&mut props);
1936            if !style.animated.is_empty()
1937                || style.direction.is_some()
1938                || !style.pending.env.is_empty()
1939            {
1940                self.finish_restyle_metadata(key, pos, positional);
1941                self.set_class_props(key, props);
1942                let id = self.nodes[key as usize].id;
1943                let _ = self.set_style(id, style);
1944                return true;
1945            }
1946            let Style {
1947                mut layout,
1948                mut view,
1949                text,
1950                paint,
1951                animated: _,
1952                z_index,
1953                vertical_align,
1954                direction: _,
1955                logical,
1956                pending,
1957                perspective,
1958            } = style;
1959            let has_logical = !logical.is_empty();
1960            let sticky = super::prepare_layout(
1961                &mut layout,
1962                &mut view,
1963                &logical,
1964                rtl,
1965                pending.sticky_position,
1966            );
1967            // An input clips whatever it sets; inputs never reach here.
1968            super::clip_overflow(&mut layout, view.overflow_hidden);
1969            let layout = self.layout.share(layout);
1970            let view = (view != ViewStyle::DEFAULT).then(|| std::rc::Rc::new(view));
1971            let text = (text != TextStyle::DEFAULT).then(|| std::rc::Rc::new(text));
1972            let paint = (paint != PaintStyle::default()).then(|| std::rc::Rc::new(paint));
1973            let props = (props != ClassProps::default()).then(|| std::rc::Rc::new(props));
1974            let entry = std::rc::Rc::new(ResolvedClassStyle {
1975                classes,
1976                layout,
1977                view,
1978                text,
1979                paint,
1980                props,
1981                sticky,
1982                object_fit: pending.object_fit,
1983                perspective,
1984                z_index,
1985                vertical_align,
1986                wants_fixed: pending.fixed_position,
1987                rtl,
1988                has_logical,
1989            });
1990            if self.resolved_styles.len() >= RESOLVED_STYLE_CACHE {
1991                self.resolved_styles.clear();
1992            }
1993            self.resolved_styles.insert(cache_key, entry.clone());
1994            entry
1995        };
1996        self.finish_restyle_metadata(key, pos, positional);
1997        self.apply_resolved_style(key, &resolved);
1998        true
1999    }
2000
2001    /// [`Self::restyle`] with `position` already known (`None`: query it).
2002    fn restyle_at(&mut self, key: Key, position: Option<u8>) {
2003        if self.try_resolve_cached(key, position) {
2004            return;
2005        }
2006        let mut base = Style::default();
2007        // The synthetic root stays sized to the host's viewport when restyled.
2008        if key == self.root {
2009            base.layout = super::root_style(self.viewport);
2010        }
2011        // Under its own classes and style, as `:where()` is in CSS.
2012        let space = self.space_of(key);
2013        if let Some(space) = space {
2014            space.apply(&mut base, false, self.resolved_rtl(key));
2015        }
2016        let spaced = space.is_some();
2017        let node = &mut self.nodes[key as usize];
2018        node.spaced = spaced;
2019        // The color it is styled with (`currentColor`, `sync_colors`).
2020        node.color_used = node.inherited_color;
2021        // CSS's `ch` (`max-w-prose`): the `0` of the font it inherits, or of
2022        // its own once its classes set one.
2023        let reads_ch = self.nodes[key as usize]
2024            .classes
2025            .as_ref()
2026            .is_some_and(|c| c.deps() & deps::CH != 0);
2027        let node = &mut self.nodes[key as usize];
2028        if node.reads_ch != reads_ch {
2029            if reads_ch {
2030                self.ch_readers += 1;
2031            } else {
2032                self.ch_readers -= 1;
2033            }
2034            node.reads_ch = reads_ch;
2035        }
2036        let inherited_font = reads_ch.then(|| self.inherited_text_style(key));
2037        let mut ch = match inherited_font {
2038            Some(font) => self.zero_advance(font),
2039            None => crate::tailwind::DEFAULT_CH,
2040        };
2041        // In a terminal, a box's fill decides its layout (a band or a
2042        // line, [`terminal_layout::Surface`]): only needed under active interaction.
2043        let need_rest = self.layout.grid().is_some()
2044            && self.styled_states(key) & INTERACTION != 0
2045            && self.nodes[key as usize]
2046                .classes
2047                .as_ref()
2048                .is_some_and(|c| c.deps() & deps::STATE != 0);
2049        let base_for_rest = need_rest.then(|| base.clone());
2050        let mut style;
2051        let mut props;
2052        match inherited_font {
2053            None => {
2054                style = base;
2055                props = ClassProps::default();
2056                self.resolve_classes(key, ch, position, &mut style, &mut props);
2057            }
2058            // Again with its own font's, once its classes set one.
2059            Some(inherited) => loop {
2060                style = base.clone();
2061                props = ClassProps::default();
2062                self.resolve_classes(key, ch, position, &mut style, &mut props);
2063                let own = self.zero_advance(inherited.inherit(&style.text));
2064                if own == ch {
2065                    break;
2066                }
2067                ch = own;
2068            },
2069        }
2070        if reads_ch {
2071            let node = &mut self.nodes[key as usize];
2072            node.ch = ch;
2073            let id = node.id;
2074            self.ch_styled.push((key, id));
2075        }
2076        let resting = base_for_rest
2077            .map(|mut rest| {
2078                let mut rest_props = ClassProps::default();
2079                self.resolve_classes_in(key, ch, position, INTERACTION, &mut rest, &mut rest_props);
2080                rest.view.background_color
2081            })
2082            .filter(|&fill| fill != style.view.background_color);
2083        self.nodes[key as usize].resting_fill = resting;
2084        style.node_props(&mut props);
2085        self.set_class_props(key, props);
2086        let id = self.nodes[key as usize].id;
2087        let _ = self.set_style(id, style);
2088    }
2089
2090    /// A moved subtree or a changed font can change every descendant's `ch`.
2091    pub(super) fn ch_changed(&mut self, key: Key) {
2092        if self.ch_readers == 0 {
2093            return;
2094        }
2095        let mut stack = vec![key];
2096        while let Some(k) = stack.pop() {
2097            let node = &self.nodes[k as usize];
2098            if node
2099                .classes
2100                .as_ref()
2101                .is_some_and(|c| c.deps() & deps::CH != 0)
2102            {
2103                self.ch_styled.push((k, node.id));
2104            }
2105            stack.extend_from_slice(&node.children);
2106        }
2107    }
2108
2109    /// The nodes with lengths in `ch` styled since the last commit are
2110    /// styled again where the font they now inherit (the tree complete)
2111    /// gives another `ch` than they were styled with.
2112    pub(super) fn sync_ch(&mut self) {
2113        if self.ch_styled.is_empty() {
2114            return;
2115        }
2116        let styled = std::mem::take(&mut self.ch_styled);
2117        for (key, id) in styled {
2118            if self.nodes.get(key as usize).is_none_or(|n| n.id != id) {
2119                continue;
2120            }
2121            let font = self.inherited_text_style(key);
2122            let font = font.inherit(&self.nodes[key as usize].text_style);
2123            if self.zero_advance(font) != self.nodes[key as usize].ch {
2124                self.restyle(key);
2125            }
2126        }
2127        // Styled just now, with the fonts in place.
2128        self.ch_styled.clear();
2129    }
2130
2131    /// The nodes queued by [`Self::inherit_color`] are styled again where
2132    /// the text color they inherit is not the one they were styled with.
2133    pub(super) fn sync_colors(&mut self) {
2134        if self.color_changed.is_empty() {
2135            return;
2136        }
2137        for (key, id) in std::mem::take(&mut self.color_changed) {
2138            let Some(node) = self.nodes.get_mut(key as usize) else {
2139                continue;
2140            };
2141            if node.id != id {
2142                continue;
2143            }
2144            node.color_queued = false;
2145            if node.inherited_color != node.color_used {
2146                self.restyle(key);
2147            }
2148        }
2149    }
2150
2151    /// The advance of `font`'s `0`, CSS's `ch` (cached per font).
2152    pub(super) fn zero_advance(&mut self, font: crate::text::ResolvedTextStyle) -> f32 {
2153        let at = (
2154            font.font_family,
2155            font.font_size.0.to_bits(),
2156            font.font_weight,
2157            font.italic,
2158        );
2159        if let Some(&w) = self.zero_advances.get(&at) {
2160            return w;
2161        }
2162        let mut text = crate::text::AttributedText::default();
2163        text.push("0", font);
2164        let prepared = self.text_engine.prepare(&text);
2165        let w = self.text_engine.measure(&prepared, None).width.0;
2166        // Fonts are few; a bound keeps scaled sizes from growing it.
2167        if self.zero_advances.len() >= 64 {
2168            self.zero_advances.clear();
2169        }
2170        self.zero_advances.insert(at, w);
2171        w
2172    }
2173
2174    /// `key`'s classes and inline style over `style`, `ch` the advance of
2175    /// its font's `0`.
2176    fn resolve_classes(
2177        &mut self,
2178        key: Key,
2179        ch: f32,
2180        position: Option<u8>,
2181        style: &mut Style,
2182        props: &mut ClassProps,
2183    ) {
2184        self.resolve_classes_in(key, ch, position, 0, style, props);
2185    }
2186
2187    /// [`Self::resolve_classes`] as if `key` were not in the states
2188    /// `without`.
2189    fn resolve_classes_in(
2190        &mut self,
2191        key: Key,
2192        ch: f32,
2193        position: Option<u8>,
2194        without: u16,
2195        style: &mut Style,
2196        props: &mut ClassProps,
2197    ) {
2198        let node = &self.nodes[key as usize];
2199        if let Some(classes) = node.classes.clone() {
2200            let group = |name: &str| self.group_states(key, name);
2201            let data = |group: Option<&str>, name: &str| match group {
2202                None => node.data.contains(&name),
2203                Some(group) => self.group_data(key, group).contains(&name),
2204            };
2205            let pos = if classes.deps() & deps::POSITION != 0 {
2206                position.unwrap_or_else(|| self.known_position(key))
2207            } else {
2208                0
2209            };
2210            let positional = pos != 0 && node.parent != NO_KEY;
2211            let window = self.class_window();
2212            let cx = Context {
2213                env: self.class_env,
2214                window,
2215                // The direction it lays out in once styled (a node created
2216                // detached takes the root's), so its sided classes land
2217                // right the first time.
2218                rtl: self.resolved_rtl(key),
2219                states: self.styled_states(key) & !without,
2220                position: pos,
2221                group: &group,
2222            };
2223            let inline = &node.inline_style;
2224            let has_inline = !inline.is_empty();
2225            let current = crate::tailwind::CurrentColor {
2226                inherited: node.inherited_color,
2227                inline: if has_inline {
2228                    inline_color(inline)
2229                } else {
2230                    None
2231                },
2232            };
2233            let rtl = cx.rtl;
2234            if has_inline {
2235                let text_color = classes.current_color(&cx, &data, current);
2236                inline.apply_defaults(style, text_color);
2237                classes.apply_with_current(
2238                    &cx,
2239                    &data,
2240                    self.tailwind.theme(),
2241                    current,
2242                    Some(text_color),
2243                    ch,
2244                    style,
2245                    props,
2246                    |s| {
2247                        inline.apply(s);
2248                        s.apply_current_color(text_color);
2249                        if let Some(space) = self.space_of(key) {
2250                            space.apply(s, true, rtl);
2251                        }
2252                    },
2253                );
2254            } else {
2255                classes.apply_with_current(
2256                    &cx,
2257                    &data,
2258                    self.tailwind.theme(),
2259                    current,
2260                    None,
2261                    ch,
2262                    style,
2263                    props,
2264                    |s| {
2265                        if let Some(space) = self.space_of(key) {
2266                            space.apply(s, true, rtl);
2267                        }
2268                    },
2269                );
2270            }
2271            self.nodes[key as usize].position_used = if positional { pos } else { 0 };
2272            if positional {
2273                self.reads_positions(self.nodes[key as usize].parent);
2274            }
2275        } else {
2276            // Without classes it reads no position: the bits it was styled
2277            // at before are no longer kept up to date (`known_position`).
2278            self.nodes[key as usize].position_used = 0;
2279            let node = &self.nodes[key as usize];
2280            let current = inline_color(&node.inline_style)
2281                .or(node.inherited_color)
2282                .unwrap_or(Color::BLACK);
2283            node.inline_style.apply_defaults(style, current);
2284            node.inline_style.apply(style);
2285            style.apply_current_color(current);
2286            if let Some(space) = self.space_of(key) {
2287                space.apply(style, true, self.resolved_rtl(key));
2288            }
2289        }
2290    }
2291
2292    /// `key`'s children inherit text color `color` (`None`: React Native's
2293    /// black) from it: those whose `currentColor` it changes are styled
2294    /// again, and the change goes on below those that set no color of their
2295    /// own.
2296    pub(super) fn inherit_color(&mut self, key: Key, color: Option<Color>) {
2297        let stack = self.nodes[key as usize].children.clone();
2298        self.pass_color(stack, color);
2299    }
2300
2301    /// [`Self::inherit_color`] for `key` itself, which joined a parent
2302    /// passing `color`.
2303    pub(super) fn inherit_color_from(&mut self, key: Key, color: Option<Color>) {
2304        self.pass_color(vec![key], color);
2305    }
2306
2307    fn pass_color(&mut self, mut stack: Vec<Key>, color: Option<Color>) {
2308        while let Some(k) = stack.pop() {
2309            let node = &mut self.nodes[k as usize];
2310            if node.inherited_color == color {
2311                continue;
2312            }
2313            node.inherited_color = color;
2314            // Styled again as the commit starts, where the color it was
2315            // styled with is not the one it inherits then (a subtree built
2316            // from the inside out passes through several).
2317            if !node.color_queued
2318                && (node.inline_style.reads_current_color()
2319                    || node
2320                        .classes
2321                        .as_ref()
2322                        .is_some_and(|c| c.deps() & deps::CURRENT_COLOR != 0))
2323            {
2324                node.color_queued = true;
2325                let id = node.id;
2326                self.color_changed.push((k, id));
2327            }
2328            let node = &self.nodes[k as usize];
2329            if node.text_style.color.is_none() {
2330                stack.extend_from_slice(&node.children);
2331            }
2332        }
2333    }
2334
2335    /// The outermost of `key` and its ancestors whose classes say
2336    /// `pointer-events-none`, with no `pointer-events-auto` above it: the
2337    /// top of the region `key`'s class `pointer-events` depends on.
2338    pub(super) fn pointer_region(&self, key: Key) -> Option<Key> {
2339        let mut top = None;
2340        let mut k = key;
2341        while k != NO_KEY {
2342            let node = &self.nodes[k as usize];
2343            match node.class_props.as_ref().and_then(|c| c.pointer_events) {
2344                Some(PointerEvents::None) => top = Some(k),
2345                // Above an `auto`, nothing reaches below it.
2346                Some(_) if top.is_some() => return top,
2347                _ => {}
2348            }
2349            k = node.parent;
2350        }
2351        top
2352    }
2353
2354    /// `parent` gained or lost a child: the region it is in follows, at
2355    /// the round's end ([`Self::flush_pointer_events`]).
2356    pub(super) fn pointer_events_moved(&mut self, parent: Key) {
2357        if let Some(top) = self.pointer_region(parent) {
2358            self.pointer_pending.push(top);
2359        }
2360    }
2361
2362    /// Works out the regions views joined, left or changed in this round
2363    /// ([`Self::update_pointer_events`]), each once, with the tree as the
2364    /// round left it: each view noted is taken to the top of the region it
2365    /// is in now (a view taken out of a region and put into another is
2366    /// worked out from that one's top, as the views above it block). A
2367    /// view released since is skipped; a key reused by another view is
2368    /// worked out where that view is.
2369    pub(super) fn flush_pointer_events(&mut self) {
2370        if self.pointer_pending.is_empty() {
2371            return;
2372        }
2373        let mut pending = std::mem::take(&mut self.pointer_pending);
2374        pending.retain(|&k| self.nodes.contains(k as usize));
2375        for k in &mut pending {
2376            *k = self.pointer_region(*k).unwrap_or(*k);
2377        }
2378        pending.sort_unstable();
2379        pending.dedup();
2380        for &top in &pending {
2381            self.update_pointer_events(top);
2382        }
2383        // The buffer, for the next round.
2384        pending.clear();
2385        self.pointer_pending = pending;
2386    }
2387
2388    /// What the views of `top`'s subtree mount for the `pointer-events-*`
2389    /// classes, as CSS's inherited `pointer-events`: a view that is
2390    /// `none` (its own class, else the nearest one above) is no target;
2391    /// it mounts `box-none` when a `pointer-events-auto` inside it is one,
2392    /// `none` when it holds none and the view above it lets touches
2393    /// through (the top of the region), and nothing more below a `none`.
2394    /// Only the views whose value changed are mounted again.
2395    pub(super) fn update_pointer_events(&mut self, top: Key) {
2396        let inherited = {
2397            let parent = self.nodes[top as usize].parent;
2398            let mut k = parent;
2399            let mut found = None;
2400            while k != NO_KEY {
2401                let node = &self.nodes[k as usize];
2402                if let Some(v) = node.class_props.as_ref().and_then(|c| c.pointer_events) {
2403                    found = Some(v);
2404                    break;
2405                }
2406                k = node.parent;
2407            }
2408            found
2409        };
2410        self.mark_pointer_auto(top, inherited);
2411        // `top` is the outermost `none` (or a view without one): nothing
2412        // above it blocks touches natively.
2413        let mut stack = vec![(top, inherited, false)];
2414        while let Some((k, inherited, blocked)) = stack.pop() {
2415            let node = &self.nodes[k as usize];
2416            let own = node.class_props.as_ref().and_then(|c| c.pointer_events);
2417            let effective = own.or(inherited);
2418            let mounted = match effective {
2419                // React Native's: the view's own, natively; what is in it
2420                // takes touches (`box-none`) or none (`box-only`).
2421                Some(p @ (PointerEvents::BoxNone | PointerEvents::BoxOnly)) if own.is_some() => p,
2422                Some(PointerEvents::None) if node.pointer_auto_inside => PointerEvents::BoxNone,
2423                // A view above already blocks the subtree.
2424                Some(PointerEvents::None) if blocked => PointerEvents::Auto,
2425                Some(PointerEvents::None) => PointerEvents::None,
2426                _ => PointerEvents::Auto,
2427            };
2428            let blocked =
2429                blocked || matches!(mounted, PointerEvents::None | PointerEvents::BoxOnly);
2430            // Neither is inherited: the views in a `box-none` take touches,
2431            // and those in a `box-only` are blocked natively.
2432            let effective = match effective {
2433                Some(PointerEvents::BoxNone | PointerEvents::BoxOnly) => Some(PointerEvents::Auto),
2434                e => e,
2435            };
2436            for &c in &node.children {
2437                stack.push((c, effective, blocked));
2438            }
2439            if self.nodes[k as usize].class_pointer != mounted {
2440                self.nodes[k as usize].class_pointer = mounted;
2441                self.mark(k, dirty::VIEW_PROPS);
2442            }
2443        }
2444    }
2445
2446    /// Sets `pointer_auto_inside` over `key`'s subtree (`inherited`: the
2447    /// class value above it); returns whether a `pointer-events-auto` is in
2448    /// it or it is one under a `none`.
2449    fn mark_pointer_auto(&mut self, key: Key, inherited: Option<PointerEvents>) -> bool {
2450        let own = self.nodes[key as usize]
2451            .class_props
2452            .as_ref()
2453            .and_then(|c| c.pointer_events);
2454        let effective = match own.or(inherited) {
2455            // Not inherited (`update_pointer_events`).
2456            Some(PointerEvents::BoxNone | PointerEvents::BoxOnly) => Some(PointerEvents::Auto),
2457            e => e,
2458        };
2459        let children = std::mem::take(&mut self.nodes[key as usize].children);
2460        let mut inside = false;
2461        for &c in &children {
2462            inside |= self.mark_pointer_auto(c, effective);
2463        }
2464        self.nodes[key as usize].children = children;
2465        self.nodes[key as usize].pointer_auto_inside = inside;
2466        // Any value of its own but `none` takes some touches under a `none`.
2467        inside
2468            || own.is_some_and(|o| o != PointerEvents::None)
2469                && inherited == Some(PointerEvents::None)
2470    }
2471
2472    /// Applies the node props classes and styles set.
2473    pub(super) fn set_class_props(&mut self, key: Key, props: ClassProps) {
2474        let is_default = props == ClassProps::default();
2475        match (&self.nodes[key as usize].class_props, is_default) {
2476            (None, true) => return,
2477            (Some(old), false) if **old == props => return,
2478            (Some(old), true) if **old == ClassProps::default() => {
2479                self.nodes[key as usize].class_props = None;
2480                return;
2481            }
2482            _ => {}
2483        }
2484        let old = self.nodes[key as usize].class_props.take();
2485        let next = (!is_default).then(|| std::rc::Rc::new(props));
2486        self.nodes[key as usize].class_props = next.clone();
2487        self.diff_class_props(key, old.as_deref(), next.as_deref());
2488    }
2489
2490    /// Applies a shared `Rc<ClassProps>` from a cached resolved style,
2491    /// skipping comparison when the same pointer is already installed.
2492    pub(super) fn set_class_props_shared(
2493        &mut self,
2494        key: Key,
2495        props: Option<&std::rc::Rc<ClassProps>>,
2496    ) {
2497        match (&self.nodes[key as usize].class_props, props) {
2498            (None, None) => return,
2499            (Some(a), Some(b)) if std::rc::Rc::ptr_eq(a, b) => return,
2500            (Some(old), None) if **old == ClassProps::default() => {
2501                self.nodes[key as usize].class_props = None;
2502                return;
2503            }
2504            (Some(old), Some(new)) if **old == **new => {
2505                self.nodes[key as usize].class_props = Some(new.clone());
2506                return;
2507            }
2508            _ => {}
2509        }
2510        let old = self.nodes[key as usize].class_props.take();
2511        self.nodes[key as usize].class_props = props.cloned();
2512        self.diff_class_props(key, old.as_deref(), props.map(|p| &**p));
2513    }
2514
2515    fn diff_class_props(&mut self, key: Key, old: Option<&ClassProps>, new: Option<&ClassProps>) {
2516        let def = ClassProps::default();
2517        let old = old.unwrap_or(&def);
2518        let props = new.unwrap_or(&def);
2519        let paragraph = old.number_of_lines != props.number_of_lines
2520            || old.selectable != props.selectable
2521            || old.ellipsize != props.ellipsize
2522            || old.no_wrap != props.no_wrap
2523            || old.pretty != props.pretty;
2524        let pointer = old.pointer_events != props.pointer_events;
2525        let none = Some(crate::props::PointerEvents::None);
2526        match (old.pointer_events == none, props.pointer_events == none) {
2527            (false, true) => self.pointer_none_classes += 1,
2528            (true, false) => self.pointer_none_classes -= 1,
2529            _ => {}
2530        }
2531        let space = old.space != props.space;
2532        let input = old.placeholder_color != props.placeholder_color
2533            || old.caret_color != props.caret_color
2534            || old.selection_color != props.selection_color;
2535        let selection = old.selection_color != props.selection_color;
2536        let kind = self.nodes[key as usize].kind;
2537        if paragraph && kind == Kind::Text {
2538            self.mark_text_block(key);
2539        }
2540        if (old.no_wrap != props.no_wrap
2541            || old.selectable != props.selectable
2542            || selection
2543            || old.pretty != props.pretty)
2544            && kind != Kind::Text
2545        {
2546            // The texts inside inherit them.
2547            self.mark_inheriting_text(key);
2548        }
2549        if pointer {
2550            let top = self.pointer_region(key).unwrap_or(key);
2551            self.pointer_pending.push(top);
2552        }
2553        if selection && kind == Kind::Text {
2554            self.mark_text_block(key);
2555        }
2556        if input && kind == Kind::Input {
2557            self.mark(key, dirty::INPUT);
2558        }
2559        if space {
2560            // The margins of its children.
2561            let children = self.nodes[key as usize].children.clone();
2562            for child in children {
2563                if self.is_element_child(child) && !self.nodes[child as usize].inline {
2564                    self.restyle(child);
2565                }
2566            }
2567        }
2568    }
2569}