# Runtime API

The `runtime` module is what generated components call, and what Kotlin written by hand calls too. Its only dependency is, on JS,
[`kotlin-browser`](https://github.com/JetBrains/kotlin-wrappers), whose DOM types components use, so a component module only depends on `runtime`. Its
package is `io.github.ayfri.lithe`.

## Reactivity

- `state(initial)` is a reactive variable, used as `var count by state(0)`. Writing a value equal to the current one does nothing.
- `derived { }` is a value computed from state, `val doubled by derived { count * 2 }`. A write replaces the value until the next change of a source.
- `ref<T>()` holds an element reference.
- `prop(accessor, default)` and `bindable(accessor, onChange)` are the locals of props. A prop is a `() -> T` accessor, so a component follows what its
  parent passes. A bound `prop var` writes through the callback and reads the parent's value back.
- `mount { }` (JS) runs a block once the component is in the page. `effect { }` (JS) runs it after the first render and again whenever something it read
  changes.
- `untracked { }` runs a block without following what it reads.
- `onDispose { }` registers a cleanup: it runs when the component, the `mount` block or the element of a `@mount` block leaves the page, and in an `effect`
  also before the next run. Called outside of all of them, it throws.
- `keySelector { }` tells whether a key is the value its block gives, and a change only runs the readers of the old and the new key.

[State and effects](/docs/components/state#when-things-run) tells when each of them runs.

## Building nodes

Components receive the `Ui` they render into as a context parameter and call functions that build nodes in document order. This is what a component written
by hand looks like, from `examples/hello`:

```kotlin
context(_: Ui)
fun Counter() {
	var count by state(0)
	StaticHtml("<h1>Hello from Lithe</h1>")
	Element("button", { attr("type", "button"); on("click") { count++ } }) {
		Text("Count: ")
		Text { count.toString() }
	}
	Choose({ if (count > 0) 0 else -1 }) {
		Element("p", { attr("class") { if (count % 2 == 0) "even" else "odd" } }) { Text("Clicked") }
	}
}
```

| Function | Builds |
|----------|--------|
| `Element(tag, attrs, content)` | One element. |
| `Text(value)`, `Text { value }` | A text node that never changes, or one that follows the state it reads. |
| `Comment(text)` | A comment. |
| `StaticHtml(html)` | A subtree that never changes, from HTML that holds exactly one top-level element. |
| `RawElement(tag, attrs, html)` | An element whose content is `html`, unescaped. |
| `Choose(branch, content)` | The content of the branch `branch` returns, nothing for a negative one, again when the number changes. |
| `Key(value, content)` | `content`, again from scratch each time `value` returns something that doesn't equal the last one. |
| `Each(items, key, content)` | `content` once per item, which it reads through an accessor. `loopItems(x)` gives the list from what a `for` loop accepts. |
| `Try(content, catch)` | `content`, and `catch(error, retry)` in its place when building it or one of its effects throws. |
| `Await(load, pending, catch, content)` | `content` with the value the suspend lambda `load` returns, `pending` while it loads, `catch` when it throws. |
| `Head(content)` | Elements of the document `<head>`. |

- `tagName(name)` gives back the name of an element that comes from a value, and fails for one that could start more markup, like `script`, `style` or
  `textarea`. A custom element name like `my-card` is one.
- With a `key`, `Each` moves the nodes of as few items as possible (swapping two moves two), and a new value for the same key updates the item in place. Two
  items with the same key are an error, which leaves the list as it was. An item that fails is left out, and built again at the next change of the list.
- `Key`, `Try` and `Await` can't be used inside `Head`.
- `@Markup` marks the type of a prop that receives markup.

## Attributes and listeners

- `attr(name, value)` sets an attribute that never changes. `null` leaves it out and `""` renders it bare (`<button disabled>`).
- `attr(name) { value }` sets an attribute that follows the state it reads. On `<input>`, `value` and `checked` also write the property, which is what the
  control shows once the user touched it, and so does `selected` on `<option>`.
- `attrValue(name) { value }` takes any value: `null` and `false` remove the attribute, `true` makes it bare, anything else is its `textOf`.
- `attributes { map }` writes every attribute of an element that spreads a map, and removes the names that left it.
- `textOf(value)` renders `null` as nothing and prints numbers like JavaScript on both platforms (`30.0` is `30`). `"even" on condition` is the string
  when the condition holds and `""` otherwise.
- `on(type, listener)` assigns the `on<type>` property of the element (`onclick`). `onEvent<E>(type) { event -> }` (JS) passes the event.
  `addListener<E>(type) { event -> }` (JS) is for the events that have no such property, custom ones and `focusout` for instance.
- `target.addListener<E>(type) { event -> }` (JS) listens on any `EventTarget`, like the window, until what called it leaves the page.
- `io.github.ayfri.lithe.dom` (JS) holds one function per typed event of the window, the document and elements (`window.onkeydown { }`), and the
  [page values](/docs/components/events#page-values). A build only ships the ones it calls.
- `bindValue({ value }) { }` and `bindChecked({ checked }) { }` (JS) bind a control both ways.
- `thisRef { }` (JS) sets a reference when the element is built, and clears it when the element leaves. `setup { element -> }` runs once the element is in
  the page, and its `onDispose` blocks run when the element leaves.

## Rendering and hydrating

- `renderPage(content)` (JVM) runs `content` and writes the HTML as it goes. It returns the `body`, the `head` (the elements of the `Head` blocks, one per
  line) and `removeReplaced(template)`, which takes out of a page template the head elements that `head` sets too. `renderToString(content)` is the body
  alone.
- `hydrate(root, content)` (JS) runs `content` against the children of `root`. A root without children is rendered from scratch, so the same call serves
  both cases. It returns once the `mount` and `effect` blocks ran, with a `Hydration` handle, and can be called for several roots. `Hydration.dispose()`
  stops the effects, runs the cleanups and removes the nodes.

[Rendering and hydration](/docs/sites/hydration) tells how the browser adopts the server nodes.

## Other modules

- `runtime-compose` mounts compositions and components inside each other, see [Compose](/docs/sites/compose).
- `kobweb` adds `LithePage`, the settings of `ctx.lithe { }` and `apiData` to a Kobweb site, see [Kobweb](/docs/sites/kobweb).
