Skip to content
Development

Composition, roles, and custom views ​

How #[compose] functions, resource borrows (res!), forwarded props (prop!), ECS systems (#[system]), and custom view descriptors (#[view] / ui!(compose Name)) fit together.

For reactive models, signals, and stylesheets, see Reactive state and styles. For event payload routing and gesture recognition, see Events and callbacks.

Composition & Flexbox
699#[model]
700#[derive(Default)]
701pub struct FlexDeck {
702 #[observe]
703 pub compact: bool,
704}
705
706#[model]
707impl FlexDeck {
708 pub fn toggle(&mut self) {
709 self.compact = !self.compact;
710 }
711}
712
713#[compose]
714fn layout_scene(deck: model!(FlexDeck)) {
715 ui! {
716 Column (
717 grow: 1.0,
718 padding: Padding::all(18),
719 row_gap: 12,
720 text_color: ColorToken::OnSurface
721 ) {
722 Row (height: 34, column_gap: 8, align: AlignItems::Center) {
723 Text (
724 text: ${ if deck.compact() { "Compact · 96 px card" } else { "Expanded · 156 px card" } },
725 capacity: 28,
726 grow: 1.0,
727 min_width: 0,
728 height: 22,
729 font_size: 13,
730 text_color: ColorToken::OnSurfaceVariant,
731 paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
732 )
733 Button (
734 "Toggle width",
735 width: 112,
736 height: 32,
737 font_size: 12,
738 border_radius: 8,
739 normal_color: ColorToken::Primary,
740 pressed_color: ColorToken::Secondary,
741 text_color: ColorToken::OnPrimary
742 ) on Tap { deck.toggle(); }
743 }
744 Row (
745 grow: 1.0,
746 padding: Padding::all(14),
747 column_gap: 10,
748 align: AlignItems::Center,
749 justify: JustifyContent::SpaceBetween,
750 bg_color: ColorToken::SurfaceVariant,
751 border_radius: 12
752 ) {
753 Column (
754 width: ${ Dimension::px(if deck.compact() { 96 } else { 156 }) },
755 height: 76,
756 padding: Padding::all(10),
757 justify: JustifyContent::SpaceBetween,
758 bg_color: ColorToken::Surface,
759 border_radius: 9
760 ) {
761 View (width: 24, height: 6, bg_color: ColorToken::Primary, border_radius: 3)
762 Text ("Primary", font_size: 12, height: 18)
763 }
764 Column (
765 grow: 1.0,
766 height: 76,
767 padding: Padding::all(10),
768 justify: JustifyContent::SpaceBetween,
769 bg_color: ColorToken::Surface,
770 border_radius: 9
771 ) {
772 View (width: 36, height: 6, bg_color: ColorToken::Secondary, border_radius: 3)
773 Text ("Flex grow: 1.0", font_size: 12, height: 18, text_color: ColorToken::OnSurfaceVariant)
774 }
775 }
776 }
777 };
778}
Loading preview…

Tap Toggle width or drag the bottom-right grip to resize the viewport—the primary card switches between 96 px and 156 px while its grow: 1.0 sibling claims the rest of the row.


Choosing state and rendering roles ​

COMPOSITION & ECS ROLES UMLStatic relationship between #[model], #[component], #[compose], #[event], #[system] & #[view]

`#[model]` holds application domain state with fine-grained `#[observe]` tracking; `#[component]` stores per-widget ECS data attached to entities; `Resource` stores app-wide services.

