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
//! Interactive pseudo-state tracking (`:hover`, `:focus`, `:focus-visible`, `:active`,
//! `:disabled`), pointer capture, and ancestor-inheriting [`CursorKind`] resolution shared across
//! [`LaidOutScene`] consumers.

use nativeview_abi::TimestampUs;
use nativeview_engine::InteractionTracker;
use nativeview_engine::tracker::PointerKey;
use nativeview_store::{NodeId, NodeStore, ResolvedRow, ResourceId, Rgba, RowPatchView};
use nativeview_tables::interaction::{
    CursorKind, FocusModality, InteractionState,
};
use nativeview_tables::snapshots::{
    LayoutSnapshot, VisualSnapshot, apply_patch_view_to_layout, apply_patch_view_to_visual,
};
use nativeview_tables::tables::{
    DragDrop, Interaction, PointerCaptureMode, TextAlign, Typography, Visual, paint_of_box,
};

use crate::{MAX_TREE_DEPTH, StoreLayoutEngine};

use super::style_cascade::StyleCascade;
use super::{LaidOutScene, layout_snapshot_of, visual_snapshot_of};

/// One pseudo-state change (`*_in_store`): the nodes whose pseudo-state changed, and whether it
/// re-ran layout (paragraph `StateRules`, `StateRules` box patches, top-layer re-hoisting).
/// Retained hosts must sync layout changes (`changed_rects()` / incremental layout delta or full
/// scene resync) when `relayout` is set; otherwise repainting `dirty` suffices.
#[must_use]
#[derive(Debug, Clone, Copy)]
pub struct InteractionChange<'a> {
    pub dirty: &'a [NodeId],
    pub relayout: bool,
}

impl<L: StoreLayoutEngine> LaidOutScene<L> {
    /// Feeds the tracker's last pseudo-state change to the engine (paragraph `StateRules`,
    /// `StateRules` `display` / `position` reflow, top-layer re-hoisting) and runs the engine's
    /// self-gated layout pass plus an overlay reconcile when anything was invalidated. Returns
    /// whether layout ran.
    pub(crate) fn sync_interaction_dirty(&mut self, store: &NodeStore) -> bool {
        let dirty = self.interaction.last_dirty();
        if dirty.is_empty() {
            return false;
        }
        let _ = self
            .layout
            .sync_interaction_paragraphs(store, &self.interaction, dirty);
        let relayout = self.recompute_layout(store);
        if relayout {
            self.reconcile_overlays_with_transform(store, |_, base| base);
        }
        relayout
    }

