Skip to content
Development

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.

Model
612#[model]
613pub struct Gauge {
614 #[observe]
615 pub level: i32,
616}
617
618impl Default for Gauge {
619 fn default() -> Self {
620 Self { level: 42 }
621 }
622}
623
624#[model]
625impl Gauge {
626 pub fn step(&mut self, delta: i32) {
627 self.level = (self.level + delta).clamp(0, 100);
628 }
629}
630
631#[compose]
632fn reactive_scene(gauge: model!(Gauge)) {
633 ui! {
634 Column (
635 grow: 1.0,
636 padding: Padding::all(20),
637 justify: JustifyContent::SpaceBetween,
638 text_color: ColorToken::OnSurface
639 ) {
640 Row (height: 28, justify: JustifyContent::SpaceBetween, align: AlignItems::Center) {
641 Text (
642 "Signal binding",
643 grow: 1.0,
644 height: 20,
645 font_size: 14,
646 text_color: ColorToken::OnSurfaceVariant,
647 paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
648 )
649 Text (
650 text: ${ format_args!("{} %", gauge.level()) },
651 capacity: 12,
652 grow: 1.0,
653 font_size: 22,
654 height: 28,
655 paragraph: ParagraphStyle::label().with_align(TextAlign::End)
656 )
657 }
658 View (height: 14, bg_color: ColorToken::SurfaceVariant, border_radius: 7, clip_children: true) {
659 View (
660 width: ${ Dimension::percent(gauge.level()) },
661 height: Dimension::percent(100),
662 bg_color: ${ if gauge.level() >= 80 { ColorToken::Primary } else { ColorToken::Secondary } },
663 border_radius: 7
664 )
665 }
666 Row (height: 40, column_gap: 8) {
667 Button (
668 "- 10",
669 grow: 1.0,
670 height: 40,
671 border_radius: 9,
672 normal_color: ColorToken::SurfaceVariant,
673 pressed_color: ColorToken::Outline,
674 text_color: ColorToken::OnSurface
675 ) on Tap { gauge.step(-10); }
676 Button (
677 "42",
678 width: 64,
679 height: 40,
680 border_radius: 9,
681 normal_color: ColorToken::SurfaceVariant,
682 pressed_color: ColorToken::Outline,
683 text_color: ColorToken::OnSurfaceVariant
684 ) on Tap { gauge.step(42 - gauge.level()); }
685 Button (
686 "+ 10",
687 grow: 1.0,
688 height: 40,
689 border_radius: 9,
690 normal_color: ColorToken::Primary,
691 pressed_color: ColorToken::Secondary,
692 text_color: ColorToken::OnPrimary
693 ) on Tap { gauge.step(10); }
694 }
695 }
696 };
697}
Loading preview…

Tap + 10 or - 10 to mutate Gauge::level—the label text, percentage bar width, and threshold color update on the same frame.

REACTIVE FLUSH PIPELINESingle-frame dirty coalescing & partial damage

A 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: No

Registered 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.