let model = app.add_model(Counter::default()).finish();Zero World exposure in user code
RoleUseUpdate path
#[model]Registered business state, including multiple instances of one typeGenerated handle methods compare #[observe] values, publish named revisions, and deliver typed effects
Signal<T>A standalone reactive value or a value published by another ownerset / update notify reactive readers
#[component]Data attached to an entityWorld insertion and replacement drive component lifecycle; model!(T) fields retain registered model identity
#[compose]Build a widget subtreemodel!(T) parameters share instances; prop!(T) inputs forward static values or getters to consuming bindings
com!(entity, T)Read a component during compositionReturns a short-lived Option<&T> without subscribing; event callbacks use query! parameters
View / #[view]Register a widget kind; nonempty bodies supply painting and empty bodies omit itIndependent hooks provide painting, attachment, gestures, observation, and systems; typed roles declare model projections and resources
#[system]Scheduled updatesmodel!(T) captures a registered instance; res!, query!, and commands! declare all other runtime access
on Event { ... }Handle gesture and widget business eventsevent borrows the typed payload; commands!() defers structural changes; callback parameters provide resource and query access
#[timer]Run a callback on a time schedulemodel!, entity!, and commands! declare callback access
#[animate]Apply a scalar motion to component statemotion!, component!, model!, entity!, and commands! declare frame access
AudioHandleShared output controls when the audio feature is enabledHost UI and demo controls read one output state and submit to one bounded bus
WorldLow-level entity, component, and resource accessAvailable for integration code; ordinary model methods and UI callbacks do not need it

#[model] does not replace components: a model has application-level identity, while components attach behavior and model bindings to individual entities. #[view] does not replace composition: it declares a widget's behavior and optional paint callback, while #[compose] builds its surrounding widget tree. Signal<T> remains useful for a small independent value; a model does not need to wrap every signal.

#[system], #[event], #[timer], #[view], and #[animate] share callback attribute routing. Conditional compilation applies to every generated item. Function attributes such as inline apply to the callback body; documentation applies to its registration module or generated motion component. cfg_attr entries are split by that purpose, and malformed or nested entries are rejected.

System, event, timer, and View factories preserve authored self:: and super:: paths when generating their registration modules. This includes typed roles, access plans, View generic bounds and hooks, and timer schedule expressions. The body remains in its declaration scope. Generic Views forward type and const arguments explicitly, including types used through associated resource types.


Compositions and prop!(T) inputs ​

Calling a #[compose] function prepares a stack-held composition without executing its body. All arguments remain owned or borrowed by that value until it is executed or dropped. Model validation, resource access, bindings, and widget creation run inside App::compose; preparing a composition does not require an active application owner. Composition outputs use concrete Rust types, including generics. Returned references may borrow application data supplied as arguments, but not the construction scope or its resources.

App::compose returns the composition's result, including entity IDs and owned values. Computed and Effect values created in that call belong to the application. Its construction scope does not escape the call; reactive ownership is restored and dirty storage is prepared before the result is returned. Structural World windows are internal to generated bindings and tree updates, not an authoring entry point.

Keep visual styling on the nodes a composition creates. Orbit Console sets its background on its own shell node without changing the caller's parent background.

Zero-allocation prop forwarding (Prop<T> & prop!(T)) ​

Prop<T> carries a static value or a shared read-only getter. Prop::from(value) stores a value; Prop::new(move || source.get()) retains a getter without evaluating it. get() reads in the caller's reactive scope, so a widget binding subscribes to the original sources. Cloning a dynamic prop shares its getter without allocating or registering another consumer. Each read evaluates the getter; use Computed when a result needs caching. Static props add no framework allocation, while each dynamic prop allocates one shared closure during preparation.

Declare composition inputs with prop!(T). Pass an ordinary value for static content or ${expression} for a getter. Intermediate compositions forward the input directly; the final widget's ${text} reads the prop in its existing binding. This registers no intermediate effects and does not reconstruct the subtree when a source changes. Static values and ${expression} results convert to the declared input type through Into; String inputs accept &str and String.

rust
use mirui::prelude::*;
use mirui::ui::widgets::Text;

#[compose]
fn caption(text: prop!(String)) -> Entity {
    ui! { Text(text: ${text}) }
}

#[compose]
fn header(text: prop!(String)) -> Entity {
    ui! { caption(text) }
}

#[compose]
fn panel(title: model!(Signal<String>)) {
    ui! {
        Column {
            header("Static subtitle")
            header(${title.get()})
        }
    };
}

Application resources (res!) ​

App::add_resource(value) immediately installs a resource in the application's existing World storage. Values move into storage without a Clone or Copy requirement; adding the same type replaces and drops its previous value. Callbacks borrow the current value through res!(T) or res!(mut T). Structural changes during a callback continue to use deferred commands.insert_resource(value) and commands.remove_resource::<T>() after parameter borrows end. Resource installation does not create model observations or a second resource registry.

