# Views and layout

A view is a value that builds its native views once, the first time it is
shown, and updates them in place after. Make your own views by composing
these, or wrap a native view with `native(..)`. Layout is
done in Rust: stacks and grids size their children from the controls'
natural sizes, and only the part of the tree that changed is laid out
again.

## Stacks, spacers and padding

```rust,no_run
use ferrokit::*;

let toolbar = hstack((
    button("Back", || {}),
    spacer(),                      // takes the free space
    text("Page 1 of 3"),
    spacer(),
    button("Next", || {}),
))
.spacing(8.0);
let page = vstack((toolbar, divider(), text("Content").fill_width())).padding(16.0);
# let _ = page;
```

- `vstack` and `hstack` take a tuple of views (or a `Vec<AnyView>` for a
  computed list). `.alignment(Align::Center)` aligns across the stack;
  `.spacing(points)` sets the gap.
- `spacer()` takes the space left over. A fixed view keeps its natural size.
- Modifiers, on any view: `.padding(p)`, `.padding_xy(horizontal,
  vertical)`, `.width(w)`, `.height(h)`, `.frame(w, h)`, `.fill_width()`,
  `.fill_height()`.
- `.min_width(w)` and `.min_height(h)`: at least that size, larger if the
  content is.
- `text(..).truncate()`: one line, shortened with "…" when its row is short
  of room (a long path, a long name), instead of pushing past the row's
  edge. A row holding truncating text gives up room before overflowing.
  Add `.min_width(w)` to keep it readable: it shrinks to `w` and no
  further, and the row's other truncating text gives up the rest.
- A stack takes a tuple of up to 16 views, a `Vec<AnyView>`, or one view
  alone: `vstack(for_each(..))`. Past 16, group some in a nested stack or
  pass a `Vec<AnyView>`.
- `zstack` puts views on top of one another, such as text over a picture
  (see [Materials and windows](10-materials-and-windows.md)).

## Grids: forms

A grid sizes its columns to their widest cell. `align_column` right-aligns
the labels of a form.

```rust,no_run
use ferrokit::*;

let (name, email) = (Signal::new(String::new()), Signal::new(String::new()));
let form = grid([
    (text("Name:"), text_field(&name).accessibility_label("Name")),
    (text("Email:"), text_field(&email).accessibility_label("Email")),
])
.align_column(0, Align::End)
.spacing(8.0, 10.0);
# let _ = form;
```

Every row of a grid has the same type. When the rows hold different
controls, wrap each cell in `AnyView::new` (or use `form` and `form_row`
from [Controls and forms](04-controls-and-forms.md),
which take any control per row):

```rust,no_run
use ferrokit::*;

let (name, plan) = (Signal::new(String::new()), Signal::new("free"));
let form = grid([
    (AnyView::new(text("Name:")), AnyView::new(text_field(&name).accessibility_label("Name"))),
    (AnyView::new(text("Plan:")), AnyView::new(picker(&plan, vec![("Free", "free"), ("Plus", "plus")]).accessibility_label("Plan"))),
])
.align_column(0, Align::End);
# let _ = form;
```

## Text that changes

`text("…")` is fixed. `text(|| …)` re-runs when the signals it reads
change, and updates only its own text field.

## Lists: `for_each` and identity

`for_each` builds a row per item and keeps rows by **identity**: when the
list changes, rows whose id is still there are kept (with their native
views and state), new ids are built, and gone ones are torn down.

```rust,no_run
use ferrokit::*;

#[derive(Clone)]
struct Task {
    id: u32,
    title: String,
}

impl Identifiable for Task {
    type Id = u32;
    fn id(&self) -> u32 {
        self.id
    }
}

let tasks = Signal::new(vec![Task { id: 1, title: "Write docs".into() }]);
let list = scroll(vstack((for_each(move || tasks.get(), |task: Task| text(task.title)),)));
tasks.update(|v| v.push(Task { id: 2, title: "Ship".into() })); // builds one row
# let _ = list;
```

## Switching subtrees: `dynamic`

`dynamic(|| …)` rebuilds its subtree when the signals it read change. Use
it for "show this or that"; use `.id(key)` on a view to keep it across
rebuilds while the key is the same.

```rust,no_run
use ferrokit::*;

let signed_in = Signal::new(false);
let body = dynamic(move || if signed_in.get() { AnyView::new(text("Welcome back")) } else { AnyView::new(button("Sign in", || {})) });
# let _ = body;
```

To hide a view and keep it, use `.hidden(|| …)` instead: its native views
stay built, with their state (a field's text, a table's scroll position),
and while hidden it takes no room in its stack. It's the better fit for a
panel shown in one mode only, which a `dynamic` would rebuild each time.

```rust,no_run
use ferrokit::*;

let advanced = Signal::new(false);
let form = vstack((
    checkbox("Show advanced options", &advanced),
    vstack((text("Cache size"), text_field(&Signal::new(String::new())))).hidden(move || !advanced.get()),
));
# let _ = form;
```

## Scrolling

`scroll(view)` puts a view in an `NSScrollView` and lays its content out
at the visible width.

## Teardown

When a view leaves the tree (a list row removed, a `dynamic` branch
switched, a window closed) its native views are removed, its effects stop
and its memory is freed. AppKit itself keeps about 0.6 KB per view ever
shown, so prefer updating views over replacing them in hot paths.
