nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Responsive (`@media` + `@container`) typography: which nodes carry responsive `Typography`
//! patches, and the exact cascade-then-inherit fold that resolves a paragraph root's effective
//! [`ResolvedTextStyle`] under a [`ResponsiveTextEnv`].

use nativeview_store::{NodeId, NodeStore, RowPatchView};
use nativeview_tables::container::{ContainerEnv, ContainerRules};
use nativeview_tables::media::MediaEnv;
use nativeview_tables::tables::{Responsive, ResponsiveRules, Typography};

use crate::measure::{ResolvedTextStyle, resolve_inherited_text};

use super::visit_node_responsive_patches;

/// Active responsive environment threaded into paragraph compilation: the `@media` environment
/// plus the `@container` environment each node resolves against.
#[derive(Clone, Copy)]
pub struct ResponsiveTextEnv<'a> {
    pub media: &'a MediaEnv,
    pub container_env_of: &'a dyn Fn(NodeId) -> ContainerEnv,
}

/// Most `Typography`/`Responsive`-bearing ancestors folded for one paragraph root; deeper chains
/// start the fold from the default style at the topmost recorded node.
const MAX_STYLED_ANCESTORS: usize = 128;

#[inline]
fn patch_touches_typography(pv: RowPatchView<'_>) -> bool {
    pv.has_table::<Typography>()
}

/// Returns `true` if `id` carries a `Responsive` rule patching any `Typography` property.
pub(crate) fn node_has_own_responsive_typo(store: &NodeStore, id: NodeId) -> bool {
    let Some(resp) = store.try_row::<Responsive>(id) else {
        return false;
    };
    let media = !resp.rules().is_none()
        && store
            .resource::<ResponsiveRules>(resp.rules())
            .is_some_and(|r| r.iter().any(|(_, pv)| patch_touches_typography(pv)));
    media
        || (!resp.container_rules().is_none()
            && store
                .resource::<ContainerRules>(resp.container_rules())
                .is_some_and(|r| r.iter().any(|(_, pv)| patch_touches_typography(pv))))
}

/// Returns `true` if paragraph root `pid` or any inline descendant carries a responsive
/// `Typography` patch. Zero allocations: inline subtrees deeper than the fixed stack answer
/// `true` (conservative: it only costs a scratch compile per measure).
pub(crate) fn paragraph_has_inline_responsive_typo(store: &NodeStore, pid: NodeId) -> bool {
    const CAP: usize = 64;
    if node_has_own_responsive_typo(store, pid) {
        return true;
    }
    let mut stack = [NodeId::NULL; CAP];
    let mut len = 0usize;
    for &c in store.children(pid) {
        if len == CAP {
            return true;
        }
        stack[len] = c;
        len += 1;
    }
    while len > 0 {
        len -= 1;
        let cur = stack[len];
        if !store.is_live(cur) {
            continue;
        }
        if node_has_own_responsive_typo(store, cur) {
            return true;
        }
        for &c in store.children(cur) {
            if len == CAP {
                return true;
            }
            stack[len] = c;
            len += 1;
        }
    }
    false
}

/// Applies every `Typography` property present in `pv` onto `style` (same validation as
/// [`resolve_inherited_text`]).
#[inline]
pub(crate) fn apply_patch_to_resolved_text_style(
    pv: RowPatchView<'_>,
    style: &mut ResolvedTextStyle,
) {
    if !pv.has_table::<Typography>() {
        return;
    }
    if let Some(c) = pv.get_prop(Typography::COLOR) {
        style.color = c;
    }
    if let Some(fs) = pv.get_prop(Typography::FONT_SIZE)
        && fs.is_finite()
        && fs >= 0.0
    {
        style.font_size = fs;
    }
    if let Some(lh) = pv.get_prop(Typography::LINE_HEIGHT)
        && (lh.is_auto() || (lh.value().is_finite() && lh.value() >= 0.0))
    {
        style.line_height = lh;
    }
    if let Some(ls) = pv.get_prop(Typography::LETTER_SPACING)
        && ls.is_finite()
    {
        style.letter_spacing = ls;
    }
    if let Some(ml) = pv.get_prop(Typography::MAX_LINES) {
        style.max_lines = ml.map_or(0, |nz| u32::from(nz.get()));
    }
    if let Some(fw) = pv.get_prop(Typography::FONT_WEIGHT) {
        style.font_weight = fw;
    }
    if let Some(st) = pv.get_prop(Typography::FONT_STYLE) {
        style.font_style = st;
    }
    if let Some(ws) = pv.get_prop(Typography::WHITE_SPACE) {
        style.white_space = ws;
    }
    if let Some(wb) = pv.get_prop(Typography::WORD_BREAK) {
        style.word_break = wb;
    }
    if let Some(ow) = pv.get_prop(Typography::OVERFLOW_WRAP) {
        style.overflow_wrap = ow;
    }
    if let Some(ta) = pv.get_prop(Typography::TEXT_ALIGN) {
        style.text_align = ta;
    }
    if let Some(td) = pv.get_prop(Typography::TEXT_DECORATION) {
        style.text_decoration = td;
    }
    if let Some(va) = pv.get_prop(Typography::VERTICAL_ALIGN) {
        style.vertical_align = va;
    }
}

