Attributes
Everything you can write inside an element's or component's parentheses — plain names, classes, styles, listeners, accessibility, node refs, states, and forwarded bundles.
Attributes are everything between a call's parentheses: row(class = "todo", on:click = select).
They set an element's classes, styles, listeners and accessibility properties, or a component's
props. Most attributes can take a signal or a closure and stay up to date as it changes.
Plain names
A name with no namespace calls the builder method of that name on an element, or the prop setter of that name on a component. Which names are valid depends on the element or component; see Elements.
use zgui::prelude::*;
view! {
column {
image(src = "logo.png", alt = "The logo")
control(disabled = move || busy.get()) {"Save"}
box(hidden = true)
}
}A plain name must be a Rust identifier. For a hyphenated name, use attr:.
Values
A value is one Rust expression. It ends at the , or ) that closes it.
row(state:open = count.get() > 0) // any expression
row(prop:mask = bits >> 2)
row(n = value as Wrapping<u8>)
row(x = if a > b { p } else { q })
row(class = {class}) // optional braces are removed
row(at = {Point { x, y }}) // a struct literal must be braced
For(key = |a: &Todo, b: &Todo| a.id > b.id, each = items) { "x" } // commas inside belong to the valueA struct literal needs braces because its { would otherwise start a children block. Attributes
are separated by commas; row(class = "a" hidden) reports attributes are separated by commas.
Shorthand
A name with no value means name = name, using the variable of that name:
let alt = "The logo";
let hidden = false;
view! {
image(src = "logo.png", alt) // alt = alt
box(hidden) // hidden = hidden
}The shorthand also works in namespaces whose names are identifiers, such as attr:role,
style:gap or a11y:label. Two exceptions:
class:,state:andcustom_state:read a bare name as= true.on:requires a handler;on:clickalone is a compile error.
Namespaces
A prefix before a colon picks what the attribute sets: class:, style:, var:, attr:,
prop:, state:, custom_state:, on:, a11y: and let:. Any other prefix is a compile error
that lists them. The summary at the end of this page shows every form in one table.
Classes
class adds classes to the element's class list. It merges: duplicates are dropped and the order
of first appearance is kept, so you can write it more than once.
vector(class = "mark__art", class = size) // both, in that orderA &str is split on whitespace. A String, a Classes list, or an iterator of ClassName also
work.
class is not reactive. For a class that comes and goes, use class:name, which toggles one
class without touching the others:
row(
class = "todo",
class:done = move || item.done.get(),
class:selected = selected, // a Signal<bool> works directly
)Inline styles
style sets the whole inline style text:
box(style = "gap: 1rem; padding: 4px")style:property sets or removes one declaration:
box(
style:position = "fixed",
style:left = move || Some(format!("{}px", x.get())),
style:top = move || Some(format!("{}px", y.get())),
)style replaces every inline declaration on the element, including those set with style:, so
don't mix the two on one element.
Both take an Option<String>; None removes the declaration. A literal is wrapped in Some for
you, so style:gap = "1rem" works.
A closure must return Option<String>: write move || Some(format!("{}px", x.get())), not
move || format!("{}px", x.get()). var: and attr: work the same way.
An unknown property or an invalid value is dropped with a warning, as in a style sheet. Styling covers where inline declarations sit in the cascade.
On a component, style = … is a compile error, because it would replace whatever the component
set itself. Forward individual declarations with style: instead.
Custom properties
var:--name sets a custom property that a style sheet reads with var(--name). Use it to pass a
computed value to CSS without the view knowing which properties use it.
const SHEET: &str = css!("
.meter__bar { width: var(--fill); background: var(--tone); }
");
view! {
box(class = "meter") {
box(
class = "meter__bar",
var:--fill = move || Some(format!("{}%", percent.get())),
var:--tone = "royalblue",
)
}
}The name must start with --; var:brand is a compile error. The value is an Option<String>. On
a component call, var: is forwarded in the attribute bundle to the element that spreads it.
Custom properties inherit, so setting one on a container reaches every descendant. Themes are built on this; see Theming.
Event listeners
on:event = handler attaches a listener. The event name fixes the handler's argument type, so a
pointer listener reads pointer fields with no annotation.
control(
on:click = move |_| count.update(|n| *n += 1),
on:key_down = move |ev| if ev.key == Key::Named(NamedKey::Enter) { save() },
) {"Add"}Modifiers follow the event name: on:<event>[:<modifier>]* = <handler>.
| Modifier | Effect |
|---|---|
:capture | run on the way down instead of the way up |
:once | remove the listener after it runs |
:passive | promise not to prevent the default behaviour |
:prevent | prevent the default behaviour before the handler runs |
:stop | stop propagation before the handler runs |
Modifiers combine in any order, as in on:click:capture:once. :passive with :prevent is a
compile error.
:capture, :prevent and :stop work. :once and :passive are recorded
but not acted on yet, so a :once listener keeps running.
A listener is attached once, when the element is built. If an element is described again, the old listener is replaced, so a handler is never attached twice.
A closure stored in a variable before it reaches on: fails with implementation of Fn is not general enough, because its argument type could not be inferred. Build it with handler:
let save = handler(events::CLICK, move |_| store.save());
view! { control(on:click = save) {"Save"} }A component's callback prop is an ordinary prop with an underscore, such as on_select = f. It
does not capture or bubble. on:click = f, with a colon, is a real listener.
Events lists every event, its payload, and the dispatch rules.
Accessibility
a11y:name sets one accessibility property: what the element means to assistive technology. All
a11y: attributes on a node are combined into one description, and each one can be reactive.
control(
a11y:role = Role::Button,
a11y:label = "Delete",
a11y:disabled = move || busy.get(),
) {"x"}| Group | Names |
|---|---|
| naming | label, description, placeholder, role_description, state_description, tooltip, keyboard_shortcut |
| value | value, numeric_value, auto_complete |
| condition | disabled, read_only, required, busy, hidden, expanded, selected, modal, invalid, toggled, toggled_on |
| structure | level, orientation, has_popup, current, sort_direction, row_index, column_index, row_span, column_span |
| announcement | live |
| relation | labelled_by, described_by, controls, owns, active_descendant, popup_for, error_message |
- Write
a11y:roleat most once per node. - Without a role, the description does not say what the element is. On a component call, this means your properties merge with the component's own role instead of replacing it.
- A relation names another node: pass a
NodeRef, or a closure returningOption<NodeRef>when the target changes.
let hint = NodeRef::new();
view! {
column {
field(a11y:described_by = hint)
text(node_ref = hint) {"Between 8 and 64 characters."}
}
}Accessibility has the types, the roles, and what the framework derives on its own.
Node references
node_ref = handle records the node this element becomes in a NodeRef you can use later.
NodeRef is Copy.
let field_node = NodeRef::new();
view! {
column {
field(node_ref = field_node)
control(on:click = move |_| field_node.focus()) {"Edit"}
}
}The handle is empty until the element is built and empty again after it is removed, so reads return
an Option instead of panicking. It offers imperative operations such as focus, bounds,
scroll_to, text_content and contains, and observations that turn geometry into signals.
Reading the handle inside a closure re-runs the closure when the handle is filled in or cleared.
Effects and lifecycle covers using one safely.
On a component call, node_ref is an ordinary prop of that component, because only the
component knows which of its elements you mean. If the component has no such prop, the compile
error says so.
Focus
tabindex makes an element focusable and says how it is reached. It takes a Focus, not an
integer:
control(tabindex = Focus::Sequential) {"Save"}
box(tabindex = move || {
if active.get() { Focus::Sequential } else { Focus::Programmatic }
})| Value | Meaning |
|---|---|
Focus::Sequential | reachable with Tab, in document order |
Focus::Programmatic | focusable only from code |
control, field and editor are focusable without it. See
Elements and
Keyboard and focus.
Selector attributes
attr:name sets an attribute that selectors can match. Use it for anything a style sheet or a test
needs to find.
row(
attr:id = "row-1",
attr:data-testid = "summary-row",
attr:data-side = move || Some(side.get().to_owned()),
)#row-1 { font-weight: 600; }
[data-side="top"] { margin-bottom: 4px; }The name may contain hyphens. The value is an Option<String>; None removes the attribute.
There is no id method: attr:id sets the element's id, which #id selectors match. Attribute
selectors also see the id and the class list, so [id], [class~="card"] and [class*="card"]
match what attr:id and class set.
Element properties
prop:name sets a typed property that the element itself reads, such as a drawing's outlines.
Selectors cannot see properties, so a value that changes on every keystroke does not trigger
selector matching.
vector(class = "mark", prop:d = paths, prop:viewBox = "0 0 24 24")The value is a PropValue: Unset, Bool, Integer, Number or Text. &str, String,
bool, i64 and f64 convert into it. A reactive value is a closure returning a PropValue.
PropValue::Unset removes the property.
| Property | Read by | Element |
|---|---|---|
d | the painter, one outline per line | vector |
viewBox | the painter, as min-x min-y width height | vector, canvas |
svg | the painter, as a whole SVG document | vector |
Interaction states
An interaction state is a flag on the element that selectors match, such as :checked. A view can
set eight of them with state:name. The rest (:hover, :focus, …) are computed from input and
cannot be set.
control(
state:disabled = move || busy.get(),
state:checked = move || item.done.get(),
) {"Save"}| Written | Matched by |
|---|---|
state:checked | :checked |
state:disabled | :disabled |
state:indeterminate | :indeterminate |
state:invalid | :invalid |
state:open | :open |
state:placeholder_shown | :placeholder-shown |
state:read_only | :read-only |
state:required | :required |
Any other name is a compile error listing the eight. For hover, active, focus,
focus_visible and focus_within, the error explains that input sets them; a headless test
produces them by sending pointer or keyboard events (see Testing). For
selected, it suggests custom_state:.
control, field and editor also accept disabled = …, which sets the same state.
Custom states
custom_state:name sets a state of your own, matched by :state(name). Use it for conditions the
built-in set does not cover: a step is complete, a row is the drop target, an item is selected.
const SHEET: &str = css!("
.step:state(complete) { color: seagreen; }
");
view! {
row(class = "step", custom_state:complete = move || step.done.get())
}The name is yours and is not checked.
Children arguments
let:name names the argument a component passes to its children. It takes no value and only works
on a component call.
view! {
Repeat(times = 3, let:index) {
text {{index.to_string()}}
}
}for item in … expands to For(each = …, key = …, let:item). See
Children and slots and Control flow.
Forward attributes to an element
{..expr} applies a bundle of attributes where it is written. A component uses it to pass its
caller's classes, listeners and accessibility properties to an element the caller cannot see.
#[component]
fn Button(
/// Whatever the caller forwarded.
#[prop(attrs)]
attrs: Attrs,
children: Children,
) -> impl IntoView {
view! {
control(class = "button", tabindex = Focus::Sequential, {..attrs}) {
{children.into_view_once()}
}
}
}view! {
Button(class = "button--primary", on:click = save, attr:data-testid = "save") {"Save"}
}#[prop(attrs)] marks the prop that receives the bundle. A component may have at most one, and its
setter is always attrs. It defaults to an empty bundle.
Which value wins
Entries apply in written order, and a later entry wins:
control(class:mine = true, {..attrs}, attr:data-x = "1")Here the component's toggle applies first, then the caller's bundle, then data-x, which the
caller cannot override. Put the spread last to let the caller override everything.
| Part | How the bundle combines |
|---|---|
| the class list | merged after the element's own classes, without duplicates |
| the accessibility description | merged over the element's own; the caller's properties win |
| listeners | added; both run, the element's own first |
| everything else | applied in written order; the last write wins |
Build a bundle in Rust
Attrs has a builder, so you can assemble a bundle outside a view:
use zgui::view::{AttrName, ClassName};
let attrs = Attrs::new()
.class_toggle(ClassName::new("mine"), true)
.attribute(AttrName::new("data-role"), "row");
view! { Button({..attrs}) {"Save"} }Elements and components
The same attribute means different things on an element and on a component:
| Written | On an element | On a component |
|---|---|---|
name = value | the builder method | the prop setter |
class = value | the class list | the class prop |
node_ref = handle | records the node | the node_ref prop |
style = value | the inline style | compile error |
let:name | compile error | names the children closure's argument |
slot | compile error | fills a slot of the parent |
| any other namespace | applied to the element | collected into the forwarded bundle |
The last row is why namespaces exist: a component call cannot write to an element directly, because it does not know which element the component renders.
Summary
A reactive attribute accepts a signal or a closure and updates when it changes. A constant is written once at build time.
| Written | Sets | Reactive |
|---|---|---|
name = value | a typed element attribute, or a component prop | depends on the attribute |
name | shorthand for name = name | same |
class = value | classes merged into the class list | no |
class:name = value | one class, on or off | yes |
style = value | the whole inline style | yes |
style:property = value | one inline declaration | yes |
var:--name = value | one custom property | yes |
on:event = handler | a listener | no, attached once |
a11y:name = value | one accessibility property | yes |
node_ref = handle | a handle filled in with the node | no |
tabindex = focus | whether and how the element takes focus | yes |
attr:name = value | one attribute that selectors can match | yes |
prop:name = value | one property the element reads; invisible to selectors | yes |
state:name = value | one of the eight interaction states a view may set | yes |
custom_state:name = value | a state of your own, matched by :state(name) | yes |
let:name | names the argument a component passes to its children | — |
slot, slot = "name" | this component fills a slot of its parent | — |
{..bundle} | replays a forwarded bundle here | each entry keeps its own |
For a value that changes often, prefer class: and custom_state: to style:: the style engine
skips a class or state change that no selector mentions, while an inline declaration is always
cascaded. The cost model has the details.
Compile errors
| You write | The message |
|---|---|
row(x-y = 1) | `x-y` is a name, not an identifier, suggesting attr:x-y |
row(var:brand = "red") | a custom property's name starts with -- |
row(state:hover = true) | not one of the states a view may set |
row(on:click) | `on:click` needs a handler |
row(on:clik = f) | `on:clik` is not an event, with the closest name |
row(on:click:passive:prevent = f) | :passive promises never to prevent the default |
row(on:click:onc = f) | `:onc` is not a listener modifier |
row(let:item) | an element passes its children no argument |
row(slot) | an element cannot fill a slot |
Button(style = "gap: 1rem") | forward style: declarations instead |
Card({attrs}) | suggests the spread, {..attrs} |
Card({..attrs} {..more}) | attributes are separated by commas |
row(at = Point { x, y }) | brace the struct literal |
if move || open.get() (class = "x") { … } | control flow takes no attributes |
Next
Events
Attach listeners with on:, handle clicks, keys, pointer, wheel and scroll input, and control how an event travels through the document.
Styling
Style elements with CSS — writing sheets with css!, style! and variants!, installing them, the cascade, state selectors, custom properties, and a reference of supported CSS.