# Events

What a page hears: presses, fields, keys, pointers, the wheel, files dropped,
things pasted, sizes changing, swipes, and things of its own carried from one
element to another (`drag=`, `dropped=`). Also `keys.*`, the element itself
(`ref=`, `el.…`) and a field's caret and selection. Back to the [map](README.md).

```mote
// docs: whole
state n = 0
state name = ""
state last = ""

action add
  n += 1

action remove(id: string)
  last = `removed ${id}`

action typed(v: string)
  name = v

column gap=8 padding=16
  button "Add" press=add
  button "Remove a" press=remove("a")
  button "Reset" press={n = 0; last = "reset"}
  input input=typed placeholder="Your name"
  text `${n} ${name} ${last}`
```

## Mental model

An event is written like any attribute: `name=handler`. The handler is one of

| Form | Example | Runs |
|---|---|---|
| an action's name | `press=add` | the action, with what the event hands over |
| a call | `press=remove(t.id)` | the action with your arguments, then what the event hands over |
| a block | `press={n += 1; open = false}` | the statements, separated by `;` |

Each becomes one DOM listener on the element (`view.rs`, `Dyn::Event`;
`emit.rs`, `Gen::handler`). A handler is like an action's body: it may write
state, wait, and use `?`. A handler that waits runs on its own; what fails
in it is logged to the console, and [`on failure`](back-end.md#when-something-fails)
hears it if the page has one (a named action keeps `failure(action)`, a
block does not, so put work that can fail in an action).

**What an event hands over** is appended after your own arguments, and the
action's last parameter must have the right type (`H067`):

```text
input type=checkbox change=set        action set(on: bool)
input input=typed                     action typed(v: string)
button press=remove(t.id)             action remove(id: string)
box pointerdown=grab                  action grab(p: {x: number, y: number})
box pointermove=drag(t.id)            action drag(id: string, p: {x: number, y: number})
```

An action named alone that takes more than the event hands over is refused
(`H071`: pass them, `press=remove(…)`). A value that is not an action is
refused (`H070`: write a block).

**In a block, `it` is what the event hands over**, with the type the table
below gives it:

```mote
// docs: whole
state draft = ""
state on = false
state at = {x: 0, y: 0}
state said = ""

column gap=8 padding=16
  input input={draft = it.trim()} placeholder="Type"
  input type=checkbox change={on = it}
  box pointerdown={at = {x: it.x, y: it.y}} contextmenu={said = `menu at ${Math.round(it.x)}`} width=200 height=80 background=card
  box key={said = it} tabindex=0 padding=8
    text "Press a key here"
  text `${draft} ${on} ${at.x}, ${at.y} ${said}`
```

A name of the page's own called `it` is still the page's. On an event that
hands nothing over (`press`), there is no `it`.

## The events

| Event | DOM event | Hands the handler |
|---|---|---|
| `press` | `click`, unless something inside took it ([below](#a-press-inside-a-press)) | nothing |
| `presses` | every `click` on the element or inside it | nothing |
| `input` | `input` | the field's value |
| `change` | `change` | the field's value |
| `submit` | Enter on a field; the form's `submit` on a `form` | nothing |
| `focus` `blur` | the same | nothing |
| `key` | `keydown` | the key's name (`"a"`, `"Enter"`, `"ArrowUp"`) |
| `keyup` | `keyup` | the key's name |
| `pointerdown` `pointerup` `pointermove` | the same | `{x, y, width, height, shift, alt, ctrl, meta, button, pressure, id, type, primary}` |
| `pointercancel` | a press that ends with no up ([below](#every-drag-ends)) | the same record: where the pointer last was |
| `dblclick` `contextmenu` | the same | the same record |
| `pointerenter` `pointerleave` | the same | nothing |
| `wheel` | the same | the pointer's record and `{dx, dy, pinch}` |
| `pinch` | two fingers moving apart or together on the element; a trackpad's pinch | `{scale, x, y, done}` |
| `swipe` | one finger, a mouse or a pen drawn along the element ([below](#swiping)) | `{dx, dy, vx, vy, phase, tx, ty, width, height, type}` |
| `scroll` | the same | nothing |
| `drop` | files let go over the element | `{name, path, data: bytes}`, once per file |
| `paste` | something pasted | `{text, files}`; each file `{name, path, data: bytes}` |
| `pastefiles` | a paste that carries files, in the element or a field inside it | the same record |
| `dropped` | something carried from a `drag=` element, let go here | `{value, kind, x, y, width, height, shift, alt, ctrl, meta}` ([Dragging](#dragging)) |
| `over` | the same, while it is held over the element | that record, or `none` once it has left |
| `resized` | the element's own size changed | `{width, height}` |
| `contents` | what is inside it changed | nothing |
| `load` | an `image` finished loading | nothing |
| `seen` | the element came into view, or left it ([below](#seen)) | `{visible, ratio}` |
| `typed` `composing` | on a `surface` only: words typed on it | a string ([drawing.md](drawing.md#typing-on-a-surface)) |

Details:

- **A field's value** is its kind's: a checkbox or radio gives a bool; a
  `number` or `range` input gives a number; anything else text.
- **`submit`** on a field is the Enter key, but not the Enter that takes
  what an input method was composing (Japanese, Chinese, Korean…): that
  one only ends the composition. On a `form` it is the form's submit, and
  the page does not reload.
- **`key`** on anything but a field is for shortcuts: typing in a field
  inside the element is not heard, but for Escape and the chords with a
  modifier that it names in `keys=` ([Keys](#keys)). On a field itself it
  hears every key.
- **`press`** is heard by the innermost thing pressed
  ([below](#a-press-inside-a-press)).
- **Pointer events** say where the pointer is from the element's corner
  (`x`, `y`), the element's size (`width`, `height`), which modifier keys are
  held (`shift`, `alt`, `ctrl`, `meta`: bools), `button` (0 the main one, 2
  the other) and `pressure` (a pen's, 0 to 1). `dblclick` and `contextmenu`
  hand over the same record. An element with both `pointerdown` and
  `pointermove` keeps the pointer for the whole drag, wherever it wanders,
  and hears how it ends ([below](#every-drag-ends)).
  `id` says which pointer it is: each finger on a screen has a number of
  its own from the moment it comes down until it lifts, so two fingers are
  two streams that can be told apart. `type` is `"mouse"`, `"touch"` or
  `"pen"`; `primary` is true of the first finger down (and of a mouse).
- **`pinch`** is two fingers on the element, or a pinch on a trackpad.
  `scale` is how far apart the fingers are against how far they were when
  the second came down (1 at first, 2 at twice as far; on a trackpad, since
  the pinch began); `x`, `y` is the point between them, from the element's
  corner; `done` is true once, when it ends. So a picture's zoom is
  `shown = zoom * p.scale` while it goes on, and `zoom = zoom * p.scale`
  when `p.done`. The browser's own panning and zooming are off on the
  element (`touch-action: none`).
- **`wheel`** adds `dx`, `dy` (how far it turned) and `pinch` (a bool: a
  pinch on a trackpad). The page does not scroll. `wheels="x"` beside it takes
  only a turn to the side (a trackpad's two fingers drawn across, Shift and a
  wheel), `wheels="y"` only one up or down; a turn the other way, and a pinch,
  are left to the page, which scrolls: `view wheel=turn wheels="x"` on a strip
  in a page that scrolls down. The value may be worked out, and `none` is not
  now.
- **`contextmenu`** (the other mouse button, a long press) takes the
  browser's menu's place.
- **`drop`**: the handler runs once for each file, with its name, path and
  bytes. A folder let go there gives every file in it and in the folders
  inside it; `path` says where each is from that folder
  (`"trip/day1/a.jpg"`). For a lone file `path` is its name. In a page
  with a `drop=` (or one that reads `screen.filesOver`), a file let go
  anywhere else is refused: the browser does not leave the page to show it.
  `screen.filesOver` is true while files are held over the window, for an
  overlay that says where to let go
  ([markup.md](markup.md#in-front-and-at-it)).
- **`paste`** is what is pasted (the paste keys, or the browser's Edit menu)
  while the keyboard is inside the element, or nowhere at all. `text` is
  the words on the clipboard, `files` its files; a copied picture is one of
  the files, a PNG. A field inside the element keeps its own pastes;
  `paste=` written on a field itself takes the paste from the field (the
  handler puts in what it wants, with `el.replace`).
- **`pastefiles`** is a paste that carries files, wherever in the element
  it lands: in a field inside it too, or on the field itself. It hands over
  the same `{text, files}`. Nothing is taken from the field: the words of
  the paste go into it as they would have, and a paste of files alone (a
  screenshot) is kept from it. So a composer takes pictures with
  `column pastefiles=attach` around its `textarea`, and words are pasted as
  ever. The
  browser asks nobody's leave for this; reading the clipboard at another
  moment is `clipboard.…` ([data.md](data.md#clipboard)).
- **`resized`** is told once when the element is on the page, then on every
  change. **`contents`** hears anything added, removed or reworded inside.
- **`seen`** is told once as the element is first on the page (whether it
  shows), then each time it comes into view or leaves it: [below](#seen).

A parameter's record type may name only the fields it uses: `{x: number, y:
number}` is enough for a pointer event.

**The keyboard on widgets and canvases.** On `editor`, `terminal` and
`flow`, `focus`, `blur` and `key` are the keyboard anywhere inside the
widget. A `canvas`, `surface` or `reel` that has a handler for one of them
takes the keyboard when it is pressed.

```mote
// docs: whole
state x = 0
state y = 0
state zoom = 1
state files: string[] = []
state size = ""

action drag(p: {x: number, y: number})
  x = p.x
  y = p.y

action turned(w: {dy: number, pinch: bool})
  zoom = Math.max(0.1, zoom - w.dy / 500)

action dropped(f: {name: string, data: bytes})
  files.push(`${f.name}: ${f.data.length} bytes`)

action grew(s: {width: number, height: number})
  size = `${s.width} by ${s.height}`

column gap=8 padding=16
  box pointerdown=drag pointermove=drag wheel=turned width=300 height=200 background=card
  box drop=dropped resized=grew padding=24 border="1px dashed" border-color=line
    text "Drop files here"
  text `${x}, ${y} · zoom ${zoom} · ${size}`
  for f in files
    text f
```

## Every drag ends

```mote
// docs: whole
state x = 0
state from = 0
state kept = 0
state held = false

action grab(p: {x: number})
  held = true
  kept = x
  from = p.x - x

action pull(p: {x: number})
  if held x = p.x - from

action drop
  held = false

action stop
  held = false
  x = kept

view pointerdown=grab pointermove=pull pointerup=drop pointercancel=stop width=300 height=60 background=card touch-action=none
  view width=60 height=60 background=accent translate=`${x}px 0` pointer-events=none
```

On an element with both `pointerdown=` and `pointermove=`, **each press is
followed by exactly one `pointerup` or one `pointercancel`** for that `id`,
and no `pointermove` of it comes after. `pointercancel` is a press that ends
with no up:

- the browser or the system took the touch away (it became a scroll, a call
  came in, an edge was swiped);
- another element took the pointer, or its capture was lost some other way;
- the page was hidden or left;
- the element was taken off the page (by its `if`, its `for`, its route),
  which is told once the page has done so;
- the up was never heard, and the mouse comes back with no button held (it
  was let go over one of the browser's own dialogs, or the browser carried
  something off).

Its record says where the pointer last was. Put back what the drag had
moved, or let it stand; what matters is that the drag is over. A handler that
does the same on both is `pointerup=drop pointercancel=drop`.

- **Each pointer by itself**: two fingers are two ids, each with its own end.
- **A mouse's drag lasts until every button is up.** A second button pressed
  meanwhile is no second `pointerdown`.
- **A mouse passing over** with no button held is told as `pointermove`, as
  ever, and so is an up whose press was somewhere else.
- **Of two such elements, one in the other,** the inner one keeps the
  pointer, and both hear all of it.
- **`touch-action`**: an element that says nothing lets the browser scroll by
  a touch that starts on it, and the drag then ends in a `pointercancel` after
  its first moves. Say `touch-action=none` (or `pan-y`, to leave it the way up
  and down) on what is dragged by finger.
- With `pointercancel=` and no `pointermove=`, the press is followed to its
  end in the same way, but not captured.

For a drag along one axis that should leave presses inside it alone, and the
page's scrolling, use [`swipe=`](#swiping).

Source: `runtime/page/touch.mote`, parts `PH` and `PCD`.

## A press inside a press

```mote
// docs: whole
state opened = ""
state starred: string[] = []

column gap=8 padding=16
  for name in ["general", "random"]
    row press={opened = name} gap=8 padding=8 background=card cursor=pointer
      text name flex=1
      button "Star" press={starred.push(name)}
      input placeholder="A note"
  text `open: ${opened}; starred: ${starred.join(", ")}`
```

**The innermost thing that takes a press hears it, and nothing around it
does.** A press on `Star` stars; it does not also open the row. A press in
the field puts the caret there and opens nothing. A press anywhere else on
the row opens it.

What takes a press itself, inside an element that has `press=`:

- anything with a `press=` of its own;
- a `button`, a `link`, a field (`input`, `textarea`, `select`), a `label`,
  a `summary`, anything `contenteditable`;
- a `dialog` or a `popover` written under the element, and all inside it.

There is no word for stopping an event, and none is needed for this: a card
that opens with a button on it that does something else is the common case,
and both running was never what was meant. For the rare case where the
inner press should also do the outer thing, call the outer action from the
inner handler: `press={star(name); open(name)}`.

**`presses=`** is for the element whose whole job is to hear presses on
whatever is put inside it (a wrapper that closes the sheet it is in, one
that counts presses): it is told of every press on it or inside it, whoever
else took it.

```mote
// docs: whole
state open = true
state saved = 0

component CloseOnPress(done: () => none)
  view display=contents presses=done
    slot

column gap=8 padding=16
  if open
    CloseOnPress done={open = false}
      button "Save" press={saved += 1}
      button "Cancel"
  text `${saved} saved`
```

Only `press` works this way. Other events (`key`, `pointerdown`, `input`, …)
are heard by every element they pass through that listens.

Source: `runtime/page/dom.mote`, part `PR`.

## Dragging

Carrying something of the page's own from one element to another. (Files
from outside the page arrive through `drop`.)

```mote
// docs: whole
shape Todo
  id: string
  title: string

state todos: Todo[] = [{id: "a", title: "Sand"}, {id: "b", title: "Prime"}, {id: "c", title: "Paint"}]
state done: string[] = []
state hint = ""

action move(to: string, d: {value: string, y: number, height: number})
  let from = todos.findIndex(t => t.id == d.value)
  let t = todos.splice(from, 1)[0]
  todos.splice(todos.findIndex(t => t.id == to) + (d.y < d.height / 2 ? 0 : 1), 0, t)

action finish(d: {value: string})
  let t = todos.find(t => t.id == d.value)
  if t == none return
  done.push(t.title)
  todos.remove(t)

row gap=24 padding=16 align-items=flex-start
  column width=200
    for t in todos key=t.id
      row drag=t.id kind="todo" dropped=move(t.id) takes="todo" padding=8 border-top="2px solid transparent" border-bottom="2px solid transparent"
        dragging opacity=0.3
        over top border-top-color=accent
        over bottom border-bottom-color=accent
        text t.title
  column dropped=finish takes="todo" over={hint = it ? "Let go to finish" : ""} width=200 min-height=120 padding=8 border="1px dashed" border-color=line
    over background=card
    text "Done" color=dim
    for d in done
      text d
    text hint color=accent
```

| Written | On | Means |
|---|---|---|
| `drag=value` | what is picked up | The element can be carried; `value` is what it carries (anything). |
| `kind="todo"` | beside `drag=` | What kind of thing it is, as a word. |
| `dropped=handler` | a receiver | Runs when something is let go over it. |
| `over=handler` | a receiver | Hears every move over it, and `none` once it is no longer over it. |
| `takes="todo photo"` | beside `dropped=` or `over=` | The kinds it receives, separated by spaces. Unsaid: anything. |

- **Picking up.** A mouse or a pen picks the element up once it has moved a
  little; a finger once it has rested on it a moment (a finger that moves at
  once is scrolling). A copy of the element follows the pointer; a copy too
  large to see past is made smaller.
- **What the receiver is handed**: `{value, kind, x, y, width, height,
  shift, alt, ctrl, meta}`. `value` is what was carried, as `json`: say its
  type where you take it (`d: {value: string}`). `x`, `y` are where it was
  let go, from the receiver's corner; `width`, `height` the receiver's size.
- **`over=`** is handed the same record on every move, and `none` when the
  thing leaves or is let go: `over={ghost = it ? snap(it.x) : none}`.
- **Calling it off.** Escape, or letting go over nothing that takes it (or
  over the element itself), puts it back: no handler runs.
- **Scrolling.** Held near the edge of something that scrolls, it scrolls.
- **The nearest receiver wins**: of the elements under the pointer, the
  innermost one that takes the kind.

**Styles meanwhile** are child lines, like `hover`
([markup.md](markup.md#conditional-styles)):

| Line | Styles | While |
|---|---|---|
| `dragging …` | what is carried | it is in hand |
| `over …` | a receiver | something it takes is held over it |
| `over top …` `over bottom …` `over left …` `over right …` | a receiver | the pointer is in that half of it |

`over top=4` is the style named `top`, not the half: a half is a bare word
followed by a style.

`drag=`, `kind=`, `dropped=`, `over=` and `takes=` on a component go on its
first element, like any event.

Source: `runtime/page/drag.mote`, part `DD`.

## Swiping

`swipe=` hears one finger (or a mouse, or a pen) drawn along the element, as
it goes:

```mote
// docs: whole
state x = 0
state held = false

action slide(s: {dx: number, vx: number, phase: string, tx: number, width: number})
  x = s.tx + s.dx
  held = s.phase == "start" || s.phase == "move"
  if s.phase == "end"
    x = Math.abs(s.vx) > 0.4 || Math.abs(x) > s.width / 2 ? Math.sign(s.vx == 0 ? x : s.vx) * 320 : 0
  if s.phase == "cancel"
    x = 0

view overflow=hidden width=320
  view swipe=slide width=320 padding=24 background=card translate=`${x}px 0` transition=(held ? "none" : "translate 300ms ease")
    text "Draw me to one side"
    button "A button still works" press={x = 0}
```

| Field | |
|---|---|
| `phase` | `"start"`, then any number of `"move"`, then exactly one `"end"` (it was let go) or `"cancel"` (it was cut short: [every way a drag can be](#every-drag-ends), or a second finger came down). |
| `dx` `dy` | How far it has gone, in pixels, right and down being more (on a page read from right to left too). Counted from where it became a swipe, so what follows it does not jump. |
| `vx` `vy` | How fast it goes now, in pixels a millisecond over about the last 100 ms, so a rest before letting go reads as 0. (A flick is 0.4 or more.) 0 in a `cancel`. |
| `tx` `ty` | The element's own translate when the swipe started, in the middle of a transition too. The same in every phase: `x = it.tx + it.dx` is where it should stand. |
| `width` `height` | The element's size. |
| `type` | `"touch"`, `"mouse"` or `"pen"`. |

`swipes=` beside it says the way:

| Written | Starts |
|---|---|
| `swipes="x"` (unsaid) | to either side |
| `swipes="y"` | up or down |
| `swipes="left"` `"right"` `"up"` `"down"` | that way only (once started, `dx` and `dy` may go back past nought) |
| `swipes=(open ? "down" : none)` | as the value says now; none: no swipe |

**When it starts.** After 8 pixels, if they are more along the axis than
across it. A finger that goes the other way is the page's (it scrolls), and
that touch is no swipe any more. The pointer is captured when the swipe
starts, not when it comes down, so presses inside are presses: a tap on a
button, a link, a checkbox. The click a browser sends at the end of a swipe
is dropped; no other is.

**What it leaves alone**:

- **Scrolling the other way.** The element's `touch-action` is `pan-y
  pinch-zoom` (`pan-x pinch-zoom` for up and down), unless you say one
  yourself.
- **Something that scrolls the same way inside** (or the element itself, if
  it says `overflow-y=auto` and is swiped up or down) keeps the finger for as
  long as it can go on that way. So a sheet with `swipes="down"` around a
  list that scrolls is swiped down from the top of the list, and from its
  head; anywhere else in the list the list scrolls. A touch that began as a
  scroll stays one until the finger lifts. (On a component whose own first
  element scrolls, put the swipe on an element around it.)
- **Fields**: a swipe does not start in an `input` (but for checkboxes, radios
  and buttons), a `textarea`, a `select` or anything editable.
- **What follows the pointer itself** inside it (`pointerdown=` with
  `pointermove=`, a `flow`, a `canvas boxes=`), and what is carried (`drag=`).
- **Swipes inside it**: of two along one axis the inner one takes it; a
  carousel (`"x"`) in a sheet (`"y"`) each take their own.
- **Pinching**: a second finger anywhere on the screen ends the swipe with a
  `cancel`, and a `pinch=` on the same element begins.
- The mouse's other buttons. A mouse that swipes chooses no words, and does
  not carry off a picture or a link. The wheel and a trackpad's two fingers
  are no swipe.

**Pixels** are the element's own: what you would write as `translate` on
something in it to keep it under the finger, and what `width` is told in. Under
`zoom` or inside something with a `scale`, 50 of the window's pixels are 100 of
an element drawn at half its size. (A `rotate` around it is not undone. The 8
pixels to a start are the window's.)

`swipe=` and `pointermove=` on one element are refused (`H180`): each would
take the pointer from the other. Put one inside the other.

Source: `runtime/page/touch.mote`, part `SW`.

## Events on a component

An event written on a component that is not one of its props goes on the
component's first element, and is heard as on the element itself, with what
it hands over.

```mote
// docs: whole
component Entry(value: string)
  row gap=8
    text "Name"
    input value=value

state name = ""
state heard = ""

action picked(v: string)
  heard = `changed to ${v}`

column gap=8 padding=16
  Entry value=name change=picked submit={heard = "submitted"} focus={heard = "in"} blur={heard = "out"} drag=name
  text heard
```

- `input` and `change` hand over the value of the field they came from,
  which may be inside the first element.
- `focus` and `blur` are the keyboard coming into the first element and
  leaving it.
- An event the component declares as a prop (`component Go(press: …)`) is
  the component's to call: the handler is handed what the component hands
  it ([markup.md](markup.md#components)).

## Keys

```mote
// docs: whole
state said = ""

action keyed(k: string)
  if k == "s" && keys.mod said = "save"
  if k == "z" && keys.mod && keys.shift said = "redo"
  if k == "Escape" said = ""

column key=keyed keys="mod+s mod+shift+z" tabindex=0 padding=16
  text "Press ⌘S here"
  text said
```

- `keys.shift` `keys.alt` `keys.ctrl` `keys.meta` `keys.mod` say which are
  held now, anywhere on the page. `mod` is ⌘ on Apple's machines and Ctrl
  elsewhere.
- `keys="mod+s mod+d tab"` beside `key=` (or `keyup=`) names the chords the
  element takes for itself, so the browser does not act on them too.
  `keys="all"` takes every key. Chords are separated by spaces; a chord is
  modifiers and a key joined by `+` (`alt`, `ctrl`, `meta`, `shift`, `mod`;
  the key's name in lower case; `space` for the space bar).
- An element hears keys only while the keyboard is in it. Give a non-field
  `tabindex=0` so it can be focused, or put `key=` on an element that holds
  the fields. A chord for the whole page, wherever the keyboard is, is a
  `shortcut` line ([below](#shortcuts-for-the-whole-page)).

### Keys typed in a field

A `key=` on an element that holds fields hears some of what is typed in
them. The rule:

| The key, typed in a field inside the element | The element's `key=` |
|---|---|
| a letter, a digit, Enter, Tab, an arrow, Backspace: typing | does not hear it, named in `keys=` or not |
| a chord named in `keys=` that holds Ctrl, Alt or the command key (`mod+k`, `alt+arrowdown`, `mod+shift+p`) | hears it, and the browser does not act on it |
| Escape | hears it |
| a chord with a modifier that `keys=` does not name (`mod+c` in the field) | does not hear it: it is the field's |

Two exceptions, both "it was somebody else's key":

- **A field (or anything between) that took the key for itself** with a
  `keys=` of its own keeps it: with `textarea key=typed keys="mod+k escape"`
  inside the frame, ⌘K and Escape in that textarea are the textarea's alone.
- **Escape in a field inside an open `dialog` or `popover`** that is itself
  inside the element closes that, and is not told to the element.

Nor is anything heard while an input method is composing.

```mote
// docs: whole
state finding = false
state said = ""

action heard(k: string)
  if k == "k" && keys.mod finding = true
  if k == "Escape" finding = false
  said = k

column key=heard keys="mod+k" gap=8 padding=16
  input placeholder="⌘K and Escape are heard from here; letters are not"
  if finding
    text "Finding…"
  text said
```

Source: `runtime/page/events.mote`, parts `KM` and `KF`.

## Shortcuts for the whole page

A `key=` hears keys only while the keyboard is inside its element, and
straight after a page opens the keyboard is nowhere. A chord the whole page
answers to is a line of its own:

```mote
// docs: whole
state finding = false
state saved = 0
state picked = 0
state draft = ""

action undo
  draft = ""
action save
  saved += 1
action pick(n: number)
  picked = n

shortcut "mod+z" undo
shortcut "mod+k" {finding = true}
shortcut "mod+s" save fields
shortcut "mod+1" pick(1)
shortcut "mod+2" pick(2)
shortcut "escape"
  finding = false
  picked = 0

column gap=8 padding=16
  input value=draft placeholder="⌘S is heard from here; ⌘Z is this field's own"
  if finding
    shortcut "enter" {finding = false}
    text "Finding… (Enter ends it)"
  text `saved ${saved} times, picked ${picked}`
```

- **The line** is `shortcut`, the chords in quotes, then what `press=` takes:
  an action's name, a call with its arguments, or a `{…}` block; or nothing,
  and statements indented under it. Nothing is handed over (there is no
  `it`).
- **The chords** are the ones `keys=` takes, read by the same code: held
  keys and a key joined by `+` (`mod`, `ctrl`, `alt`, `shift`, `meta`; the
  key's name in lower case, `space` for the space bar). Several chords,
  separated by spaces, run the same thing: `shortcut "mod+z ctrl+y" undo`.
  A symbol typed with Shift is named as it is typed: `"shift+?"`. A name the
  keyboard does not have is refused when compiled (`H101`).
- **Where it is written is when it is live.** At the top of any file (the
  entry or one it `use`s): from the moment the page opens. In a component:
  while the component is drawn. Under an `if` or a `route`: while that is
  shown, as `task`, `every` and `watch` are
  ([reactivity.md](reactivity.md#tasks-and-timers-inside-markup)).
- **Heard wherever the keyboard is**: on a button, on nothing, in another
  part of the page. The browser's own use of the chord is prevented when a
  line hears it (⌘S opens no save dialog), and only then.
- **A field keeps its keys.** While an `input`, a `textarea`, a `select`,
  an `editor` or anything editable has the caret, nothing is heard but
  Escape, so ⌘Z, ⌘A, ⌘C and the arrows stay the field's. A line that ends in
  `fields` is heard there too: `shortcut "mod+s" save fields`.
- **Enter and the space bar press what the keyboard is on.** With nothing
  held but Shift they are left to a focused button or link.
- **An element's own `key=` comes first.** When the keyboard is inside an
  element whose `keys=` names the chord, that element hears it and the
  `shortcut` does not.
- **A dialog or a popover.** A line written under a `dialog` or a `popover`
  (or in a component drawn inside one) is heard only while it is open, and
  then before the page's line for the same chord; the innermost one open
  wins. Lines outside go on hearing every other chord. Escape with a dialog
  or popover open closes it, as the browser does, and is told to no line
  outside it.
- **Twice.** Two lines at the top of the program's files that name the same
  chord are refused (`H022`, naming both places): one could never be heard.
  Anywhere else the two take turns: of those live, the one that came to the
  page later is heard.

`mod+k` on an outer element with `tabindex=-1`, to catch keys for a whole
page, is no longer needed: write the `shortcut` line.

Source: `compiler/src/parse.rs` (`Node::Shortcut`), `compiler/src/tables.rs`
(`chord_error`), `runtime/page/events.mote`, part `KS`.

## The element itself

```mote
// docs: whole
state box: element? = none
state lines = ["one"]
state pinned = true

action scrolled
  pinned = el.scrollHeight(box) - el.scrollTop(box) - el.height(box) < 24

action grew(s: {width: number, height: number})
  if pinned el.scrollTo(box, el.scrollHeight(box))

action more
  lines.push(`line ${lines.length + 1}`)

column gap=8 padding=16
  button "More" press=more
  column ref=box scroll=scrolled height=120 overflow-y=auto
    column resized=grew
      for l in lines
        text l
```

Declare `state box: element? = none`, then `ref=box` on an element fills it.
Wherever a call below takes an element, it also takes **the id of one**
(`el.rect("composer")`), which is found wherever on the page it was drawn:
so one component can read, focus or put the caret in a field another
component drew. (So can a ref: a `state box: element?` at the top of a
file is the whole program's, and any component may write `ref=box` or call
`el.focus(box)`.)

| Call | Gives |
|---|---|
| `el.width(box)` `el.height(box)` | its inner size |
| `el.scrollTop(box)` `el.scrollLeft(box)` | where it is scrolled to |
| `el.scrollHeight(box)` `el.scrollWidth(box)` | the size of what it holds |
| `el.rect(box)` | `{x, y, width, height}` in the window |
| `el.transform(box)` | `{tx, ty, sx, sy}`: its translate (in pixels) and its scale at this moment, in the middle of a transition or an animation too, from `translate`, `rotate`, `scale` and `transform` together. A strip caught as it slides: `x = el.transform(strip).tx`, with its transition off. `{0, 0, 1, 1}` for an element that is not there |
| `el.rect(box, scroller)` | the same, with `x` and `y` measured in what `scroller` (an element or an id) holds: where it is in the list, however far the list is scrolled. `el.scrollTo(list, el.rect(row, list).y)` puts it at the top |
| `el.scrollTo(box, top, left?, smooth?)` | scrolls it; `smooth` is a bool |
| `el.focus(box)` `el.blur(box)` | moves the keyboard |
| `el.from()` | `{id, row, data}`: where the event being handled happened ([below](#where-it-happened)) |
| `el.at(x, y)` | the same, of what is drawn at that point of the window |
| `el.row(list, key)` | the first element of the row with that key in the `for` drawn inside `list` (an element or an id); `none` if no row has it (or, in a [virtual list](markup.md#long-lists), if it is not drawn). An `element?`, for the calls above and for `scroll` and `focus` |
| `el.inView(list, key)` `el.shown(list)` | a row of a virtual list: whether it shows; which places show ([below](#a-row-of-a-long-list)) |
| `el.selection(field)` `el.select(field, start, end?)` `el.replace(field, start, end, words)` `el.caret(field, at?)` | a field's caret and selection ([below](#a-fields-caret-and-selection)) |

Before the element is on the page (and for an id nothing has) the reads give 0 and the rest do nothing.

**What an action has just made appear** is not on the page until the action
is done: `open = true` writes the state, and the row an `if open` draws
comes a moment later. So what is *done* to an element named by its id
(`focus("id")`, `scroll("id", …)`, `el.focus`, `el.scrollTo`, `el.select`,
`el.replace`) and finds nothing is done once the page has drawn what was
written; nothing more is needed:

```text
action addLink
  linkOpen = true
  focus("link-field")          // the field an `if linkOpen` draws
```

A *read* (`el.rect`, `el.width`) cannot be put off, and neither can a call
on a `ref` (it is none until the element is made). For those, `drawn()`
waits until the page shows what has been written so far:

```text
action openPanel
  panelOpen = true
  drawn()
  wide = el.width("panel")
```
The reads are not reactive: they give the value at the moment of the call.
Read them in a handler (`scroll=`, `resized=`), not in a binding you expect
to follow the element.

`focus(target)` and `scroll(target, …)` take an id or a ref likewise
([language.md](language.md#built-in)). Both `el.focus(box)` and
`focus("id")` leave a field's caret where it was.

**Into view.** `scroll(target, {inside, block, behavior})` brings one
element into view:

```mote
// docs: whole
state rows = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

action show(n: number)
  scroll(`row-${n}`, {inside: "list", block: "center", behavior: "instant"})

column gap=8 padding=16
  button "Show row 15" press=show(15)
  column id="list" height=120 overflow-y=auto
    for n in rows
      text `Row ${n}` id=`row-${n}`
```

| Option | |
|---|---|
| `block` | Where in the view it comes to stand: `"start"`, `"center"`, `"end"`, or `"nearest"` (unsaid): no further than it takes to show it, and not at all if it is in view. |
| `behavior` | `"smooth"` (unsaid: it glides) or `"instant"`. Where less motion is wanted ([markup.md](markup.md#values-of-the-whole-page)) it is always at once. |
| `inside` | The scroller to move (an id or a ref), and no other: the page itself stays where it is. Left out, everything that holds the element scrolls as far as it must, the page too. |

An instant scroll has happened when the call returns, so what is read next
(`el.scrollTop`) is the new place.

## Where it happened

One handler on a list hears a key, or a press, from every row; `el.from()`
tells it which. It gives where the event now being handled happened:

| Field | |
|---|---|
| `row` | The key of the `for` row it happened in (`for m in msgs key=m.id`: `m.id`, as text). `""` outside a keyed `for`. Of the nearest `for`, if one is inside another. |
| `id` | The id of the nearest element that has one, from where it happened upwards. `""` if none. |
| `data` | The `data-*` attributes of the nearest element that has any, as `json`: `data-kind="tool"` is `at.data.kind`. |

```mote
// docs: whole
shape Msg
  id: string
  words: string

state msgs: Msg[] = [{id: "m1", words: "one"}, {id: "m2", words: "two"}]
state editing = ""
state top = ""

action keyed(k: string)
  let at = el.from()
  if k == "e" && at.data.kind != "tool" editing = at.row

action whichTop
  let r = el.rect("list")
  top = el.at(r.x + 8, r.y + 4).row

column gap=8 padding=16
  column id="list" key=keyed scroll=whichTop height=120 overflow-y=auto
    for m in msgs key=m.id
      row tabindex=0 gap=8
        text m.words
        button "react" data-kind="tool"
  text `editing ${editing}; at the top ${top}`
```

- It is the event being handled *now*: ask before anything waits. After a
  wait, in a timer, or in `resized=`, `contents=` and `drop=` (which are told
  later than the event), every field is empty.
- `el.at(x, y)` gives the same of whatever is drawn at a point of the
  window: with `el.rect`, "which row is at the top of what shows".
- `el.row("list", m.id)` is that row's element, so a row needs no id or
  `ref` of its own to be measured, scrolled to or given the keyboard:
  `el.scrollTo("list", el.rect(el.row("list", id), "list").y)`.

Source: `runtime/page/popover.mote` (parts `ELW`, `UT`: `UTW`, `DRW`); the
key is put on a row's nodes by `runtime/page/core.mote` (part `L`), or
`runtime/page/virtual.mote` (part `VR`) for a virtual list.

## Seen

`seen=` is told when the element comes into view and when it leaves it,
with `{visible, ratio}`: whether any of it shows now, and how much (0 to
1). `seen-margin=` beside it counts that much outside the view as in it:
`seen-margin=400` (pixels, every side), or a margin as CSS writes it
(`seen-margin="800px 0px"`). In view means on the screen: inside the
window, and inside every box around it that scrolls.

```mote
// docs: whole
state shown: string[] = []
state pages = 1

column height=300 overflow-y=auto gap=8 padding=8
  for n in Array.from({length: pages * 20}, (x, i) => i)
    image src=`https://picsum.photos/seed/${n}/300/120` width=300 height=120 loading="lazy" seen={if it.visible && !shown.includes(`${n}`) shown.push(`${n}`)}
  text "Loading more…" seen={if it.visible pages += 1} seen-margin=600
text `${shown.length} pictures have been seen`
```

- **More at the end**: `seen=` on a line after a list, with a margin, asks
  for the next page before the reader is there.
- **A picture that loads late**: `image … loading="lazy"` is the browser's
  own; `seen=` is for what the program does itself (a thumbnail made, a
  video started, "read" marked on a message).
- One observer serves every element with the same margin; an element taken
  off the page is no longer watched.

## A row of a long list

A row of a [virtual list](markup.md#long-lists) that is not drawn has no
element: `el.row` gives `none`, and `scroll("row-id", …)` finds nothing.
These name it by its list:

| Call | |
|---|---|
| `scroll(list, {row: key})` | Brings the row with that key into view, drawing it first. `block` and `behavior` as above (`block` unsaid: `"nearest"`). A long way off it goes at once; a row already drawn glides. |
| `scroll(list, {index: 5000})` | The same, by its place in the list. |
| `el.inView(list, key)` | Whether that row shows now (any of it). |
| `el.shown(list)` | `{first, last, count}`: the places of the first and last rows that show (`-1` when none do), and how many rows there are. |

`list` is the element the `for` is drawn in, one around it, or its
scroller (an id or a ref). Called in the action that changed the list, they
wait until the page has drawn it.

```mote
// docs: whole
state rows = Array.from({length: 100000}, (x, i) => ({id: `r${i}`, n: i}))
state said = ""

action where
  let s = el.shown("list")
  said = `${s.first + 1} to ${s.last + 1} of ${s.count}; r500 ${el.inView("list", "r500") ? "shows" : "does not show"}`

column gap=8 padding=16
  row gap=8
    button "Row 500" press={scroll("list", {row: "r500", block: "center"})}
    button "The end" press={scroll("list", {index: rows.length - 1, behavior: "instant"})}
    button "Where?" press=where
  column id="list" height=300 overflow-y=auto
    for r in rows key=r.id virtual=32
      text `Row ${r.n}` height=32 padding="6px 8px"
  text said
```

A selection that runs past the rows drawn (Shift and a press, a range) is
the program's own, by key: the rows between are known from the list, not
from the page.

```mote
// docs: whole
state rows = Array.from({length: 50000}, (x, i) => ({id: `r${i}`, n: i}))
state picked: string[] = []
state last = -1

action pick(n: number, shift: bool)
  if shift && last >= 0
    picked = [...picked, ...rows.slice(Math.min(last, n), Math.max(last, n) + 1).map(r => r.id).filter(k => !picked.includes(k))]
  else
    picked = picked.includes(rows[n].id) ? picked.filter(k => k != rows[n].id) : [...picked, rows[n].id]
  last = n

column height=300 overflow-y=auto
  for r in rows key=r.id virtual=32
    row height=32 padding="0 8px" align-items=center pointerdown={pick(r.n, it.shift)} background=(picked.includes(r.id) ? "card" : "bg")
      text `Row ${r.n}`
text `${picked.length} picked`
```

## A field's caret and selection

```mote
// docs: whole
state box: element? = none
state draft = "hello brave world"
state menu = {x: 0, y: 0, height: 0}
state offering = false

// What is selected is wrapped in marks, and stays selected inside them.
action bold
  let s = el.selection(box)
  el.replace(box, s.start, s.end, `**${s.text}**`)
  el.select(box, s.start + 2, s.end + 2)

// A menu is put under the caret when the word being typed starts with @.
action typed
  let s = el.selection(box)
  let word = draft.slice(0, s.start).split(" ").pop() ?? ""
  offering = word.startsWith("@")
  if offering menu = el.caret(box, s.start - word.length)

// The word at the caret becomes the name; the caret stands after it.
action take(name: string)
  let s = el.selection(box)
  let word = draft.slice(0, s.start).split(" ").pop() ?? ""
  el.replace(box, s.start - word.length, s.start, `@${name} `)
  offering = false

column gap=8 padding=16
  button "Bold" press=bold
  textarea ref=box value=draft input=typed rows=3
  if offering
    column position=fixed left=menu.x top=(menu.y + menu.height) padding=4 background=card
      button "Ada" press=take("Ada")
      button "Grace" press=take("Grace")
```

For an `input` or a `textarea` held through `ref=`. Places are counted in
characters from 0, as `s.slice` counts them.

| Call | Does |
|---|---|
| `el.selection(field)` | `{start, end, text}`: where the selection begins and ends, and the words in it. With nothing selected `start == end` (the caret) and `text` is `""`. |
| `el.select(field, start, end)` | Selects from `start` to `end`. `el.select(field, at)` puts the caret at `at`. It does not move the keyboard: `el.focus(field)` does. |
| `el.replace(field, start, end, words)` | The words from `start` to `end` become `words`; the caret stands after them and the keyboard is in the field. `start == end` inserts; `""` deletes. |
| `el.caret(field)` | `{x, y, height}`: where the caret stands in the window (the top of its line, and the line's height), as `el.rect` measures. For a selection it is its end. |
| `el.caret(field, at)` | The same for the character at `at`, wherever the caret is: where a word begins, say. |

- **`el.replace` is typing.** The field's own undo takes it back (⌘Z), its
  `input=` runs once, and a state bound with `value=` is written. So a bound
  field and its state never disagree, and nothing puts the caret at the end.
- **Writing the state instead** also works: `draft = "…"` then
  `el.select(box, 4)`. The field gets its words a moment after the action
  (bindings run when it is done), and `el.select` is applied again then, so
  the caret lands where it was told to in either order. The field's undo
  does not know of a change made this way.
- **Typing in the middle stays in the middle.** A bound field is only given
  its value when the state differs from what it already shows, so the
  caret does not move while a person types.
- **A menu at the caret**: `position=fixed left=at.x top=(at.y + at.height)`
  with `at = el.caret(box)`. The place is the window's, so work it out again
  when the field scrolls or the words change (`input=`, `scroll=`).
- **`el.caret` counts the field's own wrapping**: a word that wrapped to
  the next line is measured there, and a field scrolled inside gives where
  the caret shows (which may be outside the field's box).
- A field whose kind has no selection (`type=number`, `date`, `color`,
  a checkbox) reads as `{start: 0, end: 0, text: ""}`; `select` and
  `replace` leave it alone. So does an element that is not a field.

Source: `runtime/page/field.mote`, part `CAR`.

## Refused

| You write | Message |
|---|---|
| `onClick=…`, `click=…` | `H041`: write `press` |
| `press=count` where `count` is a number | `H070`: write a block, `press={…}` |
| `press=remove` where `remove` takes an id | `H071`: pass them, `press=remove(…)` |
| `change=set` on a checkbox with `action set(v: string)` | `H067`: `change` hands `set` a bool |
| `wheels="x"` with no `wheel=` beside it | `H195`: write both on one element |
| `wheel=turn wheels="across"` | `H196`: `"x"` or `"y"` |
| `shortcut "cmd+k" find`, `"esc"`, `"mod+return"` | `H101`: `mod`, `escape`, `enter` |
| `shortcut find`, `shortcut "mod+k"` | `H101`: the chord in quotes, then what it runs |
| `shortcut "mod+1" pick` where `pick` takes a number | `H071`: pass them, `shortcut "…" pick(…)` |
| two `shortcut "mod+k" …` lines at the top of the program's files | `H022`: names both places |

## Pitfalls

- **A block is one line.** Statements in `{…}` are separated by `;`. For
  more than two or three, write an action.
- **There is no event object.** A handler gets the value in the table above
  and nothing else (`it`, in a block). There is no word to stop an event
  travelling up. A `press` needs none: the innermost thing pressed hears it
  ([A press inside a press](#a-press-inside-a-press)). For any other event,
  put the handler on the element that should hear it.
- **A shortcut and a field that both act on a key.** Escape typed in a
  field is heard by a `key=` around it. If the field has something of its
  own to close first (a list of completions), give the field `keys="escape"`
  while that is open: the key is then the field's alone.
- **`press` on a `row` is not a button.** Use `button` for anything a
  keyboard should reach, or add `role=button tabindex=0` and a `key=`.
- **`input` versus binding.** `input value=draft` already writes `draft`
  back; add `input=` only for something else to do on each keystroke.
- **`drop` is files; `dropped` is the page's own things.** A file from the
  desktop never reaches `dropped=`, and a `drag=` element never reaches
  `drop=`.
- **What is carried is `json`.** `it.value` in a block is unchecked; in an
  action, type the parameter (`d: {value: string}`).
- **Every control gets a `data-mote` name** from its handler or binding, for
  tests and agents ([agents.md](agents.md)).

## In the source

| What | Where |
|---|---|
| The event table | `compiler/src/tables.rs`, `event` |
| What each event hands over, and its type | `compiler/src/types.rs`: `Checker::payload`, `Checker::handler` |
| Listeners | `compiler/src/view.rs`: `Dyn::Event` in `Gen::el` |
| Handler bodies | `compiler/src/emit.rs`: `Gen::handler` |
| Pointer, wheel, pinch, drop, paste, keys | `runtime/page/events.mote`: parts `PT`, `WH`, `WHW`, `PN`, `DR`, `FG`, `PST`, `KM` |
| Which keys typed in a field are heard around it | `runtime/page/events.mote`: part `KF`; `compiler/src/view.rs`: `Gen::listen` |
| `shortcut` lines | `compiler/src/parse.rs` (`Parser::node`), `tables.rs` (`chord_error`, `chords`), `build.rs` (`shortcuts_twice`); `runtime/page/events.mote`: part `KS` |
| The innermost press | `runtime/page/dom.mote`: part `PR`; `compiler/src/view.rs`: `Gen::listen` (`Listen::plain`) |
| A field's caret and selection | `runtime/page/field.mote`: part `CAR`; `compiler/src/types.rs` and `emit.rs` under `"el"` |
| `it` in a block | `compiler/src/types.rs`: `Checker::handler_block`; `compiler/src/emit.rs`: `Gen::handler` |
| Events through a component | `compiler/src/types.rs`: `Checker::handed` |
| `drag=`, `dropped=`, `over=` | `runtime/page/drag.mote`: part `DD`; `compiler/src/view.rs` (`DDT`, `DDO`) |
| `dragging`, `over` lines | `compiler/src/parse.rs` (the pseudo words); `compiler/src/emit.rs`: `Css` |
| A field's value | `runtime/page/dom.mote`: part `P` |
| Recorded behaviour | `tests/shortcuts`, `tests/el`, `tests/keys`, `tests/events2`, `tests/input2`, `tests/drag`, `tests/desk`, `tests/pages/kitchen` |
