nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! `display: contents` for the Taffy adapter. Taffy 0.16 has no `Display::Contents`, so a parent
//! whose children include contents nodes exposes Taffy a flattened box-children list: every
//! contents child is replaced, recursively and in document order, by its own children. Contents
//! nodes are never laid out; the rounding pass passes their parent's origin straight through.

use nativeview_store::{NodeId, NodeStore};
use super::node::NodeLists;

#[cfg(test)]
mod tests;
use crate::{DisplayEnv, TopLayerIndex};

/// Box children of every parent with at least one `display: contents` child.
#[derive(Debug, Default)]
pub(crate) struct BoxChildren {
    lists: NodeLists,
    /// `true` when the parent's box children differ from `NodeStore::children` (read `lists`).
    flattened: Vec<bool>,
    /// The parent whose list ends with hoisted top-layer roots, and how many (the layout root).
    extras: Option<(NodeId, usize)>,
    /// Reused DFS stack of the flattening walk.
    stack: Vec<NodeId>,
    /// Reused flattened output, written to `lists` in one exact-length `extend`.
    out: Vec<NodeId>,
}

impl BoxChildren {
    pub(crate) fn ensure_len(&mut self, len: usize) {
        self.lists.ensure_len(len);
        if self.flattened.len() < len {
            self.flattened.resize(len, false);
        }
    }

    pub(crate) fn reset(&mut self) {
        self.lists.reset();
        self.flattened.clear();
        self.extras = None;
        self.stack.clear();
        self.out.clear();
    }

    #[cfg(test)]
    pub(crate) fn list_capacity(&self, parent: NodeId) -> usize {
        self.lists.capacity_of(parent.index())
    }

    #[cfg(test)]
    pub(crate) fn dead_slots(&self) -> usize {
        self.lists.dead_slots()
    }

    /// Pool accounting invariant of the underlying lists; unflattened parents own no capacity.
    #[cfg(test)]
    pub(crate) fn assert_consistent(&self) {
        self.lists.assert_consistent();
        for (idx, &flat) in self.flattened.iter().enumerate() {
            assert!(
                flat || self.lists.capacity_of(idx) == 0,
                "unflattened parent {idx} pins list capacity"
            );
        }
    }

    /// Forgets `idx`'s list (node slot created or removed).
    pub(crate) fn release(&mut self, idx: usize) {
        self.lists.release(idx);
        if let Some(f) = self.flattened.get_mut(idx) {
            *f = false;
        }
        if self.extras.is_some_and(|(p, _)| p.index() == idx) {
            self.extras = None;
        }
    }

    /// Recomputes `parent`'s box children from the live tree, omitting top-layer roots hoisted
    /// to the layout root and appending `extra_children` (the hoisted roots, on the root only).
    /// `env` (the engine's committed effective-display inputs) decides which children are `contents`.
    pub(crate) fn rebuild(
        &mut self,
        store: &NodeStore,
        top_layer: &TopLayerIndex,
        parent: NodeId,
        extra_children: &[NodeId],
        env: &DisplayEnv<'_>,
    ) {
        let idx = parent.index();
        if self.extras.is_some_and(|(p, _)| p == parent) {
            self.extras = None;
        }
        // Paragraph roots are box leaves: their children are inline runs compiled into
        // `ParagraphStore`, never Taffy boxes (`[INV:inline-zero-boxes]`).
        if store.is_inline_context_root(parent) {
            if self.flattened.get(idx).copied().unwrap_or(false) {
                self.release(idx);
            }
            return;
        }
        let children = store.children(parent);
        let flatten = !extra_children.is_empty()
            || children.iter().any(|&c| {
                env.is_display_contents(store, c)
                    || store.is_inline(c)
                    || top_layer.is_hoisted(c)
            });
        if !flatten {
            // Return the capacity: a parent that stops flattening must not pin its peak list.
            if self.flattened.get(idx).copied().unwrap_or(false) {
                self.release(idx);
            }
            return;
        }
        let Some(flag) = self.flattened.get_mut(idx) else {
            return;
        };
        *flag = true;
        self.out.clear();
        self.stack.clear();
        self.stack.extend(children.iter().rev());
        while let Some(child) = self.stack.pop() {
            if store.is_inline(child) {
                continue;
            }
            if env.is_display_contents(store, child) {
                if !store.is_inline_context_root(child) {
                    self.stack.extend(store.children(child).iter().rev());
                }
            } else if !top_layer.is_hoisted(child) {
                self.out.push(child);
            }
        }
        self.out.extend_from_slice(extra_children);
        if !extra_children.is_empty() {
            self.extras = Some((parent, extra_children.len()));
        }
        self.lists.clear(idx);
        self.lists.extend(idx, self.out.iter().copied());
    }

    /// Whether `parent` exposes a flattened list (some child is `display: contents`).
    #[inline]
    pub(crate) fn is_flattened(&self, parent: NodeId) -> bool {
        self.flattened.get(parent.index()).copied().unwrap_or(false)
    }

    /// Repacks the list pool once rebuilds have fragmented it.
    pub(crate) fn compact_if_fragmented(&mut self) {
        self.lists.compact_if_fragmented();
    }

    /// The children Taffy lays out under `parent`.
    #[inline]
    pub(crate) fn get<'a>(&'a self, store: &'a NodeStore, parent: NodeId) -> &'a [NodeId] {
        if store.is_inline_context_root(parent) {
            &[]
        } else if self.is_flattened(parent) {
            self.lists.get(parent.index())
        } else {
            store.children(parent)
        }
    }

    /// [`Self::get`] without the hoisted top-layer roots appended to the layout root, so
    /// intrinsic sizing reuses committed lists while floating overlays never inflate it.
    #[inline]
    pub(crate) fn get_in_flow<'a>(&'a self, store: &'a NodeStore, parent: NodeId) -> &'a [NodeId] {
        let all = self.get(store, parent);
        match self.extras {
            Some((p, n)) if p == parent && self.is_flattened(parent) => {
                &all[..all.len().saturating_sub(n)]
            }
            _ => all,
        }
    }
}