nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Query-container scopes: what a node's `@container` rules resolve against, the cache-key chain
//! hash covering every enclosing container, and the generation-stamped per-node tables they are
//! recorded in.
//!
//! There is no explicit container stack: layout keeps one [`ActiveContainer`] frame and saves the
//! previous one on the Rust call stack while a container's children lay out (zero heap, no depth
//! cap). Ancestors and out-of-flow boxes find their scope through one flat-tree walk over the
//! per-container [`ContainerRecord`]s ([`nearest_container_record`]).

use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::container::ContainerEnv;
use nativeview_tables::tables::ContainerType;

use crate::MAX_TREE_DEPTH;

use super::super::responsive::container_env_hash;

/// Occupancy tag of a [`GenSlots`] slot: `EMPTY`, or the writing node's generation + 1 (node
/// generations start at 0, so the generation alone cannot double as the empty marker).
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct SlotTag(u16);

impl SlotTag {
    const EMPTY: Self = Self(0);

    #[inline(always)]
    fn of(id: NodeId) -> Self {
        Self(u16::from(id.generation()) + 1)
    }
}

/// Dense per-node values stamped with the node generation that wrote them, so a recycled slot
/// never reads a removed node's value and an unset slot never reads as a value.
#[derive(Debug, Clone, Default)]
pub(crate) struct GenSlots<T: Copy + Default> {
    slots: Vec<(SlotTag, T)>,
}

impl<T: Copy + Default> GenSlots<T> {
    #[inline]
    pub(crate) fn get(&self, id: NodeId) -> Option<T> {
        self.slots
            .get(id.index())
            .filter(|(tag, _)| *tag == SlotTag::of(id))
            .map(|&(_, v)| v)
    }

    #[inline]
    pub(crate) fn set(&mut self, id: NodeId, value: T) {
        if let Some(slot) = self.slots.get_mut(id.index()) {
            *slot = (SlotTag::of(id), value);
        }
    }

    /// Forgets the value at slot `index` regardless of generation.
    #[inline]
    pub(crate) fn clear_slot(&mut self, index: usize) {
        if let Some(slot) = self.slots.get_mut(index) {
            *slot = (SlotTag::EMPTY, T::default());
        }
    }

    #[inline]
    pub(crate) fn ensure_len(&mut self, cap: usize) {
        if self.slots.len() < cap {
            self.slots.resize(cap, (SlotTag::EMPTY, T::default()));
        }
    }

    #[inline]
    pub(crate) fn len(&self) -> usize {
        self.slots.len()
    }

    #[inline]
    pub(crate) fn reset_all(&mut self) {
        self.slots.fill((SlotTag::EMPTY, T::default()));
    }

    #[inline]
    pub(crate) fn release(&mut self) {
        self.slots.clear();
    }
}

#[cfg(test)]
mod gen_slots_tests {
    use super::GenSlots;
    use nativeview_store::NodeStore;

    #[test]
    fn unset_and_cleared_slots_never_read_as_generation_zero_values() {
        let mut store = NodeStore::new();
        let id = {
            let mut tx = store.tx();
            let id = tx.create();
            tx.commit_into(&mut nativeview_store::ChangeSet::default());
            id
        };
        assert_eq!(id.generation(), 0, "fresh nodes start at generation 0");
        let mut slots = GenSlots::<u32>::default();
        slots.ensure_len(store.capacity());
        assert_eq!(slots.get(id), None, "unset slot");
        slots.set(id, 7);
        assert_eq!(slots.get(id), Some(7));
        slots.clear_slot(id.index());
        assert_eq!(slots.get(id), None, "cleared slot");
        slots.set(id, 9);
        slots.reset_all();
        assert_eq!(slots.get(id), None, "reset slot");
    }
}

/// A container's resolved `padding + border` widths along both axes.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(crate) struct PaddingBorder {
    pub(crate) x: f32,
    pub(crate) y: f32,
}

/// What descendants of a point in the tree resolve `@container` rules against, plus a chain hash
/// folding every enclosing container's env (the O(1) cache key of responsive subtrees).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(crate) struct ContainerScope {
    pub(crate) env: ContainerEnv,
    pub(crate) chain: u64,
}

impl ContainerScope {
    /// The scope inside a `ct` container with border box `(w, h)` sitting in `self`.
    #[inline]
    pub(crate) fn nested(self, ct: ContainerType, w: f32, h: f32, pb: PaddingBorder) -> Self {
        if ct == ContainerType::Normal {
            return self;
        }
        let env = self
            .env
            .nested(ct, (w - pb.x).max(0.0), (h - pb.y).max(0.0));
        Self {
            env,
            chain: container_env_hash(self.chain, env),
        }
    }
}

/// Per box-generating container: the scope its descendants see and the padding+border its own
/// layout resolved (exact under percentage padding, which resolves against the containing block).
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct ContainerRecord {
    pub(crate) inner: ContainerScope,
    pub(crate) padding_border: PaddingBorder,
}

/// The innermost container whose children are being laid out, and the scope it itself sees
/// (a container never queries itself).
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct ActiveContainer {
    pub(crate) owner: NodeId,
    pub(crate) inner: ContainerScope,
    pub(crate) enclosing: ContainerScope,
}

impl ActiveContainer {
    pub(crate) const ROOT: Self = Self {
        owner: NodeId::NULL,
        inner: ContainerScope {
            env: ContainerEnv::NONE,
            chain: 0,
        },
        enclosing: ContainerScope {
            env: ContainerEnv::NONE,
            chain: 0,
        },
    };

    #[inline]
    pub(crate) fn scope_for(&self, id: NodeId) -> ContainerScope {
        if self.owner == id && !id.is_null() {
            self.enclosing
        } else {
            self.inner
        }
    }

    /// The frame active while `owner`'s children lay out.
    #[inline]
    pub(crate) fn entering(&self, owner: NodeId, inner: ContainerScope) -> Self {
        Self {
            owner,
            inner,
            enclosing: self.scope_for(owner),
        }
    }

    /// A frame for a box positioned outside its flat-tree ancestors' layout (out-of-flow).
    #[inline]
    pub(crate) const fn detached(scope: ContainerScope) -> Self {
        Self {
            owner: NodeId::NULL,
            inner: scope,
            enclosing: scope,
        }
    }
}

/// The scope `id` resolves `@container` rules against: its nearest flat-tree ancestor container's
/// recorded inner scope (CSS queries follow the flat tree, never the containing block).
pub(crate) fn nearest_container_record(
    store: &NodeStore,
    records: &GenSlots<ContainerRecord>,
    id: NodeId,
) -> Option<ContainerRecord> {
    let mut cur = store.parent(id).filter(|&p| p != id);
    for _ in 0..MAX_TREE_DEPTH {
        let anc = cur?;
        if let Some(rec) = records.get(anc) {
            return Some(rec);
        }
        cur = store.parent(anc).filter(|&p| p != anc);
    }
    None
}

#[inline]
pub(crate) fn scope_of(
    store: &NodeStore,
    records: &GenSlots<ContainerRecord>,
    id: NodeId,
) -> ContainerScope {
    nearest_container_record(store, records, id).map_or(ContainerScope::default(), |r| r.inner)
}

/// Committed env a node resolved its `@container` rules against (`NONE` when stale/unset).
#[inline]
pub(crate) fn committed_container_env(envs: &GenSlots<ContainerEnv>, id: NodeId) -> ContainerEnv {
    envs.get(id).unwrap_or(ContainerEnv::NONE)
}