nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Subtree-scoped inheritance propagation (`resolved_rtl`, `resolved_text`, `was_contents`,
//! `was_transformed`, flattened `box_children`, and inherited paragraph sync) for
//! [`super::TaffyStoreLayout`].
//!
//! Full-tree walks from `root` still run on initial load, resets, root changes, `@media`
//! display-reshaping changes, or when more than [`MAX_INHERIT_DIRTY_ROOTS`] distinct roots are
//! dirtied in one frame. Localized edits (typography, direction, child-list mutations, or
//! `display: contents` flips) walk only their disjoint dirty subtrees using each root's already
//! committed parent `(resolved_rtl, resolved_text)`.

use nativeview_engine::InteractionTracker;
use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::tables::{Direction as NvDirection, Layout as NvLayout};

use crate::{ResolvedTextStyle, resolve_inherited_text};

use super::container::scope::committed_container_env;
use super::{TaffyStoreLayout, gen_tag};
use super::responsive::text::ResponsiveTextEnv;
use super::transform_cb::has_store_transform;

/// Cap on distinct localized inheritance roots per frame; overflowing falls back to a full walk.
pub(super) const MAX_INHERIT_DIRTY_ROOTS: usize = 16;

impl TaffyStoreLayout {
    /// Schedules a full-tree inheritance walk from `root`.
    #[inline]
    pub(super) fn mark_inherit_full(&mut self) {
        self.inherit_dirty = true;
        self.inherit_full = true;
        self.inherit_dirty_roots.clear();
        self.committed_store_rev = None;
    }

    /// Schedules a localized inheritance walk rooted at `id`.
    ///
    /// When `promote_box_parent` is `true` (child-list changes, `display: contents` flips,
    /// inline/box transitions, or `Responsive` edits that may alter `display: contents`), the root
    /// is promoted to its nearest box-generating (non-`display: contents`) ancestor so that
    /// ancestor rebuilds its flattened `box_children`.
    pub(super) fn enqueue_inherit_root(
        &mut self,
        store: &NodeStore,
        id: NodeId,
        promote_box_parent: bool,
        interaction: Option<&InteractionTracker>,
    ) {
        self.inherit_dirty = true;
        self.committed_store_rev = None;
        if self.inherit_full || self.counts_dirty || self.inherit_walks == 0 {
            self.inherit_full = true;
            self.inherit_dirty_roots.clear();
            return;
        }
        if !store.is_live(id) || store.is_inline(id) {
            return;
        }
        let root_id = self.last_viewport.map_or(NodeId::ROOT, |(r, _, _)| r);
        let mut target = id;
        if promote_box_parent {
            // If `target` itself flipped `display: contents`, its parent owns the flattened list;
            // if `target` or an ancestor is `display: contents`, keep climbing to the nearest
            // box-generating ancestor (or `root_id`).
            let flipped_contents =
                self.display_change_reshapes_boxes(store, target, interaction);
            if flipped_contents
                && target != root_id
                && let Some(p) = store.parent(target).filter(|&p| p != target)
            {
                target = p;
            }
            for _ in 0..crate::MAX_TREE_DEPTH {
                if target == root_id {
                    break;
                }
                let idx = target.index();
                let is_contents = self.was_contents.get(idx).copied().unwrap_or(false)
                    || display_env!(self, interaction).is_display_contents(store, target);
                if !is_contents {
                    break;
                }
                match store.parent(target).filter(|&p| p != target) {
                    Some(p) => target = p,
                    None => break,
                }
            }
        }
        if target == root_id {
            self.inherit_full = true;
            self.inherit_dirty_roots.clear();
            return;
        }
        if self.inherit_dirty_roots.contains(&target) {
            return;
        }
        if self.inherit_dirty_roots.len() >= MAX_INHERIT_DIRTY_ROOTS {
            self.inherit_full = true;
            self.inherit_dirty_roots.clear();
            return;
        }
        self.inherit_dirty_roots.push(target);
    }

    /// Validates and deduplicates `self.inherit_dirty_roots` against `root`. Returns `true` when a
    /// full-tree walk from `root` must run instead of subtree walks.
    fn resolve_inherit_roots(&mut self, store: &NodeStore, root: NodeId) -> bool {
        if self.inherit_full || self.counts_dirty || self.inherit_walks == 0 {
            return true;
        }
        let len = self.inherit_dirty_roots.len();
        if len == 0 {
            return false;
        }
        let mut write = 0usize;
        for read in 0..len {
            let r = self.inherit_dirty_roots[read];
            if !store.is_live(r) || store.is_inline(r) {
                continue;
            }
            if r == root {
                return true;
            }
            let Some(parent) = store.parent(r) else {
                // Detached orphan outside `root`: unreachable from `root`.
                continue;
            };
            // Verify `r` reaches `root` and is not already covered by a dirty ancestor.
            let mut cur = Some(parent);
            let mut reached_root = false;
            let mut covered = false;
            for _ in 0..=crate::MAX_TREE_DEPTH {
                let Some(p) = cur else {
                    break;
                };
                if !store.is_live(p) {
                    break;
                }
                if self.inherit_dirty_roots[..len].contains(&p) {
                    covered = true;
                    reached_root = true;
                    break;
                }
                if p == root {
                    reached_root = true;
                    break;
                }
                cur = store.parent(p).filter(|&gp| gp != p);
            }
            if !reached_root || covered {
                continue;
            }
            // Parent must already hold committed inheritance state from an earlier walk.
            let pidx = parent.index();
            if pidx >= self.node_gens.len() || self.node_gens[pidx] != gen_tag(parent) {
                return true;
            }
            self.inherit_dirty_roots[write] = r;
            write += 1;
        }
        self.inherit_dirty_roots.truncate(write);
        false
    }

    pub(super) fn propagate_inheritance(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        interaction: Option<&InteractionTracker>,
    ) {
        if !self.inherit_dirty {
            return;
        }
        let do_full = self.resolve_inherit_roots(store, root);
        self.inherit_dirty = false;
        self.inherit_full = false;
        if self.counts_dirty {
            self.rebuild_responsive_counters(store);
        }
        self.inherit_stack.clear();
        if do_full {
            self.inherit_dirty_roots.clear();
            self.inherit_walks = self.inherit_walks.wrapping_add(1);
            self.full_inherit_walks = self.full_inherit_walks.wrapping_add(1);
            self.inherit_stack
                .push((root, false, ResolvedTextStyle::default()));
        } else {
            if self.inherit_dirty_roots.is_empty() {
                self.committed_store_rev = Some((store.instance_id(), store.frame()));
                return;
            }
            self.inherit_walks = self.inherit_walks.wrapping_add(1);
            for i in (0..self.inherit_dirty_roots.len()).rev() {
                let r = self.inherit_dirty_roots[i];
                let Some(p) = store.parent(r) else {
                    continue;
                };
                let pidx = p.index();
                self.inherit_stack
                    .push((r, self.resolved_rtl[pidx], self.resolved_text[pidx]));
            }
            self.inherit_dirty_roots.clear();
        }

        while let Some((id, parent_rtl, parent_text)) = self.inherit_stack.pop() {
            if !store.is_live(id) || store.is_inline(id) {
                continue;
            }
            self.inherit_nodes_visited = self.inherit_nodes_visited.wrapping_add(1);
            let idx = id.index();
            let rtl = if let Some(l) = store.try_row::<NvLayout>(id) {
                match l.direction() {
                    NvDirection::Inherit => parent_rtl,
                    NvDirection::Ltr => false,
                    NvDirection::Rtl => true,
                }
            } else {
                parent_rtl
            };

            let text = resolve_inherited_text(store, id, parent_text);
            let dir_changed = self.resolved_rtl[idx] != rtl;

            self.node_gens[idx] = gen_tag(id);
            self.resolved_rtl[idx] = rtl;
            let contents = id != root
                && display_env!(self, interaction).is_display_contents(store, id);
            // A flip between `contents` and a box (`@media`, pseudo-state) reshapes this node's
            // parent's box children and its own layout: cached Taffy outputs of either shape are
            // stale. On a subtree walk, also climb to the nearest non-`contents` ancestor `p`
            // and rebuild its flattened `box_children` in case `p` was outside the subtree.
            if self.was_contents[idx] != contents {
                self.was_contents[idx] = contents;
                self.mark_dirty(store, id);
                if !do_full && id != root {
                    let mut anc = store.parent(id);
                    for _ in 0..crate::MAX_TREE_DEPTH {
                        match anc {
                            Some(p)
                                if p != root
                                    && self.was_contents.get(p.index()).copied().unwrap_or(false) =>
                            {
                                anc = store.parent(p).filter(|&gp| gp != p);
                            }
                            _ => break,
                        }
                    }
                    if let Some(p) = anc
                        && store.is_live(p)
                        && !store.is_inline_context_root(p)
                    {
                        let env = display_env!(self, interaction);
                        let extras = if p == root {
                            self.top_layer.hoisted()
                        } else {
                            &[]
                        };
                        self.box_children
                            .rebuild(store, &self.top_layer, p, extras, &env);
                        if p == root {
                            self.full_layout_needed = true;
                        }
                        self.mark_dirty(store, p);
                    }
                }
            }
            self.was_transformed[idx] = has_store_transform(store, id);
            self.resolved_text[idx] = text;

            if store.is_inline_context_root(id) {
                let cenvs = &self.resolved_container_env;
                let lookup = |n: NodeId| committed_container_env(cenvs, n);
                let (para_layout_changed, _) = self.paragraphs.sync_inherited_paragraph(
                    store,
                    id,
                    parent_text,
                    parent_rtl,
                    interaction,
                    (self.responsive_node_count > 0).then_some(ResponsiveTextEnv {
                        media: &self.media_env,
                        container_env_of: &lookup,
                    }),
                );
                if idx < self.para_last_env_hash.len() {
                    self.para_last_env_hash[idx] = 0;
                }
                if dir_changed || para_layout_changed {
                    self.mark_dirty(store, id);
                }
                self.box_children.release(idx);
                continue;
            }
            if dir_changed {
                self.mark_dirty(store, id);
            }
            if id != root {
                if contents {
                    self.hoisted.release(idx);
                    self.box_children.release(idx);
                } else {
                    let env = display_env!(self, interaction);
                    self.box_children
                        .rebuild(store, &self.top_layer, id, &[], &env);
                }
            }

            for &child in store.children(id).iter().rev() {
                self.inherit_stack.push((child, rtl, text));
            }
        }
        // Root caches are cleared by `reshape_top_layer` whenever the hoisted set changes.
        if do_full && store.is_live(root) && !store.is_inline_context_root(root) {
            let env = display_env!(self, interaction);
            self.box_children
                .rebuild(store, &self.top_layer, root, self.top_layer.hoisted(), &env);
        }
        self.box_children.compact_if_fragmented();
        self.committed_store_rev = Some((store.instance_id(), store.frame()));
    }
}