nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Style inputs and stacking-context classification shared by [`super::StackingPlan`] and
//! backend `COMPOSITE` fast paths.

use std::cell::Cell;

use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::tables::{
    Display, Interaction, Isolation, Overflow, Position, Scroll, TextContent, is_closed_overlay,
    is_translucent_opacity,
};
use nativeview_tables::transform::Transform2D;

use crate::MAX_TREE_DEPTH;

use super::StackingBucket;
use super::super::style_cascade::{ResponsivePatches, StackingStyle, StyleCascade};

/// Effective style inputs consulted by [`super::StackingPlan::build`] (allowing backends to layer
/// `StateRules` and live animation overrides such as `MotionDriver` opacity/transform).
pub trait StackingStyleSource {
    fn is_display_none(&self, store: &NodeStore, id: NodeId) -> bool;
    fn is_display_contents(&self, store: &NodeStore, id: NodeId) -> bool;
    fn display_of(&self, store: &NodeStore, id: NodeId) -> Display;
    fn position_of(&self, store: &NodeStore, id: NodeId) -> Position;
    fn z_index_of(&self, store: &NodeStore, id: NodeId) -> Option<i32>;
    fn opacity_of(&self, store: &NodeStore, id: NodeId) -> f32;
    fn isolation_of(&self, store: &NodeStore, id: NodeId) -> Isolation;
    fn has_transform(&self, store: &NodeStore, id: NodeId) -> bool;
    fn visibility_hidden(&self, store: &NodeStore, id: NodeId, inherited_hidden: bool) -> bool;
    fn clips_overflow(&self, store: &NodeStore, id: NodeId) -> bool;
    fn is_scrollable(&self, store: &NodeStore, id: NodeId) -> bool;
}

/// Live animation overrides (transform & opacity) layered onto [`SceneStackingStyleSource`].
/// Any transform closure `Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>` implements this
/// with identity opacity.
pub trait StackingOverrides {
    fn resolve_transform(&self, id: NodeId, base: Option<Transform2D>) -> Option<Transform2D>;

    #[inline]
    fn resolve_opacity(&self, _id: NodeId, base: f32) -> f32 {
        base
    }
}

impl<F: Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>> StackingOverrides for F {
    #[inline]
    fn resolve_transform(&self, id: NodeId, base: Option<Transform2D>) -> Option<Transform2D> {
        (self)(id, base)
    }
}

/// The scene's [`StyleCascade`] (base -> `@media` -> `@container` -> state rules) + optional
/// animated transform/opacity overrides. Every accessor reads one [`StackingStyle`] per node: the
/// builder asks a node for ~10 properties in a row, so the last node's style is kept.
pub struct SceneStackingStyleSource<'a, F, R: ResponsivePatches + ?Sized = dyn ResponsivePatches> {
    cascade: StyleCascade<'a, R>,
    overrides: F,
    last: Cell<Option<(NodeId, StackingStyle)>>,
}

impl<'a, F, R: ResponsivePatches + ?Sized> SceneStackingStyleSource<'a, F, R> {
    #[inline]
    pub fn new(cascade: StyleCascade<'a, R>, overrides: F) -> Self {
        Self {
            cascade,
            overrides,
            last: Cell::new(None),
        }
    }

    #[inline]
    fn style(&self, store: &NodeStore, id: NodeId) -> StackingStyle {
        if let Some((last_id, style)) = self.last.get()
            && last_id == id
        {
            return style;
        }
        let style = self.cascade.stacking_style(store, id);
        self.last.set(Some((id, style)));
        style
    }
}

impl<F: StackingOverrides, R: ResponsivePatches + ?Sized> StackingStyleSource
    for SceneStackingStyleSource<'_, F, R>
{
    #[inline]
    fn is_display_none(&self, store: &NodeStore, id: NodeId) -> bool {
        !store.is_live(id) || self.display_of(store, id) == Display::None
    }

    #[inline]
    fn is_display_contents(&self, store: &NodeStore, id: NodeId) -> bool {
        id != NodeId::ROOT && store.is_live(id) && self.display_of(store, id) == Display::Contents
    }

    #[inline]
    fn display_of(&self, store: &NodeStore, id: NodeId) -> Display {
        self.style(store, id).display
    }

    #[inline]
    fn position_of(&self, store: &NodeStore, id: NodeId) -> Position {
        self.style(store, id).position
    }

    #[inline]
    fn z_index_of(&self, store: &NodeStore, id: NodeId) -> Option<i32> {
        self.style(store, id).z_index
    }

    #[inline]
    fn opacity_of(&self, store: &NodeStore, id: NodeId) -> f32 {
        self.overrides.resolve_opacity(id, self.style(store, id).opacity)
    }

    #[inline]
    fn isolation_of(&self, store: &NodeStore, id: NodeId) -> Isolation {
        self.style(store, id).isolation
    }

    #[inline]
    fn has_transform(&self, store: &NodeStore, id: NodeId) -> bool {
        self.overrides
            .resolve_transform(id, self.style(store, id).transform)
            .is_some_and(|t| !t.is_identity())
    }

    #[inline]
    fn visibility_hidden(&self, store: &NodeStore, id: NodeId, inherited_hidden: bool) -> bool {
        self.style(store, id)
            .visibility
            .map_or(inherited_hidden, |v| v.resolve(inherited_hidden))
    }

    #[inline]
    fn clips_overflow(&self, store: &NodeStore, id: NodeId) -> bool {
        if store.has::<Scroll>(id) {
            return true;
        }
        let s = self.style(store, id);
        let clips = |o: Overflow| matches!(o, Overflow::Hidden | Overflow::Scroll | Overflow::Auto);
        s.overflow_x.is_some_and(clips) || s.overflow_y.is_some_and(clips)
    }

    #[inline]
    fn is_scrollable(&self, store: &NodeStore, id: NodeId) -> bool {
        if store.has::<Scroll>(id) {
            return true;
        }
        let s = self.style(store, id);
        let scrollable = |o: Overflow| matches!(o, Overflow::Scroll | Overflow::Auto);
        s.overflow_x.is_some_and(scrollable) || s.overflow_y.is_some_and(scrollable)
    }
}

