# Keyboard and focus

<a data-kui-example="400" href="live/gallery.html?example=tutorial/06_keyboard">Live chapter example</a>

At the end of this chapter, the arrow keys move a cursor over a grid,
space lights a cell, Tab walks the cells and the button, and the screen
says where focus is.

## Focus is one node

At any moment, one node has keyboard focus, or none does. Tab moves it
to the next node in the *ring*: every button, control and editor, in
tree order. Shift-Tab moves back. Enter or space presses the focused
button.

A multiline editor keeps Tab for indentation, as a code editor does.
Escape then Tab moves on from it, and Ctrl+M (Ctrl+Shift+M on macOS)
turns "Tab moves focus" on for the window; `ui.tab_moves_focus()` reads
it, for a status label.

You get all of that without writing anything. The stock widgets are in
the ring. A plain box joins it with `.focusable()`.

```rust,noplayground
                ui.with(NodeSpec::column().gap(4.0), |ui| {
                    for row in 0..SIDE {
                        ui.with(NodeSpec::row().gap(4.0), |ui| {
                            for col in 0..SIDE {
                                let i = row * SIDE + col;
                                let bg = match (self.lit[i], i == self.cursor) {
                                    (true, _) => t.accent,
                                    (false, true) => t.accent_soft,
                                    (false, false) => t.sunken,
                                };
                                // `focusable` puts a plain box in the Tab
                                // ring; `focus_bg` is what it shows there.
                                // A clickable box is a button to a screen
                                // reader, so `label` gives it a name.
                                ui.leaf_keyed(
                                    &format!("cell {i}"),
                                    NodeSpec::row()
                                        .size(36.0, 36.0)
                                        .radius(6.0)
                                        .bg(bg)
                                        .label(format!("cell {i}"))
                                        .focusable()
                                        .focus_bg(t.accent_hover)
                                        .on_click(Msg::Pick { cell: i }),
                                );
                            }
                        });
                    }
                });
```

`.focus_bg(..)` is what a focusable box shows while focused. Without
it, kui draws a ring, around a key sink too. `.focus_ring(colour)` on a
box colours that ring for everything inside it, and a transparent one
turns it off.

## Reading focus

The view can ask where focus is:

```rust,noplayground
                // Where focus is, as the core knows it, by the node's label.
                let focused = ui
                    .focused()
                    .and_then(|k| ui.core().label_of(k).map(str::to_string))
                    .unwrap_or_else(|| "nothing".into());
                let by_keyboard = ui.focus_visible();
                ui.text(
                    &format!(
                        "focus: {focused}{} · last key: {}",
                        if by_keyboard { " (by keyboard)" } else { "" },
                        self.last_key
                    ),
                    TextStyle::new(12.0).color(t.muted),
                );
```

`ui.focus_visible()` is true when focus got there by keyboard, and
false after a click. It is how a view shows a focus ring only when the
ring is useful.

## Keys are events on a sink

A key press is data, like a click. It is delivered to a **key sink**: a
box with `.on_key(msg)`. The press goes to the focused node and bubbles
up to the nearest sink above it. So a sink at the root hears every key,
whatever is focused inside it.

The message is yours, like a button's — except a sink sends it on every
key rather than on a click, with the key inside it under `key`. This app has one sink, so one
variant with no fields is enough to say "a key arrived":

```rust,noplayground
#[derive(Message, Clone, Debug, PartialEq)]
enum Msg {
    /// The key sink's message: every key press arrives as it, with the
    /// key's data inside it under `key`.
    Key,
    Pick {
        cell: usize,
    },
    Clear,
}
```

```rust,noplayground
        // `on_key` makes this box a key sink. A key goes to the focused
        // node and bubbles up to the nearest sink above it, so the root
        // hears the arrows even while a cell or a button has focus.
        // `take_key_focus` below gives the sink focus on its first frame,
        // so it hears keys before anything is clicked.
        let sink = ui.with_keyed(
            "app",
            NodeSpec::column()
                .fill()
                .pad(20.0)
                .gap(12.0)
                .cross_align(Align::Start)
                .bg(t.bg)
                .on_key(Msg::Key),
            |ui| {
```

A sink hears keys only while something under it has focus. On the
first frame nothing does, so the view gives the sink focus itself with
`ui.take_key_focus(sink)`. That runs on the frame the declaration
*starts* and not again, so a later Tab is not undone.

## Reading a key

```rust,noplayground
    fn on_event(&mut self, ev: UiEvent) {
        match ev.message::<Msg>() {
            Some(Msg::Key) => {
                // The message says which sink; `key_press` reads the key
                // event's data, under the message's `key` field, typed.
                let Some((KeyPhase::Down, key)) = ev.key_press() else {
                    return;
                };
                self.last_key = format!("{:?}", key.code);
                let (row, col) = (self.cursor / SIDE, self.cursor % SIDE);
                match key.code {
                    KeyCode::Left => self.cursor = row * SIDE + col.saturating_sub(1),
                    KeyCode::Right => self.cursor = row * SIDE + (col + 1).min(SIDE - 1),
                    KeyCode::Up => self.cursor = row.saturating_sub(1) * SIDE + col,
                    KeyCode::Down => self.cursor = (row + 1).min(SIDE - 1) * SIDE + col,
                    KeyCode::Space => self.lit[self.cursor] = !self.lit[self.cursor],
                    _ => {}
                }
            }
            Some(Msg::Pick { cell }) => {
                self.cursor = cell;
                self.lit[cell] = !self.lit[cell];
            }
            Some(Msg::Clear) => self.lit = [false; SIDE * SIDE],
            None => {}
        }
    }
```

The message says which sink. `ev.key_press()` reads the key itself:
a `KeyPhase` (down or up — a sink hears releases only if it asks with
`.key_up()`) and a `KeyPress` with the `code`, the modifiers and the
text the press would type.

`KeyCode::Char('a')` is a character key, as the keyboard layout
produced it. `KeyCode::Left` and the rest are the named keys.

## Try this

- Bind `KeyCode::Enter` to lighting the cell too.
- Press Tab until a cell has focus, then space. The cell lights —
  and it was the sink that heard the space, not the cell. Now make the
  cell a real button (`.on_click`) and see Enter press it.

## Where this is decided

- The full `key` event:
  [`docs/props.md`](https://github.com/qxuken/kui/blob/main/docs/props.md#events), events.
- The reference example, with focus regions and the verbs that move
  focus: [`examples/rust/features/focus.rs`](examples/features/focus.md).
