nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Direct `NodeStore` layout engine trait (`StoreLayoutEngine`) and its runtime-switchable
//! boxed form (`DynLayoutEngine`).
//!
//! Backends such as `HeadlessBackend<L>` and `SkiaBackend<L>` are generic over
//! [`StoreLayoutEngine`] (defaulting to `TaffyStoreLayout` for zero dynamic-dispatch overhead)
//! while also supporting dynamic runtime switching via [`DynLayoutEngine`].

use std::sync::Arc;

pub use nativeview_abi::{NvSizeConstraints as SizeConstraints, NvSurfaceMeasure as SurfaceMeasure};
use nativeview_engine::{InteractionTracker, LayoutRect, Viewport};
use nativeview_store::{ChangeSet, NodeId, NodeStore, RowPatchView, TableSlot};
use nativeview_tables::media::{ConditionalTier, MediaEnv};

use crate::{LeafMeasureHook, ParagraphStore, ResolvedBoxEdges, TextMeasurer, TopLayerIndex};

/// Direct `NodeStore` layout engine trait implemented by [`crate::TaffyStoreLayout`], real
/// React Native Yoga (`packages/modules/layout-yoga`), custom layout engines,
/// and [`DynLayoutEngine`] (`Box<dyn StoreLayoutEngine>`).
///
/// Computed rectangles returned by [`StoreLayoutEngine::layout_of`] are expressed in
/// surface-space (root-relative absolute) coordinates in logical points.
pub trait StoreLayoutEngine: Send {
    /// Human-readable engine identifier (e.g. `"taffy"`, `"yoga"`).
    fn name(&self) -> &'static str;

    /// Invalidates cached layout entries for every layout/measure/structural change in `changes`.
    ///
    /// Every engine owns one [`TopLayerIndex`] and syncs it first (`TopLayerIndex::sync`), then
    /// hoists exactly its [`TopLayerIndex::hoisted`] roots to the layout root.
    fn sync_changes(&mut self, store: &NodeStore, changes: &ChangeSet);

    /// The engine's top-layer index: the single source of which overlay roots are hoisted. After
    /// every [`Self::sync_changes`] it covers every store slot (`TopLayerIndex::sync` guarantees
    /// it); the runtime publishes its `states()` zero-copy as the `top_layer_states` scene fact.
    fn top_layer(&self) -> &TopLayerIndex;

    /// Variant of [`Self::sync_changes`] that also resolves active `:hover`/`:active` state rules
    /// on inline paragraph runs.
    fn sync_changes_with_interaction(
        &mut self,
        store: &NodeStore,
        changes: &ChangeSet,
        _interaction: Option<&InteractionTracker>,
    ) {
        self.sync_changes(store, changes);
    }

    /// Computes layout for `root` at `viewport` directly from `store` word columns.
    ///
    /// **Self-gating contract**: the engine is the single owner of the clean-frame gate. Callers
    /// invoke this on every frame after [`StoreLayoutEngine::sync_changes`]; when nothing that
    /// affects layout changed since the last pass (no layout/measure/structural change, same
    /// `root` and viewport, no measurer swap or reset), the engine returns `false` without
    /// running a pass and every [`StoreLayoutEngine::layout_of`] result stays current. Returns
    /// `true` when a pass ran (layout results may have changed). A pass that unwinds (e.g. a
    /// panicking host `TextMeasurer`) must leave the engine dirty so the next call retries.
    fn compute_layout(&mut self, store: &NodeStore, root: NodeId, viewport: Viewport) -> bool;

    /// Variant of [`Self::compute_layout`] that threads active `InteractionTracker` state into
    /// compiled paragraph runs when deferred inheritance runs.
    fn compute_layout_with_interaction(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        viewport: Viewport,
        _interaction: Option<&InteractionTracker>,
    ) -> bool {
        self.compute_layout(store, root, viewport)
    }

    /// Recompiles only paragraphs owning `dirty_nodes` after an interactive pseudo-state change
    /// (`:hover`/`:active`/`:focus`). Returns `(layout_dirty_paragraphs, paint_dirty_paragraphs)`.
    fn sync_interaction_paragraphs(
        &mut self,
        _store: &NodeStore,
        _interaction: &InteractionTracker,
        _dirty_nodes: &[NodeId],
    ) -> (&[NodeId], &[NodeId]) {
        (&[], &[])
    }

