nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Relayout containment boundaries (`ContainerType::Size` + `Contain::LAYOUT`) for
//! [`super::TaffyStoreLayout`].
//!
//! When an edit is strictly inside a committed `ContainerType::Size` container `A` whose own size
//! is definite (non-auto `width` and `height`), has `Contain::LAYOUT`, is neither hidden nor
//! `display: contents`, and has no out-of-flow descendant escaping above `A`, `mark_dirty` stops
//! at `A` and records `A` in `dirty_boundaries` instead of invalidating ancestors up to `root`.
//!
//! During `compute_layout`, Taffy and the rounding pass run directly on each disjoint dirty
//! boundary using `A`'s exact saved `LayoutInput` and committed unrounded parent origin, keeping
//! `root` and sibling caches completely warm. Any OOF escape, unexpected border-box size delta, or
//! top-layer/container-env interaction transparently falls back to a full-root pass.

use nativeview_engine::{InteractionTracker, Viewport};
use nativeview_store::{NodeId, NodeStore};
use taffy::LayoutPartialTree;
use taffy::geometry::{Line, Size};
use taffy::style::AvailableSpace;
use taffy::tree::{LayoutInput, RunMode, SizingMode};

use super::container::scope::{ActiveContainer, ContainerScope, scope_of};
use super::layout_view::LayoutView;
use super::{TaffyStoreLayout, gen_tag};

/// Cap on distinct dirty boundaries tracked in one frame; beyond this, fall back to a full pass.
pub(super) const MAX_DIRTY_BOUNDARIES: usize = 16;

/// Exact Taffy `PerformLayout` input and containment properties captured when a
/// `ContainerType::Size` node lays out during a full (or boundary) pass.
#[derive(Debug, Clone, Copy)]
pub(super) struct BoundaryLayoutInfo {
    pub(super) parent_size: Size<Option<f32>>,
    pub(super) available_space: Size<AvailableSpace>,
    pub(super) known_dimensions: Size<Option<f32>>,
    pub(super) known_dimensions_are_definite: Size<bool>,
    pub(super) sizing_mode: SizingMode,
    /// `true` when any out-of-flow candidate bubbled past this container during its last layout.
    pub(super) oof_escaped: bool,
    /// `true` when `ContainerType::Size`, `Contain::LAYOUT`, non-auto `width`/`height`,
    /// non-hidden, and non-`display: contents`.
    pub(super) definite_size: bool,
}

impl Default for BoundaryLayoutInfo {
    fn default() -> Self {
        Self {
            parent_size: Size::NONE,
            available_space: Size {
                width: AvailableSpace::MaxContent,
                height: AvailableSpace::MaxContent,
            },
            known_dimensions: Size::NONE,
            known_dimensions_are_definite: Size {
                width: false,
                height: false,
            },
            sizing_mode: SizingMode::InherentSize,
            oof_escaped: true,
            definite_size: false,
        }
    }
}

/// Committed relayout-boundary metadata for one `ContainerType::Size` node.
#[derive(Debug, Clone, Copy, Default)]
pub(super) struct BoundaryRecord {
    pub(super) layout: BoundaryLayoutInfo,
    pub(super) layout_valid: bool,
    pub(super) parent_origin: (f32, f32),
    pub(super) hoisted: bool,
    pub(super) round_valid: bool,
}

impl BoundaryRecord {
    #[inline]
    pub(super) fn is_usable(self) -> bool {
        self.layout_valid
            && self.round_valid
            && self.layout.definite_size
            && !self.layout.oof_escaped
    }

    #[inline]
    pub(super) fn to_layout_input(self) -> LayoutInput {
        LayoutInput {
            run_mode: RunMode::PerformLayout,
            sizing_mode: self.layout.sizing_mode,
            axis: taffy::tree::RequestedAxis::Both,
            known_dimensions: self.layout.known_dimensions,
            known_dimensions_are_definite: self.layout.known_dimensions_are_definite,
            parent_size: self.layout.parent_size,
            available_space: self.layout.available_space,
            vertical_margins_are_collapsible: Line::FALSE,
        }
    }
}

