# Reactivity

When things run and re-run: state, derive, bindings, resources, tasks,
timers, `watch`; what is tracked; what moves to workers and why. Back to the
[map](README.md).

```mote
// docs: whole
shape Post
  id: number
  title: string

state tag = "all"
state ticks = 0

resource posts: Post[] = net.get(`posts-${tag}.json`) else []

every 1000
  ticks += 1

column gap=8 padding=16
  row gap=8
    for t in ["all", "rust", "web"]
      button t press={tag = t} font-weight=(t == tag ? 700 : 400)
    button "Reload" press={refresh(posts)}
  if pending(posts)
    text "Loading…" color=dim
  if failed(posts)
    text `Could not load: ${failure(posts) ?? ""}` color=danger
  for p in posts key=p.id
    text p.title
  text `open for ${ticks} s` color=dim
```

## Mental model

There are two kinds of thing (`runtime/page/core.mote`, part `core`):

- A **signal** holds a value and remembers who read it. Every `state` is
  one. So is a `derive`, a `resource`, each row's item in a `for`, and
  `pending(x)` / `failure(x)`.
- An **effect** is a piece of work that runs, notes every signal it read
  while running, and runs again when one of them changes. Every binding in
  markup is one: a text, a dynamic attribute, a computed style, the test of
  an `if`, the list of a `for`.

Nothing is declared. An effect follows exactly what it read on its last run,
so `text (on ? a : b)` follows `on` and whichever of `a` and `b` it showed.

What follows from that:

- **Updates are precise.** Changing `n` runs the effects that read `n`: one
  text node, one attribute. No component re-renders; a component's function
  runs once, when it is built.
- **Updates are batched.** A write queues the effects; they run together in
  a microtask, after the handler that wrote has finished. Several writes in
  one handler cost one update. Effects run oldest first, so an `if` that
  just turned false removes its contents before they would update.
- **Assigning the same value does nothing.** `n = n` tells no one (compared
  with `!=`).
- **A change in place always tells.** `todos.push(x)`, `t.done = true`:
  the compiler follows the written value back to its state and tells that
  state's readers (`emit.rs`, `Gen::write`). Readers of `todos` run again
  even if they only read another item. A `for` with a `key` keeps the rows
  whose keys stayed, so this is cheap.
- **A write into what was handed in tells who may hold it.** In
  `action bump(l: Row)` the compiler cannot see which state `l` came from,
  so `l.n += 1` tells every state that could hold it: all but those whose
  type is a number, a text, a bool, or one of those or none. A component is
  better placed: when it writes into a prop (`list.push(x)`), its caller
  tells the states the prop's value was made from and no others
  (`Adder list=todos` tells `todos`). The caller hands over the telling as
  `list$n` beside the value, only to a component that writes into
  something (`ast::writes_in_place`), or hands a prop on to one that does.
- **What is built owns what it made.** An `if` branch, a `for` row and a
  route own the effects, timers and tasks created inside them. When the
  branch is removed, they stop.

## State

`state n = 0` compiles to `const $n = S(0)`; a read is `$n.v`, an assignment
`$n.v = …`, a change in place is followed by `$n.n()` ("tell").

`persist` adds one effect that writes the value to `localStorage` as JSON
whenever it changes (`PW`): an effect runs at the end of the turn, so the
value is kept before anything else can happen to the page.

