Reactive state and styles
mirui drives widget attributes and tree structure declaratively from #[model] instances, Signal<T>, Computed<T>, and StyleSheetPlugin. Mutate a model field or signal and only the widgets that read it update on the next frame—no manual diffing or observer wiring.
For #[compose] functions, res!(T) resources, prop!(T) forwarding, ECS systems, and custom #[view] descriptors, see Composition, roles, and custom views. For storage and autosave, see Persistence.
//~focus-start:reactive
#[model]
pub struct Gauge {
#[observe]
pub level: i32,
}
impl Default for Gauge {
fn default() -> Self {
Self { level: 42 }
}
}
#[model]
impl Gauge {
pub fn step(&mut self, delta: i32) {
self.level = (self.level + delta).clamp(0, 100);
}
}
#[compose]
fn reactive_scene(gauge: model!(Gauge)) {
ui! {
Column (
grow: 1.0,
padding: Padding::all(20),
justify: JustifyContent::SpaceBetween,
text_color: ColorToken::OnSurface
) {
Row (height: 28, justify: JustifyContent::SpaceBetween, align: AlignItems::Center) {
Text (
"Signal binding",
grow: 1.0,
height: 20,
font_size: 14,
text_color: ColorToken::OnSurfaceVariant,
paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
)
Text (
text: ${ format_args!("{} %", gauge.level()) },
capacity: 12,
grow: 1.0,
font_size: 22,
height: 28,
paragraph: ParagraphStyle::label().with_align(TextAlign::End)
)
}
View (height: 14, bg_color: ColorToken::SurfaceVariant, border_radius: 7, clip_children: true) {
View (
width: ${ Dimension::percent(gauge.level()) },
height: Dimension::percent(100),
bg_color: ${ if gauge.level() >= 80 { ColorToken::Primary } else { ColorToken::Secondary } },
border_radius: 7
)
}
Row (height: 40, column_gap: 8) {
Button (
"- 10",
grow: 1.0,
height: 40,
border_radius: 9,
normal_color: ColorToken::SurfaceVariant,
pressed_color: ColorToken::Outline,
text_color: ColorToken::OnSurface
) on Tap { gauge.step(-10); }
Button (
"42",
width: 64,
height: 40,
border_radius: 9,
normal_color: ColorToken::SurfaceVariant,
pressed_color: ColorToken::Outline,
text_color: ColorToken::OnSurfaceVariant
) on Tap { gauge.step(42 - gauge.level()); }
Button (
"+ 10",
grow: 1.0,
height: 40,
border_radius: 9,
normal_color: ColorToken::Primary,
pressed_color: ColorToken::Secondary,
text_color: ColorToken::OnPrimary
) on Tap { gauge.step(10); }
}
}
};
}
//~focus-end:reactiveA callback mutates `gauge.level` from 40 to 50. At the outermost method return, the generated handle compares the `#[observe]` snapshot (`40 != 50`).
gauge.step(10); // 40 -> 50 (snapshot changed)Allocations: 0 B · Widget tree touched: NoRegistered model instances
Place #[model] on a struct and one inherent impl to generate its instance handle and forwarded methods. Each app.add_model(value).finish() call registers an independent instance; cloning a handle refers to the same instance without cloning its data.
use mirui::prelude::*;
#[model]
struct Counter {
#[observe]
count: u32,
}
#[model]
impl Counter {
#[observe]
fn is_even(&self) -> bool { self.count % 2 == 0 }
fn increment(&mut self) { self.count += 1; }
fn decrement(&mut self) { self.count = self.count.saturating_sub(1); }
}
let mut app = App::headless(32, 32);
let counter = app.add_model(Counter { count: 0 }).finish();
counter.increment();- Field getters (
#[observe]):#[observe]creates a handle getter for aClone + Eqfield (includingStringandVec<T>). Readingcounter.count()inside${...}subscribes the widget to that field. Unchanged values and changes restored within the same transaction do not notify subscribers. Field getters return owned clones rather than references into the Model. - Derived getters (
#[observe] fn): An#[observe]method taking&selfwith no arguments and aClone + Eqreturn value publishes only when its computed result changes. - Fallible transactions (
Result<Change, E>): Mutating methods return the model's change type (()by default) orResult<Change, E>. ReturningErrskips publishing observations or revisions and discards pending effects. Validate before modifying the model—rejected commands are not a rollback mechanism. - Named change masks: For changes that cannot be observed as a small value, declare
#[model(change = ChangeSet, watch(visual = ChangeSet::VISUAL))]. A mutating method returning aChangeSetcontainingVISUALincrementsmodel.visual_revision()and notifies its readers. - Business effect extractors (
#[effects]): Declare an effect extractor returningOption<E>or[Option<E>; N]in the markedimpl:
#[effects]
fn take_note(&mut self) -> Option<Note> {
self.pending_note.take()
}
player.on_effect(move |note: &Note| play_note(note.pitch))?;model.on_effect(handler) installs one consumer per effect type and Model instance. Delivery occurs after state publication and release of the Model data borrow; consumers can read committed state but cannot start another Model write transaction.
Owned child models
Declare child: model!(owned Child) inside a #[model] struct to store child data in its parent. Construct the field from raw data with .into() and register only the parent. Use model!(owned ModelList<Item>), model!(owned ModelMap<Key, Item>), or model!(owned ModelSet<Key>) for collections (see Model collections).
use mirui::prelude::*;
#[model]
struct Scoreboard {
left: model!(owned Counter),
right: model!(owned Counter),
}
#[model]
impl Scoreboard {
fn new() -> Self {
Self {
left: Counter { count: 0 }.into(),
right: Counter { count: 0 }.into(),
}
}
#[observe]
fn total(&self) -> u32 {
self.left.count() + self.right.count()
}
fn increment_both(&mut self) {
self.left.increment();
self.right.increment();
}
}One outermost mutating method call commits the whole registered tree, whether called through the parent or a child. Observed fields and derived values publish only when their final values differ.
Model roles (model!(T))
Model roles keep generated handle types out of application signatures. A model!(T) field in a #[component] stores one registered instance, while a model!(T) parameter in a #[compose] function receives one:
use mirui::prelude::*;
use mirui::ui::widgets::{Button, Text};
#[compose]
fn counter_value(counter: model!(Counter), label: &'static str) -> Entity {
ui! {
Text(text: ${ format!("{label}: {}", counter.count()) })
}
}
#[compose]
fn counter_controls(counter: model!(Counter)) {
ui! {
Row {
Button(text: "−") on Tap { counter.decrement(); }
Button(text: "+") on Tap { counter.increment(); }
counter_value(counter, "count")
}
};
}Generated ui! callbacks and direct child compose calls automatically share counter without requiring manual .clone() calls at each use site.
Primitives (Signal, Computed, Effect)
Three standalone reactive primitives live in mirui::core::reactive:
use mirui::core::reactive::{Signal, Computed, Effect};
let count = Signal::new(0i32); // holds a value, tracks readers
count.set(1); // replace
count.update(|n| *n += 1); // mutate in place
let n = count.get(); // read (subscribes the caller)
count.with(|n| println!("{n}")); // borrow without cloning
let doubled = {
let count = count.clone();
Computed::new(move || count.get() * 2) // lazy, recomputes when count changes
};
let _effect = Effect::new(move || {
// re-runs whenever a signal read inside it changes
});Signal<T>owns a standalone reactive value.get()/with()subscribe the current reader;set()/update()mark subscribers dirty.Computed<T>derives a value lazily: it only recomputes when one of its inputs changed, and only when read.Effectruns a closure immediately and re-runs whenever the signals it read change. Inside a composition,effect_with_widget(entity, closure)binds the effect's lifetime to a widget entity.
For a full comparison of #[model], Signal<T>, #[component], #[compose], and #[view], see Choosing state and rendering roles.
Reusable styles
style! produces a typed preset of declared fields. Apply it with style: and override individual fields directly on the widget.
const STEP: StylePreset = style!(grow: 1.0, height: 44, border_radius: 22);
ui! {
Row (column_gap: 4) {
Button (style: STEP, text: "-")
Button (style: STEP, height: 48, text: "+")
}
};Stylesheet classes
Register shared class rules when installing StyleSheetPlugin. A widget can declare one class, an ordered list, or a reactive expression that selects classes. The last class setting a field wins; the widget's own preset and direct inline fields have higher priority.
Use .bind_class(name, getter) on StyleSheetPlugin or StyleSheet to calculate a shared rule from reactive state once per update regardless of how many widgets use it:
#[compose]
fn register_compact_steps() {
res!(mut StyleSheet).with(|mut styles| {
styles.set("step", style!(grow: 1.0, height: 36, border_radius: 18));
});
}Reactive attributes
Inside ui!, prefix an attribute value with $ to bind it reactively. attr: $signal is shorthand for attr: ${ signal.get() }:
let label = Signal::new(0i32);
#[compose]
fn counter_label(label: Signal<i32>) {
ui! {
Text (text: ${ alloc::format!("Count: {}", label.get()) }, height: 40)
};
}When label changes, only that attribute updates—the widget is not rebuilt. Reactive binding is supported on:
- Layout & geometry:
width,height,left,top,direction,visible,scroll_offset - Visual & style:
style,class,bg_color,text_color,border_color,border_width,render_key,Button.normal_color - Text & paths:
text,font_size,Text.paragraph,path - Controls:
ProgressBar.value,Slider.value,Switch.on,Checkbox.checked
Programmatic updates to Slider.value, Switch.on, or Checkbox.checked through reactive bindings update the control and its animation without emitting user gesture events (ValueChanged / Toggled).
Layout-responsive attributes
$ reacts to application state. @ reacts to computed layout geometry and lists every dependency in its head:
ui! {
Column (container: true) {
Text(
"Status",
font_size: @width {
if width < Fixed::from_int(520) { 18_u16 } else { 30_u16 }
},
padding: @(width, height) {
Padding::all(width.min(height) / 24)
}
)
View(id: "stage", width: Dimension::percent(100), height: 180)
Text(
"Stage label",
width: @id(stage).width { stage.width },
top: @id("stage").height as stage_height { stage_height / 8 }
)
}
}Bare width and height resolve to the nearest ancestor marked container: true. Named dependencies use the widget ID registry. One widget can declare up to 4 distinct geometry dependencies with zero runtime allocation.
Reactive control flow
A $ on a control-flow head makes its selection reactive:
#[compose]
fn status_panel(show: Signal<bool>, other: Signal<bool>, state: Signal<Load>) {
ui! {
Column (grow: 1.0) {
if ${ show.get() } {
Text ("visible")
} elif ${ other.get() } {
Text ("alt")
} else {
Text ("hidden")
}
match ${ state.get() } {
Load::Loading => { Text ("loading") }
Load::Ready(s) => { Text (s) }
}
}
};
}if $cond/elif/elseconstruct every branch once, then switch visibility without discarding widget state.match $exprcaches every arm when no pattern binds a value (e.g.,Load::Loading). If any arm binds a payload (as inLoad::Ready(s)), the match rebuilds its active arm when the source changes so the body receives the new payload.- A head without
$is static—evaluated once at build time and never re-run.
Lists
walk iterates a collection. With $ it re-evaluates when the collection changes:
- Index-based (
walk ${ items.get() } with item): rows align by position. Growing appends tail rows; shrinking despawns tail rows. Best for append/drop-tail logs. - Keyed (
walk ${ items.entries() } with row by row.0): rows align by stable identity (ModelItemIdor key). When an item is inserted, removed, or reordered in the middle, surviving rows keep their entities and state.
See Model collections for bounded ModelList, ModelMap, and ModelSet APIs.
The flush model
Setting a signal or mutating a #[model] does not mutate widgets mid-callback. It marks subscribers dirty and enqueues them. On the frame schedule—after systems and plugin updates, and right before layout—flush_signal_dirty drains the queue once: dirty effects re-run and dirty widget properties apply. Multiple mutations to the same source before a flush coalesce into a single update.
Limits
- Observed values:
#[observe]fields and derived getters requireClone + Eq. Owned field observations retain one comparison snapshot per registered instance. - View dependencies:
model!(component.field)alone does not subscribe a custom#[view]; addwatch(...)to subscribe to specific fields, getters, or named revisions. Paint callbacks are read-only. - Computed & Effect ownership:
ComputedandEffectinstances created inside anAppbelong to thatAppand cannot read models from two differentAppinstances. - Cached branches (
if $/match $): Unselected cached branches pause their display-property bindings until selected again, and their widget IDs must be unique across branches. Put nested reactiveif,match, orwalkblocks inside a container widget so their dynamic children stay under the branch root.