Skip to main content

nativeview_layout/scene/stacking/
build.rs

1//! Zero-allocation iterative CSR builder for [`super::StackingPlan`].
2
3use nativeview_store::{NodeId, NodeStore};
4use nativeview_tables::tables::{Display, Interaction, Overlay, Position, TextContent};
5
6use crate::MAX_TREE_DEPTH;
7
8use super::super::ResolvedOverlay;
9use super::{
10    CS_CLIPS, CS_HAS_SCROLL, CS_IS_STICKY, CS_IS_TOP_LAYER, CS_IS_TRANSFORM, ClipScrollIdx,
11    ClipScrollNode, DfsFrame, ItemCount, ItemPaintPhase, SCOPE_HAS_SCROLL, SCOPE_IS_MODAL, SCOPE_IS_STICKY, SCOPE_IS_TOP_LAYER, ScopeIdx, ScopeKind,
12    StackingBucket, StackingItem, StackingPlan, StackingScope, TopLayerScope, ZOrder,
13};
14use super::style::{
15    StackingStyleSource, bucket_for_sc_z, classify_node_sc_with_parent_display,
16};
17
18impl StackingPlan {
19    /// Rebuilds the entire stacking tree and clip/scroll graph in-place with **0 steady-state
20    /// heap allocations** once capacity is warm.
21    pub fn build<S: StackingStyleSource>(
22        &mut self,
23        store: &NodeStore,
24        open_overlays: &[ResolvedOverlay],
25        style: &S,
26    ) {
27        self.clear();
28        let cap = store.capacity();
29        if self.node_to_scope.len() < cap {
30            self.node_to_scope.resize(cap, ScopeIdx::NONE);
31        }
32        if self.node_to_item.len() < cap {
33            self.node_to_item.resize(cap, u32::MAX);
34        }
35
36        let mut next_tree_order = 0u32;
37
38        // Pass 1: Document root tree (skipping `Overlay` nodes — open ones build in Pass 2).
39        if store.is_live(NodeId::ROOT) && !style.is_display_none(store, NodeId::ROOT) {
40            self.root = self.build_subtree(store, style, NodeId::ROOT, None, &mut next_tree_order);
41        }
42
43        // Pass 2: Hoisted top-layer roots in document paint order. `TopLayerIndex` already
44        // resolved effective `display` (incl. `StateRules`, `@media`) on every root's chain.
45        for &ro in open_overlays {
46            if !store.is_live(ro.node) {
47                continue;
48            }
49            if let Some(scope) =
50                self.build_subtree(store, style, ro.node, Some(ro), &mut next_tree_order)
51            {
52                self.top_layers.push(TopLayerScope {
53                    scope,
54                    node_id: ro.node,
55                    is_modal: ro.is_modal,
56                    backdrop: ro.backdrop(),
57                });
58            }
59        }
60
61        // Propagate `min_descendant_clip` bottom-up across parent scopes (scopes are pre-ordered).
62        for s in (0..self.scopes.len()).rev() {
63            let parent = self.scopes[s].parent_scope;
64            if parent.is_some() {
65                let child_min = self.scopes[s].min_descendant_clip;
66                let cur_min = self.scopes[parent.index()].min_descendant_clip;
67                if child_min != cur_min {
68                    let lca = self.lca_clip(cur_min, child_min);
69                    self.scopes[parent.index()].min_descendant_clip = lca;
70                }
71            }
72        }
73
74        // Stage 2: O(N) CSR prefix sum + linear scatter + selective zero-alloc unstable sort.
75        self.write_cursors.clear();
76        let mut cursor = 0u32;
77        for s in 0..self.scopes.len() {
78            let count = self.scope_counts[s];
79            self.scopes[s].items_start = cursor;
80            self.scopes[s].items_len = ItemCount(count);
81            self.scopes[s].neg_end = 0;
82            self.write_cursors.push(cursor);
83            cursor += count;
84        }
85
86        self.ordered_items
87            .resize(cursor as usize, StackingItem::default());
88        for i in 0..self.staging.len() {
89            let (owner, item) = self.staging[i];
90            let oi = owner.index();
91            let dst = self.write_cursors[oi] as usize;
92            self.write_cursors[oi] += 1;
93            self.ordered_items[dst] = item;
94            if item.paint_phase != ItemPaintPhase::FgOnly {
95                let nidx = item.node_id.index();
96                if nidx < self.node_to_item.len() {
97                    self.node_to_item[nidx] = dst as u32;
98                }
99            }
100        }
101
102        for s in 0..self.scopes.len() {
103            let flags = self.scope_sort_flags[s];
104            let len = self.scopes[s].items_len.as_usize();
105            if len == 0 {
106                continue;
107            }
108            if len > 1 && flags.needs_sort() {
109                self.resort_scope_in_place(ScopeIdx(s as u32));
110            } else if flags.has_neg() {
111                self.recompute_scope_neg_end(ScopeIdx(s as u32));
112            }
113        }
114    }
115
116    fn build_subtree<S: StackingStyleSource>(
117        &mut self,
118        store: &NodeStore,
119        style: &S,
120        root_id: NodeId,
121        top_layer: Option<ResolvedOverlay>,
122        next_tree_order: &mut u32,
123    ) -> Option<ScopeIdx> {
124        let mut root_scope: Option<ScopeIdx> = None;
125        self.dfs_stack.clear();
126        self.dfs_stack.push(DfsFrame {
127            id: root_id,
128            cur_sc: ScopeIdx::NONE,
129            cur_inflow_owner: ScopeIdx::NONE,
130            box_parent_display: Display::Block,
131            box_clip: ClipScrollIdx::NONE,
132            abs_clip: ClipScrollIdx::NONE,
133            fixed_clip: ClipScrollIdx::NONE,
134            inherited_hidden: false,
135            depth: 0,
136            is_root_of_pass: true,
137            is_top_layer_root: top_layer.is_some(),
138        });
139
140        while let Some(frame) = self.dfs_stack.pop() {
141            let id = frame.id;
142            if frame.depth as usize > MAX_TREE_DEPTH
143                || !store.is_live(id)
144                || store.is_inline(id)
145                || style.is_display_none(store, id)
146            {
147                continue;
148            }
149            if !frame.is_root_of_pass && store.has::<Overlay>(id) {
150                continue;
151            }
152
153            let effective_hidden = style.visibility_hidden(store, id, frame.inherited_hidden);
154
155            // Non-root `display: contents` generates no box: pass visibility through and flatten
156            // children directly into the nearest box ancestor's stacking & clip environment.
157            if !frame.is_root_of_pass && style.is_display_contents(store, id) {
158                for &cid in store.children(id).iter().rev() {
159                    self.dfs_stack.push(DfsFrame {
160                        id: cid,
161                        inherited_hidden: effective_hidden,
162                        depth: frame.depth + 1,
163                        is_root_of_pass: false,
164                        is_top_layer_root: false,
165                        ..frame
166                    });
167                }
168                continue;
169            }
170
171            let tree_order = *next_tree_order;
172            *next_tree_order = next_tree_order.wrapping_add(1);
173
174            let (creates_sc, sc_z, has_transform, pos, display) =
175                classify_node_sc_with_parent_display(
176                    store,
177                    style,
178                    id,
179                    frame.box_parent_display,
180                    frame.is_top_layer_root,
181                );
182
183            let cb_clip = if frame.is_root_of_pass {
184                ClipScrollIdx::NONE
185            } else {
186                match pos {
187                    Position::Absolute => frame.abs_clip,
188                    Position::Fixed => frame.fixed_clip,
189                    Position::Static | Position::Relative | Position::Sticky => frame.box_clip,
190                }
191            };
192
193            let clips = style.clips_overflow(store, id);
194            let has_scroll = style.is_scrollable(store, id);
195            let is_sticky = !frame.is_top_layer_root && pos == Position::Sticky;
196            let mut cs_flags = 0u8;
197            if clips {
198                cs_flags |= CS_CLIPS;
199            }
200            if has_scroll {
201                cs_flags |= CS_HAS_SCROLL;
202            }
203            if is_sticky {
204                cs_flags |= CS_IS_STICKY;
205            }
206            if frame.is_top_layer_root {
207                cs_flags |= CS_IS_TOP_LAYER;
208            }
209            if has_transform {
210                cs_flags |= CS_IS_TRANSFORM;
211            }
212
213            let child_cs = if cs_flags != 0 {
214                let idx = ClipScrollIdx(self.clips.len() as u32);
215                let depth = self.clip_depth(cb_clip).saturating_add(1);
216                self.clips.push(ClipScrollNode {
217                    parent: cb_clip,
218                    owner: id,
219                    depth,
220                    flags: cs_flags,
221                });
222                idx
223            } else {
224                cb_clip
225            };
226
227            let next_box_clip = child_cs;
228            let next_abs_clip =
229                if frame.is_top_layer_root || has_transform || pos != Position::Static {
230                    child_cs
231                } else {
232                    frame.abs_clip
233                };
234            let next_fixed_clip = if frame.is_top_layer_root || has_transform {
235                child_cs
236            } else {
237                frame.fixed_clip
238            };
239
240            let mut scope_flags = 0u8;
241            if frame.is_top_layer_root {
242                scope_flags |= SCOPE_IS_TOP_LAYER;
243                if top_layer.is_some_and(|ro| ro.is_modal) {
244                    scope_flags |= SCOPE_IS_MODAL;
245                }
246            }
247            if has_scroll {
248                scope_flags |= SCOPE_HAS_SCROLL;
249            }
250            if is_sticky {
251                scope_flags |= SCOPE_IS_STICKY;
252            }
253
254            let children = if store.is_inline_context_root(id) {
255                &[][..]
256            } else {
257                store.children(id)
258            };
259            let (next_sc, next_inflow) = if frame.is_root_of_pass {
260                let s = self.alloc_scope(StackingScope {
261                    node_id: id,
262                    parent_scope: ScopeIdx::NONE,
263                    clip_scroll: ClipScrollIdx::NONE,
264                    min_descendant_clip: ClipScrollIdx::NONE,
265                    items_start: 0,
266                    items_len: ItemCount::ZERO,
267                    neg_end: 0,
268                    kind: ScopeKind::RealStackingContext,
269                    hidden: effective_hidden,
270                    has_transform,
271                    flags: scope_flags,
272                });
273                root_scope = Some(s);
274                (s, s)
275            } else if creates_sc {
276                let s = self.alloc_scope(StackingScope {
277                    node_id: id,
278                    parent_scope: frame.cur_sc,
279                    clip_scroll: cb_clip,
280                    min_descendant_clip: cb_clip,
281                    items_start: 0,
282                    items_len: ItemCount::ZERO,
283                    neg_end: 0,
284                    kind: ScopeKind::RealStackingContext,
285                    hidden: effective_hidden,
286                    has_transform,
287                    flags: scope_flags,
288                });
289                self.push_item(
290                    frame.cur_sc,
291                    StackingItem {
292                        node_id: id,
293                        child_scope: s,
294                        clip_scroll: cb_clip,
295                        z_index: ZOrder(sc_z),
296                        tree_order,
297                        bucket: bucket_for_sc_z(sc_z),
298                        paint_phase: ItemPaintPhase::Full,
299                        hidden: effective_hidden,
300                    },
301                );
302                (s, s)
303            } else if pos != Position::Static {
304                let child_scope = if children.is_empty() && !has_scroll {
305                    ScopeIdx::NONE
306                } else {
307                    self.alloc_scope(StackingScope {
308                        node_id: id,
309                        parent_scope: frame.cur_sc,
310                        clip_scroll: cb_clip,
311                        min_descendant_clip: cb_clip,
312                        items_start: 0,
313                        items_len: ItemCount::ZERO,
314                        neg_end: 0,
315                        kind: ScopeKind::PseudoStackingContext,
316                        hidden: effective_hidden,
317                        has_transform: false,
318                        flags: scope_flags,
319                    })
320                };
321                self.push_item(
322                    frame.cur_sc,
323                    StackingItem {
324                        node_id: id,
325                        child_scope,
326                        clip_scroll: cb_clip,
327                        z_index: ZOrder(0),
328                        tree_order,
329                        bucket: StackingBucket::Step8,
330                        paint_phase: ItemPaintPhase::Full,
331                        hidden: effective_hidden,
332                    },
333                );
334                (frame.cur_sc, child_scope)
335            } else {
336                let parent_is_flex_or_grid = matches!(
337                    frame.box_parent_display,
338                    Display::Flex | Display::InlineFlex | Display::Grid
339                );
340                let is_atomic_inline = parent_is_flex_or_grid
341                    || matches!(
342                        display,
343                        Display::Inline | Display::InlineBlock | Display::InlineFlex
344                    );
345                if is_atomic_inline || has_scroll {
346                    let bucket = if is_atomic_inline {
347                        StackingBucket::InFlowInline
348                    } else {
349                        StackingBucket::InFlowBlock
350                    };
351                    let child_scope = if children.is_empty() && !has_scroll {
352                        ScopeIdx::NONE
353                    } else {
354                        self.alloc_scope(StackingScope {
355                            node_id: id,
356                            parent_scope: frame.cur_inflow_owner,
357                            clip_scroll: cb_clip,
358                            min_descendant_clip: cb_clip,
359                            items_start: 0,
360                            items_len: ItemCount::ZERO,
361                            neg_end: 0,
362                            kind: ScopeKind::PseudoStackingContext,
363                            hidden: effective_hidden,
364                            has_transform: false,
365                            flags: scope_flags,
366                        })
367                    };
368                    self.push_item(
369                        frame.cur_inflow_owner,
370                        StackingItem {
371                            node_id: id,
372                            child_scope,
373                            clip_scroll: cb_clip,
374                            z_index: ZOrder(0),
375                            tree_order,
376                            bucket,
377                            paint_phase: ItemPaintPhase::Full,
378                            hidden: effective_hidden,
379                        },
380                    );
381                    (frame.cur_sc, child_scope)
382                } else if store.has::<TextContent>(id)
383                    || store
384                        .try_row::<Interaction>(id)
385                        .is_some_and(|i| i.captures_text_keys())
386                {
387                    self.push_item(
388                        frame.cur_inflow_owner,
389                        StackingItem {
390                            node_id: id,
391                            child_scope: ScopeIdx::NONE,
392                            clip_scroll: cb_clip,
393                            z_index: ZOrder(0),
394                            tree_order,
395                            bucket: StackingBucket::InFlowBlock,
396                            paint_phase: ItemPaintPhase::BgOnly,
397                            hidden: effective_hidden,
398                        },
399                    );
400                    self.push_item(
401                        frame.cur_inflow_owner,
402                        StackingItem {
403                            node_id: id,
404                            child_scope: ScopeIdx::NONE,
405                            clip_scroll: cb_clip,
406                            z_index: ZOrder(0),
407                            tree_order,
408                            bucket: StackingBucket::InFlowInline,
409                            paint_phase: ItemPaintPhase::FgOnly,
410                            hidden: effective_hidden,
411                        },
412                    );
413                    (frame.cur_sc, frame.cur_inflow_owner)
414                } else {
415                    self.push_item(
416                        frame.cur_inflow_owner,
417                        StackingItem {
418                            node_id: id,
419                            child_scope: ScopeIdx::NONE,
420                            clip_scroll: cb_clip,
421                            z_index: ZOrder(0),
422                            tree_order,
423                            bucket: StackingBucket::InFlowBlock,
424                            paint_phase: ItemPaintPhase::Full,
425                            hidden: effective_hidden,
426                        },
427                    );
428                    (frame.cur_sc, frame.cur_inflow_owner)
429                }
430            };
431
432            if !children.is_empty() {
433                for &cid in children.iter().rev() {
434                    self.dfs_stack.push(DfsFrame {
435                        id: cid,
436                        cur_sc: next_sc,
437                        cur_inflow_owner: next_inflow,
438                        box_parent_display: display,
439                        box_clip: next_box_clip,
440                        abs_clip: next_abs_clip,
441                        fixed_clip: next_fixed_clip,
442                        inherited_hidden: effective_hidden,
443                        depth: frame.depth + 1,
444                        is_root_of_pass: false,
445                        is_top_layer_root: false,
446                    });
447                }
448            }
449        }
450        root_scope
451    }
452}