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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Shared zero-allocation CSS 2.1 Appendix E stacking tree & containing-block clip/scroll plan
//! consumed by both [`super::LaidOutScene`] hit-testing and `SkiaBackend`'s retained compositor.
//!
//! Every node/item/scope/clip record is a strictly `Copy` POD stored in flat, capacity-retaining
//! `Vec`s so rebuilding or in-place z-resorting performs **0 heap allocations** in steady state.

use nativeview_abi::ColorRgba;
use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::tables::Display;

mod build;
mod style;

pub use style::{
    SceneStackingStyleSource, StackingNodeRole, StackingOverrides, StackingStyleSource,
    bucket_for_sc_z, classify_node_sc_with_parent_display, resolve_node_sc_state,
};

/// Dense index into [`StackingPlan::scopes`] (`NONE` when absent).
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ScopeIdx(pub u32);

impl ScopeIdx {
    pub const NONE: Self = Self(u32::MAX);

    #[inline]
    pub const fn is_none(self) -> bool {
        self.0 == u32::MAX
    }

    #[inline]
    pub const fn is_some(self) -> bool {
        self.0 != u32::MAX
    }

    #[inline]
    pub const fn index(self) -> usize {
        self.0 as usize
    }
}

/// CSS stacking context z-order level (distinct from DOM tree order and array indices).
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct ZOrder(pub i32);

/// Count of [`StackingItem`] entries in a [`StackingScope`]'s contiguous CSR span.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ItemCount(pub u32);

impl ItemCount {
    pub const ZERO: Self = Self(0);

    #[inline]
    pub const fn get(self) -> u32 {
        self.0
    }

    #[inline]
    pub const fn as_usize(self) -> usize {
        self.0 as usize
    }

    #[inline]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

/// Per-scope build-time sort flags packed into one byte.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct ScopeSortFlags(u8);

impl ScopeSortFlags {
    const NEEDS_SORT: u8 = 1 << 0;
    const HAS_NEG: u8 = 1 << 1;

    #[inline]
    pub(crate) const fn needs_sort(self) -> bool {
        (self.0 & Self::NEEDS_SORT) != 0
    }

    #[inline]
    pub(crate) const fn has_neg(self) -> bool {
        (self.0 & Self::HAS_NEG) != 0
    }

    #[inline]
    pub(crate) fn mark_needs_sort(&mut self) {
        self.0 |= Self::NEEDS_SORT;
    }

    #[inline]
    pub(crate) fn mark_has_neg(&mut self) {
        self.0 |= Self::NEEDS_SORT | Self::HAS_NEG;
    }
}

/// Dense index into [`StackingPlan::clips`] (`NONE` when unclipped/unshifted viewport space).
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ClipScrollIdx(pub u32);

impl ClipScrollIdx {
    pub const NONE: Self = Self(u32::MAX);

    #[inline]
    pub const fn is_none(self) -> bool {
        self.0 == u32::MAX
    }

    #[inline]
    pub const fn is_some(self) -> bool {
        self.0 != u32::MAX
    }

    #[inline]
    pub const fn index(self) -> usize {
        self.0 as usize
    }
}

/// Whether a [`StackingScope`] establishes a real CSS stacking context or an atomic in-flow /
/// positioned-auto pseudo-stacking context (whose positioned/SC descendants still hoist out).
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeKind {
    RealStackingContext = 0,
    PseudoStackingContext = 1,
}

/// CSS 2.1 Appendix E stacking layer bucket (ordered back-to-front).
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StackingBucket {
    /// Step 2: real stacking context with `z_index < 0`.
    NegSc = 0,
    /// Step 3: non-atomic in-flow block background/border.
    InFlowBlock = 1,
    /// Step 5/7: atomic inline/flex/grid pseudo-SC, inline leaf, or split block foreground.
    InFlowInline = 2,
    /// Step 8: positioned `z-index: auto` pseudo-SC or real SC with `z_index == 0`.
    Step8 = 3,
    /// Step 9: real stacking context with `z_index > 0`.
    PosSc = 4,
}

/// Which local paint ops a [`StackingItem`] emits (splits non-atomic block Step 3 vs Step 7).
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ItemPaintPhase {
    Full = 0,
    BgOnly = 1,
    FgOnly = 2,
}

pub const CS_CLIPS: u8 = 1 << 0;
pub const CS_HAS_SCROLL: u8 = 1 << 1;
pub const CS_IS_STICKY: u8 = 1 << 2;
pub const CS_IS_TOP_LAYER: u8 = 1 << 3;
pub const CS_IS_TRANSFORM: u8 = 1 << 4;

/// One containing-block clip / scroll / sticky / top-layer / transform ancestor node (12 B POD).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClipScrollNode {
    pub parent: ClipScrollIdx,
    pub owner: NodeId,
    /// 1-based depth from `ClipScrollIdx::NONE` (`parent.depth + 1`).
    pub depth: u16,
    pub flags: u8,
}

