# Compose

Compose HTML and Lithe can share a page because both write plain DOM. A module that uses Compose enables it in its `module.yaml` and lists the libraries it
needs, and [site builds](/docs/sites/static-sites) and the [dev server](/docs/sites/dev-server) then run the Compose compiler plugin on it. Compose is
opt-in: a site with no such module ships **none of it**.

The `runtime-compose` module joins the two. It depends on the runtime and Compose HTML, and a module that lists it enables Compose:

```yaml
dependencies:
  - ../../../runtime
  - ../../../runtime-compose

settings:
  compose: enabled
```

## Both directions

Its package is `io.github.ayfri.lithe.compose`, browser code that static rendering leaves out:

- `composeInto(element) { }` composes into an element until the Lithe block that calls it is disposed, so in a `@mount` block the composition goes with the
  element. It only works inside a component, a `mount`, an `effect` or a `@mount` block.
- `Lithe { }` is a composable that mounts a component in a `div` of its own, which takes the attributes given as `Lithe({ classes("card") }) { }`. The
  component is disposed when the `div` leaves the composition.
- `composeState { value }` is a Compose state that follows the Lithe state the block reads, so a composition that reads it recomposes. The
  [composable tags](/docs/components/children#composables) pass their arguments this way.

`examples/features/compose` shows both directions:

```html
<script kotlin>
	import io.github.ayfri.lithe.compose.composeInto
</script>

<div @mount={ composeInto(it) { widgets.Counter { Badge() } } }></div>
```

```kotlin
@Composable
fun Counter(nested: context(Ui) () -> Unit) {
	var shown by remember { mutableStateOf(true) }
	Button({ onClick { shown = !shown } }) { Text("Toggle") }
	if (shown) Lithe({ id("nested") }, nested)
}
```

The layout of this site is a Compose function of Kobweb, and its search box, its theme switch and every code block are Lithe components mounted with
`Lithe { }`.

## Two kinds of state

Reading one kind of state from the other without a bridge isn't possible: Compose `mutableStateOf` doesn't update Lithe markup, and a Lithe `state` read
inside a composable doesn't recompose it, because each tracks only its own reads.

- From Lithe to Compose, `composeState` and composable tags are the bridge.
- `Lithe { }` keeps the content of its first composition, so values cross back through callbacks, `key(value) { Lithe { } }`, which mounts a new component,
  or a Lithe `state` that the composable writes.

## Cost

Compose is most of the download of a site that uses it: on `examples/todo`, a client on a runtime made with Compose is about **7 times** the size of the
Lithe one, see [Performance](/docs/reference/performance#client-size). Use it where it pays off, and only there.