    /// Wraps the tracker's last change with whether it re-ran layout.
    #[inline]
    fn interaction_change(&mut self, store: &NodeStore) -> InteractionChange<'_> {
        let relayout = self.sync_interaction_dirty(store);
        InteractionChange {
            dirty: self.interaction.last_dirty(),
            relayout,
        }
    }

    #[inline]
    pub fn interaction_tracker(&self) -> &InteractionTracker {
        &self.interaction
    }

    /// Bumped on every pseudo-state change (pointer, focus, disabled, capture): state-rule
    /// results may differ since a caller last saw another value.
    #[inline]
    pub fn interaction_epoch(&self) -> u64 {
        self.interaction_epoch
    }

    /// The engine's [`StoreLayoutEngine::responsive_epoch`]: `@media` / `@container` results may
    /// differ since a caller last saw another value.
    #[inline]
    pub fn responsive_epoch(&self) -> u64 {
        self.layout.responsive_epoch()
    }

    #[inline]
    pub(crate) fn bump_interaction_epoch(&mut self) {
        self.interaction_epoch = self.interaction_epoch.wrapping_add(1).max(1);
    }

    #[inline]
    pub fn interaction_tracker_mut(&mut self) -> &mut InteractionTracker {
        self.bump_interaction_epoch();
        &mut self.interaction
    }

    #[inline]
    pub fn interaction_state(&self, node_id: NodeId) -> InteractionState {
        self.interaction.state(node_id)
    }

    /// Returns `true` when `id` or any ancestor up to root is disabled (via `Interaction::disabled`
    /// or [`InteractionTracker::is_disabled`]).
    #[inline]
    pub fn is_subtree_disabled(&self, store: &NodeStore, id: NodeId) -> bool {
        let mut cur = Some(id);
        for _ in 0..MAX_TREE_DEPTH {
            let Some(nid) = cur else {
                break;
            };
            if self.interaction.is_disabled(nid)
                || store
                    .try_row::<Interaction>(nid)
                    .is_some_and(|i| i.disabled())
            {
                return true;
            }
            cur = store.parent(nid).filter(|&p| p != nid);
        }
        false
    }

    /// Marks `id` disabled or enabled in the [`InteractionTracker`] (dropping `:active`, focus
    /// and every pointer capture on it), returning the dirty `NodeId`s.
    pub fn set_node_disabled(&mut self, id: NodeId, disabled: bool) -> &[NodeId] {
        self.bump_interaction_epoch();
        self.interaction.set_disabled_slice(id, disabled)
    }

    /// Returns `true` when `id` participates in pointer hover/active/cursor hit-testing.
    #[inline]
    pub fn is_interaction_target(&self, store: &NodeStore, id: NodeId) -> bool {
        if !self.is_displayed(store, id) {
            return false;
        }
        let has_inter = store.try_row::<Interaction>(id).is_some_and(|i| {
            !i.listeners().is_empty()
                || i.cursor() != CursorKind::Auto
                || i.disabled()
                || i.focusable()
                || i.capture_mode() != PointerCaptureMode::None
                || !i.state_rules().is_none()
                || i.captures_text_keys()
                || i.tab_index().is_some()
        });
        let has_drag = store.try_row::<DragDrop>(id).is_some_and(|d| {
            d.draggable() || !d.accept().is_empty() || !d.listeners().is_empty()
        });
        has_inter
            || has_drag
            || self.interaction.is_disabled(id)
    }

    /// Returns `true` when `id` is an active drop target (`DragDrop::accept != EMPTY`).
    #[inline]
    pub fn is_drop_target(store: &NodeStore, id: NodeId) -> bool {
        // Visibility is decided by the cascaded stacking plan the hit test walks.
        store.is_live(id)
            && store.try_row::<DragDrop>(id).is_some_and(|d| !d.accept().is_empty())
    }

    /// Returns `true` when `id` is a live visible draggable source (`DragDrop::draggable == true`).
    #[inline]
    pub fn is_draggable_target(store: &NodeStore, id: NodeId) -> bool {
        // Visibility is decided by the cascaded stacking plan the hit test walks.
        store.is_live(id)
            && store.try_row::<DragDrop>(id).is_some_and(|d| d.draggable())
    }

    /// Hit-tests `(x, y)` in reverse paint order for the deepest interaction-eligible node.
    pub fn hit_test_interaction(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
        self.hit_test_where(store, x, y, |id| self.is_interaction_target(store, id))
    }

    /// Hit-tests `(x, y)` in reverse paint order for the deepest drop-zone target.
    pub fn hit_test_drop_zone(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
        self.hit_test_where(store, x, y, |id| Self::is_drop_target(store, id))
    }

    /// Hit-tests `(x, y)` in reverse paint order for the deepest draggable source node.
    pub fn hit_test_draggable(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
        self.hit_test_where(store, x, y, |id| Self::is_draggable_target(store, id))
    }

    /// Visits every [`RowPatchView`] overriding `id`'s base style in cascade order: matching
    /// `@media`, then `@container` rules (committed layout env), then state rules matching its
    /// current [`InteractionState`] (zero allocations up to 16 rules).
    pub fn visit_effective_patches<'a>(
        &self,
        store: &'a NodeStore,
        id: NodeId,
        mut f: impl FnMut(RowPatchView<'a>),
    ) {
        self.style_cascade().visit(store, id, |_, pv| f(pv));
    }

    /// Whether `id` is live and its cascaded `display` is not `none`.
    #[inline]
    pub fn is_displayed(&self, store: &NodeStore, id: NodeId) -> bool {
        store.is_live(id) && !self.style_cascade().effective_box(store, id).is_none()
    }

    /// The scene's single `base -> @media -> @container -> state` style cascade.
    #[inline]
    pub fn style_cascade(&self) -> StyleCascade<'_, L> {
        StyleCascade {
            responsive: &self.layout,
            interaction: Some(&self.interaction),
            inert: Some(&self.overlays),
        }
    }

    /// Resolves the effective [`VisualSnapshot`] for `id` with responsive and pseudo-state rules
    /// applied.
    pub fn effective_visual(&self, store: &NodeStore, id: NodeId) -> VisualSnapshot {
        let mut visual = visual_snapshot_of(store, id);
        self.visit_effective_patches(store, id, |pv| apply_patch_view_to_visual(pv, &mut visual));
        paint_of_box(store, id, visual)
    }

    /// Resolves both [`LayoutSnapshot`] and [`VisualSnapshot`] for `id` with responsive and
    /// pseudo-state rules applied.
    pub fn effective_layout_and_visual(
        &self,
        store: &NodeStore,
        id: NodeId,
    ) -> (LayoutSnapshot, VisualSnapshot) {
        let mut layout = layout_snapshot_of(store, id);
        let mut visual = visual_snapshot_of(store, id);
        self.visit_effective_patches(store, id, |pv| {
            apply_patch_view_to_layout(pv, &mut layout);
            apply_patch_view_to_visual(pv, &mut visual);
        });
        (layout, paint_of_box(store, id, visual))
    }

    /// Resolves the effective `BackgroundFillRes` resource id for `id`, respecting responsive and
    /// state-rule patches (including solid `background` overrides clearing a base gradient).
    #[inline]
    pub fn effective_background_fill_res(&self, store: &NodeStore, id: NodeId) -> Option<ResourceId> {
        let mut patched: Option<ResourceId> = None;
        self.visit_effective_patches(store, id, |pv| {
            if let Some(rid) = pv.get_res_id(Visual::BACKGROUND_FILL) {
                patched = Some(rid);
            } else if pv.get_prop(Visual::BACKGROUND).is_some() {
                patched = Some(ResourceId::NONE);
            }
        });
        match patched {
            Some(rid) => (!rid.is_none()).then_some(rid),
            None => store
                .try_row::<Visual>(id)
                .map(|v| v.background_fill())
                .filter(|rid| !rid.is_none()),
        }
    }

    /// Resolves inherited `(font_weight, text_align, text_color, font_size)` for `id` using
    /// branchless `ResolvedRow<Typography>` over `parent_text`, layered with responsive/state
    /// patches and an optional animated text color override.
    #[inline]
    pub fn resolve_text_style_fields(
        &self,
        store: &NodeStore,
        id: NodeId,
        style: &VisualSnapshot,
        parent_text: Option<(u16, TextAlign, Rgba, f32)>,
        color_hooked: bool,
    ) -> (u16, TextAlign, Rgba, f32) {
        let mut parent_row = ResolvedRow::<Typography>::root(store);
        if let Some((w, align, color, size)) = parent_text {
            parent_row.override_prop(Typography::COLOR, color);
            parent_row.override_prop(Typography::FONT_SIZE, size);
            parent_row.override_prop(Typography::FONT_WEIGHT, w);
            parent_row.override_prop(Typography::TEXT_ALIGN, align);
        }
        let resolved_typo = ResolvedRow::<Typography>::resolve(store, id, &parent_row);
        let typo = resolved_typo.get();
        let (mut color_ov, mut size_ov, mut weight_ov, mut align_ov) =
            (color_hooked, false, None, None);
        self.visit_effective_patches(store, id, |pv| {
            if pv.get_prop(Typography::COLOR).is_some() {
                color_ov = true;
            }
            if pv.get_prop(Typography::FONT_SIZE).is_some() {
                size_ov = true;
            }
            if let Some(w) = pv.get_prop(Typography::FONT_WEIGHT) {
                weight_ov = Some(w);
            }
            if let Some(a) = pv.get_prop(Typography::TEXT_ALIGN) {
                align_ov = Some(a);
            }
        });
        (
            weight_ov.unwrap_or_else(|| typo.font_weight()),
            align_ov.unwrap_or_else(|| typo.text_align()),
            if color_ov { Rgba::from(style.text_color) } else { typo.color() },
            if size_ov { style.font_size } else { typo.font_size() },
        )
    }

    fn local_cursor_of(&self, store: &NodeStore, id: NodeId) -> CursorKind {
        let inter = store.try_row::<Interaction>(id);
        let base_cursor = inter.map(|i| i.cursor()).unwrap_or(CursorKind::Auto);
        let captures_text = inter.is_some_and(|i| i.captures_text_keys());
        let base = if base_cursor == CursorKind::Auto && captures_text {
            CursorKind::Text
        } else {
            base_cursor
        };
        self.style_cascade()
            .patched(store, id, Interaction::CURSOR)
            .unwrap_or(base)
    }

    /// Resolves the effective [`CursorKind`] for `id` in a single `O(depth)` leaf-to-root walk,
    /// converting `Pointer` to `NotAllowed` whenever `id` or any ancestor is disabled.
    pub fn effective_cursor(&self, store: &NodeStore, id: NodeId) -> CursorKind {
        if !self.is_displayed(store, id) {
            return CursorKind::Auto;
        }
        let mut cur = Some(id);
        let mut found: Option<CursorKind> = None;
        let mut disabled_seen = false;
        for _ in 0..MAX_TREE_DEPTH {
            let Some(nid) = cur else {
                break;
            };
            if self.interaction.is_disabled(nid)
                || store.try_row::<Interaction>(nid).is_some_and(|i| i.disabled())
            {
                disabled_seen = true;
                if found == Some(CursorKind::Pointer) {
                    return CursorKind::NotAllowed;
                }
            }
            if found.is_none() {
                let resolved = self.local_cursor_of(store, nid);
                if resolved != CursorKind::Auto {
                    if resolved != CursorKind::Pointer {
                        return resolved;
                    }
                    if disabled_seen {
                        return CursorKind::NotAllowed;
                    }
                    found = Some(resolved);
                }
            }
            cur = store.parent(nid).filter(|&p| p != nid);
        }
        found.unwrap_or(CursorKind::Auto)
    }

    /// Resolves the active cursor in `O(depth)`: checks captured node first, then the deepest
    /// live hovered node, then the deepest live active node, falling back to `CursorKind::Default`.
    pub fn current_cursor(&self, store: &NodeStore) -> CursorKind {
        if let Some(cap) = self.interaction.captured_node() {
            let c = self.effective_cursor(store, cap);
            return if c == CursorKind::Auto {
                CursorKind::Default
            } else {
                c
            };
        }
        if let Some(&leaf) = self
            .interaction
            .hovered_chain()
            .iter()
            .find(|&&id| self.is_displayed(store, id))
        {
            let c = self.effective_cursor(store, leaf);
            if c != CursorKind::Auto {
                return c;
            }
        }
        if let Some(&leaf) = self
            .interaction
            .active_chain()
            .iter()
            .find(|&&id| self.is_displayed(store, id))
        {
            let c = self.effective_cursor(store, leaf);
            if c != CursorKind::Auto {
                return c;
            }
        }
        CursorKind::Default
    }

    /// Moves the mouse ([`PointerKey::MOUSE`]) to `target` directly, bypassing hit testing and
    /// event synthesis (pseudo-state drivers: benches, inspectors). Hosts route samples through
    /// [`Self::resolve_pointer`].
    #[inline]
    pub fn pointer_move_in_store(
        &mut self,
        store: &NodeStore,
        target: Option<NodeId>,
    ) -> InteractionChange<'_> {
        self.bump_interaction_epoch();
        let _ = self
            .interaction
            .pointer_move_with(PointerKey::MOUSE, target, |id| store.parent(id));
        self.interaction_change(store)
    }

    /// Presses the mouse's primary button on `target` directly (see [`Self::pointer_move_in_store`]).
    #[inline]
    pub fn pointer_down_in_store(
        &mut self,
        store: &NodeStore,
        target: Option<NodeId>,
    ) -> InteractionChange<'_> {
        self.bump_interaction_epoch();
        let _ = self.interaction.pointer_down_with(
            PointerKey::MOUSE,
            [0.0, 0.0],
            TimestampUs::ZERO,
            target,
            |id| store.parent(id),
        );
        self.interaction_change(store)
    }

    /// Releases the mouse over `target` directly, returning `(clicked_node, change)` (see
    /// [`Self::pointer_move_in_store`]).
    #[inline]
    pub fn pointer_up_in_store(
        &mut self,
        store: &NodeStore,
        target: Option<NodeId>,
    ) -> (Option<NodeId>, InteractionChange<'_>) {
        self.bump_interaction_epoch();
        let end = self
            .interaction
            .pointer_up_with(PointerKey::MOUSE, target, |id| store.parent(id));
        (end.clicked, self.interaction_change(store))
    }

    /// The pointer left the surface: clears `:hover` (an uncaptured press also drops `:active`).
    #[inline]
    pub fn pointer_leave_in_store(&mut self, store: &NodeStore) -> InteractionChange<'_> {
        self.bump_interaction_epoch();
        let _ = self.interaction.pointer_leave_slice();
        self.interaction_change(store)
    }

    /// Cancels every pointer (window blur): ends every pointer and its capture and clears
    /// `:hover`, `:active` and `:drag-over`.
    #[inline]
    pub fn pointer_cancel_in_store(&mut self, store: &NodeStore) -> InteractionChange<'_> {
        self.bump_interaction_epoch();
        let _ = self.interaction.pointer_cancel_all();
        self.interaction_change(store)
    }

    /// Zero-alloc `:drag-over` ancestor-chain update against `store`, syncing inline paragraphs.
    #[inline]
    pub fn set_drag_over_in_store(
        &mut self,
        store: &NodeStore,
        target: Option<NodeId>,
    ) -> InteractionChange<'_> {
        self.bump_interaction_epoch();
        let _ = self
            .interaction
            .set_drag_over_with(target, |id| store.parent(id));
        self.interaction_change(store)
    }

    /// Zero-alloc `:active` press clear against `store` (used on drag activation).
    #[inline]
    pub fn clear_active_in_store(&mut self, store: &NodeStore) -> InteractionChange<'_> {
        self.bump_interaction_epoch();
        let _ = self.interaction.clear_active_slice();
        self.interaction_change(store)
    }

    /// Zero-alloc focus update against `store`, syncing any affected inline paragraphs and
    /// capturing the focus anchor for deterministic post-commit unmount recovery.
    #[inline]
    pub fn set_focus_in_store(
        &mut self,
        store: &NodeStore,
        node_id: Option<NodeId>,
        modality: FocusModality,
    ) -> InteractionChange<'_> {
        self.last_focus_transition = None;
        self.bump_interaction_epoch();
        let is_text = node_id.is_some_and(|id| nativeview_engine::is_text_entry_node(store, id));
        let _ = self.interaction.set_focus_ex(node_id, modality, is_text);
        if self.interaction.focused() == node_id {
            let mut anchor = core::mem::take(self.interaction.focus_anchor_mut());
            nativeview_engine::snapshot_focus_anchor(
                store,
                &super::cascade_of(&self.layout, &self.interaction),
                &mut anchor,
                node_id,
                modality,
                &mut self.focus_dfs_scratch,
            );
            *self.interaction.focus_anchor_mut() = anchor;
        }
        self.interaction_change(store)
    }
}