Without macros
What view!,
The macros in zgui are shorthand. view! expands to builder calls on elements, #[component] to a
function, a props struct and a builder, and css!, style! and variants! to constants and small
types. Everything they generate is ordinary public API, so you can write any interface without them,
or mix the two styles in one application.
The rest of these docs use the macros, because they are shorter and give better compile errors. This page is for readers who prefer plain Rust, want to know what the macros do, or are building their own abstractions on top of zgui.
The same component, both ways
A counter with a label, a reactive class, accessibility properties, a listener and its own stylesheet:
use zgui::prelude::*;
const COUNTER_CSS: &str = css!(
".counter { display: flex; gap: 8px; align-items: center; }
.counter.negative .counter__value { color: crimson; }"
);
#[component]
pub fn Counter(
/// What the counter counts.
#[prop(into)]
title: String,
/// The starting value.
#[prop(default = 0)]
start: i32,
) -> impl IntoView {
install_stylesheet("counter", COUNTER_CSS);
let count = RwSignal::new(start);
view! {
row(
class = "counter",
class:negative = move || count.get() < 0,
a11y:role = Role::Group,
a11y:label = title
) {
label(class = "counter__value") {{move || count.get().to_string()}}
control(
tabindex = Focus::Sequential,
a11y:role = Role::Button,
a11y:label = "Increment",
on:click = move |_| count.update(|n| *n += 1)
) {"+"}
}
}
}
fn main() -> Result<(), zgui::Error> {
app()
.with_title("Counter")
.run(|| view! { Counter(title = "Clicks", start = 2) })
}Both versions build the same document, with the same classes and accessibility tree, and both appear as a component in the inspector. The differences:
- Each node in
view!is a builder call. Children are.child(…)calls. #[component]wraps the body inScoped::named, which gives it its own reactive scope and a name for development tools. The hand-written version does that explicitly.css!only checks the CSS at compile time. Without it, the text is a plain string.
What each macro generates
| Macro | Generates | Write instead |
|---|---|---|
view! | a chain of element builder calls, ShowProps/ForProps for if and for, and a tuple for several roots | the same builder calls |
#[component] | the function itself, a NameProps struct, a builder for it that checks required props at compile time, and render(), which wraps the body in Scoped::named | a props type and a function that returns Scoped::named(…) |
#[slot] | a struct with a builder, filled from a child marked slot | an ordinary struct field on the props type |
css! | the same &'static str, after a structural check | a string literal or include_str! |
style! | a type with a CLASS constant (a class derived from a hash) and a CSS constant with :scope replaced by that class | your own class name and CSS written against it |
variants! | one enum per axis, class()/name() on each, and class_list(), classes() and data_attributes() on the combination | your own enums and a match |
To see the exact expansion of your own code, run cargo expand
on the module that contains it. The expansion names everything through ::zgui::expansion, which
re-exports zgui::view and zgui::elements; in your own code, use those two modules directly.
Build elements
Each element name has a function in zgui::elements that starts a builder. The functions are not in
the prelude, so import the ones you use. box is a Rust keyword, so its function is r#box.
use zgui::elements::{column, label, r#box};
let card = r#box().class("card").child(label().child("Hello"));Every method takes the element by value and returns it, and nothing is created until the view is
built. An Element<T> can be stored, passed to a function and returned like any other value.
Children
In view! | Without the macro |
|---|---|
"text" | .child("text") |
{value} | .child(value), for anything that implements IntoView |
{move || count.get().to_string()} | .child(move || count.get().to_string()): a closure child is a reactive hole |
label { … } | .child(label().child(…)) |
{children.into_view_once()} | .child(children.into_view_once()) |
| several nodes at the root | a tuple: (text().child("Title"), text().child("Subtitle")) |
For a list of children built from an iterator, use .children, which takes AnyViews:
use zgui::elements::{label, row};
fn chips(names: Vec<String>) -> impl IntoView {
row().children(
names
.into_iter()
.map(|name| AnyView::new(label().class("chip").child(name))),
)
}AnyView::new erases a view's type. Use it wherever two branches return different element types.
Attributes
Every attribute form in view! maps to one builder method. Names that view! writes as plain
identifiers become typed names from zgui::view:
In view! | Without the macro |
|---|---|
class = "a b" | .class("a b"). Repeated calls merge, in order, without duplicates. |
class:active = on | .class_toggle(ClassName::new("active"), on) |
style = "…" | .style_text("…"). It replaces all inline declarations. |
style:width = value | .style_property("width", value) |
var:--accent = value | .custom_property(CustomPropertyName::new("accent"), value). The name has no leading --. |
attr:data-kind = value | .attribute(AttrName::new("data-kind"), value) |
prop:name = value | .property(PropKey::new("name"), value) |
state:disabled = on | .state(UiState::DISABLED, on) |
custom_state:busy = on | .custom_state(Ident::new("busy"), on) |
a11y:role = …, a11y:label = … | .a11y(A11yBinding::new(…).label(…)). See Accessibility. |
node_ref = r | .node_ref(r) |
tabindex = Focus::Sequential | .tabindex(Focus::Sequential) |
src = …, alt = …, value = …, placeholder = …, disabled = … | the method of the same name, on the elements that take it |
{..attrs} | .attrs(attrs) |
on:click = handler | .on(events::CLICK, handler). See Listeners. |
The same rule decides what updates as in view!: a plain value is written once, and a signal, memo
or closure is tracked and written again when it changes. The value's type decides this, not how it is
written. Methods that take a value accept anything that implements IntoReactiveValue.
use zgui::elements::column;
use zgui::view::{AttrName, ClassName, CustomPropertyName};
fn panel(busy: RwSignal<bool>, width: RwSignal<f32>) -> impl IntoView {
column()
.class("panel")
.class_toggle(ClassName::new("busy"), move || busy.get())
.style_property("width", move || Some(format!("{}px", width.get())))
.custom_property(CustomPropertyName::new("accent"), "tomato")
.attribute(AttrName::new("data-kind"), "settings")
.state(UiState::DISABLED, move || busy.get())
}.state() accepts any UiState, but a view may only set CHECKED, DISABLED, INDETERMINATE,
INVALID, OPEN, PLACEHOLDER_SHOWN, READ_ONLY and REQUIRED. The input system computes hover,
active and focus states. view! rejects the others at compile time; the builder does not.
Listeners
.on takes an event constant from events and a handler. The constant fixes the handler's argument
type, so an inline closure needs no annotation:
control().on(events::CLICK, move |_| count.update(|n| *n += 1))Listener modifiers become code in the handler or a ListenerOptions value:
In view! | Without the macro |
|---|---|
on:key_down:prevent | call ev.prevent_default() at the start of the handler |
on:key_down:stop | call ev.stop_propagation() at the start of the handler |
on:pointer_down:capture | .on_with(events::POINTER_DOWN, ListenerOptions { capture: true, ..ListenerOptions::DEFAULT }, handler) |
:once, :passive | the once and passive fields of ListenerOptions |
use zgui::elements::field;
fn search(query: RwSignal<String>) -> impl IntoView {
field()
.on(events::KEY_DOWN, move |ev| {
ev.prevent_default();
ev.stop_propagation();
})
.on_with(
events::POINTER_DOWN,
ListenerOptions { capture: true, once: true, ..ListenerOptions::DEFAULT },
move |_| query.set(String::new()),
)
}A closure stored in a variable before it reaches .on does not compile, because Rust cannot infer
its argument type. Build it with handler, as you would for on: in a view
(Define a handler outside the view):
let toggle = handler(events::CLICK, move |_| open.update(|open| *open = !*open));
control().on(events::CLICK, toggle).child("Toggle")Control flow
if and for in a view are shorthand for the Show and For components. Without the macro, use
their props builders, and Dynamic and Portal as values:
use zgui::elements::{column, label, row, text};
#[derive(Clone)]
struct Todo {
id: u32,
title: String,
}
fn todos(items: RwSignal<Vec<Todo>>, tab: RwSignal<u8>, menu_open: RwSignal<bool>) -> impl IntoView {
column()
// if move || items.get().is_empty() { … } else { … }
.child(
ShowProps::builder()
.when(move || items.get().is_empty())
.children(|| label().child("Nothing to do"))
.fallback(move || label().child(move || format!("{} left", items.get().len())))
.build()
.render(),
)
// for todo in move || items.get(), key = |todo: &Todo| todo.id { … }
.child(
ForProps::builder()
.each(move || items.get())
.key(|todo: &Todo| todo.id)
.children(|todo: Todo| row().class("todo").child(todo.title))
.build()
.render(),
)
// A view chosen at run time.
.child(Dynamic::new(move || match tab.get() {
0 => AnyView::new(text().child("Inbox")),
_ => AnyView::new(text().child("Archive")),
}))
// Content on an overlay layer.
.child(
ShowProps::builder()
.when(move || menu_open.get())
.children(|| Portal::new(|| AnyView::new(column().class("menu").child("Menu"))))
.build()
.render(),
)
}They behave exactly as their view forms: the condition and the list are tracked closures, a hidden branch does not exist, and rows are kept by key. See Control flow.
Accessibility
All a11y: attributes on one element become one A11yBinding. Start it with one of three
constructors:
| Constructor | Use it when |
|---|---|
A11yBinding::new(role) | the role is fixed |
A11yBinding::with_role(value) | the role follows a signal or closure |
A11yBinding::unspecified() | you set properties but no role, for example on a component call, so the component's own role is kept |
Each property is a method with the same name as its a11y: attribute, and takes a plain or
reactive value: .label(…), .description(…), .disabled(…), .expanded(…), .selected(…),
.toggled_on(…), .busy(…), .live(…), .level(…) and so on. Relations take a NodeRef, which
resolves once the other element exists:
use zgui::elements::{column, field, label};
fn email(invalid: RwSignal<bool>) -> impl IntoView {
let caption = NodeRef::new();
let error = NodeRef::new();
column()
.child(label().node_ref(caption).child("Email"))
.child(
field()
.tabindex(Focus::Sequential)
.state(UiState::INVALID, move || invalid.get())
.a11y(
A11yBinding::new(Role::TextInput)
.labelled_by(caption)
.error_message(error)
.required(true),
),
)
.child(label().node_ref(error).child("Enter a valid address"))
}Calling .a11y twice on one element merges the bindings, and the later one wins where they
disagree. .attrs(…) merges a caller's binding the same way, which is how a caller's label
overrides a component's. A property with no method yet can be added with .step(|a11y| …).
States and accessibility properties are separate, as in view!: .state(UiState::DISABLED, …)
makes the element match :disabled and leave the tab order, and .disabled(…) on the binding
announces it. Set both. See Accessibility.
Components
What #[component] generates
For the counter at the top of this page, the macro keeps the function and adds a props type. In shortened form:
pub fn Counter(title: String, start: i32) -> impl IntoView { /* your body */ }
pub struct CounterProps { title: String, start: i32 }
impl CounterProps {
pub fn builder() -> CounterPropsBuilder { /* every prop unset */ }
pub const COMPONENT_META: ComponentMeta = ComponentMeta {
name: "my_app::Counter",
file: "src/counter.rs",
line: 7,
};
pub fn render(self) -> impl IntoView {
Scoped::named(&Self::COMPONENT_META, move || Counter(self.title, self.start))
}
}
// CounterPropsBuilder has one setter per prop, and `build()`, which only compiles
// once every required prop is set:
// .title(impl Into<String>) from #[prop(into)]
// .start(i32) from #[prop(default = 0)]A call in a view, Counter(title = "Clicks", start = 2), becomes:
CounterProps::builder().title("Clicks").start(2).build().render()So view! only needs CounterProps in scope at the call site. You can write that chain yourself
to use a macro-defined component from macro-free code.
The generated Counter function is still callable, but calling it directly skips render, so the
body runs without its own scope. Go through CounterProps instead.
Why the scope matters
Scoped is what makes a function a component. It creates a child reactive owner and builds the body
inside it:
| A plain function that returns a view | Scoped::new / Scoped::named | |
|---|---|---|
| signals, effects and stored values it creates | belong to the caller's scope | belong to the component, and are freed when it unmounts |
on_cleanup_local | runs when the caller's scope ends | runs when the component unmounts |
| tasks it spawns | belong to the enclosing component | are cancelled when the component unmounts or rebuilds |
provide_context | visible to the caller's other children too | visible only inside the component |
| shown in the inspector's component tree | no | only with Scoped::named |
A function with no state of its own, such as one that styles a button, can stay a plain function. Use
Scoped as soon as it creates signals, effects, tasks, timers or context.
Write props by hand
The props type is any struct you like. A common shape is a new that takes the required props and
setters for the optional ones. Each #[prop] option has a plain Rust equivalent:
With #[component] | Without |
|---|---|
| a prop with no attribute (required) | an argument of new |
#[prop(into)] | a setter or argument that takes impl Into<T> |
#[prop(optional)] | a field initialised with Default::default() |
#[prop(default = expr)] | a field initialised with expr |
Option<T> with optional | an Option<T> field and a setter that takes T |
Signal<T> with into | a setter that takes impl Into<Signal<T>>, so callers can pass a value, a signal or a memo |
children: Children | a Children field, made with Children::from_view(view) or Children::new(|| AnyView::new(…)) |
children: ChildrenFn | a ChildrenFn field, for children built more than once |
children with let: | a field holding a closure that takes the value |
a #[slot] | an ordinary field, often an Option |
#[prop(into, optional)] class: Classes | a Classes field, applied with a second .class(…) on the root |
#[prop(attrs)] attrs: Attrs | an Attrs field, applied with .attrs(…) on the root, last |
a callback prop such as on_close | a Callback<T> field, or UnsyncCallback<T> for closures that are not Send |
A panel with children, a callback and forwarded classes and attributes:
use zgui::elements::{column, control, label, row};
use zgui::view::{ComponentMeta, Scoped};
pub struct PanelProps {
title: String,
on_close: Option<Callback<()>>,
class: Classes,
attrs: Attrs,
children: Children,
}
impl PanelProps {
pub fn new(title: impl Into<String>, children: impl IntoView + 'static) -> Self {
Self {
title: title.into(),
on_close: None,
class: Classes::default(),
attrs: Attrs::new(),
children: Children::from_view(children),
}
}
pub fn on_close(mut self, on_close: impl Fn(()) + Send + Sync + 'static) -> Self {
self.on_close = Some(Callback::new(on_close));
self
}
pub fn class(mut self, class: impl Into<Classes>) -> Self {
self.class = class.into();
self
}
pub fn attrs(mut self, attrs: Attrs) -> Self {
self.attrs = attrs;
self
}
}
static PANEL: ComponentMeta = ComponentMeta {
name: concat!(module_path!(), "::Panel"),
file: file!(),
line: line!(),
};
pub fn panel(props: PanelProps) -> impl IntoView {
Scoped::named(&PANEL, move || {
let PanelProps { title, on_close, class, attrs, children } = props;
column()
.class("panel")
.class(class)
.a11y(A11yBinding::new(Role::Group).label(title.clone()))
// The caller's bundle goes last, so it wins over the component's own values.
.attrs(attrs)
.child(
row()
.class("panel__header")
.child(label().child(title))
.child(
control()
.a11y(A11yBinding::new(Role::Button).label("Close"))
.on(events::CLICK, move |_| {
if let Some(on_close) = &on_close {
on_close.run(());
}
})
.child("×"),
),
)
.child(children.into_view_once())
})
}
// Using it:
let details = panel(
PanelProps::new("Details", label().child("Body"))
.class("wide")
.on_close(move |()| open.set(false)),
);To forward attributes from Rust, build an Attrs bundle with the same methods as an element:
Attrs::new().attribute(AttrName::new("data-kind"), "demo"). See
Forward attributes to an element for the
merge rules.
Mix both styles
The two styles combine freely, in both directions.
- A builder inside a view is a braced child, because every element implements
IntoView:view! { row { {panel(PanelProps::new("Details", "Body"))} } }. - A view inside a builder is a child like any other:
.child(view! { Counter(title = "Clicks") }). - A macro component from Rust is its props chain:
CounterProps::builder().title("Clicks").build().render().
A hand-written component can also be called with component syntax in view!. The call
Badge(text = "New", tone = "info") only requires a BadgeProps type in scope with a builder()
function, one method per prop, build() and render():
use zgui::elements::label;
use zgui::view::{ComponentMeta, Scoped};
#[derive(Default)]
pub struct BadgeProps {
text: String,
tone: Option<String>,
}
impl BadgeProps {
pub fn builder() -> Self {
Self::default()
}
pub fn text(mut self, text: impl Into<String>) -> Self {
self.text = text.into();
self
}
pub fn tone(mut self, tone: impl Into<String>) -> Self {
self.tone = Some(tone.into());
self
}
pub fn build(self) -> Self {
self
}
pub fn render(self) -> impl IntoView {
static META: ComponentMeta = ComponentMeta {
name: concat!(module_path!(), "::Badge"),
file: file!(),
line: line!(),
};
Scoped::named(&META, move || {
label()
.class("badge")
.class(self.tone.unwrap_or_default())
.child(self.text)
})
}
}
let badge = view! { Badge(text = "New", tone = "info") };This version has no compile-time check for missing props. #[component] gets that check from a
builder whose type records which required props are set.
Styles
Plain stylesheets
css! returns the text you gave it, unchanged. Its only job is a structural check at compile time:
unclosed blocks, strings and comments, rules with no selector, declarations with no value, and //
comments, which CSS does not have. Without it, use a string literal or load a file:
const APP_CSS: &str = include_str!("app.css");
app().with_stylesheet(APP_CSS).run(|| root())The CSS parser still checks the sheet when it is installed. Anything it cannot use is dropped and
logged under the zgui::css tracing target, in debug and release builds. See
Invalid CSS.
Scoped component styles
style! { pub ToolbarStyle => ":scope { … }" } generates a type with two constants:
CLASS, which iszs-followed by a hash of the name and the CSS. It changes when the CSS changes.CSS, the rules with every:scopeoutside strings and comments replaced by.and that class.
Without the macro, choose a class name that no other sheet uses and write the CSS against it. Prefix it with your crate's name:
use zgui::elements::row;
pub struct ToolbarStyle;
impl ToolbarStyle {
pub const CLASS: &'static str = "my-app-toolbar";
pub const CSS: &'static str = "
.my-app-toolbar { display: flex; gap: 4px; }
.my-app-toolbar > control { flex: none; }
";
}
fn toolbar() -> impl IntoView {
install_stylesheet(ToolbarStyle::CLASS, ToolbarStyle::CSS);
row().class(ToolbarStyle::CLASS)
}install_stylesheet is the same call either way. Installing a name that is already installed with
the same text does nothing, so a component can call it from its body every time it is built. The
stylesheet name is shared by the whole document, which is why the class makes a good name.
Variants
variants! generates an enum per axis with a class() method, plus helpers that join the classes
or produce data-* attributes. By hand, write the enum and match on it:
use zgui::elements::control;
use zgui::view::AttrName;
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub enum ButtonVariant {
#[default]
Default,
Outline,
Ghost,
}
fn button(variant: Signal<ButtonVariant>) -> impl IntoView {
control().class("btn").attribute(AttrName::new("data-variant"), move || {
let name = match variant.get() {
ButtonVariant::Default => "default",
ButtonVariant::Outline => "outline",
ButtonVariant::Ghost => "ghost",
};
Some(name.to_owned())
})
}A stylesheet then selects on .btn[data-variant=outline].
Debugging and tooling
Compile errors
The macros check more at compile time and report errors in terms of what you wrote. Without them, the same mistakes are ordinary type errors, or are found at run time:
| Mistake | With macros | Without |
|---|---|---|
| a required prop is missing | "`Counter` is missing the required prop `title`" | depends on your props type; arguments of new are checked by the compiler |
| a misspelled event | "`on:clik` is not an event", with the closest name | an unresolved events:: constant |
a view sets a state such as hover | an error listing the allowed states | compiles; see the warning under Attributes |
| broken CSS structure | a compile error pointing at the sheet | a zgui::css warning when the sheet is installed |
The inspector's component tree
The inspector shows each component instance with its name, file
and line. That information comes from the ComponentMeta passed to Scoped::named. With the
instrument feature on, which the inspector turns on, each named instance puts two marker nodes
around its content (see Component boundaries).
Scoped::named(&META, …)appears in the tree like a#[component].Scoped::new(…)has its own scope but no name, so it does not appear.- A plain function does not appear; its elements are listed under the nearest named component.
Use concat!(module_path!(), "::Name"), file!() and line!() for the metadata, as the examples on
this page do. The macro fills in the same values.
Tests
The testkits work on the built document, so they do not care how a view
was written. A test that mounts counter(CounterProps::new("Clicks")) and one that mounts
view! { Counter(title = "Clicks") } see the same tree, the same classes and the same accessibility
properties.