# Boxes and computed

> Read when declaring state. Make a box, derive a cached computed value, make one per argument, stand for outside state with an atom, and read a value outside an update.

## Example

A box is observable state, named with a `$` prefix. A computed value is
derived from what its function reads and cached until a source it read
changes. `$canSend` reads two boxes declared in [Start](../start/index.md).

```ts
import { Computed } from "@frondruntime/sorus";
import { app } from "./realm.ts";

const $canSend = Computed.make(
  app,
  (read) => read($composer).text.trim() !== "" && read($connection) === "open",
  { name: "canSend" },
);
```

`$scrollTop` replaces the comparison. `lastMessageIn(roomId)` is a computed
value per room, read from a [collection](./collections.md)'s `rows`.

```ts
import { Box, Computed, Source } from "@frondruntime/sorus";
import { $messages } from "./messages.ts";
import { app } from "./realm.ts";
import { $canSend, $roomId } from "./state.ts";

// A scroll within a pixel of the current position notifies nobody.
const $scrollTop = Box.make(app, 0, {
  name: "scrollTop",
  equals: (previous, next) => Math.abs(previous - next) < 1,
});

// One computed value per room id, shared while something observes it.
const lastMessageIn = Computed.fn(
  app,
  (read, roomId: string) =>
    read($messages.rows)
      .filter((message) => message.roomId === roomId)
      .at(-1),
  { name: "lastMessageIn" },
);

const $lastInRoom = Computed.make(app, (read) => read(lastMessageIn(read($roomId))));

// An event handler reads one value once, with nothing tracked.
const logRoom = () => console.info("room", Source.peek($roomId));

Source.inspect($canSend).name; // "canSend"
```

## Rules

- A box holds plain data and is written whole. A change in place reaches no
  watcher, so finer grain is more boxes or a [collection](./collections.md).
- A computed value only reads. A write, watch, autorun, `Source.observe`, or
  release inside it throws, as does its `equals`, because it must stay a
  function of its sources.
- A computed value that throws keeps the error and throws it to each read
  until a source it read changes.
- Observed (by a watch, an autorun, a mounted `useValue`, `Source.observe`, or
  another observed computed value), a computed value stays linked and a write
  marks it stale. Unobserved, it holds no links and a read checks its sources.
- `Computed.fn` compares arguments by identity, one per position, and drops an
  entry nothing observes, so the next call makes a new one.

## Answers

| Call | Answers |
| --- | --- |
| `Box.make(realm, initial, { name?, equals? })` | A box. A write equal to the current value notifies nobody. `equals` defaults to `Object.is`, so a new array counts as a change. |
| `Computed.make(realm, (read) => ..., { name?, equals? })` | A computed value. |
| `Computed.fn(realm, (read, ...args) => ..., options?)` | A function from arguments to a computed value, shared while observed. |
| `Atom.make(realm)` | An atom, state kept outside Sorus. `read($atom)` returns `undefined` and subscribes. |
| `write.changed($atom)` | Reruns what observed the atom, inside an update. An atom nothing observes counts as changed on every check. |
| `class X extends Model.Class` | A model without a schema: `new X(realm)`, field initializers read `this.realm`, writes go through methods that call `Realm.update`. With Effect: [Classes](../effect/classes.md). |
| `read($x)` | The value, and a subscription where reads are tracked ([Reacting](./reacting.md)). |
| `Read` | The type of `read`: `(read: Read) => ...`. |
| `Source.peek($x)` | The value, once, outside every place that reads, with nothing tracked. |
| `{ name }` | Labels a value for tools: `Source.inspect` reports it, and a computed value's errors name it. |

## See also

- [Updates](./updates.md): writing boxes.
- [Collections](./collections.md): rows by key, tracked per row.
- [Lifecycles](./lifecycles.md): what observing a value starts.
- [Schema-checked boxes](../effect/boxes.md): a box that checks every write.