    /// Borrowed compiled [`ParagraphStore`] shared with `nativeview-runtime`, `SkiaBackend`, and a11y.
    fn paragraphs(&self) -> Option<&ParagraphStore> {
        None
    }

    /// Mutable borrow of the compiled [`ParagraphStore`] (used to lock capacity before publish).
    fn paragraphs_mut(&mut self) -> Option<&mut ParagraphStore> {
        None
    }

    /// Measures `root` under `constraints` (or unconstrained intrinsic sizing when `ideal` is
    /// `true`) without mutating committed layout boxes, published rects, or viewport state.
    fn measure_root(
        &mut self,
        _store: &NodeStore,
        _root: NodeId,
        _constraints: SizeConstraints,
        _ideal: bool,
    ) -> SurfaceMeasure {
        SurfaceMeasure {
            width: 0.0,
            height: 0.0,
            first_baseline: f32::NAN,
            last_baseline: f32::NAN,
        }
    }

    /// Returns the absolute rounded layout rect of `id` from the latest pass, if live.
    fn layout_of(&self, id: NodeId) -> Option<LayoutRect>;

    /// Exact set of reachable live nodes whose committed [`Self::layout_of`] changed (bitwise) or
    /// became newly laid out during the latest [`Self::compute_layout`] pass, or `None` when the
    /// full delta is unavailable and callers must fall back to scanning all live nodes.
    ///
    /// **Contract:**
    /// - `Some(&[])` after a clean frame where [`Self::compute_layout`] returned `false` or after
    ///   [`Self::reset`].
    /// - `Some(ids)` includes nodes transitioning to/from `display: none` or `display: contents`
    ///   when their committed rect changes, as well as newly laid-out / slot-reused nodes.
    /// - Removed nodes are reported via `ChangeSet::removed`; inline/box transitions via
    ///   [`ParagraphStore`].
    /// - `None` for engines without delta tracking (default) or when the entire tree was
    ///   invalidated (e.g. dead root or a multi-pass `top_layer_rerun` fallback).
    fn changed_rects(&self) -> Option<&[NodeId]> {
        None
    }

    /// Enables or disables opt-in resolved CSS box-edge capture (`margin`/`border`/`padding`/
    /// `content_size`) for the Visual Layout Inspector. Disabled by default (0 B overhead).
    fn set_capture_box_edges(&mut self, _enabled: bool) {}

    /// Returns whether opt-in box-edge capture is currently active.
    fn capture_box_edges(&self) -> bool {
        false
    }

    /// Returns the exact resolved box edges of `id` from the latest layout pass when opt-in
    /// capture is enabled, or `None` when disabled or unsupported by this engine.
    fn box_edges_of(&self, _id: NodeId) -> Option<ResolvedBoxEdges> {
        None
    }

    /// Installs a custom text measurer and invalidates cached text measurements.
    fn set_text_measurer(&mut self, measurer: Arc<dyn TextMeasurer>);

    /// Registers an intrinsic [`LeafMeasureHook`] for nodes carrying `slot`, invalidating cached
    /// layout entries, and returns `true` if a prior hook at `slot` was replaced. Engines without
    /// leaf-hook support ignore it and return `false` by default.
    fn register_measure_hook(&mut self, _slot: TableSlot, _hook: Arc<dyn LeafMeasureHook>) -> bool {
        false
    }

    /// Clears all cached layout state.
    fn reset(&mut self);

    /// Sets the `@media` environment (`compute_layout` supplies the viewport size). Returns `true`
    /// when it changed. Engines without responsive support ignore it.
    fn set_media_env(&mut self, _env: MediaEnv) -> bool {
        false
    }

