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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! Top-layer floating [`Overlay`] reconciliation and visual-rect queries on [`LaidOutScene`].
//!
//! Resolves viewport-space top-layer origins for every hoisted `nv.overlay` root of the layout
//! engine's [`crate::TopLayerIndex`] (anchored via `DebugId::id` through
//! [`crate::overlay::compute_overlay_position`], or viewport-centered for unanchored modals)
//! using reusable zero-alloc dense storage.

use nativeview_abi::hash::HashMap;
use nativeview_abi::ColorRgba;
use nativeview_abi::xxh64;
use nativeview_store::{ChangeSet, NodeId, NodeStore, NvTable, TableStorage};
use nativeview_tables::tables::{
    DebugId, Layout as NvLayout, Overlay, OverlayFlags, OverlayLayer,
    Transform as TransformTable,
};
use nativeview_tables::transform::Transform2D;

use crate::overlay::{
    PositionOptions, Rect, Size, Viewport as OverlayViewport, compute_overlay_position,
};
use crate::{MAX_TREE_DEPTH, StoreLayoutEngine};

use super::super::LaidOutScene;
use super::resolved::{ResolvedOverlay, topmost_modal_index};

const OVERLAY_NONE: u32 = u32::MAX;

/// Reusable zero-allocation top-layer overlay state owned by [`LaidOutScene`].
#[derive(Debug, Clone, Default)]
pub struct OverlayState {
    resolved: Vec<ResolvedOverlay>,
    /// Dense `NodeId::index() -> index into resolved` (`OVERLAY_NONE` when absent).
    node_to_overlay: Vec<u32>,
    /// `TopLayerIndex::generation` the resolved set was built from.
    top_layer_generation: u64,
    /// Reusable `xxh64(DebugId::id) -> NodeId` index rebuilt in O(D) only when open anchored
    /// overlays exist (0 steady-state allocations).
    anchor_index: HashMap<u64, NodeId>,
    /// Resolved anchor `NodeId`s for currently open anchored overlays (empty when only unanchored
    /// modals or zero overlays are open), enabling O(1) composite-frame gating.
    anchored_nodes: Vec<NodeId>,
    /// Index in `resolved` (paint order) of the last modal.
    topmost_modal: Option<u32>,
    /// Monotonic count of completed full overlay reconcile passes (diagnostic & regression guard).
    reconcile_count: u64,
    /// Monotonic generation bumped whenever open overlay state changes (invalidates `stacking_cache`).
    generation: u64,
}

impl OverlayState {
    #[inline]
    pub fn generation(&self) -> u64 {
        self.generation
    }

    #[inline]
    pub fn reconcile_count(&self) -> u64 {
        self.reconcile_count
    }

    #[inline]
    pub fn anchored_nodes(&self) -> &[NodeId] {
        &self.anchored_nodes
    }

    #[inline]
    fn bump_generation(&mut self) {
        self.generation = self.generation.wrapping_add(1).max(1);
    }

    #[inline]
    pub fn open_overlays(&self) -> &[ResolvedOverlay] {
        &self.resolved
    }

    #[inline]
    pub fn get(&self, id: NodeId) -> Option<ResolvedOverlay> {
        let &idx = self.node_to_overlay.get(id.index())?;
        if idx == OVERLAY_NONE {
            return None;
        }
        let ro = *self.resolved.get(idx as usize)?;
        (ro.node == id).then_some(ro)
    }

    #[inline]
    pub fn is_open_overlay(&self, id: NodeId) -> bool {
        self.get(id).is_some()
    }

    #[inline]
    pub fn clear(&mut self) {
        self.topmost_modal = None;
        for ro in &self.resolved {
            let i = ro.node.index();
            if i < self.node_to_overlay.len() {
                self.node_to_overlay[i] = OVERLAY_NONE;
            }
        }
        self.resolved.clear();
        // Never a real generation: the next gated reconcile always runs.
        self.top_layer_generation = u64::MAX;
        self.anchor_index.clear();
        self.anchored_nodes.clear();
        self.bump_generation();
    }

