zgui

Overlays and portals

Render a popover, menu or dialog above the page with Portal, place it next to its trigger, close it on an outside press or Escape, and keep focus inside a modal.

An overlay is content drawn in front of the rest of the window: a tooltip, a menu, a dialog, a toast. You render it with Portal, place it yourself from observed geometry, and close it with listeners on the window root. Read Events and Keyboard and focus first.

The component library's primitives already do all of this: Popper places a surface, DismissableLayer closes it, FocusScope traps focus and Presence keeps it mounted for an exit animation. Use this page to build an overlay without zgui-ui, or to understand what they do.

Render content above the page

Portal renders its children on an overlay layer above the page instead of where it is written:

use zgui::prelude::*;

#[component]
fn Toolbar() -> impl IntoView {
    let open = RwSignal::new(false);

    view! {
        row(class = "toolbar") {
            control(on:click = move |_| open.set(true)) {"Delete"}
            if move || open.get() {
                Portal(layer = OverlayLayer::Modal) {
                    box(class = "dialog") {"Really delete?"}
                }
            }
        }
    }
}

layer takes an OverlayLayer and defaults to OverlayLayer::Popover. The children are required. The portal leaves a marker where it was written, so opening and closing move only the content.

There are four layers. Later layers paint above earlier ones.

Layerz-indexUse for
OverlayLayer::Content10portalled content that belongs with the page
OverlayLayer::Popover20popovers, menus, tooltips, dropdowns (the default)
OverlayLayer::Modal30dialogs, sheets, drawers
OverlayLayer::Toast40toasts and notices, above dialogs

Choose the layer by what the surface is, not by when it opens. A toast raised before a dialog still paints above it.

Why a portal is needed

A menu written inside the row that opens it is a descendant of that row, so the row's ancestors affect it:

AncestorEffect on the menu
overflow: hidden, auto or scrollclipped to the ancestor's box
opacity, filter, transform, clip-path, isolationpainted as one unit with the ancestor's subtree, so its z-index cannot lift it above the ancestor's siblings
position: relative with a z-indexthe whole subtree has one place in paint order

Paint order is also hit-test order, so a menu painted behind something cannot be clicked there either. Layout lists the properties that create a stacking context.

What changes for portalled content

  • Context and ownership follow the place it is written. The children are built in the scope that wrote the portal, so use_context works as it would in place, and unmounting that component removes the surface.
  • Events do not bubble to the component that wrote it. The surface's ancestors are the overlay layer, the overlay root and the window root. Pass a signal or a callback prop instead of relying on bubbling.
  • Empty layer area does not take the pointer. A press beside an open popover reaches whatever is underneath. Only the portal's top-level elements and their descendants receive pointer events.
  • Fixed positions are window coordinates. The overlay root covers the whole window, including any scrollbar gutter, so a position: fixed surface is placed relative to the window.

How the overlay layers work shows the style rules behind this.

Place a popover next to its trigger

zgui does not position portalled content for you. Observe the geometry you need and compute the position:

NeedSource
where the trigger isanchor.observe_border_box()
how big the surface ispositioner.observe_content_size()
where the window edges arepositioner.window_root(), then observe_border_box() on it
device pixels per CSS pixelpositioner.scale()

Observed values are signals. They are written during the frame that changes them, before painting, so a surface positioned from them is drawn in its final place in that same frame. See Effects and lifecycle.

Two rules:

  • Convert to CSS pixels last. Observations are in device pixels. Inline left and top are CSS pixels. Divide by scale(), or the surface lands too far away on high-density displays.
  • Mount hidden, not absent. An element that is not in the document has no size to measure. Use visibility: hidden until the first placement exists. The box keeps its layout but is not painted.

This component places its children below the anchor, or above it when there is no room below:

use zgui::geom::{Device, DevicePx, Rect};
use zgui::reactive::RenderEffect;

