# Components

`engine-ui-view` (`ui/view/`) runs Elm-style components on the [retained tree](toolkit.md#the-retained-tree-uisrctreers), after Effect UI's. A component is a model, the messages that change it, a pure `update` and a `view` that returns elements. A `Mount` turns the view into tree nodes and, on each later render, sets only what changed. Work outside the update runs as commands and subscriptions, and components are tested as stories (the update alone) or plays (the mounted component, pressed through hit testing). The crate depends only on `engine-ui`, and its runtime needs no window: a bare `Tree` is enough.

## A component

```rust
use engine_ui_view::{Component, Element, column, row, text};

struct Counter;

#[derive(Clone)]
enum Message {
    Add(i64),
}

impl Component for Counter {
    type Props = u32; // the font, from Host::font or Fonts
    type Model = i64;
    type Message = Message;
    type Output = ();

    fn update(count: &mut i64, message: Message) -> Option<()> {
        match message {
            Message::Add(by) => *count += by,
        }
        None
    }

    fn view(&font: &u32, count: &i64) -> Element<Message> {
        let button = |caption: &str, by: i64| {
            row().key(caption).size(56.0, 36.0).justify_center().items_center()
                .bg(0x2d333bff).hover_bg(0x39414bff).press_bg(0x4e5967ff).radius(8.0)
                .focusable().role(1, caption).on_press(Message::Add(by))
                .child(text(font, caption, 0xe2e6ecff))
        };
        column().grow().grow_y().justify_center().items_center().gap(16.0)
            .child(text(font, &count.to_string(), 0xf2ece0ff))
            .child(row().gap(12.0).child(button("−", -1)).child(button("+", 1)))
    }
}
```

- **Props** come from whoever holds the component and must be `PartialEq`: a render with equal props and no message since the last costs one comparison.
- **The model** is the component's own state; only `update` changes it.
- **`Output`** is what `update` may hand back to the holder (a dialog's chosen button, a menu's picked item), as Effect UI's events up.

`ui/view/examples/counter.rs` is this counter in a window (`cargo run -p engine-ui-view --example counter`; `-- --capture out.png` presses + three times in a hidden window and saves the frame).

## Elements

A view returns an `Element`, built by chained calls; the tree's [flex layout](toolkit.md#the-retained-tree-uisrctreers) places it.

| Kind | Calls |
| --- | --- |
| Boxes and content | `column()`, `row()`, `text(font, text, colour)`, `text_runs(font, text, colour, runs)`, `image(image, source, tint)` |
| Size and flow | `w`, `h`, `size`, `grow`, `grow_y`, `p`, `px`, `py`, `pl`, `pt`, `pr`, `pb`, `gap`, `absolute(x, y)`, `at(rect)`, `scroll`, `clip` |
| Alignment | `items_start`, `items_center`, `items_end`, `justify_center`, `justify_end`, `justify_between` |
| Paint | `bg`, `hover_bg`, `press_bg`, `border`, `radius`, `radii`, `shadow` |
| Text | `elide_end`, `elide_start` |
| Identity and behaviour | `key`, `on_press(message)`, `on_hover(message)`, `role(role, label)`, `focusable`, `hit_through` |
| Children | `child`, `children`, `child_if` |

Colours are `0xRRGGBBAA`, sizes logical pixels, fonts and images the numbers `Host` hands out. `memo(key, props, build)` is a child built by `build(&props)` only when its props differ from the ones it was last built with: a row of a long list, so a change to one row builds and compares only that row.

## Mounting

```rust
let mut counter: Mount<Counter> = Mount::new(parent, 0, 0); // under `parent`, after its children, count 0
counter.render(host.tree(), font);

// On a press: the message of the element under the pointer (or of the nearest one above it) goes to the update,
// and the view renders again.
let hit = host.tree().hit(x, y);
counter.press(host.tree(), hit);
counter.render_again(host.tree());
```

- **Reconciliation.** Each render matches the view's elements to the nodes made last time, by key or else by position among unkeyed elements of the same kind, and sets only the properties that changed. A reorder of keyed rows moves nodes and makes none; memoized children that leave a list are detached and parked, and come back without new nodes. `Mount::work` counts what a render created, removed, set and moved.
- **Input.** `press(nodes, node)` and `hover(nodes, node)` send the message of the element the tree hit, or of the nearest element above it that names one; `message_at` asks without sending; `send(message)` sends one directly. Hover and press fills stay the tree's own (`Tree::pointer`, `Tree::press`).
- **Lookup and removal.** `node_of(key)` is the node made for a key (for its bounds after a frame), `owns(nodes, node)` whether a node is the component's, `unmount(nodes)` removes everything it made.
- **The tree.** A mount calls the tree through the `Nodes` trait, which `Tree` and `&mut Tree` implement. A host that reaches its tree through a handle of its own implements `Nodes` for that handle.

## Commands

Work outside the update runs as commands (`engine_ui_view::command`). The host's state implements `Runtime`: where its `Commands<Self>` live, and a `Poster` that hands work to its main thread.

```rust
use engine_ui_view::{Commands, Overlap, Poster, Queue, Runtime};

struct App {
    results: Vec<String>,
    commands: Commands<App>,
    queue: Queue<App>,
}

impl Runtime for App {
    fn commands(&mut self) -> &mut Commands<Self> {
        &mut self.commands
    }
    fn poster(&self) -> Poster<Self> {
        self.queue.poster()
    }
}

// The queue wakes the host's loop when work arrives: Queue::new(move || waker.wake()), with `waker` from Host::waker.
app.command("search", Overlap::Switch, move |token| search(&query, token), |app, found| app.results = found);

// In the host's loop, after polling events: run what arrived.
for job in app.queue.take() {
    job(&mut app);
}
```

- **`command(name, overlap, job, apply)`** runs `job` on a thread and `apply` with its result on the main thread.
- **Overlap.** A new run of a name still running runs beside it (`Overlap::Concurrent`), takes over from it (`Switch`: the earlier run's `Token` is cancelled and its result dropped) or waits for it (`Queue`).
- **`stream(name, overlap, job, on)`** hands each update the job emits to `on` while the run counts; `emit` returns false once the job should stop.
- **State for views.** `Commands::is_running(name)` answers a view instead of a flag; `cancel(name)` stops a name's runs and drops what they hand back.
- **Hosts with their own queue.** `Poster::new(post)` wraps any way of reaching the main thread; a host that counts its work in flight overrides `Runtime::spawn`. A job that calls code with a cancellation flag of its own shares the token's (`Token::flag`).

## Subscriptions

A subscription is a stream the state wants while it is in the list given to `Runtime::subscribe`, keyed by what it watches, as Effect UI's `subscriptions(model)`:

```rust
fn subscriptions(app: &App) -> Vec<Subscription<App>> {
    app.watching.iter().map(|path| {
        let path = path.clone();
        Subscription::new(("watch", path.clone()), move |token, emit: &dyn Fn(Change) -> bool| {
            while !token.is_cancelled() && emit(wait_for_change(&path)) {}
        }, |app, change| app.changed(change))
    }).collect()
}

// After each update (each turn of the loop):
app.subscribe(subscriptions(&app));
```

New keys start their stream on a thread, keys that left are cancelled and their late updates dropped, and a key that stays keeps running as it is. `Commands::is_subscribed(key)` tells whether one runs.

## Tests

### Stories

A story drives an update with no nodes:

```rust
let story = Story::<Counter>::given(0).send(Message::Add(1)).send(Message::Add(-3));
assert_eq!(story.model, -2);
assert!(story.outputs.is_empty());
```

### Plays

A play mounts a component on a `Surface` and drives it as a user would, finding elements as an assistive technology does:

```rust
let surface = Headless::new(400.0, 300.0); // a tree laid out with measuring fonts: no window or GPU
let root = surface.root();
let mut play: Play<Counter, _> = Play::mount(surface, root, 0, font);
let plus = play.find(BUTTON, "+").unwrap(); // by role and label
play.press(&plus); // hit testing at its centre, then the view renders again
assert_eq!(play.mount.model, 1);
```

- **Surfaces.** `Headless` lays out a bare `Tree` (`Tree::layout`), so a play runs wherever the crate builds; `engine_ui::Host` (a hidden window from `Host::open_headless`) draws each frame too. A host implements `Surface` for its own window handle.
- **Driving.** `find(role, label)` and `find_all(role)` read the accessible nodes; `press` and `hover` go through hit testing at an element's centre and draw what the message changed; `send` sends a message; `render(props)` renders with new props.
- **Time.** It moves only when the test moves it. The mount stops the surface's clock at 0 (`Host::set_clock`, or `Tree::tick` for `Headless`); `advance(duration)` moves it a 60 Hz frame at a time, so springs and the caret's blink step as on screen, and `settle(most)` advances until no spring runs. `Tree::property` reads a value a spring moves.

## Kit

`engine_ui_view::kit` holds behaviours without a look, which a host's components share while keeping their own look: `place_at` and `place_within` keep a popup inside the window, `step` and `first` move through a list's enabled items, and `Typeahead` selects the item whose label starts with what was typed.