    /// The topmost (last painted) resolved modal.
    #[inline]
    pub fn topmost_modal(&self) -> Option<NodeId> {
        self.topmost_modal.map(|i| self.resolved[i as usize].node)
    }

    /// Paint-order index in [`Self::open_overlays`] of the topmost resolved modal, in O(1).
    #[inline]
    pub fn topmost_modal_index(&self) -> Option<usize> {
        self.topmost_modal.map(|i| i as usize)
    }

    /// `true` when a modal is resolved and `id`'s nearest resolved ancestor-or-self overlay is
    /// painted below the topmost modal, or there is none (the background): HTML modal-dialog
    /// `inert`. O(depth) with an O(1) paint position per hop. Non-modal backdrop scrims block
    /// pointers in hit-testing but make nothing inert.
    pub fn is_inert_under_modal(&self, store: &NodeStore, id: NodeId) -> bool {
        let Some(modal) = self.topmost_modal else {
            return false;
        };
        let mut cur = id;
        for _ in 0..MAX_TREE_DEPTH {
            if let Some(&pos) = self.node_to_overlay.get(cur.index())
                && pos != OVERLAY_NONE
                && self.resolved[pos as usize].node == cur
            {
                return pos < modal;
            }
            match store.parent(cur) {
                Some(p) if p != cur => cur = p,
                _ => return true,
            }
        }
        true
    }

    fn clear_indices(&mut self) {
        let had = !self.resolved.is_empty();
        self.topmost_modal = None;
        for ro in &self.resolved {
            let i = ro.node.index();
            if i < self.node_to_overlay.len() {
                self.node_to_overlay[i] = OVERLAY_NONE;
            }
        }
        self.resolved.clear();
        self.anchored_nodes.clear();
        if had {
            self.bump_generation();
        }
    }

    fn set_index(&mut self, id: NodeId, idx: u32) {
        let i = id.index();
        if i >= self.node_to_overlay.len() {
            self.node_to_overlay.resize(i + 1, OVERLAY_NONE);
        }
        self.node_to_overlay[i] = idx;
    }
}

fn find_anchor_node_linear(store: &NodeStore, anchor_id: &str) -> Option<NodeId> {
    let TableStorage {
        owners, row_count, ..
    } = store.table_storage(DebugId::slot())?;
    for &nid in owners.iter().take(row_count) {
        if nid.is_null() || !store.is_connected(nid) {
            continue;
        }
        if store
            .try_row::<DebugId>(nid)
            .is_some_and(|d| d.id() == anchor_id)
        {
            return Some(nid);
        }
    }
    None
}

pub(crate) fn lookup_anchor_node(
    store: &NodeStore,
    anchor_index: &HashMap<u64, NodeId>,
    anchor_id: &str,
) -> Option<NodeId> {
    let hash = xxh64(anchor_id.as_bytes(), 0);
    if let Some(&nid) = anchor_index.get(&hash) {
        if store.is_connected(nid)
            && store
                .try_row::<DebugId>(nid)
                .is_some_and(|d| d.id() == anchor_id)
        {
            return Some(nid);
        }
        return find_anchor_node_linear(store, anchor_id);
    }
    None
}

impl<L: StoreLayoutEngine> LaidOutScene<L> {
    /// Open top-layer overlays in deterministic document paint order.
    #[inline]
    pub fn open_overlays(&self) -> &[ResolvedOverlay] {
        self.overlays.open_overlays()
    }

    /// Reconciled top-layer geometry for `id` if it is currently an open [`Overlay`].
    #[inline]
    pub fn resolved_overlay(&self, id: NodeId) -> Option<ResolvedOverlay> {
        self.overlays.get(id)
    }

    /// Monotonic count of completed full overlay reconcile passes.
    #[inline]
    pub fn overlay_reconcile_count(&self) -> u64 {
        self.overlays.reconcile_count()
    }