/// Maps a real stacking context's effective `z_index` to its CSS 2.1 Appendix E bucket.
#[inline]
pub const fn bucket_for_sc_z(z: i32) -> StackingBucket {
    if z < 0 {
        StackingBucket::NegSc
    } else if z == 0 {
        StackingBucket::Step8
    } else {
        StackingBucket::PosSc
    }
}

/// Classifies stacking-context creation and effective `z_index` for `id` given its nearest box
/// ancestor's `Display` mode. Single source of truth shared by `StackingPlan::build` and Skia's
/// `COMPOSITE` fast path.
#[inline]
pub fn classify_node_sc_with_parent_display<S: StackingStyleSource>(
    store: &NodeStore,
    style: &S,
    id: NodeId,
    box_parent_display: Display,
    is_top_layer_root: bool,
) -> (bool, i32, bool, Position, Display) {
    let pos = style.position_of(store, id);
    let display = style.display_of(store, id);
    let is_positioned = pos != Position::Static;
    let parent_is_flex_or_grid = matches!(
        box_parent_display,
        Display::Flex | Display::InlineFlex | Display::Grid
    );
    let z_applies = is_positioned || parent_is_flex_or_grid;
    let eff_z = if z_applies {
        style.z_index_of(store, id)
    } else {
        None
    };
    let has_transform = style.has_transform(store, id);
    let creates_sc = id == NodeId::ROOT
        || is_top_layer_root
        || eff_z.is_some()
        || matches!(pos, Position::Fixed | Position::Sticky)
        || is_translucent_opacity(style.opacity_of(store, id))
        || has_transform
        || style.isolation_of(store, id) == Isolation::Isolate
        || store
            .node_tables(id)
            .intersects(store.stacking_context_tables());
    (creates_sc, eff_z.unwrap_or(0), has_transform, pos, display)
}

/// Resolves `(creates_sc, sc_z, has_transform)` for `id` by walking past any `display: contents`
/// ancestors to obtain `box_parent_display`.
pub fn resolve_node_sc_state<S: StackingStyleSource>(
    store: &NodeStore,
    style: &S,
    id: NodeId,
    is_top_layer_root: bool,
) -> (bool, i32, bool) {
    let box_parent_display = if id == NodeId::ROOT || is_top_layer_root {
        Display::Block
    } else {
        let mut cur = store.parent(id);
        let mut parent_display = Display::Block;
        for _ in 0..MAX_TREE_DEPTH {
            let Some(p) = cur else {
                break;
            };
            if !style.is_display_contents(store, p) {
                parent_display = style.display_of(store, p);
                break;
            }
            cur = store.parent(p).filter(|&gp| gp != p);
        }
        parent_display
    };
    let (creates_sc, sc_z, has_transform, _, _) = classify_node_sc_with_parent_display(
        store,
        style,
        id,
        box_parent_display,
        is_top_layer_root,
    );
    (creates_sc, sc_z, has_transform)
}

/// Snapshot of a box node's stacking, clip, scroll, and visibility structural role used by
/// retained incremental layout/paragraph fast paths to verify `StackingPlan` invariance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StackingNodeRole {
    pub absent: bool,
    pub position: Position,
    pub display: Display,
    pub is_real_sc: bool,
    pub sc_z: i32,
    pub has_transform: bool,
    pub clips_children: bool,
    pub has_scroll_table: bool,
    pub is_scrollable: bool,
    pub effective_hidden: bool,
    pub has_text_split: bool,
}

impl StackingNodeRole {
    /// Resolves `id`'s current structural role under `style` and `parent_hidden`.
    ///
    /// Runs `resolve_node_sc_state` first (which inspects the box parent before `id`) so `id`
    /// stays hot in `SceneStackingStyleSource`'s 1-entry cache for every remaining query.
    pub fn resolve<S: StackingStyleSource>(
        store: &NodeStore,
        style: &S,
        id: NodeId,
        is_top_layer: bool,
        parent_hidden: bool,
    ) -> Self {
        let (is_real_sc, sc_z, has_transform) =
            resolve_node_sc_state(store, style, id, is_top_layer);
        let is_contents = style.is_display_contents(store, id);
        let absent = style.is_display_none(store, id)
            || is_closed_overlay(store, id)
            || (!is_top_layer && is_contents);
        let position = style.position_of(store, id);
        let display = style.display_of(store, id);
        let has_scroll_table = store.has::<Scroll>(id);
        Self {
            absent,
            position,
            display,
            is_real_sc,
            sc_z,
            has_transform,
            clips_children: !is_contents && style.clips_overflow(store, id),
            has_scroll_table,
            is_scrollable: has_scroll_table || style.is_scrollable(store, id),
            effective_hidden: style.visibility_hidden(store, id, parent_hidden),
            has_text_split: store.has::<TextContent>(id)
                || store
                    .try_row::<Interaction>(id)
                    .is_some_and(|i| i.captures_text_keys()),
        }
    }
}