nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! The single style cascade (`[INV:single-style-cascade]`, `[INV:top-layer-single-definition]`):
//! base row -> matching `@media` -> matching `@container` -> state rules matching the node's live
//! `InteractionState`. Scene consumers (paint, stacking, hit-testing, semantics, focus) read it
//! with the layout engine's committed envs; the layout engines themselves resolve the same
//! [`StyleCascade::effective_box`] with their in-pass envs (`ResponsivePatches` impls), and
//! `TopLayerIndex` with the committed ones (`DisplayEnv`).

use nativeview_engine::InteractionTracker;
use nativeview_store::{NodeId, NodeStore, NvTable, Prop, RowPatchView, ScalarField};
use nativeview_tables::interaction::visit_state_rules_in_cascade;
use nativeview_tables::media::{ConditionalTier, cascade_display};
use nativeview_tables::semantics::SemanticStyleOracle;
use nativeview_tables::snapshots::transform_from_patch_view;
use nativeview_tables::tables::{
    ContainerType, Display, GridItem, GridLayout, Interaction, Isolation, Layout, LayoutRef, Overflow, Position,
    StateRules, StateRulesView, Transform as TransformTable, Typography, Visibility, Visual,
    is_closed_overlay,
};
use nativeview_tables::transform::Transform2D;

use crate::StoreLayoutEngine;
use crate::scene::OverlayState;

/// Responsive (`@media` / `@container`) patches of one node under a layout engine's committed
/// environment, in cascade order.
pub trait ResponsivePatches {
    fn visit_responsive_patches<'a>(
        &self,
        store: &'a NodeStore,
        id: NodeId,
        f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
    );

    /// `id`'s `show_on` gate fails (`display: none` beating every rule, like Web's `!important`).
    fn is_show_on_hidden(&self, store: &NodeStore, id: NodeId) -> bool;
}

impl<L: StoreLayoutEngine + ?Sized> ResponsivePatches for L {
    #[inline]
    fn visit_responsive_patches<'a>(
        &self,
        store: &'a NodeStore,
        id: NodeId,
        f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
    ) {
        StoreLayoutEngine::visit_responsive_patches(self, store, id, f);
    }

    #[inline]
    fn is_show_on_hidden(&self, store: &NodeStore, id: NodeId) -> bool {
        StoreLayoutEngine::is_show_on_hidden(self, store, id)
    }
}

/// `base -> @media -> @container -> state` for one scene. `Copy`, zero allocations; generic over
/// the responsive source so scenes dispatch statically (`dyn` only where a source is erased).
pub struct StyleCascade<'a, R: ResponsivePatches + ?Sized = dyn ResponsivePatches> {
    pub responsive: &'a R,
    /// Live pseudo-state; `None` resolves without state rules.
    pub interaction: Option<&'a InteractionTracker>,
    /// The scene's overlay resolution, for modal inertness ([`SemanticStyleOracle::is_inert`]);
    /// `None` (layout-internal cascades) treats nothing as inert.
    pub inert: Option<&'a OverlayState>,
}

impl<R: ResponsivePatches + ?Sized> Clone for StyleCascade<'_, R> {
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

impl<R: ResponsivePatches + ?Sized> Copy for StyleCascade<'_, R> {}

/// Every style input of CSS 2.1 Appendix E stacking for one node, from one cascade visit.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct StackingStyle {
    pub(crate) display: Display,
    pub(crate) position: Position,
    pub(crate) z_index: Option<i32>,
    pub(crate) opacity: f32,
    pub(crate) isolation: Isolation,
    /// Non-identity transform before backend animation overrides.
    pub(crate) transform: Option<Transform2D>,
    pub(crate) visibility: Option<Visibility>,
    pub(crate) overflow_x: Option<Overflow>,
    pub(crate) overflow_y: Option<Overflow>,
}