    /// Returns `true` iff any open anchored overlay's resolved anchor (or one of its DOM
    /// ancestors) is present in `dirty_nodes`. O(1) `false` when no anchored overlays are open
    /// (e.g., no overlays or only unanchored modals).
    pub fn any_overlay_anchor_affected(&self, store: &NodeStore, dirty_nodes: &[NodeId]) -> bool {
        let anchors = self.overlays.anchored_nodes();
        if anchors.is_empty() || dirty_nodes.is_empty() {
            return false;
        }
        for &anchor_id in anchors {
            let mut cur = Some(anchor_id);
            for _ in 0..MAX_TREE_DEPTH {
                let Some(nid) = cur else {
                    break;
                };
                if dirty_nodes.contains(&nid) {
                    return true;
                }
                cur = store.parent(nid).filter(|&p| p != nid);
            }
        }
        false
    }

    /// Fast-path guard around [`Self::reconcile_overlays_with_transform`] for the commit
    /// pipeline: skips all work in `O(1)` when neither the hoisted set nor any overlay input
    /// (`layout`, `scroll`, `transform`, `DebugId`, tree structure) changed.
    pub(crate) fn reconcile_overlays_if_needed(
        &mut self,
        store: &NodeStore,
        changes: &ChangeSet,
        layout_or_scroll_changed: bool,
        resolve_transform: impl Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>,
    ) {
        let top_layer = self.layout.top_layer();
        if top_layer.hoisted().is_empty() {
            if !self.overlays.resolved.is_empty() {
                self.overlays.clear_indices();
            }
            self.overlays.top_layer_generation = top_layer.generation();
            return;
        }
        if !layout_or_scroll_changed
            && self.overlays.top_layer_generation == top_layer.generation()
            && changes.removed.is_empty()
            && changes.children.is_empty()
            && changes.table(Overlay::slot()).is_none()
            && changes.table(DebugId::slot()).is_none()
            && changes.table(TransformTable::slot()).is_none()
            && changes.table(NvLayout::slot()).is_none()
        {
            return;
        }
        self.reconcile_overlays_with_transform(store, resolve_transform);
    }

    /// Reconciles viewport-space top-layer coordinates for every hoisted overlay root of the
    /// layout engine's [`crate::TopLayerIndex`], in its document paint order (O(1) fast-exit
    /// when nothing is hoisted; zero heap allocations in steady state). Anchor visual rects are
    /// read through `resolve_transform` so animated anchor transforms reposition anchored
    /// overlays in lockstep (backends call this directly after scroll-only frames).
    pub fn reconcile_overlays_with_transform(
        &mut self,
        store: &NodeStore,
        resolve_transform: impl Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>,
    ) {
        self.overlays.clear_indices();
        self.scroll.take_moved();
        let top_layer = self.layout.top_layer();
        self.overlays.top_layer_generation = top_layer.generation();
        let hoisted_len = top_layer.hoisted().len();
        if hoisted_len == 0 {
            return;
        }
        let any_anchored = top_layer.hoisted().iter().any(|&id| {
            store
                .try_row::<Overlay>(id)
                .is_some_and(|ov| !ov.anchor_id().is_empty())
        });
        self.overlays.reconcile_count = self.overlays.reconcile_count.wrapping_add(1);

        let mut anchor_index = core::mem::take(&mut self.overlays.anchor_index);
        anchor_index.clear();
        if any_anchored
            && let Some(TableStorage {
                owners: dbg_owners,
                row_count: dbg_count,
                ..
            }) = store.table_storage(DebugId::slot())
        {
            for &nid in dbg_owners.iter().take(dbg_count) {
                if !nid.is_null()
                    && store.is_connected(nid)
                    && let Some(d) = store.try_row::<DebugId>(nid)
                    && !d.id().is_empty()
                {
                    let h = xxh64(d.id().as_bytes(), 0);
                    anchor_index.entry(h).or_insert(nid);
                }
            }
        }

        for i in 0..hoisted_len {
            let id = self.layout.top_layer().hoisted()[i];
            let Some(ov) = store.try_row::<Overlay>(id) else {
                continue;
            };
            let ro = self.compute_resolved_overlay(store, id, ov, &anchor_index, &resolve_transform);
            if !ro.anchor.is_null() && !self.overlays.anchored_nodes.contains(&ro.anchor) {
                self.overlays.anchored_nodes.push(ro.anchor);
            }
            let slot_idx = self.overlays.resolved.len() as u32;
            self.overlays.resolved.push(ro);
            self.overlays.set_index(id, slot_idx);
        }
        self.overlays.topmost_modal = topmost_modal_index(&self.overlays.resolved).map(|i| i as u32);
        self.overlays.bump_generation();
        self.overlays.anchor_index = anchor_index;
    }

