Skip to main content

nativeview_layout/
engine.rs

1//! Direct `NodeStore` layout engine trait (`StoreLayoutEngine`) and its runtime-switchable
2//! boxed form (`DynLayoutEngine`).
3//!
4//! Backends such as `HeadlessBackend<L>` and `SkiaBackend<L>` are generic over
5//! [`StoreLayoutEngine`] (defaulting to `TaffyStoreLayout` for zero dynamic-dispatch overhead)
6//! while also supporting dynamic runtime switching via [`DynLayoutEngine`].
7
8use std::sync::Arc;
9
10pub use nativeview_abi::{NvSizeConstraints as SizeConstraints, NvSurfaceMeasure as SurfaceMeasure};
11use nativeview_engine::{InteractionTracker, LayoutRect, Viewport};
12use nativeview_store::{ChangeSet, NodeId, NodeStore, RowPatchView, TableSlot};
13use nativeview_tables::media::{ConditionalTier, MediaEnv};
14
15use crate::{LeafMeasureHook, ParagraphStore, ResolvedBoxEdges, TextMeasurer, TopLayerIndex};
16
17/// Direct `NodeStore` layout engine trait implemented by [`crate::TaffyStoreLayout`], real
18/// React Native Yoga (`packages/modules/layout-yoga`), custom layout engines,
19/// and [`DynLayoutEngine`] (`Box<dyn StoreLayoutEngine>`).
20///
21/// Computed rectangles returned by [`StoreLayoutEngine::layout_of`] are expressed in
22/// surface-space (root-relative absolute) coordinates in logical points.
23pub trait StoreLayoutEngine: Send {
24    /// Human-readable engine identifier (e.g. `"taffy"`, `"yoga"`).
25    fn name(&self) -> &'static str;
26
27    /// Invalidates cached layout entries for every layout/measure/structural change in `changes`.
28    ///
29    /// Every engine owns one [`TopLayerIndex`] and syncs it first (`TopLayerIndex::sync`), then
30    /// hoists exactly its [`TopLayerIndex::hoisted`] roots to the layout root.
31    fn sync_changes(&mut self, store: &NodeStore, changes: &ChangeSet);
32
33    /// The engine's top-layer index: the single source of which overlay roots are hoisted. After
34    /// every [`Self::sync_changes`] it covers every store slot (`TopLayerIndex::sync` guarantees
35    /// it); the runtime publishes its `states()` zero-copy as the `top_layer_states` scene fact.
36    fn top_layer(&self) -> &TopLayerIndex;
37
38    /// Variant of [`Self::sync_changes`] that also resolves active `:hover`/`:active` state rules
39    /// on inline paragraph runs.
40    fn sync_changes_with_interaction(
41        &mut self,
42        store: &NodeStore,
43        changes: &ChangeSet,
44        _interaction: Option<&InteractionTracker>,
45    ) {
46        self.sync_changes(store, changes);
47    }
48
49    /// Computes layout for `root` at `viewport` directly from `store` word columns.
50    ///
51    /// **Self-gating contract**: the engine is the single owner of the clean-frame gate. Callers
52    /// invoke this on every frame after [`StoreLayoutEngine::sync_changes`]; when nothing that
53    /// affects layout changed since the last pass (no layout/measure/structural change, same
54    /// `root` and viewport, no measurer swap or reset), the engine returns `false` without
55    /// running a pass and every [`StoreLayoutEngine::layout_of`] result stays current. Returns
56    /// `true` when a pass ran (layout results may have changed). A pass that unwinds (e.g. a
57    /// panicking host `TextMeasurer`) must leave the engine dirty so the next call retries.
58    fn compute_layout(&mut self, store: &NodeStore, root: NodeId, viewport: Viewport) -> bool;
59
60    /// Variant of [`Self::compute_layout`] that threads active `InteractionTracker` state into
61    /// compiled paragraph runs when deferred inheritance runs.
62    fn compute_layout_with_interaction(
63        &mut self,
64        store: &NodeStore,
65        root: NodeId,
66        viewport: Viewport,
67        _interaction: Option<&InteractionTracker>,
68    ) -> bool {
69        self.compute_layout(store, root, viewport)
70    }
71
72    /// Recompiles only paragraphs owning `dirty_nodes` after an interactive pseudo-state change
73    /// (`:hover`/`:active`/`:focus`). Returns `(layout_dirty_paragraphs, paint_dirty_paragraphs)`.
74    fn sync_interaction_paragraphs(
75        &mut self,
76        _store: &NodeStore,
77        _interaction: &InteractionTracker,
78        _dirty_nodes: &[NodeId],
79    ) -> (&[NodeId], &[NodeId]) {
80        (&[], &[])
81    }
82
83    /// Borrowed compiled [`ParagraphStore`] shared with `nativeview-runtime`, `SkiaBackend`, and a11y.
84    fn paragraphs(&self) -> Option<&ParagraphStore> {
85        None
86    }
87
88    /// Mutable borrow of the compiled [`ParagraphStore`] (used to lock capacity before publish).
89    fn paragraphs_mut(&mut self) -> Option<&mut ParagraphStore> {
90        None
91    }
92
93    /// Measures `root` under `constraints` (or unconstrained intrinsic sizing when `ideal` is
94    /// `true`) without mutating committed layout boxes, published rects, or viewport state.
95    fn measure_root(
96        &mut self,
97        _store: &NodeStore,
98        _root: NodeId,
99        _constraints: SizeConstraints,
100        _ideal: bool,
101    ) -> SurfaceMeasure {
102        SurfaceMeasure {
103            width: 0.0,
104            height: 0.0,
105            first_baseline: f32::NAN,
106            last_baseline: f32::NAN,
107        }
108    }
109
110    /// Returns the absolute rounded layout rect of `id` from the latest pass, if live.
111    fn layout_of(&self, id: NodeId) -> Option<LayoutRect>;
112
113    /// Exact set of reachable live nodes whose committed [`Self::layout_of`] changed (bitwise) or
114    /// became newly laid out during the latest [`Self::compute_layout`] pass, or `None` when the
115    /// full delta is unavailable and callers must fall back to scanning all live nodes.
116    ///
117    /// **Contract:**
118    /// - `Some(&[])` after a clean frame where [`Self::compute_layout`] returned `false` or after
119    ///   [`Self::reset`].
120    /// - `Some(ids)` includes nodes transitioning to/from `display: none` or `display: contents`
121    ///   when their committed rect changes, as well as newly laid-out / slot-reused nodes.
122    /// - Removed nodes are reported via `ChangeSet::removed`; inline/box transitions via
123    ///   [`ParagraphStore`].
124    /// - `None` for engines without delta tracking (default) or when the entire tree was
125    ///   invalidated (e.g. dead root or a multi-pass `top_layer_rerun` fallback).
126    fn changed_rects(&self) -> Option<&[NodeId]> {
127        None
128    }
129
130    /// Enables or disables opt-in resolved CSS box-edge capture (`margin`/`border`/`padding`/
131    /// `content_size`) for the Visual Layout Inspector. Disabled by default (0 B overhead).
132    fn set_capture_box_edges(&mut self, _enabled: bool) {}
133
134    /// Returns whether opt-in box-edge capture is currently active.
135    fn capture_box_edges(&self) -> bool {
136        false
137    }
138
139    /// Returns the exact resolved box edges of `id` from the latest layout pass when opt-in
140    /// capture is enabled, or `None` when disabled or unsupported by this engine.
141    fn box_edges_of(&self, _id: NodeId) -> Option<ResolvedBoxEdges> {
142        None
143    }
144
145    /// Installs a custom text measurer and invalidates cached text measurements.
146    fn set_text_measurer(&mut self, measurer: Arc<dyn TextMeasurer>);
147
148    /// Registers an intrinsic [`LeafMeasureHook`] for nodes carrying `slot`, invalidating cached
149    /// layout entries, and returns `true` if a prior hook at `slot` was replaced. Engines without
150    /// leaf-hook support ignore it and return `false` by default.
151    fn register_measure_hook(&mut self, _slot: TableSlot, _hook: Arc<dyn LeafMeasureHook>) -> bool {
152        false
153    }
154
155    /// Clears all cached layout state.
156    fn reset(&mut self);
157
158    /// Sets the `@media` environment (`compute_layout` supplies the viewport size). Returns `true`
159    /// when it changed. Engines without responsive support ignore it.
160    fn set_media_env(&mut self, _env: MediaEnv) -> bool {
161        false
162    }
163
164    /// Visits `id`'s matching `@media` then `@container` rule patches (cascade order) under the
165    /// environment of the last committed pass. Engines without responsive support visit nothing.
166    fn visit_responsive_patches<'a>(
167        &self,
168        _store: &'a NodeStore,
169        _id: NodeId,
170        _f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
171    ) {
172    }
173
174    /// Whether `id`'s `Responsive::show_on` gate fails under the engine's `@media` environment
175    /// (`display: none` that beats every rule). Engines without responsive support never hide.
176    fn is_show_on_hidden(&self, _store: &NodeStore, _id: NodeId) -> bool {
177        false
178    }
179
180    /// Bumped whenever responsive styles may resolve differently without a store commit (the
181    /// media signature or a committed `@container` env changed). Caches of derived style (e.g.
182    /// stacking plans) key on it. Engines without responsive support stay at `0`.
183    fn responsive_epoch(&self) -> u64 {
184        0
185    }
186}
187
188/// Type alias for a runtime-switchable boxed `NodeStore` layout engine.
189pub type DynLayoutEngine = Box<dyn StoreLayoutEngine>;
190
191impl<L: StoreLayoutEngine + ?Sized> StoreLayoutEngine for Box<L> {
192    fn name(&self) -> &'static str {
193        (**self).name()
194    }
195
196    fn sync_changes(&mut self, store: &NodeStore, changes: &ChangeSet) {
197        (**self).sync_changes(store, changes);
198    }
199
200    fn top_layer(&self) -> &TopLayerIndex {
201        (**self).top_layer()
202    }
203
204    fn sync_changes_with_interaction(
205        &mut self,
206        store: &NodeStore,
207        changes: &ChangeSet,
208        interaction: Option<&InteractionTracker>,
209    ) {
210        (**self).sync_changes_with_interaction(store, changes, interaction);
211    }
212
213    fn compute_layout(&mut self, store: &NodeStore, root: NodeId, viewport: Viewport) -> bool {
214        (**self).compute_layout(store, root, viewport)
215    }
216
217    fn compute_layout_with_interaction(
218        &mut self,
219        store: &NodeStore,
220        root: NodeId,
221        viewport: Viewport,
222        interaction: Option<&InteractionTracker>,
223    ) -> bool {
224        (**self).compute_layout_with_interaction(store, root, viewport, interaction)
225    }
226
227    fn sync_interaction_paragraphs(
228        &mut self,
229        store: &NodeStore,
230        interaction: &InteractionTracker,
231        dirty_nodes: &[NodeId],
232    ) -> (&[NodeId], &[NodeId]) {
233        (**self).sync_interaction_paragraphs(store, interaction, dirty_nodes)
234    }
235
236    fn paragraphs(&self) -> Option<&ParagraphStore> {
237        (**self).paragraphs()
238    }
239
240    fn paragraphs_mut(&mut self) -> Option<&mut ParagraphStore> {
241        (**self).paragraphs_mut()
242    }
243
244    fn measure_root(
245        &mut self,
246        store: &NodeStore,
247        root: NodeId,
248        constraints: SizeConstraints,
249        ideal: bool,
250    ) -> SurfaceMeasure {
251        (**self).measure_root(store, root, constraints, ideal)
252    }
253
254    fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
255        (**self).layout_of(id)
256    }
257
258    fn changed_rects(&self) -> Option<&[NodeId]> {
259        (**self).changed_rects()
260    }
261
262    fn set_capture_box_edges(&mut self, enabled: bool) {
263        (**self).set_capture_box_edges(enabled);
264    }
265
266    fn capture_box_edges(&self) -> bool {
267        (**self).capture_box_edges()
268    }
269
270    fn box_edges_of(&self, id: NodeId) -> Option<ResolvedBoxEdges> {
271        (**self).box_edges_of(id)
272    }
273
274    fn set_text_measurer(&mut self, measurer: Arc<dyn TextMeasurer>) {
275        (**self).set_text_measurer(measurer);
276    }
277
278    fn register_measure_hook(&mut self, slot: TableSlot, hook: Arc<dyn LeafMeasureHook>) -> bool {
279        (**self).register_measure_hook(slot, hook)
280    }
281
282    fn reset(&mut self) {
283        (**self).reset();
284    }
285
286    fn set_media_env(&mut self, env: MediaEnv) -> bool {
287        (**self).set_media_env(env)
288    }
289
290    fn visit_responsive_patches<'a>(
291        &self,
292        store: &'a NodeStore,
293        id: NodeId,
294        f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
295    ) {
296        (**self).visit_responsive_patches(store, id, f);
297    }
298
299    fn is_show_on_hidden(&self, store: &NodeStore, id: NodeId) -> bool {
300        (**self).is_show_on_hidden(store, id)
301    }
302
303    fn responsive_epoch(&self) -> u64 {
304        (**self).responsive_epoch()
305    }
306}