impl<R: ResponsivePatches + ?Sized> StyleCascade<'_, R> {
    /// [`StackingStyle`] of `id`: base rows, then one cascade visit for every property (the box
    /// half through [`Self::fold_box`], so it can never diverge from [`Self::effective_box`]).
    pub(crate) fn stacking_style(&self, store: &NodeStore, id: NodeId) -> StackingStyle {
        let visual = store.try_row::<Visual>(id);
        let mut style = StackingStyle {
            display: Display::None,
            position: Position::Static,
            z_index: visual.and_then(|v| v.z_index()),
            opacity: visual.map_or(1.0, |v| v.opacity()),
            isolation: visual.map_or(Isolation::Auto, |v| v.isolation()),
            transform: transform_of_row(store, id),
            visibility: visual.map(|v| v.visibility()),
            overflow_x: visual.map(|v| v.overflow_x()),
            overflow_y: visual.map(|v| v.overflow_y()),
        };
        let effective = self.fold_box(store, id, |_, pv| {
            if let Some(z) = pv.get_prop(Visual::Z_INDEX) {
                style.z_index = z;
            }
            if let Some(o) = pv.get_prop(Visual::OPACITY) {
                style.opacity = o;
            }
            if let Some(i) = pv.get_prop(Visual::ISOLATION) {
                style.isolation = i;
            }
            if let Some(v) = pv.get_prop(Visual::VISIBILITY) {
                style.visibility = Some(v);
            }
            if let Some(x) = pv.get_prop(Visual::OVERFLOW_X) {
                style.overflow_x = Some(x);
            }
            if let Some(y) = pv.get_prop(Visual::OVERFLOW_Y) {
                style.overflow_y = Some(y);
            }
            if let Some(tf) = transform_from_patch_view(pv) {
                style.transform = (!tf.is_identity()).then_some(tf);
            }
        });
        style.display = effective.display;
        style.position = effective.position;
        style
    }

    /// Visits every patch overriding `id`'s base rows in cascade order; `tier` is `None` for
    /// state rules.
    #[inline]
    pub fn visit<'s>(
        &self,
        store: &'s NodeStore,
        id: NodeId,
        mut f: impl FnMut(Option<ConditionalTier>, RowPatchView<'s>),
    ) {
        self.responsive
            .visit_responsive_patches(store, id, &mut |tier, pv| f(Some(tier), pv));
        self.visit_state(store, id, |pv| f(None, pv));
    }

    /// Visits `id`'s active state-rule patches (the cascade's last tier). The `StateRules` row is
    /// checked before the O(chain) pseudo-state lookup.
    #[inline]
    fn visit_state<'s>(&self, store: &'s NodeStore, id: NodeId, f: impl FnMut(RowPatchView<'s>)) {
        let Some(interaction) = self.interaction else {
            return;
        };
        let Some(rules) = state_rules_of(store, id) else {
            return;
        };
        let state = interaction.state(id);
        if !state.is_empty() {
            visit_state_rules_in_cascade(rules, state, f);
        }
    }

    /// `id`'s effective box: hidden input / closed overlay / failing `show_on` -> `none`; base
    /// row; `@media` / `@container` patches (under the `contents` rule of [`cascade_display`]);
    /// active state-rule patches. The one definition layout (Taffy, Yoga), top-layer hoisting,
    /// paint, stacking, hit-testing, semantics, focus and accessibility share.
    #[inline]
    pub fn effective_box(&self, store: &NodeStore, id: NodeId) -> EffectiveBox {
        self.fold_box(store, id, |_, _| {})
    }

    /// The one box fold: [`Self::effective_box`]'s ordering, also handing every visited patch to
    /// `also` (one cascade visit for callers that need more than the box). A forced-hidden node
    /// visits nothing: it generates no box, so nothing else about it is consulted.
    #[inline]
    fn fold_box<'s>(
        &self,
        store: &'s NodeStore,
        id: NodeId,
        mut also: impl FnMut(Option<ConditionalTier>, RowPatchView<'s>),
    ) -> EffectiveBox {
        if self.responsive.is_show_on_hidden(store, id) {
            return EffectiveBox::FORCED_HIDDEN;
        }
        let mut effective = EffectiveBox::base(store, id);
        if effective.forced_hidden {
            return effective;
        }
        self.responsive
            .visit_responsive_patches(store, id, &mut |tier, pv| {
                effective.apply(store, id, Some(tier), pv);
                also(Some(tier), pv);
            });
        self.fold_state(store, id, effective, |pv| also(None, pv))
    }

    /// The cascade's state tier over an already responsive-resolved `base` (Taffy feeds its
    /// per-pass responsive memo here; [`Self::effective_box`] feeds the visited patches).
    #[inline]
    pub(crate) fn apply_state(&self, store: &NodeStore, id: NodeId, base: EffectiveBox) -> EffectiveBox {
        self.fold_state(store, id, base, |_| {})
    }

    #[inline]
    fn fold_state<'s>(
        &self,
        store: &'s NodeStore,
        id: NodeId,
        mut base: EffectiveBox,
        mut also: impl FnMut(RowPatchView<'s>),
    ) -> EffectiveBox {
        if !base.forced_hidden {
            self.visit_state(store, id, |pv| {
                base.apply(store, id, None, pv);
                also(pv);
            });
        }
        if base.display == Display::None {
            base.container_type = ContainerType::Normal;
        }
        base
    }

    /// The last cascaded override of `prop` on `id` (`None` = the base row value stands).
    #[inline]
    pub fn patched<T: NvTable, V: ScalarField>(
        &self,
        store: &NodeStore,
        id: NodeId,
        prop: Prop<T, V>,
    ) -> Option<V> {
        let mut out = None;
        self.visit(store, id, |_, pv| {
            if let Some(v) = pv.get_prop(prop) {
                out = Some(v);
            }
        });
        out
    }

    /// `id`'s effective `display`, the one definition layout, top-layer hoisting, paint,
    /// stacking, hit-testing and accessibility share: hidden input / closed overlay / failing
    /// `show_on` -> `none`; base row; `@media` / `@container` patches (under the `contents` rule
    /// of [`cascade_display`]); active state-rule patches.
    #[inline]
    pub fn display(&self, store: &NodeStore, id: NodeId) -> Display {
        self.effective_box(store, id).display
    }
}