/// Places its children below (or above) `anchor`, inside the window.
#[component]
fn Anchored(
    /// What the surface is placed against.
    anchor: NodeRef,
    /// Distance from the anchor, in CSS pixels.
    #[prop(default = 4.0)]
    gap: f32,
    /// Classes on the positioner.
    #[prop(into, optional)]
    class: Classes,
    /// The surface.
    children: Children,
) -> impl IntoView {
    let positioner = NodeRef::new();
    let anchor_box = anchor.observe_border_box();
    let surface_size = positioner.observe_content_size();

    // The window root is reachable only once `positioner` is bound, so acquire it from an effect.
    let window_box: RwSignal<
        Option<Signal<Option<Rect<DevicePx, Device>>, LocalStorage>>,
        LocalStorage,
    > = RwSignal::new_local(None);
    let watching = RenderEffect::new(move |_| {
        if positioner.get().is_none() || window_box.get_untracked().is_some() {
            return;
        }
        if let Some(root) = positioner.window_root() {
            window_box.set(Some(root.observe_border_box()));
        }
    });
    on_cleanup_local(move || drop(watching));

    let origin = Signal::derive_local(move || {
        let anchor = anchor_box.get()?;
        let size = surface_size.get();
        // Not measured yet: stay hidden rather than flash at the wrong place.
        if size.width.0 <= 0.0 && size.height.0 <= 0.0 {
            return None;
        }
        let window = window_box.get()?.get()?;
        let scale = positioner.scale();
        let gap = gap * scale;

        let below = anchor.origin.y.0 + anchor.size.height.0 + gap;
        let above = anchor.origin.y.0 - size.height.0 - gap;
        // Flip only when below does not fit and above does, so the surface does not oscillate.
        let fits_below = below + size.height.0 <= window.origin.y.0 + window.size.height.0;
        let y = if fits_below || above < window.origin.y.0 { below } else { above };

        // Slide horizontally until the surface is inside the window.
        let furthest = window.origin.x.0 + window.size.width.0 - size.width.0;
        let x = anchor.origin.x.0.clamp(window.origin.x.0, furthest.max(window.origin.x.0));

        Some((x / scale, y / scale))
    });

    let left = move || origin.get().map(|(x, _)| format!("{x}px"));
    let top = move || origin.get().map(|(_, y)| format!("{y}px"));
    let hidden = move || origin.get().is_none().then(|| "hidden".to_owned());

    view! {
        box(
            class = class,
            node_ref = positioner,
            style:position = "fixed",
            style:left = left,
            style:top = top,
            style:visibility = hidden
        ) {
            {children.into_view_once()}
        }
    }
}

Use it inside a Portal, with a NodeRef on the trigger:

let trigger = NodeRef::new();

view! {
    control(node_ref = trigger, on:click = move |_| open.update(|o| *o = !*o)) {"Options"}
    if move || open.get() {
        Portal {
            Anchored(anchor = trigger, class = "popover") {
                column { "…" }
            }
        }
    }
}

This surface is unmounted while closed, so it observes nothing while closed. A surface that stays mounted should use the _while forms, such as observe_border_box_while(move || open.get()), so it is not re-placed every time something scrolls.

To make a surface as wide as its trigger, set its width from anchor_box in the same way. The component library's Popper publishes this as --zui-popper-anchor-width in CSS pixels, so a style sheet can write width: var(--zui-popper-anchor-width).

Close an overlay

Close onListen with
a press outsidea capture listener on the window root, plus NodeRef::contains
Escapeon:key_down on the surface, or a capture listener on the window root
focus leavingfocused_node() plus NodeRef::contains

Close on a press outside

A press elsewhere in the window lands on a node your view did not create. NodeRef::window_root() returns a handle on the window's root element, and NodeRef::listen attaches a listener to it for as long as you hold the returned ListenerGuard:

/// Calls `close` when a press lands outside both `surface` and `trigger`.
/// Call from a component body; the listener lives as long as that scope.
fn close_on_outside_press(surface: NodeRef, trigger: NodeRef, close: UnsyncCallback<()>) {
    let guard: StoredValue<Option<ListenerGuard>, LocalStorage> = StoredValue::new_local(None);

    let attaching = RenderEffect::new(move |_| {
        // Re-runs when `surface` binds.
        if surface.get().is_none() || guard.with_value(Option::is_some) {
            return;
        }
        let Some(window) = surface.window_root() else {
            return;
        };
        guard.set_value(window.listen(
            events::POINTER_DOWN,
            ListenerOptions::CAPTURE,
            move |ev: &mut EventCx<'_, events::PointerDown>| {
                if surface.get_untracked().is_none() {
                    return; // closed and unmounted
                }
                if !surface.contains(ev.target) && !trigger.contains(ev.target) {
                    close.run(());
                }
            },
        ));
    });

    on_cleanup_local(move || {
        drop(attaching);
        guard.set_value(None);
    });
}
  • Listen in the capture phase so the decision is made before the pressed element's own handlers run.
  • Exclude the trigger. Otherwise a press on the trigger closes the surface, and the click that follows opens it again.

A surface with a backdrop does not need this. The backdrop covers the window, so a press outside the surface is a press on the backdrop. The modal dialog below works that way.

Close on Escape

Key events target the focused element and bubble. When focus is inside the surface, a listener on the surface sees Escape:

on:key_down = move |ev| {
    if ev.key == Key::Named(NamedKey::Escape) {
        ev.stop_propagation(); // one Escape closes one surface
        open.set(false);
    }
}

When focus may be elsewhere (a tooltip never takes focus), listen for events::KEY_DOWN on the window root in the capture phase, as for an outside press. When nothing is focused, the key's target is the window root itself. All listeners on the target run even after stop_propagation(), so call ev.stop_immediate_propagation() to keep the application's own root-level Escape handler from also firing. The component library's DismissableLayer does this, and only the innermost open layer responds.

