nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
use nativeview_engine::InteractionTracker;
use nativeview_store::{ChangeSet, NodeId, NodeStore, RowPatch, Transaction};
use nativeview_tables::interaction::{InteractionState, StateStyleRule};
use nativeview_tables::media::{MediaEnv, MediaQuery, ResponsiveRule};
use nativeview_tables::tables::{
    Display, Interaction, Layout, Overlay, OverlayFlags, OverlayLayer, Responsive,
    ResponsiveRules, StateRules, TextContent, TopLayerState,
};

use super::TopLayerIndex;
use crate::DisplayEnv;

const STATIC: DisplayEnv<'static> = DisplayEnv {
    media: None,
    container_envs: None,
    interaction: None,
};

fn open(tx: &mut Transaction<'_>, id: NodeId, layer: OverlayLayer) {
    tx.edit::<Overlay>(id)
        .layer(layer)
        .options(OverlayFlags::OPEN);
}

fn commit(store: &mut NodeStore, f: impl FnOnce(&mut Transaction<'_>)) -> ChangeSet {
    let mut changes = ChangeSet::default();
    let mut tx = store.tx();
    f(&mut tx);
    tx.commit_into(&mut changes);
    changes
}

fn display_patch(display: Display) -> RowPatch {
    let mut patch = RowPatch::new();
    patch.set(Layout::DISPLAY, display);
    patch
}

/// `root > [a > [ov_a > [nested]], b > [ov_b], closed > [inside]]`.
struct Tree {
    store: NodeStore,
    index: TopLayerIndex,
    a: NodeId,
    b: NodeId,
    ov_a: NodeId,
    nested: NodeId,
    ov_b: NodeId,
    closed: NodeId,
    inside: NodeId,
}

impl Tree {
    fn sync(&mut self, f: impl FnOnce(&mut Transaction<'_>)) -> bool {
        let changes = commit(&mut self.store, f);
        self.index.sync(&self.store, &changes, &STATIC)
    }
}

fn tree() -> Tree {
    let mut store = NodeStore::new();
    let mut ids = [NodeId::NULL; 7];
    let changes = commit(&mut store, |tx| {
        ids = [(); 7].map(|_| tx.create());
        let [a, b, ov_a, nested, ov_b, closed, inside] = ids;
        tx.set_children(NodeId::ROOT, &[a, b, closed]);
        tx.set_children(a, &[ov_a]);
        tx.set_children(ov_a, &[nested]);
        tx.set_children(b, &[ov_b]);
        tx.set_children(closed, &[inside]);
        open(tx, ov_a, OverlayLayer::Popover);
        open(tx, nested, OverlayLayer::Modal);
        open(tx, ov_b, OverlayLayer::Tooltip);
        tx.edit::<Overlay>(closed).layer(OverlayLayer::Menu);
        open(tx, inside, OverlayLayer::Popover);
    });
    let [a, b, ov_a, nested, ov_b, closed, inside] = ids;
    let mut index = TopLayerIndex::new();
    assert!(index.sync(&store, &changes, &STATIC));
    Tree {
        store,
        index,
        a,
        b,
        ov_a,
        nested,
        ov_b,
        closed,
        inside,
    }
}

#[test]
fn hoists_open_roots_in_document_order_and_hides_closed_subtrees() {
    let t = tree();
    assert_eq!(t.index.hoisted(), &[t.ov_a, t.nested, t.ov_b]);
    assert_eq!(t.index.state(t.closed), TopLayerState::Hidden);
    assert_eq!(
        t.index.state(t.inside),
        TopLayerState::None,
        "open under a closed overlay"
    );
    assert_eq!(t.index.state(t.a), TopLayerState::None);
    assert_eq!(t.index.states()[t.ov_b.index()] as u8, 1);
}

#[test]
fn unrelated_display_toggle_skips_recompute_but_ancestor_toggle_unhoists() {
    let mut t = tree();
    let before = t.index.recompute_count();
    let gen_before = t.index.generation();
    let b = t.b;
    let ov_b = t.ov_b;
    let mut sibling = NodeId::NULL;
    // `b` gained a child: `b` is an ancestor of `ov_b`, so this recomputes (set unchanged).
    assert!(!t.sync(|tx| {
        sibling = tx.create();
        tx.set_children(b, &[ov_b, sibling]);
    }));
    assert_eq!(t.index.generation(), gen_before);
    assert_eq!(t.index.recompute_count(), before + 1);

    assert!(!t.sync(|tx| {
        tx.edit::<Layout>(sibling).display(Display::None);
    }));
    assert_eq!(
        t.index.recompute_count(),
        before + 1,
        "leaf toggle must not recompute"
    );

    let a = t.a;
    assert!(t.sync(|tx| {
        tx.edit::<Layout>(a).display(Display::None);
    }));
    assert_eq!(t.index.hoisted(), &[t.ov_b]);
    assert!(t.index.transitions().contains(&t.ov_a));
    assert!(t.index.transitions().contains(&t.nested));
}

#[test]
fn display_contents_display_none_and_paragraph_ancestors_never_hoist() {
    let mut t = tree();
    let (ov_b, a) = (t.ov_b, t.a);
    assert!(t.sync(|tx| {
        tx.edit::<Layout>(ov_b).display(Display::Contents);
        tx.edit::<Layout>(a).display(Display::None);
    }));
    assert!(t.index.hoisted().is_empty());
}

/// R2 P1 #1: a hoisted overlay detached from its parent (the parent is no other overlay's
/// ancestor) must leave the top layer although no ancestor chain still crosses the old parent.
#[test]
fn detached_overlay_leaves_the_top_layer() {
    let mut t = tree();
    let ov_b = t.ov_b;
    assert!(t.sync(|tx| tx.detach_child(ov_b)));
    assert_eq!(t.index.hoisted(), &[t.ov_a, t.nested]);
    assert_eq!(t.index.state(ov_b), TopLayerState::None);
    assert!(t.index.transitions().contains(&ov_b));

    // Re-attaching elsewhere hoists it again, in its new document position.
    let a = t.a;
    let ov_a = t.ov_a;
    assert!(t.sync(|tx| tx.set_children(a, &[ov_b, ov_a])));
    assert_eq!(t.index.hoisted(), &[ov_b, t.ov_a, t.nested]);
}

#[test]
fn reparent_and_sibling_reorder_update_paint_order() {
    let mut t = tree();
    let (a, b, closed) = (t.a, t.b, t.closed);
    assert!(t.sync(|tx| tx.set_children(NodeId::ROOT, &[b, a, closed])));
    assert_eq!(t.index.hoisted(), &[t.ov_b, t.ov_a, t.nested]);

    // Reparent `ov_b` under the modal: still hoisted, now painted after its new ancestor.
    let (ov_b, nested) = (t.ov_b, t.nested);
    assert!(t.sync(|tx| tx.set_children(nested, &[ov_b])));
    assert_eq!(t.index.hoisted(), &[t.ov_a, nested, ov_b]);
}

/// R2 P2: states, paint positions and transitions are keyed by full ids, so a reused slot never
/// reads the previous node's state and both ids are reported.
#[test]
fn slot_reuse_is_generation_safe() {
    let mut t = tree();
    let old = t.ov_b;
    assert!(t.sync(|tx| tx.remove(old)));
    let mut fresh = NodeId::NULL;
    let b = t.b;
    // The store reuses freed slots in a later transaction.
    let changes = commit(&mut t.store, |tx| {
        fresh = tx.create();
        tx.set_children(b, &[fresh]);
        open(tx, fresh, OverlayLayer::Popover);
    });
    assert!(t.index.sync(&t.store, &changes, &STATIC));
    assert_eq!(
        fresh.index(),
        old.index(),
        "slot must be reused for this probe"
    );
    assert!(t.index.is_hoisted(fresh));
    assert!(
        !t.index.is_hoisted(old),
        "stale id must not read the new node's state"
    );
    assert!(t.index.transitions().contains(&fresh));
}

/// A removal and a slot-reusing creation folded into one recompute (an engine that skipped the
/// removal frame): the replaced id and the new id are both reported.
#[test]
fn reused_slot_reports_both_transitions() {
    let mut t = tree();
    let (old, b) = (t.ov_b, t.b);
    let _removal = commit(&mut t.store, |tx| tx.remove(old));
    let mut fresh = NodeId::NULL;
    let reuse = commit(&mut t.store, |tx| {
        fresh = tx.create();
        tx.set_children(b, &[fresh]);
        open(tx, fresh, OverlayLayer::Popover);
    });
    assert_eq!(
        fresh.index(),
        old.index(),
        "slot must be reused for this probe"
    );
    let _ = t.index.sync(&t.store, &reuse, &STATIC);
    assert!(t.index.transitions().contains(&fresh));
    assert!(
        t.index.transitions().contains(&old),
        "the replaced id is a transition too"
    );
    assert!(t.index.is_hoisted(fresh) && !t.index.is_hoisted(old));
}

/// R2 P2: a table attach that turns an ancestor into a paragraph root (no display / children
/// change) un-hoists the overlays below it.
#[test]
fn inline_context_transition_on_an_ancestor_unhoists() {
    let mut t = tree();
    let b = t.b;
    assert!(t.sync(|tx| {
        tx.edit::<TextContent>(b).text("now a paragraph");
    }));
    assert!(t.store.is_inline_context_root(b));
    assert_eq!(t.index.state(t.ov_b), TopLayerState::None);
}

/// R2 P1 #2: `@media` display patches decide hoisting through the engine's `DisplayEnv`.
#[test]
fn media_display_rules_decide_hoisting() {
    let mut t = tree();
    let a = t.a;
    let changes = commit(&mut t.store, |tx| {
        tx.edit::<Responsive>(a)
            .rules(Some(&ResponsiveRules::new(vec![ResponsiveRule {
                query: MediaQuery::min_width(800),
                patch: display_patch(Display::None),
            }])));
    });
    let wide = MediaEnv {
        width_pt: 1000.0,
        ..MediaEnv::default()
    };
    let narrow = MediaEnv {
        width_pt: 600.0,
        ..MediaEnv::default()
    };
    let env = DisplayEnv {
        media: Some(&wide),
        ..DisplayEnv::default()
    };
    assert!(t.index.sync(&t.store, &changes, &env));
    assert_eq!(
        t.index.hoisted(),
        &[t.ov_b],
        "`a` is display:none at 1000pt"
    );

    // A media change invalidates; the rebuild hoists again.
    t.index.invalidate();
    let env = DisplayEnv {
        media: Some(&narrow),
        ..DisplayEnv::default()
    };
    assert!(t.index.refresh(&t.store, NodeId::ROOT, &env));
    assert_eq!(t.index.hoisted(), &[t.ov_a, t.nested, t.ov_b]);
}

/// R2 P1 #2: an active `StateRules` `display: none` on an ancestor un-hoists the modal below
/// it; clearing the pseudo-state hoists it again.
#[test]
fn state_rules_display_decides_hoisting() {
    let mut t = tree();
    let a = t.a;
    let changes = commit(&mut t.store, |tx| {
        tx.set_resource(
            a,
            Interaction::STATE_RULES,
            Some(&StateRules::new(vec![StateStyleRule::new(
                InteractionState::HOVER,
                display_patch(Display::None),
            )])),
        );
    });
    assert!(
        !t.index.sync(&t.store, &changes, &STATIC),
        "not hovered yet"
    );

    let mut tracker = InteractionTracker::new();
    let store = &t.store;
    let _ = tracker.pointer_move_with(nativeview_engine::tracker::PointerKey::MOUSE, Some(a), |id| store.parent(id));
    let env = DisplayEnv {
        interaction: Some(&tracker),
        ..DisplayEnv::default()
    };
    assert!(t.index.sync_nodes(store, tracker.last_dirty(), &env));
    assert_eq!(
        t.index.hoisted(),
        &[t.ov_b],
        "the hidden modal is not hoisted"
    );

    let _ = tracker.pointer_move_with(nativeview_engine::tracker::PointerKey::MOUSE, None, |id| store.parent(id));
    let env = DisplayEnv {
        interaction: Some(&tracker),
        ..DisplayEnv::default()
    };
    assert!(t.index.sync_nodes(store, tracker.last_dirty(), &env));
    assert_eq!(t.index.hoisted(), &[t.ov_a, t.nested, t.ov_b]);
}

#[test]
fn removal_and_reopen_round_trip_restores_the_set() {
    let mut t = tree();
    let b = t.b;
    assert!(t.sync(|tx| tx.remove(b)));
    assert_eq!(t.index.hoisted(), &[t.ov_a, t.nested]);
    assert_eq!(t.index.state(t.ov_b), TopLayerState::None);

    let closed = t.closed;
    assert!(t.sync(|tx| {
        tx.edit::<Overlay>(closed).options(OverlayFlags::OPEN);
    }));
    assert_eq!(t.index.hoisted(), &[t.ov_a, t.nested, t.closed, t.inside]);
    let generation = t.index.generation();
    assert!(!t.index.sync(&t.store, &ChangeSet::default(), &STATIC));
    assert_eq!(t.index.generation(), generation);
}

#[test]
fn subtree_root_scopes_hoisting_and_disconnected_overlays_stay_inline() {
    let mut t = tree();
    assert!(t.index.refresh(&t.store, t.a, &STATIC));
    assert_eq!(
        t.index.hoisted(),
        &[t.ov_a, t.nested],
        "only overlays under the root `a`"
    );
    assert!(t.index.refresh(&t.store, t.ov_a, &STATIC));
    assert_eq!(
        t.index.hoisted(),
        &[t.nested],
        "the root itself never hoists"
    );
    let mut orphan = NodeId::NULL;
    let changes = commit(&mut t.store, |tx| {
        orphan = tx.create();
        open(tx, orphan, OverlayLayer::Modal);
    });
    assert!(t.index.refresh(&t.store, NodeId::ROOT, &STATIC));
    assert!(!t.index.sync(&t.store, &changes, &STATIC));
    assert_eq!(t.index.state(orphan), TopLayerState::None);
}