Skip to main content

nativeview_layout/scene/stacking/
mod.rs

1//! Shared zero-allocation CSS 2.1 Appendix E stacking tree & containing-block clip/scroll plan
2//! consumed by both [`super::LaidOutScene`] hit-testing and `SkiaBackend`'s retained compositor.
3//!
4//! Every node/item/scope/clip record is a strictly `Copy` POD stored in flat, capacity-retaining
5//! `Vec`s so rebuilding or in-place z-resorting performs **0 heap allocations** in steady state.
6
7use nativeview_abi::ColorRgba;
8use nativeview_store::{NodeId, NodeStore};
9use nativeview_tables::tables::Display;
10
11mod build;
12mod style;
13
14pub use style::{
15    SceneStackingStyleSource, StackingNodeRole, StackingOverrides, StackingStyleSource,
16    bucket_for_sc_z, classify_node_sc_with_parent_display, resolve_node_sc_state,
17};
18
19/// Dense index into [`StackingPlan::scopes`] (`NONE` when absent).
20#[repr(transparent)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
22pub struct ScopeIdx(pub u32);
23
24impl ScopeIdx {
25    pub const NONE: Self = Self(u32::MAX);
26
27    #[inline]
28    pub const fn is_none(self) -> bool {
29        self.0 == u32::MAX
30    }
31
32    #[inline]
33    pub const fn is_some(self) -> bool {
34        self.0 != u32::MAX
35    }
36
37    #[inline]
38    pub const fn index(self) -> usize {
39        self.0 as usize
40    }
41}
42
43/// CSS stacking context z-order level (distinct from DOM tree order and array indices).
44#[repr(transparent)]
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
46pub struct ZOrder(pub i32);
47
48/// Count of [`StackingItem`] entries in a [`StackingScope`]'s contiguous CSR span.
49#[repr(transparent)]
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
51pub struct ItemCount(pub u32);
52
53impl ItemCount {
54    pub const ZERO: Self = Self(0);
55
56    #[inline]
57    pub const fn get(self) -> u32 {
58        self.0
59    }
60
61    #[inline]
62    pub const fn as_usize(self) -> usize {
63        self.0 as usize
64    }
65
66    #[inline]
67    pub const fn is_empty(self) -> bool {
68        self.0 == 0
69    }
70}
71
72/// Per-scope build-time sort flags packed into one byte.
73#[repr(transparent)]
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
75pub(crate) struct ScopeSortFlags(u8);
76
77impl ScopeSortFlags {
78    const NEEDS_SORT: u8 = 1 << 0;
79    const HAS_NEG: u8 = 1 << 1;
80
81    #[inline]
82    pub(crate) const fn needs_sort(self) -> bool {
83        (self.0 & Self::NEEDS_SORT) != 0
84    }
85
86    #[inline]
87    pub(crate) const fn has_neg(self) -> bool {
88        (self.0 & Self::HAS_NEG) != 0
89    }
90
91    #[inline]
92    pub(crate) fn mark_needs_sort(&mut self) {
93        self.0 |= Self::NEEDS_SORT;
94    }
95
96    #[inline]
97    pub(crate) fn mark_has_neg(&mut self) {
98        self.0 |= Self::NEEDS_SORT | Self::HAS_NEG;
99    }
100}
101
102/// Dense index into [`StackingPlan::clips`] (`NONE` when unclipped/unshifted viewport space).
103#[repr(transparent)]
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
105pub struct ClipScrollIdx(pub u32);
106
107impl ClipScrollIdx {
108    pub const NONE: Self = Self(u32::MAX);
109
110    #[inline]
111    pub const fn is_none(self) -> bool {
112        self.0 == u32::MAX
113    }
114
115    #[inline]
116    pub const fn is_some(self) -> bool {
117        self.0 != u32::MAX
118    }
119
120    #[inline]
121    pub const fn index(self) -> usize {
122        self.0 as usize
123    }
124}
125
126/// Whether a [`StackingScope`] establishes a real CSS stacking context or an atomic in-flow /
127/// positioned-auto pseudo-stacking context (whose positioned/SC descendants still hoist out).
128#[repr(u8)]
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum ScopeKind {
131    RealStackingContext = 0,
132    PseudoStackingContext = 1,
133}
134
135/// CSS 2.1 Appendix E stacking layer bucket (ordered back-to-front).
136#[repr(u8)]
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum StackingBucket {
139    /// Step 2: real stacking context with `z_index < 0`.
140    NegSc = 0,
141    /// Step 3: non-atomic in-flow block background/border.
142    InFlowBlock = 1,
143    /// Step 5/7: atomic inline/flex/grid pseudo-SC, inline leaf, or split block foreground.
144    InFlowInline = 2,
145    /// Step 8: positioned `z-index: auto` pseudo-SC or real SC with `z_index == 0`.
146    Step8 = 3,
147    /// Step 9: real stacking context with `z_index > 0`.
148    PosSc = 4,
149}
150
151/// Which local paint ops a [`StackingItem`] emits (splits non-atomic block Step 3 vs Step 7).
152#[repr(u8)]
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum ItemPaintPhase {
155    Full = 0,
156    BgOnly = 1,
157    FgOnly = 2,
158}
159
160pub const CS_CLIPS: u8 = 1 << 0;
161pub const CS_HAS_SCROLL: u8 = 1 << 1;
162pub const CS_IS_STICKY: u8 = 1 << 2;
163pub const CS_IS_TOP_LAYER: u8 = 1 << 3;
164pub const CS_IS_TRANSFORM: u8 = 1 << 4;
165
166/// One containing-block clip / scroll / sticky / top-layer / transform ancestor node (12 B POD).
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub struct ClipScrollNode {
169    pub parent: ClipScrollIdx,
170    pub owner: NodeId,
171    /// 1-based depth from `ClipScrollIdx::NONE` (`parent.depth + 1`).
172    pub depth: u16,
173    pub flags: u8,
174}
175
176impl ClipScrollNode {
177    #[inline]
178    pub const fn clips(self) -> bool {
179        (self.flags & CS_CLIPS) != 0
180    }
181
182    #[inline]
183    pub const fn has_scroll(self) -> bool {
184        (self.flags & CS_HAS_SCROLL) != 0
185    }
186
187    #[inline]
188    pub const fn is_sticky(self) -> bool {
189        (self.flags & CS_IS_STICKY) != 0
190    }
191
192    #[inline]
193    pub const fn is_top_layer(self) -> bool {
194        (self.flags & CS_IS_TOP_LAYER) != 0
195    }
196
197    #[inline]
198    pub const fn is_transform(self) -> bool {
199        (self.flags & CS_IS_TRANSFORM) != 0
200    }
201}
202
203pub const SCOPE_IS_TOP_LAYER: u8 = 1 << 0;
204pub const SCOPE_HAS_SCROLL: u8 = 1 << 1;
205pub const SCOPE_IS_STICKY: u8 = 1 << 2;
206pub const SCOPE_IS_MODAL: u8 = 1 << 3;
207
208/// One ordered entry inside a [`StackingScope`]'s item span (24 B Copy POD).
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub struct StackingItem {
211    pub node_id: NodeId,
212    pub child_scope: ScopeIdx,
213    pub clip_scroll: ClipScrollIdx,
214    pub z_index: ZOrder,
215    pub tree_order: u32,
216    pub bucket: StackingBucket,
217    pub paint_phase: ItemPaintPhase,
218    pub hidden: bool,
219}
220
221impl Default for StackingItem {
222    fn default() -> Self {
223        Self {
224            node_id: NodeId::NULL,
225            child_scope: ScopeIdx::NONE,
226            clip_scroll: ClipScrollIdx::NONE,
227            z_index: ZOrder(0),
228            tree_order: 0,
229            bucket: StackingBucket::InFlowBlock,
230            paint_phase: ItemPaintPhase::Full,
231            hidden: false,
232        }
233    }
234}
235
236/// One real stacking context or atomic pseudo-stacking context (32 B Copy POD).
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub struct StackingScope {
239    pub node_id: NodeId,
240    pub parent_scope: ScopeIdx,
241    pub clip_scroll: ClipScrollIdx,
242    pub min_descendant_clip: ClipScrollIdx,
243    pub items_start: u32,
244    pub items_len: ItemCount,
245    /// Relative offset inside `items_start..items_start + items_len` separating Step 2 (`NegSc`)
246    /// from Steps 3..9.
247    pub neg_end: u32,
248    pub kind: ScopeKind,
249    pub hidden: bool,
250    pub has_transform: bool,
251    pub flags: u8,
252}
253
254impl StackingScope {
255    #[inline]
256    pub const fn is_top_layer(self) -> bool {
257        (self.flags & SCOPE_IS_TOP_LAYER) != 0
258    }
259
260    #[inline]
261    pub const fn has_scroll(self) -> bool {
262        (self.flags & SCOPE_HAS_SCROLL) != 0
263    }
264
265    #[inline]
266    pub const fn is_sticky(self) -> bool {
267        (self.flags & SCOPE_IS_STICKY) != 0
268    }
269
270    #[inline]
271    pub const fn is_modal(self) -> bool {
272        (self.flags & SCOPE_IS_MODAL) != 0
273    }
274}
275
276/// Root scope of one open top-layer [`Overlay`] painted and hit-tested above the document root.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub struct TopLayerScope {
279    pub scope: ScopeIdx,
280    pub node_id: NodeId,
281    pub is_modal: bool,
282    /// Viewport scrim painted (and hit-blocking) behind this top layer, if any.
283    pub backdrop: Option<ColorRgba>,
284}
285
286const _: () = assert!(std::mem::size_of::<ClipScrollNode>() <= 16);
287const _: () = assert!(std::mem::size_of::<StackingItem>() <= 24);
288const _: () = assert!(std::mem::size_of::<StackingScope>() <= 32);
289
290#[derive(Debug, Clone, Copy)]
291pub(crate) struct DfsFrame {
292    pub(crate) id: NodeId,
293    pub(crate) cur_sc: ScopeIdx,
294    pub(crate) cur_inflow_owner: ScopeIdx,
295    pub(crate) box_parent_display: Display,
296    pub(crate) box_clip: ClipScrollIdx,
297    pub(crate) abs_clip: ClipScrollIdx,
298    pub(crate) fixed_clip: ClipScrollIdx,
299    pub(crate) inherited_hidden: bool,
300    pub(crate) depth: u16,
301    pub(crate) is_root_of_pass: bool,
302    pub(crate) is_top_layer_root: bool,
303}
304
305pub(crate) const BUCKET_NONE: u8 = u8::MAX;
306
307/// Flat, zero-allocation reusable CSS 2.1 Appendix E stacking tree and clip/scroll graph.
308#[derive(Debug, Clone, Default)]
309pub struct StackingPlan {
310    pub root: Option<ScopeIdx>,
311    pub top_layers: Vec<TopLayerScope>,
312    pub scopes: Vec<StackingScope>,
313    pub ordered_items: Vec<StackingItem>,
314    pub clips: Vec<ClipScrollNode>,
315    /// Dense `NodeId::index() -> ScopeIdx` (`ScopeIdx::NONE` if leaf/absent).
316    pub node_to_scope: Vec<ScopeIdx>,
317    /// Dense `NodeId::index() -> index in ordered_items` (`u32::MAX` if root/absent).
318    pub node_to_item: Vec<u32>,
319    // --- Reusable build scratch (cleared, never shrunk, 0 steady-state allocations) ---
320    pub(crate) dfs_stack: Vec<DfsFrame>,
321    pub(crate) staging: Vec<(ScopeIdx, StackingItem)>,
322    pub(crate) scope_counts: Vec<u32>,
323    pub(crate) write_cursors: Vec<u32>,
324    pub(crate) scope_sort_flags: Vec<ScopeSortFlags>,
325    pub(crate) scope_last_bucket: Vec<u8>,
326}
327
328impl StackingPlan {
329    pub fn clear(&mut self) {
330        self.root = None;
331        self.top_layers.clear();
332        self.scopes.clear();
333        self.ordered_items.clear();
334        self.clips.clear();
335        self.node_to_scope.fill(ScopeIdx::NONE);
336        self.node_to_item.fill(u32::MAX);
337        self.dfs_stack.clear();
338        self.staging.clear();
339        self.scope_counts.clear();
340        self.write_cursors.clear();
341        self.scope_sort_flags.clear();
342        self.scope_last_bucket.clear();
343    }
344
345    #[inline]
346    pub fn is_empty(&self) -> bool {
347        self.root.is_none() && self.top_layers.is_empty()
348    }
349
350    #[inline]
351    pub fn scope_items(&self, scope: ScopeIdx) -> &[StackingItem] {
352        let Some(s) = self.scopes.get(scope.index()) else {
353            return &[];
354        };
355        let start = s.items_start as usize;
356        let end = start.saturating_add(s.items_len.as_usize());
357        self.ordered_items.get(start..end).unwrap_or(&[])
358    }
359
360    #[inline]
361    pub fn scope_for_node(&self, id: NodeId) -> Option<ScopeIdx> {
362        let &s = self.node_to_scope.get(id.index())?;
363        if s.is_none() {
364            return None;
365        }
366        (self.scopes.get(s.index()).is_some_and(|sc| sc.node_id == id)).then_some(s)
367    }
368
369    #[inline]
370    pub fn item_idx_for_node(&self, id: NodeId) -> Option<usize> {
371        let &idx = self.node_to_item.get(id.index())?;
372        if idx == u32::MAX {
373            return None;
374        }
375        let i = idx as usize;
376        (self.ordered_items.get(i).is_some_and(|it| it.node_id == id)).then_some(i)
377    }
378
379    #[inline]
380    pub fn clip_depth(&self, idx: ClipScrollIdx) -> u16 {
381        if idx.is_none() {
382            0
383        } else {
384            self.clips.get(idx.index()).map_or(0, |c| c.depth)
385        }
386    }
387
388    /// Lowest common ancestor of two [`ClipScrollIdx`] handles in `O(|depth_a - depth_b| + hops)`.
389    #[inline]
390    pub fn lca_clip(&self, mut a: ClipScrollIdx, mut b: ClipScrollIdx) -> ClipScrollIdx {
391        if a == b {
392            return a;
393        }
394        if a.is_none() || b.is_none() {
395            return ClipScrollIdx::NONE;
396        }
397        let mut da = self.clip_depth(a);
398        let mut db = self.clip_depth(b);
399        while da > db && a.is_some() {
400            a = self.clips[a.index()].parent;
401            da -= 1;
402        }
403        while db > da && b.is_some() {
404            b = self.clips[b.index()].parent;
405            db -= 1;
406        }
407        while a != b && a.is_some() && b.is_some() {
408            a = self.clips[a.index()].parent;
409            b = self.clips[b.index()].parent;
410        }
411        if a == b { a } else { ClipScrollIdx::NONE }
412    }
413
414    /// Re-sorts one scope's existing `ordered_items` span in place with **0 heap allocations**
415    /// (called on 120 Hz `COMPOSITE` `z_index` changes that preserve SC membership).
416    pub fn resort_scope_in_place(&mut self, scope: ScopeIdx) {
417        let Some(s) = self.scopes.get(scope.index()).copied() else {
418            return;
419        };
420        let start = s.items_start as usize;
421        let end = start.saturating_add(s.items_len.as_usize());
422        let Some(span) = self.ordered_items.get_mut(start..end) else {
423            return;
424        };
425        if span.len() > 1 {
426            span.sort_unstable_by_key(|it| (it.bucket as u8, it.z_index.0, it.tree_order));
427        }
428        let mut neg_end = 0u32;
429        for (offset, it) in span.iter().enumerate() {
430            if it.bucket == StackingBucket::NegSc {
431                neg_end = (offset + 1) as u32;
432            }
433            if it.paint_phase != ItemPaintPhase::FgOnly {
434                let nidx = it.node_id.index();
435                if nidx < self.node_to_item.len() {
436                    self.node_to_item[nidx] = (start + offset) as u32;
437                }
438            }
439        }
440        self.scopes[scope.index()].neg_end = neg_end;
441    }
442
443    /// Returns `true` iff `id` is a `RealStackingContext` item whose recorded `z_index` or bucket
444    /// differs from `new_z` (read-only check for speculative fast-path bail-outs before mutating).
445    #[inline]
446    pub fn sc_item_z_changed(&self, id: NodeId, new_z: i32) -> bool {
447        let Some(item_idx) = self.item_idx_for_node(id) else {
448            return false;
449        };
450        let item = &self.ordered_items[item_idx];
451        let new_bucket = bucket_for_sc_z(new_z);
452        item.z_index.0 != new_z || item.bucket != new_bucket
453    }
454
455    /// Updates an existing `RealStackingContext` item's `z_index` & bucket in-place and returns
456    /// its owning scope for [`Self::resort_scope_in_place`].
457    #[inline]
458    pub fn update_sc_item_z(&mut self, id: NodeId, new_z: i32) -> Option<ScopeIdx> {
459        let item_idx = self.item_idx_for_node(id)?;
460        let item = &mut self.ordered_items[item_idx];
461        let new_bucket = bucket_for_sc_z(new_z);
462        if item.z_index.0 == new_z && item.bucket == new_bucket {
463            return None;
464        }
465        item.z_index = ZOrder(new_z);
466        item.bucket = new_bucket;
467        let child_scope = item.child_scope;
468        self.scopes
469            .get(child_scope.index())
470            .map(|sc| sc.parent_scope)
471            .filter(|s| s.is_some())
472    }
473
474    /// Returns `true` iff any live box in this plan disagrees with `style.has_transform(store, id)`.
475    /// Used by `LaidOutScene::hit_test_where_with_transform` to detect live animated transform
476    /// transitions (`identity <-> non-identity`) without a store commit while staying 0-alloc.
477    pub fn has_transform_mismatch<S: StackingStyleSource>(
478        &self,
479        store: &NodeStore,
480        style: &S,
481    ) -> bool {
482        for sc in &self.scopes {
483            if sc.has_transform != style.has_transform(store, sc.node_id) {
484                return true;
485            }
486        }
487        for item in &self.ordered_items {
488            if item.child_scope.is_none() && style.has_transform(store, item.node_id) {
489                return true;
490            }
491        }
492        false
493    }
494
495    #[inline]
496    pub(crate) fn recompute_scope_neg_end(&mut self, scope: ScopeIdx) {
497        let s = self.scopes[scope.index()];
498        let start = s.items_start as usize;
499        let end = start + s.items_len.as_usize();
500        let mut neg_end = 0u32;
501        for (off, it) in self.ordered_items[start..end].iter().enumerate() {
502            if it.bucket == StackingBucket::NegSc {
503                neg_end = (off + 1) as u32;
504            } else {
505                break;
506            }
507        }
508        self.scopes[scope.index()].neg_end = neg_end;
509    }
510
511    #[inline]
512    pub(crate) fn alloc_scope(&mut self, scope: StackingScope) -> ScopeIdx {
513        let idx = ScopeIdx(self.scopes.len() as u32);
514        let nidx = scope.node_id.index();
515        if nidx < self.node_to_scope.len() {
516            self.node_to_scope[nidx] = idx;
517        }
518        self.scopes.push(scope);
519        self.scope_counts.push(0);
520        self.scope_sort_flags.push(ScopeSortFlags::default());
521        self.scope_last_bucket.push(BUCKET_NONE);
522        idx
523    }
524
525    #[inline]
526    pub(crate) fn push_item(&mut self, owner: ScopeIdx, item: StackingItem) {
527        let oi = owner.index();
528        self.staging.push((owner, item));
529        self.scope_counts[oi] += 1;
530        let b = item.bucket as u8;
531        let last = self.scope_last_bucket[oi];
532        if item.bucket == StackingBucket::NegSc {
533            self.scope_sort_flags[oi].mark_has_neg();
534        } else if item.z_index.0 != 0 || (last != BUCKET_NONE && b < last) {
535            self.scope_sort_flags[oi].mark_needs_sort();
536        }
537        self.scope_last_bucket[oi] = b;
538
539        let cur_min = self.scopes[oi].min_descendant_clip;
540        if item.clip_scroll != cur_min {
541            let lca = self.lca_clip(cur_min, item.clip_scroll);
542            self.scopes[oi].min_descendant_clip = lca;
543        }
544    }
545}