    /// Visits `id`'s matching `@media` then `@container` rule patches (cascade order) under the
    /// environment of the last committed pass. Engines without responsive support visit nothing.
    fn visit_responsive_patches<'a>(
        &self,
        _store: &'a NodeStore,
        _id: NodeId,
        _f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
    ) {
    }

    /// Whether `id`'s `Responsive::show_on` gate fails under the engine's `@media` environment
    /// (`display: none` that beats every rule). Engines without responsive support never hide.
    fn is_show_on_hidden(&self, _store: &NodeStore, _id: NodeId) -> bool {
        false
    }

    /// Bumped whenever responsive styles may resolve differently without a store commit (the
    /// media signature or a committed `@container` env changed). Caches of derived style (e.g.
    /// stacking plans) key on it. Engines without responsive support stay at `0`.
    fn responsive_epoch(&self) -> u64 {
        0
    }
}

/// Type alias for a runtime-switchable boxed `NodeStore` layout engine.
pub type DynLayoutEngine = Box<dyn StoreLayoutEngine>;

impl<L: StoreLayoutEngine + ?Sized> StoreLayoutEngine for Box<L> {
    fn name(&self) -> &'static str {
        (**self).name()
    }

    fn sync_changes(&mut self, store: &NodeStore, changes: &ChangeSet) {
        (**self).sync_changes(store, changes);
    }

    fn top_layer(&self) -> &TopLayerIndex {
        (**self).top_layer()
    }

    fn sync_changes_with_interaction(
        &mut self,
        store: &NodeStore,
        changes: &ChangeSet,
        interaction: Option<&InteractionTracker>,
    ) {
        (**self).sync_changes_with_interaction(store, changes, interaction);
    }

    fn compute_layout(&mut self, store: &NodeStore, root: NodeId, viewport: Viewport) -> bool {
        (**self).compute_layout(store, root, viewport)
    }

    fn compute_layout_with_interaction(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        viewport: Viewport,
        interaction: Option<&InteractionTracker>,
    ) -> bool {
        (**self).compute_layout_with_interaction(store, root, viewport, interaction)
    }

    fn sync_interaction_paragraphs(
        &mut self,
        store: &NodeStore,
        interaction: &InteractionTracker,
        dirty_nodes: &[NodeId],
    ) -> (&[NodeId], &[NodeId]) {
        (**self).sync_interaction_paragraphs(store, interaction, dirty_nodes)
    }

    fn paragraphs(&self) -> Option<&ParagraphStore> {
        (**self).paragraphs()
    }

    fn paragraphs_mut(&mut self) -> Option<&mut ParagraphStore> {
        (**self).paragraphs_mut()
    }

    fn measure_root(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        constraints: SizeConstraints,
        ideal: bool,
    ) -> SurfaceMeasure {
        (**self).measure_root(store, root, constraints, ideal)
    }

    fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
        (**self).layout_of(id)
    }

    fn changed_rects(&self) -> Option<&[NodeId]> {
        (**self).changed_rects()
    }

    fn set_capture_box_edges(&mut self, enabled: bool) {
        (**self).set_capture_box_edges(enabled);
    }

    fn capture_box_edges(&self) -> bool {
        (**self).capture_box_edges()
    }

    fn box_edges_of(&self, id: NodeId) -> Option<ResolvedBoxEdges> {
        (**self).box_edges_of(id)
    }

    fn set_text_measurer(&mut self, measurer: Arc<dyn TextMeasurer>) {
        (**self).set_text_measurer(measurer);
    }

    fn register_measure_hook(&mut self, slot: TableSlot, hook: Arc<dyn LeafMeasureHook>) -> bool {
        (**self).register_measure_hook(slot, hook)
    }

    fn reset(&mut self) {
        (**self).reset();
    }

    fn set_media_env(&mut self, env: MediaEnv) -> bool {
        (**self).set_media_env(env)
    }

    fn visit_responsive_patches<'a>(
        &self,
        store: &'a NodeStore,
        id: NodeId,
        f: &mut dyn FnMut(ConditionalTier, RowPatchView<'a>),
    ) {
        (**self).visit_responsive_patches(store, id, f);
    }

    fn is_show_on_hidden(&self, store: &NodeStore, id: NodeId) -> bool {
        (**self).is_show_on_hidden(store, id)
    }

    fn responsive_epoch(&self) -> u64 {
        (**self).responsive_epoch()
    }
}