# Events and page values

## Events

`@event={...}` attaches a listener. The content is one or more Kotlin statements, where `it` is the event. `@event={e -> ...}` names it.

```html
<button @click={count++}>+</button>
<input @input={name = it.target.value.trim()}>
<form @submit={it.preventDefault(); save()}>...</form>
```

Events have no modifiers. You call `preventDefault()`, `stopPropagation()` and the like on the event object, so the handler shows everything it does.

The event object is typed per event and element: `@click` gives a `PointerEvent`, and `@input` on an `<input>` gives an `InputEvent` whose target is an
`HTMLInputElement`, so `it.target.value` is a typed `String`. `currentTarget` has the type of the element on every element, and `target` too on `<input>`,
`<textarea>` and `<select>`, which have no element children. The handler's result is ignored, so a handler can be any expression.

### Handlers by name

A handler calls what it names. `@click={save()}` calls a function that takes nothing. `@click={::save}` hands the event to a function that takes it, like
`@click={save(it)}`, and `@click={form::save}` is `form.save(it)`:

```html
<script kotlin>
	import web.pointer.PointerEvent

	var open by state(true)
	var x by state(0.0)

	fun close() { open = false }
	fun pick(event: PointerEvent) { x = event.clientX }
</script>

<button @click={close()}>Close (it's not a trap)</button>
<canvas @click={::pick}></canvas>
```

The compiler writes the call itself, so the page holds no function reference. A bare name, `@click={save}`, is an error, because it would read the function
without calling it.

### Custom events

Any event name works, custom events included, like the ones of web components. The name is written as it is dispatched, and an event browsers don't send
is a `CustomEvent`, whose `detail` the handler reads:

```html
<sl-select @sl-change={size = it.detail.toString()}></sl-select>
<ul @item-picked={picked++} @focusout={open = false}>...</ul>
```

On an element whose tag has no `-`, a name without one that browsers don't send is a warning, because it is usually a typo, like `@onClick`.

### Events of components

A component declares its own events as function props, and `@name={...}` on a component passes the `name` prop:

```html
<script kotlin>
	prop val id: Int
	prop val label: String
	prop val select: (event: SelectEvent) -> Any? = {}
</script>

<li @click={select(SelectEvent(id))}>{label}</li>
```

```html
<Item id={1} label="First" @select={selected = it.id} />
```

`@select={::pick}` hands the event to `pick`, like on an element, so it needs an event prop that takes one value.

## Element references

`@ref={variable}` stores the DOM element in a `ref` variable, available in `mount` and in event handlers. It is `null` during static rendering.

```html
<script kotlin>
	import web.html.HTMLCanvasElement

	var canvas by ref<HTMLCanvasElement>()

	mount {
		console.log(canvas!!.width)
	}
</script>

<canvas @ref={canvas} width="300" height="150"></canvas>
```

`@mount={ ... }` runs Kotlin code with the element once it is in the page, in the browser only, and `it` is the element. It covers per-element setup without
declaring a variable, and `onDispose` inside it runs when the element leaves the page. `@mount={ element -> ... }` names the element. Both go on elements.

```html
<div @mount={
	val observer = ResizeObserver { entries, _ -> width = entries[0].contentRect.width.toInt() }
	observer.observe(it)
	onDispose { observer.disconnect() }
}>...</div>
```

## Window, document and body

The script listens to the window, the document and any element with one function per event, named `on` and the event: `window.onkeydown { }`. The event is
`it`, typed. The listener leaves with what added it, so one of a component rendered by an `@if` only listens while it shows.

```html
<script kotlin>
	import web.dom.document
	import web.window.window

	val width by window.innerWidth()
	var scroll by window.scrollY()

	window.onkeydown { if (it.key == "Escape") close() }
	document.onvisibilitychange { pause() }
	document.body.onmouseleave { showExitOffer() }
</script>

<button @click={scroll = 0.0}>Back to top, from {scroll} on a {width} px window</button>
```

This component reads the size and the scroll of the window and the last key pressed. Go on, scroll, resize the window or mash a key:


- There is a function for every event Kotlin's browser types declare for the window, the document and elements. A custom event takes
  `addListener<CustomEvent<*>>("item-picked") { }` on the same targets.
- A block calls the function, and `=` writes the property of the same name: `window.onclick = ...` is a single handler that never leaves on its own.
- They work in the script of a component, `mount`, `effect` and `@mount`. Elsewhere, such as in an event handler, nothing would remove the listener, so
  calling one is an error.
- A `.kt` file of the browser sources imports them from `io.github.ayfri.lithe.dom`. A component has that import already.

### Page values

These values follow the page, as a `val` or, for the scroll position, a `var` that scrolls the page when written:

| Value                          | Type       | Static rendering |
|--------------------------------|------------|------------------|
| `window.innerWidth()`          | `Int`      | `0`              |
| `window.innerHeight()`         | `Int`      | `0`              |
| `window.scrollX()`             | `Double`   | `0.0`, writable  |
| `window.scrollY()`             | `Double`   | `0.0`, writable  |
| `document.hidden()`            | `Boolean`  | `false`          |
| `document.activeElement()`     | `Element?` | Browser only     |
| `document.fullscreenElement()` | `Element?` | Browser only     |
| `document.body.clientWidth()`  | `Int`      | `0`              |
| `document.body.clientHeight()` | `Int`      | `0`              |
| `window.route()`               | `String`   | `"/"`, writable  |

- With `()` the value follows the page, without it `window.innerWidth` reads it once. `window.route()` is the path of the URL, see
  [Routing](/docs/sites/routing).
- Static rendering knows them only when a declaration of the script is the call itself, `val width by window.innerWidth()`. The page takes the real value
  once the component is in it.
- `activeElement()` and `fullscreenElement()` can't be read by the markup, because static rendering has no element types, so they serve `effect` and event
  handlers.
- `clientWidth()` and `clientHeight()` work on any HTML element, such as `it.clientWidth()` in `@mount`.
- `{::scroll}` binds a scroll position declared as a `var`.
- Writing a scroll position scrolls the page, except on its first run, because the browser restores the position on reload.