/// The cascade as the display half of a [`SemanticStyleOracle`]: focus management, semantic
/// queries and the shared top-layer predicate resolve exactly what layout and paint resolve.
impl<R: ResponsivePatches + ?Sized> SemanticStyleOracle for StyleCascade<'_, R> {
    #[inline]
    fn is_display_none(&self, store: &NodeStore, id: NodeId) -> bool {
        !store.is_live(id) || self.effective_box(store, id).is_none()
    }

    #[inline]
    fn is_display_contents(&self, store: &NodeStore, id: NodeId) -> bool {
        id != NodeId::ROOT && store.is_live(id) && self.effective_box(store, id).is_contents()
    }

    #[inline]
    fn visibility(&self, store: &NodeStore, id: NodeId) -> Visibility {
        self.patched(store, id, Visual::VISIBILITY).unwrap_or_else(|| {
            store
                .try_row::<Visual>(id)
                .map_or(Visibility::Inherit, |v| v.visibility())
        })
    }

    #[inline]
    fn is_inert(&self, store: &NodeStore, id: NodeId) -> bool {
        self.inert.is_some_and(|o| o.is_inert_under_modal(store, id))
    }

    #[inline]
    fn is_node_disabled(&self, store: &NodeStore, id: NodeId) -> bool {
        self.interaction.is_some_and(|i| i.is_disabled(id))
            || store.try_row::<Interaction>(id).is_some_and(|i| i.disabled())
    }
}

/// `id`'s non-identity `Transform` row, if any.
#[inline]
pub(crate) fn transform_of_row(store: &NodeStore, id: NodeId) -> Option<Transform2D> {
    let t = store.try_row::<TransformTable>(id)?;
    let tf = Transform2D {
        translate_x: t.translate_x(),
        translate_y: t.translate_y(),
        scale_x: t.scale_x(),
        scale_y: t.scale_y(),
        rotate_deg: t.rotate_deg(),
        origin_x: t.origin_x(),
        origin_y: t.origin_y(),
    };
    (!tf.is_identity()).then_some(tf)
}

/// A node's effective box-generating properties ([`StyleCascade::effective_box`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EffectiveBox {
    pub display: Display,
    pub position: Position,
    /// `Normal` whenever the node is hidden.
    pub container_type: ContainerType,
    /// Hidden regardless of `display` (hidden input, closed overlay, failing `show_on`).
    pub forced_hidden: bool,
}