impl TaffyStoreLayout {
    /// Whether `id` currently qualifies as a committed relayout containment boundary.
    #[inline]
    pub(super) fn is_valid_boundary(&self, id: NodeId, root: NodeId) -> bool {
        if self.capture_box_edges
            || self.size_container_count == 0
            || self.rect_valid_gen == 0
            || id == root
            || self.top_layer.is_hoisted(id)
        {
            return false;
        }
        let idx = id.index();
        idx < self.rect_gen.len()
            && self.rect_gen[idx] == self.rect_valid_gen
            && self.node_gens[idx] == gen_tag(id)
            && self.boundary_records.get(id).is_some_and(BoundaryRecord::is_usable)
    }

    /// Attempts to stop a `mark_dirty` ascent at strict ancestor `id`. Returns `true` when `id`
    /// absorbed the invalidation into `self.dirty_boundaries`.
    #[inline]
    pub(super) fn try_record_dirty_boundary(&mut self, id: NodeId, root: NodeId) -> bool {
        if self.full_layout_needed || !self.is_valid_boundary(id, root) {
            return false;
        }
        if self.dirty_boundaries.contains(&id) {
            return true;
        }
        if self.dirty_boundaries.len() >= MAX_DIRTY_BOUNDARIES {
            self.full_layout_needed = true;
            return false;
        }
        self.dirty_boundaries.push(id);
        true
    }

    /// Clears Taffy caches from `start`'s parent up to `root` (used when promoting boundary-scoped
    /// invalidations to a full-root pass so cached intermediates never hide a dirty boundary).
    pub(super) fn clear_ancestors_to_root(&mut self, store: &NodeStore, start: NodeId, root: NodeId) {
        let mut cur = store.parent(start);
        for _ in 0..=crate::MAX_TREE_DEPTH {
            let Some(p) = cur else {
                break;
            };
            if !store.is_live(p) {
                break;
            }
            let idx = p.index();
            if idx < self.caches.len() {
                self.caches[idx].clear();
            }
            if p == root {
                break;
            }
            cur = store.parent(p).filter(|&gp| gp != p);
        }
    }

    /// Promotes every recorded dirty boundary up to `root` and clears `dirty_boundaries`.
    pub(super) fn promote_dirty_boundaries_to_root(&mut self, store: &NodeStore, root: NodeId) {
        for i in 0..self.dirty_boundaries.len() {
            let b = self.dirty_boundaries[i];
            if store.is_live(b) {
                self.clear_ancestors_to_root(store, b, root);
            }
        }
        self.dirty_boundaries.clear();
        if let Some(c) = self.caches.get_mut(root.index()) {
            c.clear();
        }
    }

    /// Validates and collapses nested entries in `self.dirty_boundaries` into a mutually disjoint
    /// set of valid boundaries reachable from `root`. Returns `false` if a full-root pass is
    /// required.
    pub(super) fn prepare_dirty_boundaries(&mut self, store: &NodeStore, root: NodeId) -> bool {
        if self.dirty_boundaries.is_empty() {
            return false;
        }
        // Validate every candidate first.
        for &b in &self.dirty_boundaries {
            if !store.is_live(b) || !self.is_valid_boundary(b, root) {
                return false;
            }
        }
        // Collapse any boundary that sits inside another dirty boundary (clearing caches along
        // the intermediate chain between them so the outer boundary visits the inner one), and
        // confirm every remaining boundary reaches `root`.
        let mut write = 0usize;
        let len = self.dirty_boundaries.len();
        for read in 0..len {
            let b = self.dirty_boundaries[read];
            let mut cur = store.parent(b);
            let mut reached_root = false;
            let mut covered_by: Option<NodeId> = None;
            for _ in 0..=crate::MAX_TREE_DEPTH {
                let Some(p) = cur else {
                    break;
                };
                if !store.is_live(p) {
                    break;
                }
                if self.dirty_boundaries[..len].contains(&p) {
                    covered_by = Some(p);
                    reached_root = true;
                    break;
                }
                if p == root {
                    reached_root = true;
                    break;
                }
                cur = store.parent(p).filter(|&gp| gp != p);
            }
            if !reached_root {
                return false;
            }
            if let Some(outer) = covered_by {
                // Clear caches strictly between `b` and `outer` so `outer`'s pass visits `b`.
                let mut walk = store.parent(b);
                for _ in 0..=crate::MAX_TREE_DEPTH {
                    let Some(p) = walk else {
                        break;
                    };
                    if p == outer {
                        break;
                    }
                    if let Some(c) = self.caches.get_mut(p.index()) {
                        c.clear();
                    }
                    walk = store.parent(p).filter(|&gp| gp != p);
                }
                continue;
            }
            self.dirty_boundaries[write] = b;
            write += 1;
        }
        self.dirty_boundaries.truncate(write);
        !self.dirty_boundaries.is_empty()
    }