Within a #[compose] Rust body, resource expressions access that composition's existing application storage. Each with closure borrows only for its call and returns a value independent of the resource reference.

OperationExpressionResult
Read a required resourceres!(T).with(read)read receives ResourceRef<'_, T>
Read an optional resourceres!(optional T).with(read)read receives Option<ResourceRef<'_, T>>
Mutate a required resourceres!(mut T).with(write)write receives ResourceMut<'_, T>
Install or replace a resourceres!().insert(value)Immediate replacement; the previous value drops
Remove a resourceres!().remove::<T>()Option<T>
rust
struct PanelConfig {
    gap: i32,
}

#[compose]
fn configured_panel() {
    let gap = res!(PanelConfig).with(|config| config.gap);
    ui! {
        Column (gap: gap) {}
    };
}

app.add_resource(PanelConfig { gap: 8 });
app.compose(root, configured_panel());

Only res!(optional T) permits an absent resource. Use required roles for dependencies installed by application or composition setup; use optional roles when absence is part of the callback's behavior, such as checking whether a clock is installed or reading a cache before its first update. Dereferencing a resource never creates a default value.

Compute resource-backed arguments before passing them to ui!, format!, or another macro; the composition attribute does not rewrite another macro's tokens.


Named widget identities (id) ​

Application creation supplies the named-widget ID registry. Compositions declare id: ... without initializing that registry, and existing named entries remain available to later compositions.

id("source") and id(source) can reference a later named widget in the same static sibling sequence, including references inside an earlier sibling's children or child-composition arguments. The macro reserves that widget's identity before executing the sequence; it initializes components, attaches the widget, and appends children in declaration order. A forward reference supplies an Entity, not an already initialized component set. IDs declared inside a conditional branch, loop body, child composition, or Niche are not reserved outside that scope. Names remain unique across the application.

rust
ui! {
    View () {
        View () [DropShadow::new(id("source"))]
        View (id: "source", width: 80, height: 40)
    }
}

Programmatic builders (App::compose closures) ​

For construction without the UI DSL, pass a closure to App::compose. Its scope accepts components, typed widget builders, and tuples of both. children returns the container entity and the closure's result.

rust
let (panel, slider) = app.compose(root, |tree| {
    tree.children(panel_style(), |column| {
        column.spawn(Text::build("Level").style(label_style()));
        let source = controls.clone();
        let slider = column.spawn(
            Slider::build(0, 100)
                .bind_property::<prop::SliderValue>(move || source.level())
                .fill_color(ColorToken::Primary)
                .style(slider_style())
                .on_event(Slider::ValueChanged, level_changed::callback(controls.clone())),
        );
        column.spawn((
            Button::build().on_event(Tap::EVENT, reset::callback(controls.clone())),
            Text::label("Reset"),
        ));
        slider
    })
});

Typed builders retain their widget type across bind_property, on_event, and style configuration. Properties use the existing reactive effects and property setters; programmatic updates do not emit widget input notifications. tree.on_event(entity, key, callback) installs a callback on an already constructed node and validates its attached source.