impl ClipScrollNode {
    #[inline]
    pub const fn clips(self) -> bool {
        (self.flags & CS_CLIPS) != 0
    }

    #[inline]
    pub const fn has_scroll(self) -> bool {
        (self.flags & CS_HAS_SCROLL) != 0
    }

    #[inline]
    pub const fn is_sticky(self) -> bool {
        (self.flags & CS_IS_STICKY) != 0
    }

    #[inline]
    pub const fn is_top_layer(self) -> bool {
        (self.flags & CS_IS_TOP_LAYER) != 0
    }

    #[inline]
    pub const fn is_transform(self) -> bool {
        (self.flags & CS_IS_TRANSFORM) != 0
    }
}

pub const SCOPE_IS_TOP_LAYER: u8 = 1 << 0;
pub const SCOPE_HAS_SCROLL: u8 = 1 << 1;
pub const SCOPE_IS_STICKY: u8 = 1 << 2;
pub const SCOPE_IS_MODAL: u8 = 1 << 3;

/// One ordered entry inside a [`StackingScope`]'s item span (24 B Copy POD).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StackingItem {
    pub node_id: NodeId,
    pub child_scope: ScopeIdx,
    pub clip_scroll: ClipScrollIdx,
    pub z_index: ZOrder,
    pub tree_order: u32,
    pub bucket: StackingBucket,
    pub paint_phase: ItemPaintPhase,
    pub hidden: bool,
}

impl Default for StackingItem {
    fn default() -> Self {
        Self {
            node_id: NodeId::NULL,
            child_scope: ScopeIdx::NONE,
            clip_scroll: ClipScrollIdx::NONE,
            z_index: ZOrder(0),
            tree_order: 0,
            bucket: StackingBucket::InFlowBlock,
            paint_phase: ItemPaintPhase::Full,
            hidden: false,
        }
    }
}

/// One real stacking context or atomic pseudo-stacking context (32 B Copy POD).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StackingScope {
    pub node_id: NodeId,
    pub parent_scope: ScopeIdx,
    pub clip_scroll: ClipScrollIdx,
    pub min_descendant_clip: ClipScrollIdx,
    pub items_start: u32,
    pub items_len: ItemCount,
    /// Relative offset inside `items_start..items_start + items_len` separating Step 2 (`NegSc`)
    /// from Steps 3..9.
    pub neg_end: u32,
    pub kind: ScopeKind,
    pub hidden: bool,
    pub has_transform: bool,
    pub flags: u8,
}

impl StackingScope {
    #[inline]
    pub const fn is_top_layer(self) -> bool {
        (self.flags & SCOPE_IS_TOP_LAYER) != 0
    }

    #[inline]
    pub const fn has_scroll(self) -> bool {
        (self.flags & SCOPE_HAS_SCROLL) != 0
    }

    #[inline]
    pub const fn is_sticky(self) -> bool {
        (self.flags & SCOPE_IS_STICKY) != 0
    }

    #[inline]
    pub const fn is_modal(self) -> bool {
        (self.flags & SCOPE_IS_MODAL) != 0
    }
}

/// Root scope of one open top-layer [`Overlay`] painted and hit-tested above the document root.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TopLayerScope {
    pub scope: ScopeIdx,
    pub node_id: NodeId,
    pub is_modal: bool,
    /// Viewport scrim painted (and hit-blocking) behind this top layer, if any.
    pub backdrop: Option<ColorRgba>,
}

const _: () = assert!(std::mem::size_of::<ClipScrollNode>() <= 16);
const _: () = assert!(std::mem::size_of::<StackingItem>() <= 24);
const _: () = assert!(std::mem::size_of::<StackingScope>() <= 32);

#[derive(Debug, Clone, Copy)]
pub(crate) struct DfsFrame {
    pub(crate) id: NodeId,
    pub(crate) cur_sc: ScopeIdx,
    pub(crate) cur_inflow_owner: ScopeIdx,
    pub(crate) box_parent_display: Display,
    pub(crate) box_clip: ClipScrollIdx,
    pub(crate) abs_clip: ClipScrollIdx,
    pub(crate) fixed_clip: ClipScrollIdx,
    pub(crate) inherited_hidden: bool,
    pub(crate) depth: u16,
    pub(crate) is_root_of_pass: bool,
    pub(crate) is_top_layer_root: bool,
}

pub(crate) const BUCKET_NONE: u8 = u8::MAX;

