nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Dense zero-steady-state-allocation per-node dirty & paint-flash heat tracker.
//!
//! Lives inside `Option<Box<InspectorState>>` on backends so disabled frames allocate 0 bytes.

use nativeview_store::NodeId;

use super::{DEFAULT_FLASH_TTL, MAX_FLASH_RECTS, SceneDirtyKind};

/// Flag bit in [`NodeHeat::flags`]: slot has been populated for a live `NodeId` (disambiguates
/// untouched/removed slots from live `generation == 0` nodes).
pub const NODE_HEAT_OCCUPIED: u8 = 1 << 0;
/// Flag bit in [`NodeHeat::flags`]: slot index is currently tracked in
/// [`InspectorHeatTracker::active_flashes`].
pub const NODE_HEAT_FLASHING: u8 = 1 << 1;

/// Dense per-node dirty/paint heat slot indexed by `NodeId::index()` (16 B `Copy` POD).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NodeHeat {
    pub generation: u8,
    pub last_kind: u8,
    pub ttl_frames: u8,
    /// Bitmask of [`NODE_HEAT_OCCUPIED`] | [`NODE_HEAT_FLASHING`].
    pub flags: u8,
    pub dirty_commits: u32,
    pub paint_reemits: u32,
    pub layout_commits: u32,
}

impl NodeHeat {
    #[inline]
    pub const fn is_occupied(self) -> bool {
        (self.flags & NODE_HEAT_OCCUPIED) != 0
    }

    #[inline]
    pub const fn is_flashing(self) -> bool {
        (self.flags & NODE_HEAT_FLASHING) != 0
    }
}

const _: () = assert!(core::mem::size_of::<NodeHeat>() == 16);

/// Zero-steady-state-allocation per-node dirty & paint-flash tracker.
#[derive(Debug, Clone)]
pub struct InspectorHeatTracker {
    heat: Vec<NodeHeat>,
    active_flashes: Vec<NodeId>,
    total_commits: u64,
    last_commit_dirty_count: u32,
    last_commit_paint_count: u32,
    last_commit_kind: u8,
}

impl Default for InspectorHeatTracker {
    fn default() -> Self {
        Self::new()
    }
}

impl InspectorHeatTracker {
    pub fn new() -> Self {
        Self {
            heat: Vec::new(),
            active_flashes: Vec::new(),
            total_commits: 0,
            last_commit_dirty_count: 0,
            last_commit_paint_count: 0,
            last_commit_kind: SceneDirtyKind::None.as_u8(),
        }
    }

    #[inline]
    pub fn ensure_capacity(&mut self, store_cap: usize) {
        if self.heat.len() < store_cap {
            self.heat.resize(store_cap, NodeHeat::default());
        }
        if self.active_flashes.capacity() < MAX_FLASH_RECTS {
            let need = MAX_FLASH_RECTS.saturating_sub(self.active_flashes.len());
            self.active_flashes.reserve_exact(need);
        }
    }

    #[inline]
    pub fn begin_commit(&mut self, store_cap: usize, kind: SceneDirtyKind) {
        self.ensure_capacity(store_cap);
        self.total_commits = self.total_commits.wrapping_add(1);
        self.last_commit_dirty_count = 0;
        self.last_commit_paint_count = 0;
        self.last_commit_kind = kind.as_u8();
    }

    #[inline]
    pub fn set_last_commit_kind(&mut self, kind: SceneDirtyKind) {
        self.last_commit_kind = kind.as_u8();
    }

    fn slot_mut_for(&mut self, id: NodeId) -> Option<&mut NodeHeat> {
        if id.is_null() {
            return None;
        }
        let idx = id.index();
        if idx >= self.heat.len() {
            self.heat.resize(idx + 1, NodeHeat::default());
        }
        let slot = &mut self.heat[idx];
        if !slot.is_occupied() || slot.generation != id.generation() {
            let was_active = slot.is_occupied() && slot.is_flashing();
            *slot = NodeHeat {
                generation: id.generation(),
                flags: NODE_HEAT_OCCUPIED | if was_active { NODE_HEAT_FLASHING } else { 0 },
                ..NodeHeat::default()
            };
            if was_active {
                if let Some(entry) = self.active_flashes.iter_mut().find(|n| n.index() == idx) {
                    *entry = id;
                } else {
                    slot.flags &= !NODE_HEAT_FLASHING;
                }
            }
        }
        Some(slot)
    }

    #[inline]
    fn activate_flash(&mut self, id: NodeId, kind: u8) {
        let idx = id.index();
        if self.heat[idx].is_flashing() {
            self.heat[idx].last_kind = self.heat[idx].last_kind.max(kind);
            self.heat[idx].ttl_frames = DEFAULT_FLASH_TTL;
            return;
        }
        self.heat[idx].last_kind = kind;
        if self.active_flashes.len() < MAX_FLASH_RECTS {
            if self.active_flashes.capacity() < MAX_FLASH_RECTS {
                let need = MAX_FLASH_RECTS.saturating_sub(self.active_flashes.len());
                self.active_flashes.reserve_exact(need);
            }
            self.heat[idx].flags |= NODE_HEAT_FLASHING;
            self.heat[idx].ttl_frames = DEFAULT_FLASH_TTL;
            self.active_flashes.push(id);
        }
    }