Systems, queries, and timers (#[system], #[timer], #[animate]) ​

Systems declare model, resource, query, and deferred-command roles explicitly. The authored function does not receive World:

rust
#[system(order = Animation)]
fn advance(
    counter: model!(Counter),
    delta: res!(mirui::ecs::DeltaTimeMs),
) {
    for _ in 0..delta.0 {
        counter.increment();
    }
}

app.add_system(advance::system(counter.clone()));

Queries also support point fetches via rows.get(entity):

rust
#[system]
fn update_selected(
    selected: res!(SelectedEntity),
    rows: query!(mut Position, optional Velocity),
) {
    if let Some((position, velocity)) = rows.get(selected.0) {
        if let Some(velocity) = velocity {
            position.x += velocity.x;
        }
    }
}

Timers (#[timer]) ​

#[timer] declares one schedule (after = ms, every = ms, repeat = (count, ms), or until = (deadline, ms)) and typed callback roles:

rust
#[timer(every = 1_000)]
fn tick(
    counter: model!(Counter),
    timer: entity!(),
    commands: commands!(),
) {
    counter.increment();
    commands.insert(timer, Selected);
}

app.add_timer(tick::timer(counter));

Scalar motion applicators (#[animate]) ​

#[animate] declares how a scalar Motion is applied. It generates the named motion component and a system constructor:

rust
use mirui::anim::{Motion, Tween};

#[component]
struct Opacity(Fixed);

#[animate(component = AnimateOpacity)]
fn apply_opacity(value: motion!(), opacity: component!(mut Opacity)) {
    opacity.0 = value;
}

app.add_system(AnimateOpacity::system());

Custom Views (#[view]) ​

#[view] generates a filtered View from its component attribute and builds model subscriptions from typed parameter roles:

rust
#[view(component = CounterTile, priority = 60, invalidation = Visual)]
fn paint_counter(
    counter: model!(component.counter, watch(count)),
    entity: entity!(),
    paint: paint!(),
) {
    let _ = (counter.count, entity, paint.rect());
}

app.with_widget(paint_counter::view());
  • model!(component.field, watch(selector)) borrows that component's model during paint and subscribes to an #[observe] field, getter, or named revision.
  • invalidation = Layout promotes watched changes from visual to layout invalidation; Visual is the default.
  • attach = initialize::callback(), input = (tap::callback(), key::callback()), and systems = [...] declare widget lifecycle and input capabilities.
  • A custom widget can also expose a reactive attribute on a component field with #[property(P)] where P: Property.
  • An empty #[view] body (such as TabPages or LazyList) registers attachment, observation, and systems without a paint callback.

Reusable Niches (ui!(compose Name)) ​

ui!(compose Name { ... }) declares a Niche with tree and slot attachment (@@slot_name / @slot_name { ... }) but no paint hook. Register its descriptor with app.with_widget(ui!(compose Name)):

ui!(compose Name)
2102ui!(compose StatusCard(title: prop!(String)) {
2103 Column (
2104 height: 92,
2105 padding: Padding::all(14),
2106 justify: JustifyContent::SpaceBetween,
2107 bg_color: ColorToken::SurfaceVariant,
2108 border_radius: 10
2109 ) {
2110 Text (text: ${ title }, height: 22, font_size: 15, text_color: ColorToken::Primary)
2111 @@body
2112 }
2113});
2114
2115#[model]
2116#[derive(Default)]
2117pub struct NicheState {
2118 #[observe]
2119 pub online: bool,
2120}
2121
2122#[model]
2123impl NicheState {
2124 pub fn toggle(&mut self) {
2125 self.online = !self.online;
2126 }
2127}
2128
2129#[compose]
2130fn compose_niche_scene(state: model!(NicheState)) {
2131 ui! {
2132 Column (
2133 grow: 1.0,
2134 padding: Padding::all(16),
2135 justify: JustifyContent::Center,
2136 text_color: ColorToken::OnSurface
2137 ) {
2138 StatusCard (
2139 title: ${ if state.online() { "StatusCard · Online" } else { "StatusCard · Standby" } }
2140 ) {
2141 @body {
2142 Row (height: 32, align: AlignItems::Center) {
2143 Text (
2144 "Slot @body injected",
2145 grow: 1.0,
2146 height: 20,
2147 font_size: 12,
2148 text_color: ColorToken::OnSurfaceVariant
2149 )
2150 Button (
2151 "Toggle",
2152 width: 72,
2153 height: 28,
2154 font_size: 12,
2155 border_radius: 7,
2156 normal_color: ColorToken::Primary,
2157 pressed_color: ColorToken::Secondary,
2158 text_color: ColorToken::OnPrimary
2159 ) on Tap { state.toggle(); }
2160 }
2161 }
2162 }
2163 }
2164 };
2165}
Loading preview…

Click Toggle inside the injected @body slot—StatusCard updates its reactive title: prop!(String) while hosting the caller's slot children at @@body.