/// Flat, zero-allocation reusable CSS 2.1 Appendix E stacking tree and clip/scroll graph.
#[derive(Debug, Clone, Default)]
pub struct StackingPlan {
    pub root: Option<ScopeIdx>,
    pub top_layers: Vec<TopLayerScope>,
    pub scopes: Vec<StackingScope>,
    pub ordered_items: Vec<StackingItem>,
    pub clips: Vec<ClipScrollNode>,
    /// Dense `NodeId::index() -> ScopeIdx` (`ScopeIdx::NONE` if leaf/absent).
    pub node_to_scope: Vec<ScopeIdx>,
    /// Dense `NodeId::index() -> index in ordered_items` (`u32::MAX` if root/absent).
    pub node_to_item: Vec<u32>,
    // --- Reusable build scratch (cleared, never shrunk, 0 steady-state allocations) ---
    pub(crate) dfs_stack: Vec<DfsFrame>,
    pub(crate) staging: Vec<(ScopeIdx, StackingItem)>,
    pub(crate) scope_counts: Vec<u32>,
    pub(crate) write_cursors: Vec<u32>,
    pub(crate) scope_sort_flags: Vec<ScopeSortFlags>,
    pub(crate) scope_last_bucket: Vec<u8>,
}

impl StackingPlan {
    pub fn clear(&mut self) {
        self.root = None;
        self.top_layers.clear();
        self.scopes.clear();
        self.ordered_items.clear();
        self.clips.clear();
        self.node_to_scope.fill(ScopeIdx::NONE);
        self.node_to_item.fill(u32::MAX);
        self.dfs_stack.clear();
        self.staging.clear();
        self.scope_counts.clear();
        self.write_cursors.clear();
        self.scope_sort_flags.clear();
        self.scope_last_bucket.clear();
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.root.is_none() && self.top_layers.is_empty()
    }

    #[inline]
    pub fn scope_items(&self, scope: ScopeIdx) -> &[StackingItem] {
        let Some(s) = self.scopes.get(scope.index()) else {
            return &[];
        };
        let start = s.items_start as usize;
        let end = start.saturating_add(s.items_len.as_usize());
        self.ordered_items.get(start..end).unwrap_or(&[])
    }

    #[inline]
    pub fn scope_for_node(&self, id: NodeId) -> Option<ScopeIdx> {
        let &s = self.node_to_scope.get(id.index())?;
        if s.is_none() {
            return None;
        }
        (self.scopes.get(s.index()).is_some_and(|sc| sc.node_id == id)).then_some(s)
    }

    #[inline]
    pub fn item_idx_for_node(&self, id: NodeId) -> Option<usize> {
        let &idx = self.node_to_item.get(id.index())?;
        if idx == u32::MAX {
            return None;
        }
        let i = idx as usize;
        (self.ordered_items.get(i).is_some_and(|it| it.node_id == id)).then_some(i)
    }

    #[inline]
    pub fn clip_depth(&self, idx: ClipScrollIdx) -> u16 {
        if idx.is_none() {
            0
        } else {
            self.clips.get(idx.index()).map_or(0, |c| c.depth)
        }
    }

    /// Lowest common ancestor of two [`ClipScrollIdx`] handles in `O(|depth_a - depth_b| + hops)`.
    #[inline]
    pub fn lca_clip(&self, mut a: ClipScrollIdx, mut b: ClipScrollIdx) -> ClipScrollIdx {
        if a == b {
            return a;
        }
        if a.is_none() || b.is_none() {
            return ClipScrollIdx::NONE;
        }
        let mut da = self.clip_depth(a);
        let mut db = self.clip_depth(b);
        while da > db && a.is_some() {
            a = self.clips[a.index()].parent;
            da -= 1;
        }
        while db > da && b.is_some() {
            b = self.clips[b.index()].parent;
            db -= 1;
        }
        while a != b && a.is_some() && b.is_some() {
            a = self.clips[a.index()].parent;
            b = self.clips[b.index()].parent;
        }
        if a == b { a } else { ClipScrollIdx::NONE }
    }

    /// Re-sorts one scope's existing `ordered_items` span in place with **0 heap allocations**
    /// (called on 120 Hz `COMPOSITE` `z_index` changes that preserve SC membership).
    pub fn resort_scope_in_place(&mut self, scope: ScopeIdx) {
        let Some(s) = self.scopes.get(scope.index()).copied() else {
            return;
        };
        let start = s.items_start as usize;
        let end = start.saturating_add(s.items_len.as_usize());
        let Some(span) = self.ordered_items.get_mut(start..end) else {
            return;
        };
        if span.len() > 1 {
            span.sort_unstable_by_key(|it| (it.bucket as u8, it.z_index.0, it.tree_order));
        }
        let mut neg_end = 0u32;
        for (offset, it) in span.iter().enumerate() {
            if it.bucket == StackingBucket::NegSc {
                neg_end = (offset + 1) as u32;
            }
            if it.paint_phase != ItemPaintPhase::FgOnly {
                let nidx = it.node_id.index();
                if nidx < self.node_to_item.len() {
                    self.node_to_item[nidx] = (start + offset) as u32;
                }
            }
        }
        self.scopes[scope.index()].neg_end = neg_end;
    }