Close when focus leaves

let focused = focused_node();
let watching = RenderEffect::new(move |_| {
    if let Some(node) = focused.get()
        && !surface.contains(node)
        && !trigger.contains(node)
    {
        open.set(false);
    }
});
on_cleanup_local(move || drop(watching));

focused_node() reads None when nothing is focused, for example after the focused element was removed. That is not focus moving elsewhere, so it does not close the surface.

Keep focus inside a modal

Without a focus trap, Tab moves out of a modal into controls behind it. NodeRef::trap_focus confines Tab to a subtree and returns a FocusTrap guard; dropping the guard releases the trap. This helper holds a trap while the surface is open:

/// Holds a focus trap on `surface` while `active` is true.
fn trap_focus_while(surface: NodeRef, options: FocusTrapOptions, active: impl Fn() -> bool + 'static) {
    let held: StoredValue<Option<FocusTrap>, LocalStorage> = StoredValue::new_local(None);

    let installing = RenderEffect::new(move |_| {
        if active() && surface.get().is_some() {
            if held.with_value(Option::is_none) {
                held.set_value(surface.trap_focus(options)); // install once
            }
        } else {
            held.set_value(None);
        }
    });

    on_cleanup_local(move || drop(installing));
}

Use FocusTrapOptions::MODAL for a dialog: Tab wraps inside it, focus moves in when it opens, and focus returns to the opener when it closes. FocusTrapOptions::CONFINE_ONLY only wraps Tab, for a menu that should not take focus from its toolbar. Traps stack, so a dialog opened from a dialog works. Trap focus in a dialog has the full rules for options, nesting and restoring focus.

Build a modal dialog

The backdrop is the portal's top-level element, so it receives pointer events. A press on it outside the dialog closes the dialog.

#[component]
fn ConfirmDialog(
    /// Whether the dialog is showing. The caller owns it.
    open: RwSignal<bool>,
    #[prop(into)]
    question: String,
    on_confirm: UnsyncCallback<()>,
) -> impl IntoView {
    let surface = NodeRef::new();
    trap_focus_while(surface, FocusTrapOptions::MODAL, move || open.get());

    view! {
        if move || open.get() {
            Portal(layer = OverlayLayer::Modal) {
                box(
                    class = "dialog__backdrop",
                    on:pointer_down = move |ev| {
                        if !surface.contains(ev.target) {
                            open.set(false);
                        }
                    }
                ) {
                    column(
                        class = "dialog",
                        node_ref = surface,
                        a11y:role = Role::Dialog,
                        a11y:modal = true,
                        a11y:label = "Confirm",
                        on:key_down = move |ev| {
                            if ev.key == Key::Named(NamedKey::Escape) {
                                ev.stop_propagation();
                                open.set(false);
                            }
                        }
                    ) {
                        text {{question.clone()}}
                        row(class = "dialog__actions") {
                            control(on:click = move |_| open.set(false)) {"Cancel"}
                            control(on:click = move |_| {
                                open.set(false);
                                on_confirm.run(());
                            }) {"Delete"}
                        }
                    }
                }
            }
        }
    }
}

const DIALOG: &str = css!(
    ".dialog__backdrop { position: fixed; inset: 0; display: flex; align-items: center;
                         justify-content: center; background-color: rgba(6, 8, 12, 0.6); }
    .dialog { min-width: 320px; gap: 16px; padding: 20px; border-radius: 12px;
              background-color: #161a22; }
    .dialog__actions { gap: 8px; justify-content: flex-end; }"
);

The trap cycles Tab inside the dialog, focuses Cancel on open, and returns focus to the opener on close. a11y:modal tells assistive technology the same thing. To stop the page behind the dialog from scrolling, see Stop the page scrolling behind a modal.

Build a dropdown menu

A menu combines the pieces above: close_on_outside_press(surface, trigger, …), trap_focus_while(surface, FocusTrapOptions::MODAL, move || open.get()), and a key handler on the list that moves focus between items.