rust
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 a Clone + Eq field (including String and Vec<T>). Reading counter.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 &self with no arguments and a Clone + Eq return value publishes only when its computed result changes.
  • Fallible transactions (Result<Change, E>): Mutating methods return the model's change type (() by default) or Result<Change, E>. Returning Err skips 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 a ChangeSet containing VISUAL increments model.visual_revision() and notifies its readers.
  • Business effect extractors (#[effects]): Declare an effect extractor returning Option<E> or [Option<E>; N] in the marked impl:
rust
#[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).

rust
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:

rust
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:

rust
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.
  • Effect runs 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.

rust
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.

StyleSheetPlugin
113 app.add_plugin(
114 StyleSheetPlugin::new()
115 .class("pill", style!(height: 36, border_radius: 8))
116 .class("pill.on", style!(text_color: ColorToken::Primary))
117 .class("pill.off", style!(text_color: ColorToken::OnSurfaceVariant)),
118 );
⋯recipes.rs:483
483#[model]
484#[derive(Default)]
485pub struct MiniPill {
486 #[observe]
487 pub active: bool,
488}
489
490#[model]
491impl MiniPill {
492 pub fn toggle(&mut self) {
493 self.active = !self.active;
494 }
495}
496
497#[compose]
498fn status_badge(title: prop!(String), active: prop!(bool), pill: model!(MiniPill)) -> Entity {
499 ui! {
500 Button (
501 text: ${ title },
502 grow: 1.0,
503 normal_color: ColorToken::SurfaceVariant,
504 pressed_color: ColorToken::Outline,
505 class: ${ ("pill", if active.get() { "pill.on" } else { "pill.off" }) }
506 ) on Tap { pill.toggle(); }
507 }
508}
509
510#[compose]
511fn mini_style_scene(pill: model!(MiniPill)) {
512 ui! {
513 Column (
514 grow: 1.0,
515 padding: Padding::all(20),
516 justify: JustifyContent::SpaceBetween,
517 text_color: ColorToken::OnSurface
518 ) {
519 Text (
520 "Both buttons share #[compose] & the 'pill' stylesheet class",
521 height: 20,
522 font_size: 13,
523 text_color: ColorToken::OnSurfaceVariant
524 )
525 Row (height: 44, column_gap: 10, align: AlignItems::Center) {
526 status_badge (
527 ${ if pill.active() { "● Active class (.pill.on)" } else { "○ Muted class (.pill.off)" } },
528 ${ pill.active() },
529 pill
530 )
531 status_badge ("Mirror badge", ${ !pill.active() }, pill)
532 }
533 }
534 };
535}
Loading preview…

Tap either pill—both buttons share the "pill" class and dynamically switch between "pill.on" and "pill.off".

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:

rust
#[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() }:

rust
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:

@width & @id(stage)
2167#[compose]
2168fn state_at_scene() {
2169 ui! {
2170 Column (
2171 container: true,
2172 grow: 1.0,
2173 padding: Padding::all(18),
2174 justify: JustifyContent::SpaceBetween,
2175 text_color: ColorToken::OnSurface
2176 ) {
2177 Text (
2178 "Drag the bottom-right grip to cross 320 px",
2179 height: 28,
2180 font_size: @width {
2181 if width < Fixed::from_int(320) { 13_u16 } else { 18_u16 }
2182 },
2183 text_color: ColorToken::Primary
2184 )
2185 View (
2186 id: "stage",
2187 width: Dimension::percent(100),
2188 height: 44,
2189 padding: Padding::all(12),
2190 bg_color: ColorToken::Secondary,
2191 border_radius: 8
2192 ) {
2193 Text ("#stage (100% width)", height: 20, font_size: 13, text_color: ColorToken::OnSecondary)
2194 }
2195 View (
2196 width: @id(stage).width { stage.width / 2 },
2197 height: 36,
2198 padding: Padding::all(8),
2199 bg_color: ColorToken::SurfaceVariant,
2200 border_radius: 8
2201 ) {
2202 Text ("@id(stage).width / 2", height: 20, font_size: 12)
2203 }
2204 }
2205 };
2206}
Loading preview…

Drag the bottom-right resize grip so the container width crosses 320 px—the top label switches font size via @width, while the bottom bar tracks @id(stage).width / 2.

rust
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:

rust
#[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 / else construct every branch once, then switch visibility without discarding widget state.
  • match $expr caches every arm when no pattern binds a value (e.g., Load::Loading). If any arm binds a payload (as in Load::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 (ModelItemId or 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 require Clone + Eq. Owned field observations retain one comparison snapshot per registered instance.
  • View dependencies: model!(component.field) alone does not subscribe a custom #[view]; add watch(...) to subscribe to specific fields, getters, or named revisions. Paint callbacks are read-only.
  • Computed & Effect ownership: Computed and Effect instances created inside an App belong to that App and cannot read models from two different App instances.
  • 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 reactive if, match, or walk blocks inside a container widget so their dynamic children stay under the branch root.