Skip to main content

nativeview_layout/scene/
style_cascade.rs

1//! The single style cascade (`[INV:single-style-cascade]`, `[INV:top-layer-single-definition]`):
2//! base row -> matching `@media` -> matching `@container` -> state rules matching the node's live
3//! `InteractionState`. Scene consumers (paint, stacking, hit-testing, semantics, focus) read it
4//! with the layout engine's committed envs; the layout engines themselves resolve the same
5//! [`StyleCascade::effective_box`] with their in-pass envs (`ResponsivePatches` impls), and
6//! `TopLayerIndex` with the committed ones (`DisplayEnv`).
7
8use nativeview_engine::InteractionTracker;
9use nativeview_store::{NodeId, NodeStore, NvTable, Prop, RowPatchView, ScalarField};
10use nativeview_tables::interaction::visit_state_rules_in_cascade;
11use nativeview_tables::media::{ConditionalTier, cascade_display};
12use nativeview_tables::semantics::SemanticStyleOracle;
13use nativeview_tables::snapshots::transform_from_patch_view;
14use nativeview_tables::tables::{
15    ContainerType, Display, GridItem, GridLayout, Interaction, Isolation, Layout, LayoutRef, Overflow, Position,
16    StateRules, StateRulesView, Transform as TransformTable, Typography, Visibility, Visual,
17    is_closed_overlay,
18};
19use nativeview_tables::transform::Transform2D;
20
21use crate::StoreLayoutEngine;
22use crate::scene::OverlayState;
23
24/// Responsive (`@media` / `@container`) patches of one node under a layout engine's committed
25/// environment, in cascade order.
26pub trait ResponsivePatches {
27    fn visit_responsive_patches<'a>(
28        &self,
29        store: &'a NodeStore,
30        id: NodeId,
31        f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
32    );
33
34    /// `id`'s `show_on` gate fails (`display: none` beating every rule, like Web's `!important`).
35    fn is_show_on_hidden(&self, store: &NodeStore, id: NodeId) -> bool;
36}
37
38impl<L: StoreLayoutEngine + ?Sized> ResponsivePatches for L {
39    #[inline]
40    fn visit_responsive_patches<'a>(
41        &self,
42        store: &'a NodeStore,
43        id: NodeId,
44        f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
45    ) {
46        StoreLayoutEngine::visit_responsive_patches(self, store, id, f);
47    }
48
49    #[inline]
50    fn is_show_on_hidden(&self, store: &NodeStore, id: NodeId) -> bool {
51        StoreLayoutEngine::is_show_on_hidden(self, store, id)
52    }
53}
54
55/// `base -> @media -> @container -> state` for one scene. `Copy`, zero allocations; generic over
56/// the responsive source so scenes dispatch statically (`dyn` only where a source is erased).
57pub struct StyleCascade<'a, R: ResponsivePatches + ?Sized = dyn ResponsivePatches> {
58    pub responsive: &'a R,
59    /// Live pseudo-state; `None` resolves without state rules.
60    pub interaction: Option<&'a InteractionTracker>,
61    /// The scene's overlay resolution, for modal inertness ([`SemanticStyleOracle::is_inert`]);
62    /// `None` (layout-internal cascades) treats nothing as inert.
63    pub inert: Option<&'a OverlayState>,
64}
65
66impl<R: ResponsivePatches + ?Sized> Clone for StyleCascade<'_, R> {
67    #[inline]
68    fn clone(&self) -> Self {
69        *self
70    }
71}
72
73impl<R: ResponsivePatches + ?Sized> Copy for StyleCascade<'_, R> {}
74
75/// Every style input of CSS 2.1 Appendix E stacking for one node, from one cascade visit.
76#[derive(Debug, Clone, Copy, PartialEq)]
77pub(crate) struct StackingStyle {
78    pub(crate) display: Display,
79    pub(crate) position: Position,
80    pub(crate) z_index: Option<i32>,
81    pub(crate) opacity: f32,
82    pub(crate) isolation: Isolation,
83    /// Non-identity transform before backend animation overrides.
84    pub(crate) transform: Option<Transform2D>,
85    pub(crate) visibility: Option<Visibility>,
86    pub(crate) overflow_x: Option<Overflow>,
87    pub(crate) overflow_y: Option<Overflow>,
88}
89
90impl<R: ResponsivePatches + ?Sized> StyleCascade<'_, R> {
91    /// [`StackingStyle`] of `id`: base rows, then one cascade visit for every property (the box
92    /// half through [`Self::fold_box`], so it can never diverge from [`Self::effective_box`]).
93    pub(crate) fn stacking_style(&self, store: &NodeStore, id: NodeId) -> StackingStyle {
94        let visual = store.try_row::<Visual>(id);
95        let mut style = StackingStyle {
96            display: Display::None,
97            position: Position::Static,
98            z_index: visual.and_then(|v| v.z_index()),
99            opacity: visual.map_or(1.0, |v| v.opacity()),
100            isolation: visual.map_or(Isolation::Auto, |v| v.isolation()),
101            transform: transform_of_row(store, id),
102            visibility: visual.map(|v| v.visibility()),
103            overflow_x: visual.map(|v| v.overflow_x()),
104            overflow_y: visual.map(|v| v.overflow_y()),
105        };
106        let effective = self.fold_box(store, id, |_, pv| {
107            if let Some(z) = pv.get_prop(Visual::Z_INDEX) {
108                style.z_index = z;
109            }
110            if let Some(o) = pv.get_prop(Visual::OPACITY) {
111                style.opacity = o;
112            }
113            if let Some(i) = pv.get_prop(Visual::ISOLATION) {
114                style.isolation = i;
115            }
116            if let Some(v) = pv.get_prop(Visual::VISIBILITY) {
117                style.visibility = Some(v);
118            }
119            if let Some(x) = pv.get_prop(Visual::OVERFLOW_X) {
120                style.overflow_x = Some(x);
121            }
122            if let Some(y) = pv.get_prop(Visual::OVERFLOW_Y) {
123                style.overflow_y = Some(y);
124            }
125            if let Some(tf) = transform_from_patch_view(pv) {
126                style.transform = (!tf.is_identity()).then_some(tf);
127            }
128        });
129        style.display = effective.display;
130        style.position = effective.position;
131        style
132    }
133
134    /// Visits every patch overriding `id`'s base rows in cascade order; `tier` is `None` for
135    /// state rules.
136    #[inline]
137    pub fn visit<'s>(
138        &self,
139        store: &'s NodeStore,
140        id: NodeId,
141        mut f: impl FnMut(Option<ConditionalTier>, RowPatchView<'s>),
142    ) {
143        self.responsive
144            .visit_responsive_patches(store, id, &mut |tier, pv| f(Some(tier), pv));
145        self.visit_state(store, id, |pv| f(None, pv));
146    }
147
148    /// Visits `id`'s active state-rule patches (the cascade's last tier). The `StateRules` row is
149    /// checked before the O(chain) pseudo-state lookup.
150    #[inline]
151    fn visit_state<'s>(&self, store: &'s NodeStore, id: NodeId, f: impl FnMut(RowPatchView<'s>)) {
152        let Some(interaction) = self.interaction else {
153            return;
154        };
155        let Some(rules) = state_rules_of(store, id) else {
156            return;
157        };
158        let state = interaction.state(id);
159        if !state.is_empty() {
160            visit_state_rules_in_cascade(rules, state, f);
161        }
162    }
163
164    /// `id`'s effective box: hidden input / closed overlay / failing `show_on` -> `none`; base
165    /// row; `@media` / `@container` patches (under the `contents` rule of [`cascade_display`]);
166    /// active state-rule patches. The one definition layout (Taffy, Yoga), top-layer hoisting,
167    /// paint, stacking, hit-testing, semantics, focus and accessibility share.
168    #[inline]
169    pub fn effective_box(&self, store: &NodeStore, id: NodeId) -> EffectiveBox {
170        self.fold_box(store, id, |_, _| {})
171    }
172
173    /// The one box fold: [`Self::effective_box`]'s ordering, also handing every visited patch to
174    /// `also` (one cascade visit for callers that need more than the box). A forced-hidden node
175    /// visits nothing: it generates no box, so nothing else about it is consulted.
176    #[inline]
177    fn fold_box<'s>(
178        &self,
179        store: &'s NodeStore,
180        id: NodeId,
181        mut also: impl FnMut(Option<ConditionalTier>, RowPatchView<'s>),
182    ) -> EffectiveBox {
183        if self.responsive.is_show_on_hidden(store, id) {
184            return EffectiveBox::FORCED_HIDDEN;
185        }
186        let mut effective = EffectiveBox::base(store, id);
187        if effective.forced_hidden {
188            return effective;
189        }
190        self.responsive
191            .visit_responsive_patches(store, id, &mut |tier, pv| {
192                effective.apply(store, id, Some(tier), pv);
193                also(Some(tier), pv);
194            });
195        self.fold_state(store, id, effective, |pv| also(None, pv))
196    }
197
198    /// The cascade's state tier over an already responsive-resolved `base` (Taffy feeds its
199    /// per-pass responsive memo here; [`Self::effective_box`] feeds the visited patches).
200    #[inline]
201    pub(crate) fn apply_state(&self, store: &NodeStore, id: NodeId, base: EffectiveBox) -> EffectiveBox {
202        self.fold_state(store, id, base, |_| {})
203    }
204
205    #[inline]
206    fn fold_state<'s>(
207        &self,
208        store: &'s NodeStore,
209        id: NodeId,
210        mut base: EffectiveBox,
211        mut also: impl FnMut(RowPatchView<'s>),
212    ) -> EffectiveBox {
213        if !base.forced_hidden {
214            self.visit_state(store, id, |pv| {
215                base.apply(store, id, None, pv);
216                also(pv);
217            });
218        }
219        if base.display == Display::None {
220            base.container_type = ContainerType::Normal;
221        }
222        base
223    }
224
225    /// The last cascaded override of `prop` on `id` (`None` = the base row value stands).
226    #[inline]
227    pub fn patched<T: NvTable, V: ScalarField>(
228        &self,
229        store: &NodeStore,
230        id: NodeId,
231        prop: Prop<T, V>,
232    ) -> Option<V> {
233        let mut out = None;
234        self.visit(store, id, |_, pv| {
235            if let Some(v) = pv.get_prop(prop) {
236                out = Some(v);
237            }
238        });
239        out
240    }
241
242    /// `id`'s effective `display`, the one definition layout, top-layer hoisting, paint,
243    /// stacking, hit-testing and accessibility share: hidden input / closed overlay / failing
244    /// `show_on` -> `none`; base row; `@media` / `@container` patches (under the `contents` rule
245    /// of [`cascade_display`]); active state-rule patches.
246    #[inline]
247    pub fn display(&self, store: &NodeStore, id: NodeId) -> Display {
248        self.effective_box(store, id).display
249    }
250}
251
252/// The cascade as the display half of a [`SemanticStyleOracle`]: focus management, semantic
253/// queries and the shared top-layer predicate resolve exactly what layout and paint resolve.
254impl<R: ResponsivePatches + ?Sized> SemanticStyleOracle for StyleCascade<'_, R> {
255    #[inline]
256    fn is_display_none(&self, store: &NodeStore, id: NodeId) -> bool {
257        !store.is_live(id) || self.effective_box(store, id).is_none()
258    }
259
260    #[inline]
261    fn is_display_contents(&self, store: &NodeStore, id: NodeId) -> bool {
262        id != NodeId::ROOT && store.is_live(id) && self.effective_box(store, id).is_contents()
263    }
264
265    #[inline]
266    fn visibility(&self, store: &NodeStore, id: NodeId) -> Visibility {
267        self.patched(store, id, Visual::VISIBILITY).unwrap_or_else(|| {
268            store
269                .try_row::<Visual>(id)
270                .map_or(Visibility::Inherit, |v| v.visibility())
271        })
272    }
273
274    #[inline]
275    fn is_inert(&self, store: &NodeStore, id: NodeId) -> bool {
276        self.inert.is_some_and(|o| o.is_inert_under_modal(store, id))
277    }
278
279    #[inline]
280    fn is_node_disabled(&self, store: &NodeStore, id: NodeId) -> bool {
281        self.interaction.is_some_and(|i| i.is_disabled(id))
282            || store.try_row::<Interaction>(id).is_some_and(|i| i.disabled())
283    }
284}
285
286/// `id`'s non-identity `Transform` row, if any.
287#[inline]
288pub(crate) fn transform_of_row(store: &NodeStore, id: NodeId) -> Option<Transform2D> {
289    let t = store.try_row::<TransformTable>(id)?;
290    let tf = Transform2D {
291        translate_x: t.translate_x(),
292        translate_y: t.translate_y(),
293        scale_x: t.scale_x(),
294        scale_y: t.scale_y(),
295        rotate_deg: t.rotate_deg(),
296        origin_x: t.origin_x(),
297        origin_y: t.origin_y(),
298    };
299    (!tf.is_identity()).then_some(tf)
300}
301
302/// A node's effective box-generating properties ([`StyleCascade::effective_box`]).
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304pub struct EffectiveBox {
305    pub display: Display,
306    pub position: Position,
307    /// `Normal` whenever the node is hidden.
308    pub container_type: ContainerType,
309    /// Hidden regardless of `display` (hidden input, closed overlay, failing `show_on`).
310    pub forced_hidden: bool,
311}
312
313impl EffectiveBox {
314    pub(crate) const FORCED_HIDDEN: Self = Self {
315        display: Display::None,
316        position: Position::Static,
317        container_type: ContainerType::Normal,
318        forced_hidden: true,
319    };
320
321    /// `id`'s base box from `layout` (its own row, or a responsive-resolved one), before state
322    /// rules; `show_on_hidden` is the already-evaluated `show_on` gate.
323    #[inline]
324    pub(crate) fn from_layout(
325        store: &NodeStore,
326        id: NodeId,
327        layout: Option<LayoutRef<'_>>,
328        show_on_hidden: bool,
329    ) -> Self {
330        if show_on_hidden || is_closed_overlay(store, id) {
331            return Self::FORCED_HIDDEN;
332        }
333        layout.map_or(
334            Self {
335                display: Display::default(),
336                position: Position::Static,
337                container_type: ContainerType::Normal,
338                forced_hidden: false,
339            },
340            |l| Self {
341                display: l.display(),
342                position: l.position(),
343                container_type: l.container_type(),
344                forced_hidden: false,
345            },
346        )
347    }
348
349    #[inline]
350    fn base(store: &NodeStore, id: NodeId) -> Self {
351        Self::from_layout(store, id, store.try_row::<Layout>(id), false)
352    }
353
354    /// Folds one cascaded patch (`tier == None` for state rules).
355    #[inline]
356    fn apply(
357        &mut self,
358        store: &NodeStore,
359        id: NodeId,
360        tier: Option<ConditionalTier>,
361        pv: RowPatchView<'_>,
362    ) {
363        if let Some(d) = pv.get_prop(Layout::DISPLAY) {
364            self.display = cascade_display(store, id, self.display, tier, d);
365        }
366        if let Some(p) = pv.get_prop(Layout::POSITION) {
367            self.position = p;
368        }
369        if let Some(c) = pv.get_prop(Layout::CONTAINER_TYPE) {
370            self.container_type = c;
371        }
372    }
373
374    #[inline]
375    pub fn is_none(self) -> bool {
376        self.display == Display::None
377    }
378
379    #[inline]
380    pub fn is_contents(self) -> bool {
381        self.display == Display::Contents
382    }
383
384    /// `position: absolute | fixed` on a box (not `none`, not `contents`).
385    #[inline]
386    pub fn is_out_of_flow(self) -> bool {
387        !matches!(self.display, Display::None | Display::Contents)
388            && matches!(self.position, Position::Absolute | Position::Fixed)
389    }
390}
391
392/// Whether any of `id`'s `StateRules` patches a box-generating property (`display`,
393/// `position`, or `container_type`): a pseudo-state change on `id` then reflows it (Web parity).
394pub fn state_rules_patch_box(store: &NodeStore, id: NodeId) -> bool {
395    state_rules_of(store, id).is_some_and(|rules| {
396        rules.iter().any(|(_, pv)| {
397            pv.get_prop(Layout::DISPLAY).is_some()
398                || pv.get_prop(Layout::POSITION).is_some()
399                || pv.get_prop(Layout::CONTAINER_TYPE).is_some()
400        })
401    })
402}
403
404/// Whether any of `id`'s `StateRules` (active or not) patches a layout-affecting table, so a
405/// state change on `id` needs a layout pass.
406pub(crate) fn state_rules_touch_layout(store: &NodeStore, id: NodeId) -> bool {
407    state_rules_of(store, id).is_some_and(|rules| {
408            rules.iter().any(|(_, pv)| {
409                pv.has_table::<Layout>()
410                    || pv.has_table::<GridLayout>()
411                    || pv.has_table::<GridItem>()
412                    || pv.has_table::<Typography>()
413            })
414        })
415}
416
417/// `id`'s `StateRules` resource: the one place the cascade's state tier is looked up.
418#[inline]
419pub(crate) fn state_rules_of(store: &NodeStore, id: NodeId) -> Option<StateRulesView<'_>> {
420    store
421        .try_row::<Interaction>(id)
422        .filter(|row| !row.state_rules().is_none())
423        .and_then(|row| store.resource::<StateRules>(row.state_rules()))
424}
425
426/// A style source without responsive rules (stacking plans built outside a laid-out scene).
427pub struct NoResponsivePatches;
428
429impl ResponsivePatches for NoResponsivePatches {
430    #[inline]
431    fn visit_responsive_patches<'a>(
432        &self,
433        _store: &'a NodeStore,
434        _id: NodeId,
435        _f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
436    ) {
437    }
438
439    #[inline]
440    fn is_show_on_hidden(&self, _store: &NodeStore, _id: NodeId) -> bool {
441        false
442    }
443}