    /// Records a commit touching/creating `id` with `kind`.
    #[inline]
    pub fn record_dirty(&mut self, id: NodeId, kind: SceneDirtyKind) {
        let k = kind.as_u8();
        let Some(slot) = self.slot_mut_for(id) else {
            return;
        };
        slot.dirty_commits = slot.dirty_commits.saturating_add(1);
        if kind == SceneDirtyKind::LayoutOrTree {
            slot.layout_commits = slot.layout_commits.saturating_add(1);
        }
        self.last_commit_dirty_count = self.last_commit_dirty_count.saturating_add(1);
        if k != SceneDirtyKind::None.as_u8() {
            self.activate_flash(id, k);
        }
    }

    /// Records a paint chunk / DOM style re-emission for `id`.
    #[inline]
    pub fn record_paint_reemit(&mut self, id: NodeId, kind: SceneDirtyKind) {
        let k = kind.as_u8();
        let Some(slot) = self.slot_mut_for(id) else {
            return;
        };
        slot.paint_reemits = slot.paint_reemits.saturating_add(1);
        self.last_commit_paint_count = self.last_commit_paint_count.saturating_add(1);
        if k != SceneDirtyKind::None.as_u8() {
            self.activate_flash(id, k);
        }
    }

    /// Retires heat and flash state for a removed node.
    #[inline]
    pub fn record_removed(&mut self, id: NodeId) {
        let idx = id.index();
        if let Some(slot) = self.heat.get_mut(idx)
            && slot.is_occupied()
            && slot.generation == id.generation()
        {
            let was_active = slot.is_flashing();
            *slot = NodeHeat::default();
            if was_active
                && let Some(pos) = self.active_flashes.iter().position(|n| n.index() == idx)
            {
                self.active_flashes.swap_remove(pos);
            }
        }
    }

    /// Decays every active flash by 1 frame, retiring settled entries in O(active) with 0 allocs.
    /// Returns `true` while at least one flash remains visible.
    pub fn decay_frame(&mut self) -> bool {
        let mut i = 0;
        while i < self.active_flashes.len() {
            let id = self.active_flashes[i];
            let idx = id.index();
            let keep = if let Some(slot) = self.heat.get_mut(idx)
                && slot.is_occupied()
                && slot.generation == id.generation()
                && slot.ttl_frames > 1
            {
                slot.ttl_frames -= 1;
                true
            } else {
                if let Some(slot) = self.heat.get_mut(idx)
                    && slot.is_occupied()
                    && slot.generation == id.generation()
                {
                    slot.ttl_frames = 0;
                    slot.flags &= !NODE_HEAT_FLASHING;
                }
                false
            };
            if keep {
                i += 1;
            } else {
                self.active_flashes.swap_remove(i);
            }
        }
        !self.active_flashes.is_empty()
    }

    /// Retires every active flash immediately while preserving cumulative dirty/paint counters.
    /// Used by DOM/CSS-transition backends whose flash fade-out runs in the browser compositor.
    pub fn clear_active_flashes(&mut self) {
        for id in self.active_flashes.drain(..) {
            if let Some(slot) = self.heat.get_mut(id.index())
                && slot.is_occupied()
                && slot.generation == id.generation()
            {
                slot.ttl_frames = 0;
                slot.flags &= !NODE_HEAT_FLASHING;
            }
        }
    }

    #[inline]
    pub fn needs_next_frame(&self) -> bool {
        !self.active_flashes.is_empty()
    }

    #[inline]
    pub fn heat_of(&self, id: NodeId) -> Option<NodeHeat> {
        let slot = self.heat.get(id.index()).copied()?;
        (slot.is_occupied() && slot.generation == id.generation()).then_some(slot)
    }

    #[inline]
    pub fn active_flashes(&self) -> &[NodeId] {
        &self.active_flashes
    }

    #[inline]
    pub fn total_commits(&self) -> u64 {
        self.total_commits
    }

    #[inline]
    pub fn last_commit_dirty_count(&self) -> u32 {
        self.last_commit_dirty_count
    }

    #[inline]
    pub fn last_commit_paint_count(&self) -> u32 {
        self.last_commit_paint_count
    }

    #[inline]
    pub fn last_commit_kind(&self) -> SceneDirtyKind {
        SceneDirtyKind::from_u8(self.last_commit_kind)
    }

    pub fn clear(&mut self) {
        self.heat.clear();
        self.active_flashes.clear();
        self.total_commits = 0;
        self.last_commit_dirty_count = 0;
        self.last_commit_paint_count = 0;
        self.last_commit_kind = SceneDirtyKind::None.as_u8();
    }
}