column(
    class = "menu__list",
    node_ref = surface,
    a11y:role = Role::Menu,
    on:key_down = move |ev| {
        match &ev.key {
            Key::Named(NamedKey::ArrowDown) => { surface.focus_move(FocusMove::Next); }
            Key::Named(NamedKey::ArrowUp) => { surface.focus_move(FocusMove::Prev); }
            Key::Named(NamedKey::Home) => { surface.focus_move(FocusMove::First); }
            Key::Named(NamedKey::End) => { surface.focus_move(FocusMove::Last); }
            Key::Named(NamedKey::Escape) => open.set(false),
            _ => return,
        }
        // These keys belong to the menu: no parent acts on them, nothing scrolls.
        ev.stop_propagation();
        ev.prevent_default();
    }
) {
    control(a11y:role = Role::MenuItem, on:click = move |_| choose("Rename")) {"Rename"}
    control(a11y:role = Role::MenuItem, on:click = move |_| choose("Delete")) {"Delete"}
}
  • control is focusable by default, so items need no tabindex. focus_move wraps because the trap has wrap set.
  • Enter and Space on a focused control produce a click, so one on:click serves pointer, keyboard and assistive technology.
  • Give the trigger a11y:has_popup = HasPopup::Menu (from zgui::vocab) and a11y:expanded = move || open.get() so it announces the menu and its state.

Build a tooltip

A tooltip combines a hover delay, keyboard focus, and a surface that ignores the pointer:

use core::time::Duration;
use zgui::view::TimeoutHandle;
use zgui::vocab::FocusCause;

// In the component body. Listeners run outside the component's scope, so take the clock here.
let clock = Timers::current().expect("a component body is inside a window");
let pending = StoredValue::new_local(None::<TimeoutHandle>);

view! {
    box(
        node_ref = trigger,
        a11y:description = tip.clone(), // the description belongs to the trigger
        on:pointer_enter = move |_| {
            pending.set_value(Some(clock.set_timeout(Duration::from_millis(500), move || open.set(true))));
        },
        on:pointer_leave = move |_| { pending.set_value(None); open.set(false); },
        on:focus_in = move |ev: &mut EventCx<'_, events::FocusIn>| {
            // Keyboard focus only: a trap's auto-focus or a programmatic focus shows nothing.
            if ev.cause == FocusCause::Keyboard { open.set(true); }
        },
        on:focus_out = move |_| { pending.set_value(None); open.set(false); }
    ) {
        {children.into_view_once()}
        if move || open.get() {
            Portal {
                Anchored(anchor = trigger, class = "tip") {
                    box(a11y:role = Role::Tooltip) {{tip.clone()}}
                }
            }
        }
    }
}
  • Give the surface pointer-events: none. A tooltip under the cursor would otherwise receive the pointer and cause the pointer_leave that closes it.
  • Dropping a TimeoutHandle cancels the timeout, so each closing path clears pending. See UI tasks and timers.
  • Close on Escape only while the tooltip is showing, or it swallows the Escape meant for a dialog around it.

What the component library adds

The zgui-ui overlays add a few behaviours on top of the patterns above:

ComponentBehaviour
Tooltipopens on hover after a delay; on focus, only when the keyboard moved focus there
Popperpublishes --zui-popper-anchor-width (CSS pixels) on the positioner
DismissableLayerlistens for Escape on the window root; the innermost open layer takes it and stops it immediately
ContextMenuinside a ContextMenuTrigger, ContextMenuPlace::current() then open_at(point) (window CSS pixels) opens the menu at that point, for example from the keyboard
MenuSubTriggeropens after a hover delay, or at once on a press

See Components and Primitives.

Common problems

SymptomCauseFix
surface is cut off or paints behind a neighbourstill inside a clipping or stacking ancestorwrap it in Portal
surface flashes in the top-left cornerplaced before it was measuredkeep it visibility: hidden until placed
surface closes as soon as it opensdismissal in the bubble phase, or trigger not excludeduse ListenerOptions::CAPTURE and exclude the trigger
surface is far off on a high-density displaydevice pixels written as CSS pixelsdivide by NodeRef::scale()
Tab leaves an open dialogno trap, or the guard was droppedhold the FocusTrap while open
focus does not return to the triggertrap without restore, or focus had already left the surfaceuse FocusTrapOptions::MODAL
one Escape closes two surfacesnothing stopped the eventstop it in the innermost surface; use stop_immediate_propagation on the window root
a listener on the trigger's parent never sees the surface's clicksthe portal moved the contentpass a signal or callback prop

How the overlay layers work

Every window has an overlay_root element under its root, with one child per layer (data-layer=content, popover, modal, toast). They are created before any view is built, and the framework's user-agent sheet styles them like this:

overlay_root                        { display: block; position: fixed; left: 0; right: 0; top: 0;
                                      width: 100vw; height: 100vh; pointer-events: none;
                                      z-index: 1000; }
overlay_root > [data-layer]         { position: absolute; inset: 0; pointer-events: none; }
overlay_root > [data-layer] > *     { pointer-events: auto; }
overlay_root > [data-layer=content] { z-index: 10; }
overlay_root > [data-layer=popover] { z-index: 20; }
overlay_root > [data-layer=modal]   { z-index: 30; }
overlay_root > [data-layer=toast]   { z-index: 40; }

Because the overlay root has z-index: 1000, application chrome with a higher z-index paints above every overlay.

Next

On this page