    /// Runs Taffy + commit rounding directly on each disjoint boundary in `self.dirty_boundaries`.
    /// Returns `Ok(envs_changed)` when every boundary stayed strictly contained, or `Err(())`
    /// when a boundary escaped (OOF bubble-out or border-box size change) before mutating `rects`,
    /// signalling the caller to run a full-root pass.
    pub(super) fn try_run_boundary_pass(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        viewport: Viewport,
        interaction: Option<&InteractionTracker>,
    ) -> Result<bool, ()> {
        let count = self.dirty_boundaries.len();
        // Phase 1: run Taffy on every boundary BEFORE mutating `rects` / `changed_rects`. If any
        // boundary bubbles an unclaimed OOF candidate or changes border-box size, abort cleanly so
        // the caller falls back to a full-root pass with `rects` untouched.
        for i in 0..count {
            let b = self.dirty_boundaries[i];
            let Some(rec) = self.boundary_records.get(b) else {
                return Err(());
            };
            let prev_box = self.boxes[b.index()];
            let enclosing = if self.container_node_count > 0 {
                scope_of(store, &self.container_records, b)
            } else {
                ContainerScope::default()
            };
            let input = rec.to_layout_input();
            let resp_memo = &self.resp_memo.get_mut()[..self.resp_memo_len.0];
            let mut view = LayoutView {
                store,
                root_index: root.index() as u32,
                root_fills_viewport: true,
                dry_run: false,
                viewport: (viewport.width, viewport.height),
                media_env: self.media_env,
                media_signature: self.media_signature,
                responsive_node_count: self.responsive_node_count,
                container_node_count: self.container_node_count,
                resolved_rtl: &self.resolved_rtl,
                resolved_text: &self.resolved_text,
                subtree_has_responsive: &self.subtree_has_responsive,
                has_responsive_typo: &self.has_responsive_typo,
                style_flags: &self.style_flags,
                paragraphs: &self.paragraphs,
                caches: &mut self.caches,
                cached_env_hash: &mut self.cached_env_hash,
                container_records: &mut self.container_records,
                boundary_records: (self.size_container_count > 0)
                    .then_some(&mut self.boundary_records),
                active_container: ActiveContainer::detached(enclosing),
                measure_paragraphs: std::cell::RefCell::new(&mut self.measure_paragraphs),
                resp_memo_slot: &self.resp_memo_slot,
                resp_memo,
                resp_pass_gen: self.resp_pass_gen,
                cache_gen: None,
                boxes: &mut self.boxes,
                box_edges: None,
                hoisted: Some(&mut self.hoisted),
                box_children: &self.box_children,
                top_layer: &self.top_layer,
                interaction,
                measurer: &*self.measurer,
                measure_hooks: &self.measure_hooks,
            };
            let out = view.compute_child_layout(taffy::NodeId::from(b.index() as u64), input);
            if !out.oof_candidates.is_empty()
                || out.size.width.to_bits() != prev_box.w.to_bits()
                || out.size.height.to_bits() != prev_box.h.to_bits()
            {
                return Err(());
            }
        }

        // Phase 2: every boundary stayed strictly isolated; commit rounded rects & `changed_rects`.
        self.hoisted.compact_if_fragmented();
        self.layout_gen = self.layout_gen.wrapping_add(1).max(1);
        self.changed_rects.clear();
        self.all_rects_changed = false;
        let mut envs_changed = false;
        for i in 0..count {
            let b = self.dirty_boundaries[i];
            let rec = self.boundary_records.get(b).unwrap_or_default();
            let enclosing = if self.container_node_count > 0 {
                scope_of(store, &self.container_records, b)
            } else {
                ContainerScope::default()
            };
            envs_changed |= self.commit_round_boundary(
                store,
                root,
                b,
                rec.parent_origin,
                enclosing,
                rec.hoisted,
                interaction,
            );
        }
        Ok(envs_changed)
    }
}