State is written only by actions, `{…}` handlers, tasks and timers
([language.md](language.md#writes)).

## Derive

`derive left = todos.filter(t => !t.done).length` is an effect that
computes the value and a signal that holds it. It runs once at once, and
again when what it read changes. Its readers are told only if the new value
differs; a derive that gives a list or a record tells them every time,
because the object may be one that state changed in place.

A derive may read other derives. It may not write (`H030`), be assigned
(`H031`) or wait (`H082`).

`let x = e` in markup is the same thing, scoped to the nodes after it.

## Resources

```mote
resource posts: Post[] = net.get(`/api?tag=${tag}`) else []
```

A resource is a value loaded in the background.

- It runs when the page opens (or when the component it is in is built).
- It runs **again when the state its call reads changes**: `tag` above. What
  counts is what is read before the first wait: the arguments of the call,
  and anything a fn it calls reads before that fn first waits.
- `refresh(posts)` runs it again by hand.
- **`else` is its value until the first answer, and after a failure.**
  Without `else`, it is `none` until then, and its type is `T?`.
- `pending(posts)` is true while a run is in flight (also the first).
  `failed(posts)` and `failure(posts)` say whether the last run failed, and
  why. A new run clears the failure when it succeeds.
- **A run that is overtaken is called off.** If `tag` changes while a run is
  in flight, the old run's answer is dropped. Its worker calls that have not
  started never start; a call already in a worker finishes, and the run
  stops at its next one.
- The call may be anything that can fail or wait: `net.get`, a `server fn`,
  a fn of your own that waits. A `?` inside it has somewhere to go: the
  resource keeps the failure.

A resource over a read of a `local model` (`resource notes = Note.find({done:
false}) else []`) also runs again when the page writes a row that read could
give ([models.md](models.md#local-models)).

A resource cannot be assigned. To change what it shows, change the state it
reads, or keep your own state and fill it in an action.

Source: `runtime/page/actions.mote`, part `RC`. The run's token is passed as
`this` to every fn that waits and on to the worker pool, which is how a run
is called off.

`live` values, which the back end keeps current, are in
[back-end.md](back-end.md#live-values).

## Tasks

```mote
// docs: whole
state saved: number[] = []
state opened = 0

task
  opened = now()

task load
  saved = db.get("saved")? ?? []

column gap=8 padding=16
  button "Load again" press=load disabled=pending(load)
  text `${saved.length} saved`
  if failed(load)
    text (failure(load) ?? "") color=danger
```

- `task` + a block: statements that run when the page opens. They may wait
  and may use `?`.
- `task load` is also an action: call it again with `load()`, and ask
  `pending(load)`, `failed(load)`, `failure(load)`.
- A named task in a file brought in with `use` starts with the page.

## Timers

`every 1000` + a block runs it each second. `after 500` runs it once, half a
second on. The number is milliseconds and may be any expression; it is read
once, when the timer starts.

## watch

```mote
// docs: whole
state active = "a"
state settings = {exposure: 0}
state trail: string[] = []
state saves = 0
state deep = false

watch active
  trail.push(`now ${active}`)

watch settings
  db.set("settings", settings)?
  saves += 1

column gap=8 padding=16
  row gap=8
    button "a" press={active = "a"}
    button "b" press={active = "b"}
    button "Brighter" press={settings.exposure += 1}
    button (deep ? "Stop counting" : "Count") press={deep = !deep}
  if deep
    watch trail.length
      log(`${trail.length} changes`)
  text `${trail.join(", ")} · saved ${saves} times`
```

`watch value` + a block: statements that run **after the value changes**.

- It never runs when the page opens: only on a change. Assigning the value
  it already has is not a change.
- A record or a list counts as changed after it is written into
  (`settings.exposure += 1`, `todos.push(x)`).
- What is watched is any expression: `watch active`, `watch a + b`,
  `watch doc.frames.length`. It runs when the expression's value differs
  from last time.
- The block is like a handler's: it may write state, wait, and use `?`
  (what fails in it is logged to the console).
- **It may not write what it watches**, straight or round by way of other
  watches (this one writes what that one watches, which writes what this
  one watches). That is refused (`H100`), so a change always settles. Do
  the write in the action that makes the change, or watch something the
  block does not write.
- State the block reads does not set it off: only the watched value does.

Use a `derive` for a value worked out from state; use `watch` for something
to *do* when state changes: save it, load what belongs to it, log it.

Source: `runtime/page/events.mote`, part `WA`; `compiler/src/emit.rs`,
`Gen::watch` and the check that refuses rounds.

## Tasks and timers inside markup

`task`, `every`, `after` and `watch` also go among markup: under a route, an `if`, a
`for` row, or in a component. They start when that part is built and stop
when it is removed, with its names in scope. A `shortcut` line is live by
the same rule ([events.md](events.md#shortcuts-for-the-whole-page)).

```mote
// docs: whole
state playing = false
state frame = 0
state log: string[] = []

column gap=8 padding=16
  button (playing ? "Stop" : "Play") press={playing = !playing}
  if playing
    every 100
      frame += 1
    task
      log.push(`started at frame ${frame}`)
    text `frame ${frame}`
  for l in log
    text l color=dim
```

The timer above exists only while `playing` is true
(`runtime/page/events.mote`, part `EV`: the timer is handed to its owner,
which clears it when it is disposed).

## Actions that wait

An action that calls something that waits is asynchronous, without saying
so. Statements after the call run when the answer has come. Meanwhile the
page stays live: other handlers run, and state may change under it.

- Two runs of one action may overlap. `pending(action)` is true while any is
  in flight. Disable the button if that matters:
  `button "Save" press=save disabled=pending(save)`. Or, where only the last
  one asked for counts, let it call the others off:
  [`newest`](#newest-a-later-run-calls-an-earlier-one-off).
- A write of a `model`'s row does not make its action wait: the row shows
  at once and the action goes on, so `pending(action)` is over in a moment.
  What is still on its way is the row: `pending(row)` is true until the
  back end has answered ([models.md](models.md#a-write-shows-at-once)).
- State written before a wait is shown before the answer comes: set a
  "saving" flag, wait, clear it.
- `failure(action)` is the last run's failure; it is cleared when a new run
  starts.

### assume: shown before the answer, taken back if it fails

A write of a `model`'s row from the page shows at once by itself
([models.md](models.md#a-write-shows-at-once)). For anything else the back
end decides, a `server fn` of your own, say what the page may assume while
it asks:

```mote
// docs: whole
shape Post
  id: string
  likes: number
  liked: bool

state posts: Post[] = [{id: "a", likes: 3, liked: false}]

server fn like(id: string): number
  if id == ""
    fail("there is no such post", {kind: "missing"})?
  return 1

action heart(p: Post)
  assume
    p.likes += 1
    p.liked = true
  like(p.id)?

for p in posts key=p.id
  button `♥ ${p.likes}` press={heart(p)}
text `${failure(heart)?.words ?? ""}`
```

- **What is under `assume` is done at once**: the count goes up in the frame
  of the press, and the action goes on to ask.
- **If the action fails after it** (the call is refused, the line is down, a
  `fail(…)?` of its own), each assignment is taken back, the last first, and
  the failure goes where it would have gone: `failure(heart)`, or
  `on failure`.
- **If the action does not fail, they stay.** A failure the action answers
  itself (`like(p.id) else 0`) is no failure of the action: nothing is taken
  back; put it right in the `else`.
- **Taken back with care for what happened meanwhile.** A `+=` or `-=` of a
  number is taken back by as much, so two quick presses of which one is
  refused leave the other's count. Any other assignment is taken back only
  if the place still holds what was put there: a later write stands. Two
  runs that both fail, the second made on top of the first, leave what was
  there before either.
- **Only assignments go under it** (`x = …`, `x.field += …`, `xs = [...xs, row]`):
  what else a block did could not be taken back (`H326`). It is an action's,
  in the page; a run that `newest` calls off keeps what it assumed, for the
  run that took its place to stand on.

### newest: a later run calls an earlier one off

A preview worked out on every change, a search on every key: only the last
one asked for counts, and the answers need not come in the order asked.

```mote
// docs: whole
state depth = 24
state shown = ""

fn fitted(depth: number): string
  let best = 0
  let i = 0
  while i < 30000000
    if (i * depth) % 97 > best % 97 best += 1
    i += 1
  return `${best} parts at ${depth}`

action preview newest
  shown = fitted(depth)

column gap=8 padding=16
  input type=range min=10 max=40 value=depth input=preview
  text (pending(preview) ? "Working…" : shown)
```

`newest` after an action's name (its parameters and its answer's type, if it
has them: `action find(q: string): Hit[] newest`) says: **when it is called
again while a run of it waits, that run is called off.** A named task takes
the word too: `task load newest`.

A run that is called off ends where it waits:

- **Nothing after that wait is done.** Whatever comes, an answer or a
  failure, is dropped: no `else` is asked, `failure(action)` is as the newer
  run leaves it, `on failure` hears nothing, nothing is logged.
- **What it did before the wait stays**: state it wrote, a row it added. Set
  what must be set whichever run ends last (a "saving" flag, say) with
  `pending(action)`, which is true until the newest run ends.
- **A newer run calls the older off by starting**, whether or not it comes to
  wait for anything: one that finds nothing to do, clears what is shown and
  returns leaves it cleared. A run that should change nothing should not be
  started: ask before the call.
- **What it waited for is stopped, where it can be.** A call that has not
  been sent to a worker never is. One that is in a worker: if it has run
  50 ms, its worker is ended and another is started when one is next needed;
  before that it is left to finish (starting a worker costs 2 to 20 ms, so
  ending it sooner would cost more than it saves), and is ended at 50 ms if
  it has not. A worker does one call at a time, so no other call is lost. A
  call to a `server fn`, or a model's read on the back end, is let go of and
  not tried again; the back end may have begun it, and what it did is done.
  Anything else (`net`, `fs`, `db`) goes on, and what it gives is dropped.
- **Bytes [moved](#what-is-copied-and-what-is-moved) to the call are gone**
  with it. The page could not have read them again: the newer run makes its
  own.
- **A fn it calls that waits ends at its wait too.** An action it calls is
  an action of its own, and goes on: say `newest` there as well if it is to
  be called off.
- **An `atomic` block is finished**: a run called off in one ends after it.
- **An action that calls it and goes on with its answer** is not called off:
  it is given what the newest run gives.

Whose runs: one action's. Two of a component each have their own; the rows
of a `for` that call one action of the page share it, whatever they hand it
(put the action in a component for one each). A component taken out of the
page while its action runs is not a newer run: the run goes on to its end, as
any action's does.

An action that waits for nothing is over before it can be called again, and
`newest` on it is refused (`H190`: a fn that is light, or that says `main
fn`, runs on the page); so is the word on anything else (`H191`). A resource
needs no word: it is [always its newest answer](#resources).

If it is called faster than it can answer, nothing new is shown until the
calls pause. Where something should be shown on the way, show a quick sketch
before the wait (what is written there stays), or use an ordinary action.

## Workers

Heavy work leaves the main thread without the program saying so.

**Batteries** (`img`, `zip`, `crypto.argon2id`, `crypto.mlkem768`, `crypto.pow`, `scan`, `search`, `syntax`,
`font`, `vid`'s file work) always run in a worker ([internals.md](internals.md#batteries)).

**A fn of your own** runs in a worker when all of these hold
(`emit.rs`, `find_off`):

1. it uses only its parameters, its own variables, and other fns that do the
   same (no state, no derives);
2. it is heavy: it loops (`for`, `while`), recurses, or calls a fn that does;
3. it is called from an action, a handler, a task or a resource (somewhere
   that can wait). Called from a derive, a binding or another fn, it runs
   right there, on the main thread.

```mote
// docs: whole
state limit = 3000000
state found = 0

fn primes(limit: number): number
  let count = 0
  let n = 2
  while n < limit
    let prime = true
    let d = 2
    while d * d <= n
      if n % d == 0
        prime = false
        break
      d += 1
    if prime count += 1
    n += 1
  return count

main fn primesHere(limit: number) = primes(limit)

action count
  found = primes(limit)

action countHere
  found = primesHere(limit)

column gap=8 padding=16
  button "In a worker" press=count disabled=pending(count)
  button "On the page" press=countHere
  text `${found} primes`
```

- `main fn` keeps a fn on the main thread whatever it does.
- `off fn` sends it to a worker even if it is light. An `off fn` that reads
  state is refused (`H084`: pass it in as a parameter).
- An `off fn`, and what it calls, may call [`crypto`](data.md#keys-of-the-pages-own):
  hashes, key derivation, sealing and opening, key exchange, signatures, a
  proof of work, all in the worker. And [`search`](text.md#search): the
  battery runs in that worker, as it would on the back end. It then waits, as
  the call of it does anyway. So may it read and write files ([`fs`, `zip`,
  `tar`](data.md#large-files)): private files are read and written in place
  there, the fast way; the pickers and `fs.save` need a window (`H410`), and
  a reader or a writer stays where it was opened (`H410`: hand the `off fn`
  the file, a path or a file picked unread). Nothing else that waits is a
  worker's (`net`, `db`, a model, a `server fn`). A fn that says nothing is
  never sent away because it calls `crypto` or `fs`: say `off fn`. (Nor is a
  fn that is handed a `reader` or a `writer`: it runs where it is called.)

### Said once, for a file or a package

A program that is mostly computation called from the page in small pieces
would write `main fn` on nearly every fn. A file says it once instead, in a
line before its first fn:

```mote
// docs: whole
fns main

state found = 0

fn squares(upTo: number): number
  let total = 0
  for n in [1, 2, 3, 4]
    if n <= upTo total += n * n
  return total

off fn slowSquares(upTo: number) = squares(upTo) * 1

action count
  found = squares(3)
action countAway
  found = slowSquares(3)

button "Here" press=count
button "In a worker" press=countAway
text `${found}`
```

- `fns main`: every plain `fn` below it in this file stays on the page, as
  if each were written `main fn`.
- `fns off`: every plain `fn` below it that can leave (it uses only its
  parameters) runs in a worker when an action calls it, light or heavy. One
  that reads state stays on the page; that is no error here (it is for a fn
  written `off fn`: `H084`).
- `fns auto`: as the compiler finds, the rule above. It is what a file says
  to set aside its package's word.
- A fn's own word wins: `main fn` and `off fn` mean what they always did.
- The line comes before the file's first fn (`H102` otherwise), and speaks
  for that file only. `server fn`s, and fns only the back end reaches, are
  not touched by any of this: no page calls them, so none is in a worker.

A whole project or a package says it in `mote.toml`
([cli.md](cli.md#motetoml)):

```toml
fns = "main"            # the project's own files

[packages]
engine = "packages/engine"

[fns]
engine = "main"         # every file of that package
```

The order, strongest first: the fn's own word, its file's `fns` line, its
package's line under `[fns]` (or, for a file that is in no package, the
`fns` at the top of `mote.toml`), then the compiler's rule. `mote check
--perf` lists which fns run in a worker, and which would and are kept on
the page by one of these words.

How it works (`runtime/page/workers.mote`, parts `WK`, `WX`): the worker's
source is built from the fns' own text. Workers start when first needed, at
most four, and never more than the machine's cores less one. A call is
queued, sent to a free worker, and awaited.

### What is copied and what is moved

Arguments are copied to the worker. Bytes and pictures can be large, so they
are **moved** (handed over without a copy) when the page cannot use them
again (`compiler/src/moves.rs`):

- a value made right where it is passed: `img.png(img.decode(b)?)`;
- a `let` at its last use that only ever held what a battery, a worker fn,
  `net.bytes`, `fs.bytes`, `bytes(…)` or `bytes.new(n)` (and `bytes.of`,
  `bytes.join`) made. Bytes the page made itself may be written into first
  (`b[i] = v`, `b.set`, `b.fill`, `b.write`) and are still moved.

A parameter, state, or a name read again later is copied. Bytes in a result
are always moved back.

```mote
let im = img.decode(file)?
shot = img.jpeg(img.fit(im, 1600)?, 80)?        // both moved
```

`mote check --perf` lists the named values that are copied on every call,
and, after a page has run under `mote dev`, what each kind of worker call
cost. A fn whose messaging costs more than its work is named: `main fn`
keeps it on the page, and `fns main` every fn of its file
([cli.md](cli.md#mote-check)).

## Pitfalls

- **A resource follows only what it reads before its first wait.** State
  read after a wait inside a fn it calls does not re-run it. Read what
  matters first, or pass it as an argument.
- **A worker fn cannot read state.** A fn that reads state is simply not
  sent to a worker. If it should be, pass the state in.
- **A heavy fn in a derive or a binding runs on the main thread.** Call it
  from an action or a resource and keep the answer in state.
- **`pending` is true from the start for a resource**, and from the call for
  an action or a named task.
- **A `watch` is not a `derive`.** It does not run at the start, so it
  cannot be what first fills a value. Fill it in a `task`, and keep it
  current with the `watch`.
- **Timers written at the top level never stop.** Put a timer under an `if`
  to switch it.
- **A handler does not see its own writes on the page until it finishes.**
  Effects run in a microtask after the write. Do not measure the page
  (`el.height`) straight after writing state in the same handler; use
  `resized=` or `contents=` to hear the change.
- **Readers of a list re-run on any change in place.** That is by design;
  give `for` a `key` so rows are kept.

## In the source

| What | Where |
|---|---|
| Signals, effects, owners, `if`, `for` | `runtime/page/core.mote`: parts `core`, `D`, `U`, `R`, `I`, `L` |
| Actions that wait, resources | `runtime/page/actions.mote`: parts `AC`, `PD`, `RC` |
| `newest` | `runtime/page/actions.mote`: part `NW`; `runtime/page/workers.mote`: part `NWS`; `compiler/src/emit.rs`: `Gen::stops` |
| Timers | `runtime/page/events.mote`: part `EV` |
| `watch` | `runtime/page/events.mote`: part `WA`; `compiler/src/emit.rs`: `Gen::watch` |
| The worker pool, wasm loading | `runtime/page/workers.mote`: parts `WK`, `WX` |
| Which fns wait | `compiler/src/emit.rs`: `find_async` |
| Which fns go to workers | `compiler/src/emit.rs`: `find_off` |
| What is moved | `compiler/src/moves.rs` |
| Tracing writes to state | `compiler/src/emit.rs`: `Gen::write`, `Gen::srcs` |
| `--perf` | `compiler/src/perf.rs` |
| Recorded behaviour | `tests/pages/feed`, `tests/pages/crunch`, `tests/perf`, `tests/pages/rewind`, `tests/events2` (`watch`), `tests/newest` |