impl EffectiveBox {
    pub(crate) const FORCED_HIDDEN: Self = Self {
        display: Display::None,
        position: Position::Static,
        container_type: ContainerType::Normal,
        forced_hidden: true,
    };

    /// `id`'s base box from `layout` (its own row, or a responsive-resolved one), before state
    /// rules; `show_on_hidden` is the already-evaluated `show_on` gate.
    #[inline]
    pub(crate) fn from_layout(
        store: &NodeStore,
        id: NodeId,
        layout: Option<LayoutRef<'_>>,
        show_on_hidden: bool,
    ) -> Self {
        if show_on_hidden || is_closed_overlay(store, id) {
            return Self::FORCED_HIDDEN;
        }
        layout.map_or(
            Self {
                display: Display::default(),
                position: Position::Static,
                container_type: ContainerType::Normal,
                forced_hidden: false,
            },
            |l| Self {
                display: l.display(),
                position: l.position(),
                container_type: l.container_type(),
                forced_hidden: false,
            },
        )
    }

    #[inline]
    fn base(store: &NodeStore, id: NodeId) -> Self {
        Self::from_layout(store, id, store.try_row::<Layout>(id), false)
    }

    /// Folds one cascaded patch (`tier == None` for state rules).
    #[inline]
    fn apply(
        &mut self,
        store: &NodeStore,
        id: NodeId,
        tier: Option<ConditionalTier>,
        pv: RowPatchView<'_>,
    ) {
        if let Some(d) = pv.get_prop(Layout::DISPLAY) {
            self.display = cascade_display(store, id, self.display, tier, d);
        }
        if let Some(p) = pv.get_prop(Layout::POSITION) {
            self.position = p;
        }
        if let Some(c) = pv.get_prop(Layout::CONTAINER_TYPE) {
            self.container_type = c;
        }
    }

    #[inline]
    pub fn is_none(self) -> bool {
        self.display == Display::None
    }

    #[inline]
    pub fn is_contents(self) -> bool {
        self.display == Display::Contents
    }

    /// `position: absolute | fixed` on a box (not `none`, not `contents`).
    #[inline]
    pub fn is_out_of_flow(self) -> bool {
        !matches!(self.display, Display::None | Display::Contents)
            && matches!(self.position, Position::Absolute | Position::Fixed)
    }
}

/// Whether any of `id`'s `StateRules` patches a box-generating property (`display`,
/// `position`, or `container_type`): a pseudo-state change on `id` then reflows it (Web parity).
pub fn state_rules_patch_box(store: &NodeStore, id: NodeId) -> bool {
    state_rules_of(store, id).is_some_and(|rules| {
        rules.iter().any(|(_, pv)| {
            pv.get_prop(Layout::DISPLAY).is_some()
                || pv.get_prop(Layout::POSITION).is_some()
                || pv.get_prop(Layout::CONTAINER_TYPE).is_some()
        })
    })
}

/// Whether any of `id`'s `StateRules` (active or not) patches a layout-affecting table, so a
/// state change on `id` needs a layout pass.
pub(crate) fn state_rules_touch_layout(store: &NodeStore, id: NodeId) -> bool {
    state_rules_of(store, id).is_some_and(|rules| {
            rules.iter().any(|(_, pv)| {
                pv.has_table::<Layout>()
                    || pv.has_table::<GridLayout>()
                    || pv.has_table::<GridItem>()
                    || pv.has_table::<Typography>()
            })
        })
}

/// `id`'s `StateRules` resource: the one place the cascade's state tier is looked up.
#[inline]
pub(crate) fn state_rules_of(store: &NodeStore, id: NodeId) -> Option<StateRulesView<'_>> {
    store
        .try_row::<Interaction>(id)
        .filter(|row| !row.state_rules().is_none())
        .and_then(|row| store.resource::<StateRules>(row.state_rules()))
}

/// A style source without responsive rules (stacking plans built outside a laid-out scene).
pub struct NoResponsivePatches;

impl ResponsivePatches for NoResponsivePatches {
    #[inline]
    fn visit_responsive_patches<'a>(
        &self,
        _store: &'a NodeStore,
        _id: NodeId,
        _f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
    ) {
    }

    #[inline]
    fn is_show_on_hidden(&self, _store: &NodeStore, _id: NodeId) -> bool {
        false
    }
}