Skip to main content

ui

Macro ui 

Source
macro_rules! ui {
    (@m [ [ $tag:ident [ $($calls:tt)* ] ] $($stack:tt)* ] < / $close:ident > $($rest:tt)*) => { ... };
    (@m [ $($stack:tt)* ] < $tag:ident $($rest:tt)*) => { ... };
    (@m [ [ $tag:ident [ $($calls:tt)* ] ] $($stack:tt)* ] $text:literal $($rest:tt)*) => { ... };
    (@m [ [ $tag:ident [ $($calls:tt)* ] ] $($stack:tt)* ] { $child:expr } $($rest:tt)*) => { ... };
    (@a [ [ $tag:ident [ $($calls:tt)* ] ] $($stack:tt)* ] on : $event:ident = { $handler:expr } $($rest:tt)*) => { ... };
    (@a [ [ $tag:ident [ $($calls:tt)* ] ] $($stack:tt)* ] $name:ident = $value:literal $($rest:tt)*) => { ... };
    (@a [ [ $tag:ident [ $($calls:tt)* ] ] $($stack:tt)* ] $name:ident = { $value:expr } $($rest:tt)*) => { ... };
    (@a [ $($stack:tt)* ] > $($rest:tt)*) => { ... };
    (@a [ [ $tag:ident [ $($calls:tt)* ] ] $($stack:tt)* ] / > $($rest:tt)*) => { ... };
    (@close [ [ $tag:ident [ $($calls:tt)* ] ] ] $close:ident) => { ... };
    (@close [ [ $tag:ident [ $($calls:tt)* ] ] [ $parent:ident [ $($parent_calls:tt)* ] ] $($stack:tt)* ] $close:ident $($rest:tt)*) => { ... };
    (< $($rest:tt)*) => { ... };
}
Expand description

Builds an Element tree from markup.

The syntax is a small subset of HTML, inside Rust:

use eternal_ui::{ui, Element};

#[derive(Clone, Debug)]
enum Msg { Save, Rename(String), Wrap(bool) }

let name = "sketch.png";
let root: Element<Msg> = ui! {
    <column class="panel" id="main">
        <row class="toolbar">
            <button id="save" shortcut="Ctrl+S" on:click={|| Msg::Save}>"Save"</button>
            <spacer/>
            <label class="dim">{format!("Editing {name}")}</label>
        </row>
        <input value={name} placeholder="File name" on:change={Msg::Rename}/>
        <checkbox checked="true" on:toggle={Msg::Wrap}>"Wrap around"</checkbox>
    </column>
};
assert_eq!(root.tag(), "column");
assert_eq!(root.children().len(), 3);
  • A tag is one of the constructors in elements: column, row, panel, label, button, checkbox, input, separator, spacer. Elements can be self-closing (<spacer/>).
  • name="literal" and name={expression} set attributes, as Element::attr does. The expression can be anything with a Display impl.
  • on:click={handler} attaches a handler; the name is one of the functions in on and the handler is a closure with the matching signature.
  • A child is another tag, a string literal, or {expression} where the expression is an element, a Vec of elements, an Option<Element>, or a String. Text inside a label becomes its text; text elsewhere becomes a child label.

A closing tag has to match its opening tag, or the macro produces a type error naming both. Every token costs a level of macro recursion, so a large template may need #![recursion_limit = "512"] on the crate.