    /// Returns `true` iff `id` is a `RealStackingContext` item whose recorded `z_index` or bucket
    /// differs from `new_z` (read-only check for speculative fast-path bail-outs before mutating).
    #[inline]
    pub fn sc_item_z_changed(&self, id: NodeId, new_z: i32) -> bool {
        let Some(item_idx) = self.item_idx_for_node(id) else {
            return false;
        };
        let item = &self.ordered_items[item_idx];
        let new_bucket = bucket_for_sc_z(new_z);
        item.z_index.0 != new_z || item.bucket != new_bucket
    }

    /// Updates an existing `RealStackingContext` item's `z_index` & bucket in-place and returns
    /// its owning scope for [`Self::resort_scope_in_place`].
    #[inline]
    pub fn update_sc_item_z(&mut self, id: NodeId, new_z: i32) -> Option<ScopeIdx> {
        let item_idx = self.item_idx_for_node(id)?;
        let item = &mut self.ordered_items[item_idx];
        let new_bucket = bucket_for_sc_z(new_z);
        if item.z_index.0 == new_z && item.bucket == new_bucket {
            return None;
        }
        item.z_index = ZOrder(new_z);
        item.bucket = new_bucket;
        let child_scope = item.child_scope;
        self.scopes
            .get(child_scope.index())
            .map(|sc| sc.parent_scope)
            .filter(|s| s.is_some())
    }

    /// Returns `true` iff any live box in this plan disagrees with `style.has_transform(store, id)`.
    /// Used by `LaidOutScene::hit_test_where_with_transform` to detect live animated transform
    /// transitions (`identity <-> non-identity`) without a store commit while staying 0-alloc.
    pub fn has_transform_mismatch<S: StackingStyleSource>(
        &self,
        store: &NodeStore,
        style: &S,
    ) -> bool {
        for sc in &self.scopes {
            if sc.has_transform != style.has_transform(store, sc.node_id) {
                return true;
            }
        }
        for item in &self.ordered_items {
            if item.child_scope.is_none() && style.has_transform(store, item.node_id) {
                return true;
            }
        }
        false
    }

    #[inline]
    pub(crate) fn recompute_scope_neg_end(&mut self, scope: ScopeIdx) {
        let s = self.scopes[scope.index()];
        let start = s.items_start as usize;
        let end = start + s.items_len.as_usize();
        let mut neg_end = 0u32;
        for (off, it) in self.ordered_items[start..end].iter().enumerate() {
            if it.bucket == StackingBucket::NegSc {
                neg_end = (off + 1) as u32;
            } else {
                break;
            }
        }
        self.scopes[scope.index()].neg_end = neg_end;
    }

    #[inline]
    pub(crate) fn alloc_scope(&mut self, scope: StackingScope) -> ScopeIdx {
        let idx = ScopeIdx(self.scopes.len() as u32);
        let nidx = scope.node_id.index();
        if nidx < self.node_to_scope.len() {
            self.node_to_scope[nidx] = idx;
        }
        self.scopes.push(scope);
        self.scope_counts.push(0);
        self.scope_sort_flags.push(ScopeSortFlags::default());
        self.scope_last_bucket.push(BUCKET_NONE);
        idx
    }

    #[inline]
    pub(crate) fn push_item(&mut self, owner: ScopeIdx, item: StackingItem) {
        let oi = owner.index();
        self.staging.push((owner, item));
        self.scope_counts[oi] += 1;
        let b = item.bucket as u8;
        let last = self.scope_last_bucket[oi];
        if item.bucket == StackingBucket::NegSc {
            self.scope_sort_flags[oi].mark_has_neg();
        } else if item.z_index.0 != 0 || (last != BUCKET_NONE && b < last) {
            self.scope_sort_flags[oi].mark_needs_sort();
        }
        self.scope_last_bucket[oi] = b;

        let cur_min = self.scopes[oi].min_descendant_clip;
        if item.clip_scroll != cur_min {
            let lca = self.lca_clip(cur_min, item.clip_scroll);
            self.scopes[oi].min_descendant_clip = lca;
        }
    }
}