nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Primary pointer-DOWN light dismiss over the open top layer: the one rule every host applies
//! ([`hide_popovers_until`]; skia-shell through [`top_layer_press`], the Web overlay runtime's
//! emulation for overlays the browser does not dismiss itself, and the C++ / Swift / Java / Dart /
//! TS ports, which run the `codegen abi` conformance vectors of this rule
//! [INV:top-layer-policy-conformance]).
//!
//! HTML "hide popovers until": walking the open overlays front to back (reverse paint order), only
//! `light_dismiss` overlays and modals take part (HTML's auto / hint popovers and modal dialogs);
//! every other overlay (manual toasts, plain hints) is skipped: a press inside it stops nothing
//! and it never closes, but the press still lands inside an open overlay (`Inside` when nothing
//! closes, and never blocked by a modal below it). The walk stops at the first overlay taking
//! part that contains the press (its hit
//! node lies within it, or the point lies inside its box), at the first `light_dismiss` overlay
//! whose *active* anchor the press lands on (the anchor toggles that overlay itself; an anchor
//! made inert by a modal above it is no anchor), and at the first modal (the barrier: nothing
//! below it sees the press). Every `light_dismiss` overlay the walk passed is outside the press,
//! so the backmost of them — and every `light_dismiss` overlay above it — closes in one batch: a
//! press outside a menu and its submenu closes both, a press inside the menu closes only the
//! submenu, a press on a manual toast above a menu closes the menu. A `light_dismiss` modal the
//! press is outside of closes with them.
//!
//! Anchors are matched by node containment of the hit node (as the DOM's `anchor.contains(target)`),
//! never by the anchor's box: a box test claims presses on content painted over the anchor.
//!
//! The host contract around the walk (every host follows it):
//! - **Modal**: only the `topmost_modal` scene fact is the modal of the walk. The overlay MODAL
//!   flags are never scanned for it; the fact is authoritative.
//! - **Hit node**: the *deepest painted* node at the press point (the node whose box is topmost
//!   in paint order), never the topmost *interactive* node: an interactive ancestor can lie
//!   outside the overlay that paints the pressed content (a popover hangs under its anchor). One
//!   hit test per press feeds this walk, press focus and the pointer-down dispatch.
//! - **After the walk**: the host sends the [`TopLayerPress::light_dismissed`] closes first, then
//!   continues the press normally (hit test, press focus, `PointerDown`) unless
//!   [`TopLayerPress::modal_barrier`]: a light-dismissing press is not swallowed (HTML: the click
//!   that closes a popover still reaches what it lands on).

use nativeview_store::NodeId;

use super::ResolvedOverlay;

/// What a primary pointer DOWN does to the open top layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PressOutcome {
    /// No overlay claims the press: normal hit-testing.
    None,
    /// Inside an open overlay (or on an active overlay anchor): normal hit-testing.
    Inside,
    /// Close [`TopLayerPress::dismissed`] (non-bubbling `close`, front to back, one batch).
    LightDismiss,
    /// Outside a modal without `light_dismiss`: the press is swallowed.
    BlockedByModal,
}

/// The decision of [`top_layer_press`] over one `overlays` slice.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TopLayerPress {
    pub outcome: PressOutcome,
    /// [`PressOutcome::LightDismiss`]: paint index of the backmost overlay to close.
    pub dismiss_from: usize,
    /// The press must not reach anything below (a modal stopped the walk).
    pub modal_barrier: bool,
}

impl TopLayerPress {
    /// The overlays to close, front to back (children before the overlays they opened from): every
    /// `light_dismiss` overlay of the decided `overlays` from [`Self::dismiss_from`] up.
    pub fn light_dismissed<'a>(&self, overlays: &'a [ResolvedOverlay]) -> impl Iterator<Item = NodeId> + 'a {
        let from = if self.outcome == PressOutcome::LightDismiss {
            self.dismiss_from
        } else {
            overlays.len()
        };
        overlays
            .get(from..)
            .unwrap_or_default()
            .iter()
            .rev()
            .filter(|ro| ro.light_dismiss)
            .map(|ro| ro.node)
    }
}

/// One open overlay as the walk sees a press (see the module docs).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PressedOverlay {
    /// The press lies inside it (hit node within it, or the point inside its box).
    pub inside: bool,
    /// The press lands on its active anchor.
    pub on_anchor: bool,
    pub light_dismiss: bool,
    pub modal: bool,
}

/// The "hide popovers until" walk over `overlays` (back-to-front paint order; see the module
/// docs). The views are produced lazily: the walk evaluates only the overlays it reaches, front
/// to back, and reads `on_anchor` only of a non-modal `light_dismiss` overlay.
pub fn hide_popovers_until(
    overlays: impl DoubleEndedIterator<Item = PressedOverlay> + ExactSizeIterator,
) -> TopLayerPress {
    let len = overlays.len();
    let mut dismiss_from = None;
    let mut modal_barrier = false;
    let mut inside = false;
    for (i, ov) in overlays.enumerate().rev() {
        if !(ov.light_dismiss || ov.modal) {
            inside |= ov.inside;
            continue;
        }
        if ov.inside {
            inside = true;
            break;
        }
        if ov.modal {
            // A press inside an overlay above the modal (a manual toast) is in the active layer.
            modal_barrier = !inside;
            if ov.light_dismiss {
                dismiss_from = Some(i);
            }
            break;
        }
        if ov.on_anchor {
            inside = true;
            break;
        }
        dismiss_from = Some(i);
    }
    let outcome = match (dismiss_from, modal_barrier, inside) {
        (Some(_), _, _) => PressOutcome::LightDismiss,
        (None, true, _) => PressOutcome::BlockedByModal,
        (None, false, true) => PressOutcome::Inside,
        (None, false, false) => PressOutcome::None,
    };
    TopLayerPress {
        outcome,
        dismiss_from: dismiss_from.unwrap_or(len),
        modal_barrier,
    }
}

/// Decides a primary pointer DOWN against the open `overlays` (back-to-front paint order; see the
/// module docs). `topmost_modal` is the `topmost_modal` scene fact (`None`, or a node that is not
/// open: no modal), `hit` the deepest painted node at the press, `is_within(node, ancestor)`
/// inclusive tree containment, and `contains(overlay)` the (transform-aware) point-in-overlay-box
/// test. Allocation-free; O(open overlays) plus O(depth) containment walks.
pub fn top_layer_press(
    overlays: &[ResolvedOverlay],
    topmost_modal: Option<NodeId>,
    hit: Option<NodeId>,
    is_within: impl Fn(NodeId, NodeId) -> bool,
    contains: impl Fn(&ResolvedOverlay) -> bool,
) -> TopLayerPress {
    let modal = topmost_modal.and_then(|m| overlays.iter().rposition(|ro| ro.node == m));
    let within = |node: NodeId| !node.is_null() && hit.is_some_and(|h| is_within(h, node));
    // The hit takes input: no modal, or it lies within the topmost modal or an overlay above it.
    let hit_active = || modal.is_none_or(|m| overlays[m..].iter().any(|ro| within(ro.node)));
    hide_popovers_until(overlays.iter().enumerate().map(|(i, ro)| {
        let is_modal = modal == Some(i);
        PressedOverlay {
            inside: within(ro.node) || contains(ro),
            on_anchor: ro.light_dismiss && !is_modal && within(ro.anchor) && hit_active(),
            light_dismiss: ro.light_dismiss,
            modal: is_modal,
        }
    }))
}

#[cfg(test)]
mod tests;