nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! The post-layout commit walk: fused cumulative rounding, absolute origin accumulation, and the
//! committed `@container` env of every box (honoring containing-block hoisting for
//! `position: absolute | fixed`, whose `@container` env still follows the flat-tree ancestor).

use nativeview_engine::{InteractionTracker, LayoutRect};
use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::container::ContainerEnv;
use nativeview_tables::tables::{ContainerType, Display as NvDisplay, Layout as NvLayout};

use crate::ResolvedBoxEdges;
use crate::scene::{EffectiveBox, NoResponsivePatches, StyleCascade};

use super::container::scope::{ContainerRecord, ContainerScope, PaddingBorder, scope_of};
use super::responsive::PassPatches;
use super::responsive::sync::NodeStyleFlags;
use super::{TaffyStoreLayout, UnroundedBox, gen_tag};

#[inline(always)]
fn same_rect_bits(a: LayoutRect, b: LayoutRect) -> bool {
    a.x.to_bits() == b.x.to_bits()
        && a.y.to_bits() == b.y.to_bits()
        && a.width.to_bits() == b.width.to_bits()
        && a.height.to_bits() == b.height.to_bits()
}

/// One pending node of the commit walk.
#[derive(Debug, Clone, Copy)]
pub(super) struct RoundFrame {
    id: NodeId,
    /// Absolute origin of the parent box (unrounded).
    px: f32,
    py: f32,
    ancestor_hidden: bool,
    /// Container scope inherited from the in-flow parent.
    scope: ContainerScope,
    /// Hoisted to a containing block: resolve the env from the flat-tree ancestor instead.
    hoisted: bool,
}

impl TaffyStoreLayout {
    /// `id`'s [`EffectiveBox`] under its in-pass `@container` env `cenv` (the shared
    /// [`StyleCascade`], live pseudo-state included), fast-pathing plain nodes that have neither
    /// `Responsive` rows nor box-patching `StateRules`.
    #[inline]
    fn box_of(
        &self,
        store: &NodeStore,
        id: NodeId,
        cenv: ContainerEnv,
        interaction: Option<&InteractionTracker>,
    ) -> EffectiveBox {
        let flags = self
            .style_flags
            .get(id.index())
            .copied()
            .unwrap_or(NodeStyleFlags::empty());
        let needs_resp =
            self.responsive_node_count > 0 && flags.contains(NodeStyleFlags::RESPONSIVE);
        let needs_state =
            interaction.is_some() && flags.contains(NodeStyleFlags::HAS_STATE_BOX_PATCH);
        if !needs_resp && !needs_state {
            let mut effective =
                EffectiveBox::from_layout(store, id, store.try_row::<NvLayout>(id), false);
            if effective.display == NvDisplay::None {
                effective.container_type = ContainerType::Normal;
            }
            return effective;
        }
        let pass = PassPatches {
            media: &self.media_env,
            container_env: cenv,
        };
        let responsive: &dyn crate::scene::ResponsivePatches = if needs_resp {
            &pass
        } else {
            &NoResponsivePatches
        };
        StyleCascade {
            responsive,
            interaction: needs_state.then_some(interaction).flatten(),
            inert: None,
        }
        .effective_box(store, id)
    }

    /// Rounds every box of `root`'s tree into `rects`, records exact `changed_rects`, and commits
    /// each box's `@container` env and relayout-boundary origin. Returns whether any committed
    /// `@container` env changed.
    pub(super) fn commit_round_pass(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        interaction: Option<&InteractionTracker>,
    ) -> bool {
        self.changed_rects.clear();
        self.all_rects_changed = false;
        let prev_valid_gen = self.rect_valid_gen;
        self.layout_gen = self.layout_gen.wrapping_add(1).max(1);
        self.rect_valid_gen = self.layout_gen;
        let cur_valid_gen = self.rect_valid_gen;
        self.commit_round_walk(
            store,
            root,
            RoundFrame {
                id: root,
                px: 0.0,
                py: 0.0,
                ancestor_hidden: false,
                scope: ContainerScope::default(),
                hoisted: false,
            },
            prev_valid_gen,
            cur_valid_gen,
            interaction,
        )
    }

