Primitives
Reference for zgui-ui-primitives, the headless behaviours behind the component library — placement, focus trapping, roving focus, exit animations, dismissal, item order and value ownership — and how to style them with your own CSS.
zgui-ui-primitives holds the behaviour of the component library without its appearance:
placement, focus trapping, roving focus, exit animations, dismissal, item order and value
ownership. Each primitive renders at most one unstyled element and writes data- attributes for
your style sheet. zgui-ui is built from these primitives, and you can use them directly with your
own CSS. The crate uses only zgui's public API.
Install
[dependencies]
zgui = "0.1"
zgui-ui-primitives = "0.1"use zgui_ui_primitives::prelude::*;The prelude has every primitive and its props type. Everything is also available by module:
popper, focus, presence, dismiss, collection and state. Listening and
popper::anchor_point are not in the prelude.
All primitives
| Primitive | Does | Kind | Renders |
|---|---|---|---|
Popper | places a floating surface next to an anchor | component | one box, position: fixed |
FocusScope | keeps focus inside a subtree and restores it afterwards | component | one box, data-focus-scope |
RovingFocus | makes a group one tab stop, with arrow-key navigation | component | one box, data-orientation |
Presence | keeps content mounted until its exit animation ends | component | nothing of its own |
DismissableLayer | closes a surface on Escape or a press outside | component | one box, data-layer |
Collection | lists a control's items in document order | value | — |
Controllable | holds a value whoever owns it | value | — |
Binding | says who owns a value prop | value | — |
The wrapper boxes are block containers and take part in layout. If a wrapper must not affect
layout, give it a class with display: contents. zgui-ui does this for FocusScope and
DismissableLayer, but never for the Popper positioner: it carries the position, so it must
generate a box.
Attributes for your style sheet
| Name | Written by | Values |
|---|---|---|
data-side | Popper positioner | top, right, bottom, left: the side the surface was actually placed on |
data-align | Popper positioner | start, center, end |
--zui-popper-anchor-width | Popper positioner | the anchor's width, in CSS pixels |
--zui-popper-anchor-x, --zui-popper-anchor-y | Popper positioner | the anchor's centre, from the surface's corner, kept inside the surface |
--zui-popper-available-width, --zui-popper-available-height | Popper positioner | the largest size that stays inside the window on the chosen side, in whole CSS pixels |
data-orientation | RovingFocus | horizontal, vertical, both |
data-layer | DismissableLayer | content, popover, modal, toast |
data-focus-scope | FocusScope | empty string |
data-state | you, from use_presence() | open, closed |
Presence writes no attribute: you bind its state on your own surface element (see the
example).
Popper
Places a floating surface, such as a menu, tooltip or list, next to an anchor, usually the control that opened it.
#[component]
pub fn Popper(
anchor: NodeRef,
#[prop(into, default = Signal::stored_local(Placement::BOTTOM))]
placement: Signal<Placement, LocalStorage>,
#[prop(default = true)] flip: bool, // cross to the other side when there is no room
#[prop(default = true)] shift: bool, // slide along the edge to stay in the window
#[prop(default = 4.0)] offset: f32, // gap to the anchor, CSS pixels
#[prop(default = 8.0)] padding: f32, // closest approach to the window edge, CSS pixels
#[prop(into, default = Signal::stored_local(true))] active: Signal<bool, LocalStorage>,
#[prop(optional)] element_ref: Option<NodeRef>,
#[prop(into, optional)] class: Classes,
children: Children,
) -> impl IntoView- It wraps the children in a positioner element of its own, because a view can only write to nodes it created.
- The positioner mounts hidden, is measured and placed in the same frame, and is shown before the first paint, so the surface never appears in the wrong place.
- It observes the anchor, its own size and the window, so it follows scrolling and resizing. While
activeis false it observes nothing. A surface unmounted byPresencealso stops observing. - Use
width: var(--zui-popper-anchor-width)to match the anchor's width, and--zui-popper-anchor-x/-yto point an arrow at the anchor's centre. - Use
max-height: var(--zui-popper-available-height)withoverflow-y: autoto keep a long surface inside the window. When neither side has room, the surface goes to the side with more.
Put it inside a Portal so the surface is not clipped or
transformed by the trigger's ancestors.
The placement types
pub enum Side { Top, Right, Bottom, Left } // default Bottom
pub enum Align { Start, Center, End } // default Center
pub struct Placement { pub side: Side, pub align: Align }
impl Placement {
pub const BOTTOM: Self; // Bottom, Center
pub const TOP: Self; // Top, Center
pub const fn new(side: Side, align: Align) -> Self;
pub const fn flipped(self) -> Self; // opposite side, same alignment
}
// Side: ALL, opposite(), is_vertical(), name(). Align: ALL, name().The solve function
The placement calculation is a public pure function, for placing something without the component:
pub fn solve(
anchor: WindowRect, // Rect<DevicePx, Device>
floating: Size<DevicePx, Device>,
viewport: WindowRect,
options: &PopperOptions, // placement, flip, shift, offset, padding (device pixels)
) -> Solution; // origin, placement actually used, overflowIt places, then flips, then shifts. It flips only when the opposite side has enough room, so a surface that fits on neither side stays on the requested side instead of flipping every frame.
FocusScope
Traps focus in a subtree so Tab cannot leave it. This is what makes a dialog modal for keyboard users.
#[component]
pub fn FocusScope(
#[prop(into, default = Signal::stored_local(true))] trapped: Signal<bool, LocalStorage>,
#[prop(default = FocusTrapOptions::MODAL)] options: FocusTrapOptions,
#[prop(optional)] element_ref: Option<NodeRef>,
#[prop(into, optional)] class: Classes,
children: Children,
) -> impl IntoView| Option | MODAL | CONFINE_ONLY | Effect |
|---|---|---|---|
wrap | yes | yes | tabbing past the last control returns to the first |
auto_focus | yes | no | focus moves inside when the trap starts |
restore | yes | no | focus returns to where it was when the trap ends |
- Use
MODALfor a dialog. UseCONFINE_ONLYfor a menu opened from a toolbar: it confines Tab without taking focus away from the toolbar. - Traps stack, and the innermost one is active. Closing an inner dialog returns navigation to the outer one.
restoredoes not pull focus back if it has already moved somewhere else outside the trap, for example to a control the closing action focused.- Setting
trappedto false releases the trap without unmounting anything.
It wraps the guard returned by NodeRef::trap_focus; dropping the guard ends the trap.
RovingFocus
Makes a group of items one tab stop, with the arrow keys moving between them. Toolbars, tab lists, menus, radio groups and listboxes all use this pattern.
#[component]
pub fn RovingFocus(
#[prop(default = Orientation::Horizontal)] orientation: Orientation,
#[prop(default = true)] wrap: bool,
#[prop(optional)] element_ref: Option<NodeRef>,
#[prop(into, optional)] class: Classes,
#[prop(attrs)] attrs: Attrs,
children: Children,
) -> impl IntoView| Key | Effect |
|---|---|
| → / ← | one step, in a Horizontal or Both group |
| ↓ / ↑ | one step, in a Vertical or Both group |
| Home / End | first or last reachable item |
- Keys for the other axis are ignored, so a vertical menu does not consume the keys of a horizontal menubar around it.
- The key event is consumed only when focus actually moves. At the end of a non-wrapping group the key propagates further.
- Pass the group's role and label through
attrs, so the keys and the semantics are on the same element.
Group items
pub fn use_roving_item(node: NodeRef) -> Option<RovingItem>;
pub fn use_roving_item_when(node: NodeRef, reachable: Signal<bool, LocalStorage>) -> Option<RovingItem>;
impl RovingItem { // Copy
pub fn tabindex(&self) -> Signal<Focus, LocalStorage>; // Sequential for the active item
pub fn is_active(&self) -> bool;
pub fn activate(&self);
pub fn id(&self) -> ItemId;
pub fn group(&self) -> RovingContext;
}
// RovingContext: collection(), active(), set_active(id), orientation(),
// step(n) -> bool, go_to_end(last) -> bool, current()An item binds tabindex and calls activate when it receives focus, so tabbing away and back
returns to the last active item. Until an item is activated, the first item is the tab stop.
Outside a group the hook returns None; fall back to Focus::Sequential so the item still works on
its own. use_roving_item_when keeps a disabled item in place (and announced) while the arrow keys
skip it.
#[component]
fn ToolbarButton(children: Children) -> impl IntoView {
let node = NodeRef::new();
let item = use_roving_item(node);
view! {
control(
node_ref = node,
tabindex = move || item.map_or(Focus::Sequential, |item| item.tabindex().get()),
on:focus_in = move |_| { if let Some(item) = item { item.activate() } }
) {
{children.into_view_once()}
}
}
}Presence
Keeps content mounted until its exit animation has finished, so you do not have to repeat a CSS duration in Rust.
#[component]
pub fn Presence(
#[prop(into)] present: Signal<bool, LocalStorage>,
surface: NodeRef, // your element, whose animation decides when the content leaves
children: ChildrenFn, // built again each time the content comes back
) -> impl IntoView
pub enum PresenceState { Open, Closed } // name(): "open" | "closed"; is_leaving()
pub fn use_presence() -> Option<PresenceContext>; // state(), state_name()When present becomes false, the state becomes closed, your sheet's [data-state="closed"]
rules start an animation or transition, and the content unmounts when it ends. If nothing is
animating, the content unmounts in the same frame.
- It waits for every running animation and transition on
surfaceto end or be cancelled, so a second animation started mid-exit is not cut off. - It re-attaches its listeners whenever
surfacebinds to a new element, so every opening animates, not just the first (Listeningdoes this). - An exit that has not finished after one second is completed anyway, so a lost animation event cannot leave a scrim and focus trap over the window.
use_presence() only works below the Presence, so the surface that binds data-state must be
its own component. If you write it inline in the parent, there is no exit animation.
DismissableLayer
Closes a surface on Escape or on a press outside it. When several surfaces are open, it decides which one a press or key belongs to.
#[component]
pub fn DismissableLayer(
on_dismiss: UnsyncCallback<DismissReason>, // OutsidePress or EscapeKey
#[prop(default = OverlayLayer::default())] layer: OverlayLayer,
#[prop(into, default = Signal::stored_local(true))]
dismiss_on_outside_press: Signal<bool, LocalStorage>,
#[prop(into, default = Signal::stored_local(true))]
dismiss_on_escape: Signal<bool, LocalStorage>,
#[prop(optional)] exclude: Option<NodeRef>, // an outside element that counts as inside
#[prop(optional)] element_ref: Option<NodeRef>,
#[prop(into, optional)] class: Classes,
children: Children,
) -> impl IntoView- It does not close anything itself. It reports through
on_dismiss, and you decide whether to close. This is how you build a confirmation that refuses to close. - Pass the trigger as
exclude. Otherwise a press on the trigger counts as outside: the layer dismisses, the press becomes a click, and the trigger reopens the surface. - Both listeners are capture listeners on the window root, so the layer decides before anything on
the event's path runs. When the layer handles an Escape, it calls
stop_immediate_propagation, so your own Escape listeners on the root do not run either. (With nothing focused, the root is the key's target.)
Only one layer responds at a time: the one on the highest
overlay band, then the most recently opened. A layer that is
closing (playing its exit animation) still responds to presses, because it is still on screen, but
stops responding to Escape immediately. So two presses of Escape close two nested
dialogs. LayerStack (push, pop, set_leaving, topmost,
answering_escape, …) is public if you need the same bookkeeping.
Collection
Gives a composite control its items in document order, so ↓ moves to the next item even when items are inside conditionals, lists, or nested components.
impl Collection { // Copy
pub fn new() -> Self;
pub fn provide() -> Self;
pub fn current() -> Option<Self>;
pub fn register(&self, node: NodeRef) -> ItemId;
pub fn register_reachable_when(&self, node: NodeRef, reachable: Signal<bool, LocalStorage>) -> ItemId;
pub fn deregister(&self, id: ItemId);
pub fn items(&self) -> Vec<CollectionItem>; // document order, subscribes
pub fn items_untracked(&self) -> Vec<CollectionItem>;
pub fn len(&self) -> usize;
pub fn is_empty(&self) -> bool;
pub fn index_of(&self, id: ItemId) -> Option<usize>;
pub fn at(&self, index: usize) -> Option<CollectionItem>;
pub fn step(&self, from: Option<ItemId>, steps: isize, wrap: bool) -> Option<CollectionItem>;
pub fn end(&self, last: bool) -> Option<CollectionItem>;
}
// CollectionItem: id(), node(), is_reachable(), focus()- Items are ordered by position in the document, not by registration order: a keyed list rebuilds only the rows that moved, so registration order would be wrong.
- Items register themselves; a decorative separator does not register.
- An item deregisters automatically when it unmounts.
stepskips unreachable items and returnsNonewhen none is reachable.- Store an
ItemId, not an index: an index points at a different item once an earlier one is removed.
Binding and Controllable
One protocol for who owns a value, so the same component works both on its own and bound to your state.
pub enum Binding<T: Clone + PartialEq + 'static> {
Unbound, // default
TwoWay(RwSignal<T, LocalStorage>), // From<RwSignal<T, LocalStorage>>
Controlled { read: Signal<T, LocalStorage>, write: UnsyncCallback<T> },
}
impl<T> Binding<T> {
pub fn controlled(read: impl Into<Signal<T, LocalStorage>>, write: impl Fn(T) + 'static) -> Self;
pub fn is_bound(&self) -> bool;
pub fn is_controlled(&self) -> bool;
pub fn get(&self) -> Option<T>;
pub fn get_untracked(&self) -> Option<T>;
pub fn write(&self, next: T);
}| You pass | Variant | A click |
|---|---|---|
| nothing | Unbound | moves the component's own value |
an RwSignal | TwoWay | writes your signal |
Binding::controlled(read, write) | Controlled | calls write; the control moves only if write changes read |
There is no From<Signal<…>> for Binding, so passing a read-only signal is a compile error
rather than a control that silently never moves. If a control must not move, disable it.
Controllable<T> is the value as the component sees it, whoever owns it:
impl<T: Clone + PartialEq + 'static> Controllable<T> { // Copy
pub fn new(binding: Binding<T>, default_value: T, on_change: Option<UnsyncCallback<T>>) -> Self;
pub fn uncontrolled(default_value: T, on_change: Option<UnsyncCallback<T>>) -> Self;
pub fn binding(&self) -> Binding<T>;
pub fn get(&self) -> T;
pub fn get_untracked(&self) -> T;
pub fn signal(&self) -> Signal<T, LocalStorage>;
pub fn is_bound(&self) -> bool;
pub fn is_controlled(&self) -> bool;
pub fn set(&self, next: T);
pub fn update(&self, change: impl FnOnce(&mut T));
}
impl Controllable<bool> { pub fn toggle(&self); }default_valueis used only when the binding isUnbound.on_changeis called in all three cases, after the binding is written. It only observes the change; a bound control works without it.- Calling
setwith the current value does nothing and calls no callbacks, so a caller that echoes changes back cannot cause a loop. - After the owning scope is disposed, a
Bindingreads as unbound (getreturnsNone) andset,updateandtoggledo nothing. An event can reach a component's listener in the same frame that removes the component; this keeps that late write away from disposed state.
How zgui-ui uses the primitives
RadioGroup in zgui-ui is a RovingFocus plus a Controllable, a context and a sheet:
// crates/zgui-ui/src/radio_group/mod.rs, abridged
install_stylesheet(SHEET, RadioGroupStyle::CSS);
let group = NodeRef::new();
provide_local_context(RadioContext {
value: Controllable::new(value, default_value.unwrap_or_default(), on_change),
disabled,
group,
});
view! {
RovingFocus(orientation = orientation, element_ref = group, class = class, {..own}, {..attrs}) {
{children.into_view_once()}
}
}Each item calls use_roving_item on its own control and selects its value on focus, because
moving through a radio group with the arrow keys selects as it goes. The radio group itself has no
key handler.
Build a popover with your own CSS
This example uses only the primitives, nothing else from the library. The nesting order matters:
Portaloutermost, so the surface is not clipped.Presence, so the exit animation finishes before unmounting.DismissableLayer, registered while the surface is on screen.Popperinnermost, because it measures what is already there.
use zgui::prelude::*;
use zgui::{component, css, view};
use zgui_ui_primitives::prelude::*;
#[component]
fn Details() -> impl IntoView {
let open = RwSignal::new_local(false);
let trigger = NodeRef::new();
let surface = NodeRef::new();
view! {
box {
control(
class = "pop-trigger",
node_ref = trigger,
tabindex = Focus::Sequential,
on:click = move |_| open.set(!open.get_untracked())
) {
"Details"
}
Portal(layer = OverlayLayer::Popover) {
Presence(present = Signal::from(open), surface = surface) {
DismissableLayer(
layer = OverlayLayer::Popover,
exclude = trigger,
on_dismiss = UnsyncCallback::new(move |_: DismissReason| open.set(false))
) {
Popper(anchor = trigger, offset = 6.0, class = "pop-at") {
Panel(element_ref = surface)
}
}
}
}
}
}
}
/// Its own component, because `use_presence` reads a context published above it.
#[component]
fn Panel(element_ref: NodeRef) -> impl IntoView {
let presence = use_presence();
view! {
box(
class = "pop-panel",
node_ref = element_ref,
attr:data-state = move || presence.map(|presence| presence.state_name().to_owned())
) {
text {"Nine files, 2.1 MB."}
}
}
}
const SHEET: &str = css!(
".pop-trigger { padding: 6px 12px; border: 1px solid #cdced6; border-radius: 6px; }
.pop-panel {
padding: 12px 14px;
border: 1px solid #d9d9e0;
border-radius: 8px;
background-color: #ffffff;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.16);
transition: opacity 140ms ease-out, transform 140ms ease-out;
}
.pop-panel[data-state=\"closed\"] { opacity: 0; transform: translateY(-4px); }
.pop-at[data-side=\"top\"] > .pop-panel[data-state=\"closed\"] { transform: translateY(4px); }"
);
fn main() -> Result<(), zgui::Error> {
app().with_stylesheet(SHEET).run(|| view! { Details() })
}The panel opens below the trigger, flips above it near the bottom of the window, stays on screen, closes on Escape or a press outside, is not closed by a press on its own trigger, and fades out before it unmounts. Rust and CSS are connected in four places:
| In the code | Why |
|---|---|
attr:data-state = … | lets [data-state="closed"] match |
the transition | is what Presence waits for; without it the panel unmounts immediately |
class = "pop-at" on Popper | gives the positioner a class to select on |
.pop-at[data-side="top"] | slides from the side the panel actually opened on |
To make it modal, wrap the panel's content in FocusScope. To add arrow-key navigation, use
RovingFocus.
Next
Components
The styled components built from these primitives.
Tokens and theming
The design tokens the styled layer reads.
Overlays and portals
Overlay bands, positioning, dismissal and focus containment in the framework.
Keyboard and focus
Traversal order, focus traps and the key vocabulary the primitives use.