    fn compute_resolved_overlay(
        &self,
        store: &NodeStore,
        id: NodeId,
        ov: nativeview_tables::tables::OverlayRef<'_>,
        anchor_index: &HashMap<u64, NodeId>,
        resolve_transform: &impl Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>,
    ) -> ResolvedOverlay {
        let base_rect = self.layout.layout_of(id).unwrap_or_default();
        let opts = ov.options();
        let layer = ov.layer();
        let is_modal = layer == OverlayLayer::Modal;
        let has_backdrop_scrim = is_modal || opts.contains(OverlayFlags::BACKDROP_SCRIM);
        let light_dismiss = opts.light_dismiss_on(layer);
        let close_on_escape = opts.closes_on_escape();
        let backdrop_color = ColorRgba::from(ov.backdrop_color());
        let pad = if ov.viewport_padding_px().is_finite() {
            ov.viewport_padding_px().max(0.0)
        } else {
            0.0
        };
        let vp_w = if self.viewport.width.is_finite() {
            self.viewport.width.max(0.0)
        } else {
            0.0
        };
        let vp_h = if self.viewport.height.is_finite() {
            self.viewport.height.max(0.0)
        } else {
            0.0
        };

        let anchor_id = ov.anchor_id();
        let anchor = if anchor_id.is_empty() {
            None
        } else {
            lookup_anchor_node(store, anchor_index, anchor_id).filter(|&aid| aid != id)
        };
        if let Some(aid) = anchor
            && let Some(ar) = self.visual_rect_of_with_transform(store, aid, resolve_transform)
        {
            let auto_size = opts.contains(OverlayFlags::AUTO_SIZE);
            let pos_opts = PositionOptions {
                placement: ov.placement(),
                offset: ov.offset_px(),
                viewport_padding: pad,
                flip: opts.contains(OverlayFlags::FLIP),
                shift: opts.contains(OverlayFlags::SHIFT),
                auto_size,
                fallback_placements: Vec::new(),
            };
            let vp_max_w = (vp_w - 2.0 * pad).max(0.0);
            let vp_max_h = (vp_h - 2.0 * pad).max(0.0);
            let mut effective_base_w = if auto_size {
                base_rect.width.max(ar.width)
            } else {
                base_rect.width
            };
            let mut effective_base_h = base_rect.height;
            if pos_opts.shift || auto_size {
                effective_base_w = effective_base_w.min(vp_max_w);
                effective_base_h = effective_base_h.min(vp_max_h);
            }
            let computed = compute_overlay_position(
                Rect::new(ar.x, ar.y, ar.width, ar.height),
                Size::new(effective_base_w, effective_base_h),
                OverlayViewport::new(vp_w, vp_h),
                &pos_opts,
            );
            let width = computed
                .max_width
                .map_or(effective_base_w, |mw| effective_base_w.min(mw));
            let height = computed
                .max_height
                .map_or(effective_base_h, |mh| effective_base_h.min(mh));
            return ResolvedOverlay {
                node: id,
                origin_x: computed.x,
                origin_y: computed.y,
                width,
                height,
                placement: computed.placement,
                layer,
                is_modal,
                has_backdrop_scrim,
                light_dismiss,
                close_on_escape,
                backdrop_color,
                anchor: aid,
            };
        }

        // Unanchored overlay: center modals when no explicit inset overrides are set; resolve
        // explicit viewport insets (`inset_bottom: 0`, `inset_left: 0`, `inset_right: 0`, …)
        // directly against the viewport so bottom sheets & corner overlays dock identically to Web.
        let layout = store.try_row::<NvLayout>(id);
        let resolve_len = |len: nativeview_store::Length, ref_size: f32| -> Option<f32> {
            let v = len.value();
            if !v.is_finite() {
                return None;
            }
            if len.is_points() {
                Some(v)
            } else if len.is_percent() {
                Some(v * 0.01 * ref_size)
            } else {
                None
            }
        };
        let (inset_top, inset_right, inset_bottom, inset_left) =
            layout.as_ref().map_or((None, None, None, None), |l| {
                (
                    resolve_len(l.inset_top(), vp_h),
                    resolve_len(l.inset_right(), vp_w),
                    resolve_len(l.inset_bottom(), vp_h),
                    resolve_len(l.inset_left(), vp_w),
                )
            });
        let has_explicit_inset = inset_top.is_some()
            || inset_right.is_some()
            || inset_bottom.is_some()
            || inset_left.is_some();

        let mut w = layout
            .as_ref()
            .and_then(|l| {
                l.width()
                    .is_percent()
                    .then(|| resolve_len(l.width(), vp_w))
                    .flatten()
            })
            .map_or(base_rect.width, |pw| pw.max(0.0));
        let mut h = layout
            .as_ref()
            .and_then(|l| {
                l.height()
                    .is_percent()
                    .then(|| resolve_len(l.height(), vp_h))
                    .flatten()
            })
            .map_or(base_rect.height, |ph| ph.max(0.0));
        if has_explicit_inset {
            if let (Some(lv), Some(rv)) = (inset_left, inset_right)
                && layout.as_ref().is_none_or(|l| l.width().is_auto())
            {
                w = (vp_w - lv - rv).max(0.0);
            }
            if let (Some(tv), Some(bv)) = (inset_top, inset_bottom)
                && layout.as_ref().is_none_or(|l| l.height().is_auto())
            {
                h = (vp_h - tv - bv).max(0.0);
            }
        }
        if let Some(ref l) = layout {
            if let Some(min_w) = resolve_len(l.min_width(), vp_w) {
                w = w.max(min_w.max(0.0));
            }
            if let Some(max_w) = resolve_len(l.max_width(), vp_w) {
                w = w.min(max_w.max(0.0));
            }
            if let Some(min_h) = resolve_len(l.min_height(), vp_h) {
                h = h.max(min_h.max(0.0));
            }
            if let Some(max_h) = resolve_len(l.max_height(), vp_h) {
                h = h.min(max_h.max(0.0));
            }
        }
        if opts.contains(OverlayFlags::AUTO_SIZE)
            || opts.contains(OverlayFlags::SHIFT)
            || (is_modal && !has_explicit_inset)
        {
            w = w.min((vp_w - 2.0 * pad).max(0.0));
            h = h.min((vp_h - 2.0 * pad).max(0.0));
        }
        let (mut ox, mut oy) = if has_explicit_inset {
            let x = if let Some(lv) = inset_left {
                lv
            } else if let Some(rv) = inset_right {
                vp_w - rv - w
            } else {
                base_rect.x
            };
            let y = if let Some(tv) = inset_top {
                tv
            } else if let Some(bv) = inset_bottom {
                vp_h - bv - h
            } else {
                base_rect.y
            };
            (x, y)
        } else if is_modal {
            (((vp_w - w) * 0.5).max(pad), ((vp_h - h) * 0.5).max(pad))
        } else {
            (base_rect.x, base_rect.y)
        };
        if opts.contains(OverlayFlags::SHIFT) {
            let max_x = (vp_w - pad - w).max(pad);
            let max_y = (vp_h - pad - h).max(pad);
            ox = ox.clamp(pad, max_x);
            oy = oy.clamp(pad, max_y);
        }
        ResolvedOverlay {
            node: id,
            origin_x: ox,
            origin_y: oy,
            width: w,
            height: h,
            placement: ov.placement(),
            layer,
            is_modal,
            has_backdrop_scrim,
            light_dismiss,
            close_on_escape,
            backdrop_color,
            anchor: anchor.unwrap_or(NodeId::NULL),
        }
    }
}