# Extensions: components and slots

At the end of this chapter, two Lua scripts draw inside a Rust window:
one a list the host placed, both a button in a toolbar the host
declared without knowing who would fill it.

<a data-kui-example="340" href="live/gallery.html?example=tutorial/11_extensions">Live Lua extensions</a>

## A guest in your frame

An **extension** is code a host loads to draw in its frame: a Lua
script, a C library, another Rust type. It does not get a window. It
gets a place in yours, and it draws there with the same nodes, on the
same frame, while you build it. What it draws is tagged with its
origin, keyed under its own name, and its events go to it first.

You load it under a **namespace** you choose, the way an import picks
an alias. The notes plugin below is `notes`, so its list is
`notes/list`:

```rust,noplayground
pub(crate) fn main() -> Result<(), Box<dyn std::error::Error>> {
    let notes = LuaExtension::from_source("notes.lua", include_str!("11_extensions/notes.lua"))?;
    let stamp = LuaExtension::from_source("stamp.lua", include_str!("11_extensions/stamp.lua"))?;
    kui_native::app("Notes")
        .size(480.0, 340.0)
        .extension_as("notes", notes)
        .extension_as("stamp", stamp)
        .run(Notes::default())
}
```

`kui-lua` is the crate that runs a Lua script as an extension. Add it
beside `kui-native`:

```bash
cargo add kui-lua
```

## A component: placed by name

The script says what it provides in a `components` table. Each entry
is a function from the environment, the host's props and the instance
to a tree — the same builders a Lua view uses:

```lua
local notes = { "Buy milk", "Call the dentist", "Water the ferns" }

components = {}

-- Placed by the host as `notes/list`: `props` is what it passed.
function components.list(env, props, inst)
  local rows = {}
  for i, title in ipairs(notes) do
    rows[#rows + 1] = button { label = title, on_click = { kind = "pick", index = i } }
  end
  return column { key = "list", gap = 6, width = "grow",
    text(props.title or "Notes", { size = 12, color = env.theme.muted }),
    table.unpack(rows),
  }
end
```

The host places it where it wants it, as often as it likes, with props
in:

```rust,noplayground
        // The notes plugin's list, placed by name, with props in and the
        // host's own message for its `onPick`.
        ui.component(
            "notes/list",
            &Value::map([
                ("title", "Today".into()),
                ("revision", Value::Int(self.revision)),
                ("onPick", Msg::Picked.into()),
            ]),
        );
```

Each placement is an **instance**, keyed by where it is (or by a `key`
prop). Its nodes are keyed under the instance, so two lists never share
a key.

## Its events are your messages

The script hears its own nodes' events in `on_event`. It answers the
host by raising one of its component's events with `emit`:

```lua
function on_event(ev)
  if ev.kind == "pick" then
    return emit("on_pick", { title = notes[ev.index] })
  elseif ev.kind == "new" then
    notes[#notes + 1] = "Note " .. (#notes + 1)
    return emit("on_run", { action = "new note" })
  end
end
```

`emit("on_pick", …)` arrives as whatever the host passed for `onPick` —
here `Msg::Picked` — with the plugin's fields in the event's field,
named for the prop without its `on`: `pick`. The host never learns the
plugin's own messages, and the plugin never learns the host's.

## A slot: placed by everyone

A component is placed by name, so the host has to know it. A toolbar
that plugins add buttons to is the other way round: the host knows the
place, not who will fill it. That is a **slot**:

```rust,noplayground
        // Whoever contributes to `app.toolbar` puts a button here, after
        // the title. The host does not know who will.
        ui.with_keyed(
            "toolbar",
            NodeSpec::row().gap(8.0).cross_align(Align::Center),
            |ui| {
                ui.text("Notes", TextStyle::new(18.0).color(t.fg));
                ui.slot("app.toolbar", &Value::map([("onRun", Msg::Ran.into())]));
            },
        );
```

A plugin contributes by naming the slot and one of its own components:

```lua
contributes = { ["app.toolbar"] = "new" }

function components.new(env, props, inst)
  return button { label = "New note", on_click = { kind = "new" } }
end
```

The stamp plugin contributes too, with `order = -1` to go first:

```lua
-- The stamp plugin of step 11: one button, first in `app.toolbar`, that
-- counts its presses.

local pressed = 0

contributes = { { slot = "app.toolbar", component = "stamp", order = -1 } }

components = {
  stamp = function(env, props, inst)
    return button { label = "Stamp (" .. pressed .. ")", on_click = { kind = "stamp" } }
  end,
}

function on_event(ev)
  if ev.kind == "stamp" then
    pressed = pressed + 1
    return emit("on_run", { action = "stamp" })
  end
end

```

Every contribution is placed in the slot as a sibling — load order,
then `order` — and each gets the slot's props. They all raise the one
message, `Msg::Ran`, and `from` says who raised it:

```rust,noplayground
    fn on_event(&mut self, ev: UiEvent) {
        match ev.message::<Msg>() {
            // The plugin's fields arrive in the event's field: `pick` for
            // `onPick`, `run` for `onRun`.
            Some(Msg::Picked) => {
                self.picked = ev.data().and_then(|d| d.get_str("title")).map(String::from);
            }
            // Every toolbar button raises the one message; `from` says
            // which plugin did.
            Some(Msg::Ran) => {
                let action = ev.data().and_then(|d| d.get_str("action")).unwrap_or("?");
                let who = ev.from.as_deref().unwrap_or("?");
                self.log.push(format!("{who}: {action}"));
                self.revision += 1;
            }
            None => {}
        }
    }
```

A slot's name is any string. The convention is `owner.place` — your
app's name, then the place — so two apps' plugins never meet by
accident. A slot nobody contributes to draws nothing and says nothing:
whether it is drawn at all is your view's call.

## Replayed unless something changed

An instance whose props are what they were, and that read nothing that
changed, is not asked again: kui pushes last frame's nodes back. That
is what makes a plugin cheap — and it is why the host passes a
`revision` to the list. "New note" changes the list's state from a
*different* instance, the toolbar button, and the list's own props are
the only thing the host can see change. Pass what moves as a prop, or
`fresh: true` to be asked every frame.

## The test

Chapter 11's `Drive` loads extensions too:

```rust,noplayground
#[cfg(test)]
mod tests {
    use super::*;
    use kui_native::Core;
    use kui_native::testing::Drive;

    fn drive() -> Drive {
        let mut d = Drive::new(Core::new(), 480.0, 340.0).framing();
        let notes = include_str!("11_extensions/notes.lua");
        let stamp = include_str!("11_extensions/stamp.lua");
        d.extension(
            "notes",
            LuaExtension::from_source("notes.lua", notes).unwrap(),
        )
        .unwrap();
        d.extension(
            "stamp",
            LuaExtension::from_source("stamp.lua", stamp).unwrap(),
        )
        .unwrap();
        d
    }

    #[test]
    fn both_plugins_add_to_the_toolbar_and_the_host_hears_who() {
        let mut app = Notes::default();
        let mut d = drive();
        d.frame(&mut app);
        // `stamp` asked for `order = -1`, so it goes first.
        assert_eq!(d.texts_under("toolbar"), ["Notes", "Stamp (0)", "New note"]);

        let new = d.key_of("New note").expect("the notes plugin's button");
        d.click_key(&mut app, new);
        assert_eq!(app.log, ["notes: new note"]);
        assert!(d.texts_under("list").contains(&"Note 4".to_string()));

        let stamp = d.key_of("Stamp (0)").expect("the stamp plugin's button");
        d.click_key(&mut app, stamp);
        assert_eq!(app.log.last().map(String::as_str), Some("stamp: stamp"));
        assert!(d.texts_under("toolbar").contains(&"Stamp (1)".to_string()));
        assert!(d.warnings().is_empty(), "{:?}", d.warnings());
    }

    #[test]
    fn a_picked_note_comes_back_as_the_hosts_message() {
        let mut app = Notes::default();
        let mut d = drive();
        d.frame(&mut app);
        let note = d.key_of("Call the dentist").expect("a row of the list");
        d.click_key(&mut app, note);
        assert_eq!(app.picked.as_deref(), Some("Call the dentist"));
        assert_eq!(d.texts_under("status"), ["picked Call the dentist · "]);
    }
}
```

```bash
cargo test -p kui-lua --example tutorial_11_extensions
```

## The other bindings

The verbs are the same everywhere: Node's `<component name props/>` and
`<slot name props/>`, Lua's `component(name, props)` and `slot(name,
props)`, C's `kui_component` and `kui_slot`. A C plugin lists
`kui_ext_components` and `kui_ext_contributions`. The next chapter
turns it around: the whole app is the Lua script, and the host is a
binary you do not write.