    /// Rounds one relayout containment boundary subtree starting at `boundary` without bumping
    /// `rect_valid_gen`, appending exact rect deltas into `self.changed_rects`.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn commit_round_boundary(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        boundary: NodeId,
        parent_origin: (f32, f32),
        enclosing_scope: ContainerScope,
        hoisted: bool,
        interaction: Option<&InteractionTracker>,
    ) -> bool {
        let valid_gen = self.rect_valid_gen;
        self.commit_round_walk(
            store,
            root,
            RoundFrame {
                id: boundary,
                px: parent_origin.0,
                py: parent_origin.1,
                ancestor_hidden: false,
                scope: enclosing_scope,
                hoisted,
            },
            valid_gen,
            valid_gen,
            interaction,
        )
    }

    fn commit_round_walk(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        start: RoundFrame,
        prev_valid_gen: u64,
        cur_valid_gen: u64,
        interaction: Option<&InteractionTracker>,
    ) -> bool {
        let mut envs_changed = false;
        let any_cont = self.container_node_count > 0;
        self.round_stack.clear();
        self.round_stack.push(start);
        while let Some(f) = self.round_stack.pop() {
            let id = f.id;
            if !store.is_live(id) || store.is_inline(id) {
                continue;
            }
            let idx = id.index();
            let scope = if f.hoisted && any_cont {
                scope_of(store, &self.container_records, id)
            } else {
                f.scope
            };
            let cenv = scope.env;
            if any_cont {
                envs_changed |= self.resolved_container_env.get(id) != Some(cenv);
                self.resolved_container_env.set(id, cenv);
            }
            let effective = self.box_of(store, id, cenv, interaction);
            let is_contents = id != root && effective.is_contents();
            let is_hidden_self = effective.is_none();
            let ct = if any_cont {
                effective.container_type
            } else {
                ContainerType::Normal
            };

            // `display: contents` generates no box: a zero rect at the parent origin, which its
            // children (laid out by Taffy as the parent's) inherit unchanged.
            let b = if is_contents {
                if self.capture_box_edges && idx < self.box_edges.len() {
                    self.box_edges[idx] = ResolvedBoxEdges::default();
                }
                UnroundedBox::default()
            } else {
                self.boxes[idx]
            };
            let cx = f.px + b.x;
            let cy = f.py + b.y;
            let rx = cx.round();
            let ry = cy.round();
            let new_rect = LayoutRect {
                x: rx,
                y: ry,
                width: (cx + b.w).round() - rx,
                height: (cy + b.h).round() - ry,
            };
            let tag = gen_tag(id);
            let was_valid = prev_valid_gen != 0
                && self.rect_gen[idx] == prev_valid_gen
                && self.node_gens[idx] == tag;
            if !was_valid || !same_rect_bits(self.rects[idx], new_rect) {
                self.changed_rects.push(id);
            }
            self.rects[idx] = new_rect;
            self.rect_gen[idx] = cur_valid_gen;
            self.node_gens[idx] = tag;

            let hidden = f.ancestor_hidden || is_hidden_self;
            // A box-generating container's committed env is its final content box: final
            // border box minus the padding + border its layout recorded.
            let child_scope = if !any_cont {
                scope
            } else if !hidden && !is_contents && ct != ContainerType::Normal {
                let padding_border = self
                    .container_records
                    .get(id)
                    .map_or(PaddingBorder::default(), |r| r.padding_border);
                let inner = scope.nested(ct, b.w, b.h, padding_border);
                self.container_records.set(
                    id,
                    ContainerRecord {
                        inner,
                        padding_border,
                    },
                );
                if self.size_container_count > 0 && ct == ContainerType::Size && id != root {
                    if let Some(mut rec) = self.boundary_records.get(id) {
                        rec.parent_origin = (f.px, f.py);
                        rec.hoisted = f.hoisted;
                        rec.round_valid = rec.layout_valid && rec.layout.definite_size;
                        self.boundary_records.set(id, rec);
                    }
                } else if self.size_container_count > 0 {
                    self.boundary_records.clear_slot(idx);
                }
                inner
            } else {
                self.container_records.clear_slot(idx);
                self.boundary_records.clear_slot(idx);
                scope
            };

            if !hidden {
                for &child in self.hoisted.get(idx).iter().rev() {
                    if store.is_live(child) {
                        self.round_stack.push(RoundFrame {
                            id: child,
                            px: cx,
                            py: cy,
                            ancestor_hidden: false,
                            scope: child_scope,
                            hoisted: true,
                        });
                    }
                }
                // A top-layer root that became `display: none` during this pass (e.g. via an
                // `@container` rule on the overlay itself) is omitted from Taffy's `hoisted[root]`
                // yet still skipped in its DOM parent until `refresh_top_layer_after_pass` runs.
                // Visit it here so its `resolved_container_env` updates and un-hoisting converges.
                if id == root && !self.top_layer.hoisted().is_empty() {
                    let root_hoisted = self.hoisted.get(idx);
                    for &ov in self.top_layer.hoisted().iter().rev() {
                        if store.is_live(ov) && !root_hoisted.contains(&ov) {
                            self.round_stack.push(RoundFrame {
                                id: ov,
                                px: cx,
                                py: cy,
                                ancestor_hidden: true,
                                scope: child_scope,
                                hoisted: true,
                            });
                        }
                    }
                }
            }
            if !store.is_inline_context_root(id) {
                for &child in store.children(id).iter().rev() {
                    // Open overlays hoisted to the root are reached through the root's hoisted
                    // list (their origin is the viewport, not this parent). Guard the OOF check
                    // behind `NodeStyleFlags::OUT_OF_FLOW` so ~98% in-flow children skip `box_of`.
                    let may_oof = self
                        .style_flags
                        .get(child.index())
                        .is_some_and(|fl| fl.contains(NodeStyleFlags::OUT_OF_FLOW));
                    if self.top_layer.is_hoisted(child)
                        || (!hidden
                            && may_oof
                            && self
                                .box_of(store, child, child_scope.env, interaction)
                                .is_out_of_flow())
                    {
                        continue;
                    }
                    self.round_stack.push(RoundFrame {
                        id: child,
                        px: cx,
                        py: cy,
                        ancestor_hidden: hidden,
                        scope: child_scope,
                        hoisted: false,
                    });
                }
            }
        }
        envs_changed
    }
}