/// Effective text style of `id` under `env`: `base -> @media -> @container` resolved on every
/// ancestor, then inherited, exactly like CSS cascade-then-inherit. When no ancestor-or-self
/// carries a `Responsive` row the fold is skipped and `resolve_inherited_text(parent_text)` is
/// returned unchanged.
pub(crate) fn responsive_inherited_text(
    store: &NodeStore,
    id: NodeId,
    parent_text: ResolvedTextStyle,
    env: ResponsiveTextEnv<'_>,
) -> ResolvedTextStyle {
    // Record only nodes that can change the fold (a `Typography` or `Responsive` row); all other
    // ancestors pass their parent's style through unchanged.
    let mut chain = [NodeId::NULL; MAX_STYLED_ANCESTORS];
    let mut len = 0usize;
    let mut any_responsive = false;
    let mut cur = Some(id);
    for _ in 0..crate::MAX_TREE_DEPTH {
        let Some(n) = cur else { break };
        let responsive = store.has::<Responsive>(n);
        if (responsive || store.has::<Typography>(n)) && len < MAX_STYLED_ANCESTORS {
            chain[len] = n;
            len += 1;
            any_responsive |= responsive;
        }
        cur = store.parent(n).filter(|&p| p != n);
    }
    if !any_responsive {
        return resolve_inherited_text(store, id, parent_text);
    }
    let mut style = ResolvedTextStyle::default();
    for &n in chain[..len].iter().rev() {
        style = resolve_inherited_text(store, n, style);
        if store.has::<Responsive>(n) {
            visit_node_responsive_patches(store, n, env.media, (env.container_env_of)(n), |_, pv| {
                apply_patch_to_resolved_text_style(pv, &mut style);
            });
        }
    }
    style
}

/// Recompile key of a responsive paragraph: the `MediaEnv` plus the committed `@container` env of
/// `pid` and of every `Responsive` ancestor whose typography it may inherit.
pub(crate) fn paragraph_env_hash(
    store: &NodeStore,
    pid: NodeId,
    media_signature: u64,
    container_env_of: &dyn Fn(NodeId) -> ContainerEnv,
) -> u64 {
    let mut chain = super::container_env_hash(0, container_env_of(pid));
    let mut cur = store.parent(pid).filter(|&p| p != pid);
    for _ in 0..crate::MAX_TREE_DEPTH {
        let Some(n) = cur else { break };
        if store.has::<Responsive>(n) {
            chain = super::container_env_hash(chain, container_env_of(n));
        }
        cur = store.parent(n).filter(|&p| p != n);
    }
    super::env_hash(media_signature, chain)
}

/// Responsive paragraphs compiled under a live layout env (the committed store holds the runs
/// of the last committed env), each compiled once per env and pass: Taffy measures a paragraph
/// several times per pass under the same env.
#[derive(Debug, Default)]
pub(crate) struct MeasureParagraphs {
    pub(crate) store: crate::ParagraphStore,
    /// Per paragraph root: `(pass_gen, env_key)` its scratch runs were compiled under.
    compiled: super::super::container::scope::GenSlots<(u64, u64)>,
    pass_gen: u64,
}

impl MeasureParagraphs {
    /// Advances the pass epoch in O(1) so base-row edits invalidate scratch compiles without
    /// sweeping every node slot.
    pub(crate) fn begin_pass(&mut self, cap: usize) {
        self.compiled.ensure_len(cap);
        self.pass_gen = self.pass_gen.wrapping_add(1);
        if self.pass_gen == 0 {
            self.compiled.reset_all();
            self.pass_gen = 1;
        }
    }

    /// Whether `pid` still needs compiling under `env_key`; records it as compiled.
    pub(crate) fn needs_compile(&mut self, pid: NodeId, env_key: u64) -> bool {
        let key = (self.pass_gen, env_key);
        if self.compiled.get(pid) == Some(key) {
            return false;
        }
        self.compiled.set(pid, key);
        true
    }

    pub(crate) fn reset(&mut self) {
        self.store.reset();
        self.compiled.release();
        self.pass_gen = 0;
    }
}