# Views

> Read when a list sorts or filters a collection, or a value follows a collection by group. Make a sorted, filtered order, the keys of each group, or a count and total per group, kept a row at a time.

## Example

A view is kept up to date a row at a time: a write to one of 10,000 rows
moves that row's key, and nothing sorts or sums the other 9,999.
`View.ordered` keeps keys sorted and filtered, `View.grouped` the keys of
each group, and `View.totals` a count and total per group.

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

const $newestFirst = Box.make(app, false, { name: "newestFirst" });

// The open room's messages, oldest first. A message written to the room moves
// one key; nothing sorts the room again.
const $timeline = View.ordered($messages, {
  // Reads $newestFirst: writing it sorts every message again.
  compare: (read) => {
    const sign = read($newestFirst) ? -1 : 1;
    return (left, right) => sign * (left.sentAt - right.sentAt);
  },
  // Reads $roomId: opening another room filters the sorted messages again.
  filter: (read) => {
    const roomId = read($roomId);
    return (message) => message.roomId === roomId;
  },
  name: "timeline",
});

// The keys the scrolled list shows: ranks 40 to 60 of the open room. A write
// that leaves those keys in place reruns nothing that reads them.
const $visible = $timeline.range(40, 60);

// "100 of 1,000 messages": the open room's messages of all the chat's
const $shown = Computed.make(
  app,
  (read) => `${read($timeline.size)} of ${read($timeline.totalSize)} messages`,
);
```

`compare` and `filter` are factories whose reads are tracked, and `range`
gives the keys at ranks for a list that scrolls. `View.totals` keeps the
unread messages, with arithmetic the caller gives.

```ts
import { Collection, View } from "@frondruntime/sorus";
import { app } from "./realm.ts";

// The messages not yet read: a message from someone else joins on arrival, and
// leaves when its room is read.
interface Unread {
  readonly id: string;
  readonly roomId: string;
  readonly mentionsMe: boolean;
}

const $unreadMessages = Collection.make(app, {
  keyOf: (unread: Unread) => unread.id,
  name: "unreadMessages",
});

// Per room, the count of unread messages and, as the total, how many mention
// the user. Whole numbers add and subtract exactly, so the total never drifts.
const $unread = View.totals($unreadMessages, {
  project: (unread) => ({ group: unread.roomId, value: unread.mentionsMe ? 1 : 0 }),
  arithmetic: {
    zero: 0,
    add: (total, mentions) => total + mentions,
    subtract: (total, mentions) => total - mentions,
  },
  name: "unread",
});

// { count: 3, total: 1 }: three unread, one of them mentions the user
const $unreadInSupport = $unread.group("support");
```

## Rules

- Keep what `compare` and `filter` read to boxes that rarely change: a write to one `compare` reads sorts every row again, `O(n log n)`; one only `filter` reads filters again, `O(n)`; a row write is `O(log n)`.
- The comparator and predicate `compare` and `filter` return, `groupOf`, and `project` read no observable, answer the same for a row every time, and see rows replaced, never mutated: a changed answer throws `sorus/view-out-of-step` or drifts a total silently.
- `View.totals` needs exact arithmetic, because `add` and `subtract` must undo each other: floating-point amounts drift, so keep cents as integers or use bigints.
- `View.grouped` copies a group's keys when one joins or leaves: a group of 10,000 keys copies 50 million keys while it fills. It fits many small groups, such as orders per customer.
- Sort, group, and total by plain fields: a view sees rows replaced, never a write to a `Model.boxField` inside a row, so a sum over a box field is a `Computed.make`.

## Answers

| Call | Answers |
| --- | --- |
| `View.ordered($items, { compare, filter?, name? })` | A view of `$items`'s keys sorted by `compare(read)`'s comparator, kept by `filter(read)`'s predicate, or every key when it returns `undefined`. |
| `view.size`, `view.totalSize` | Computed values of the count of keys that pass the filter, and of every key. |
| `view.keys` | A computed value of every key that passes the filter, in order; it reruns on any change to that order. |
| `view.range(start, end)` | A computed value of the keys at ranks `start` up to, not including, `end`, clamped to `size`. |
| `View.grouped($items, { groupOf, name? })` | A view of `$items`'s keys by `groupOf(row, key)`, or out of every group for `undefined`. |
| `view.group(group)` | A computed value of the group's keys, in the order they joined; empty for a group with none. |
| `view.groups` | A computed value of the groups that hold a key. |
| `View.totals($items, { project, arithmetic, name? })` | A view of a count and total per group: `project(row, key)` gives `{ group, value }`, or `undefined` to leave the row out. `arithmetic` is `{ zero, add, subtract, equals? }`. |
| `view.group(group)` | A computed value of `{ count, total }` for the group. |
| `View.dispose(view)` | Stops the view where its owner ends; a second call does nothing, and a read through it throws `sorus/view-disposed`. |
| `View.status(view)` | `"open"`, or `"disposed"` after `View.dispose` or `Realm.dispose`. |

`name` names the view in errors and in `testRealm`, and its computed values
for `Source.inspect`, such as `<name>.size`.

## With Effect

`View.orderedScoped`, `View.groupedScoped`, and `View.totalsScoped` from
`sorus-effect` take the arguments of the plain calls and dispose the view
when the scope closes.

## See also

- [Collections](./collections.md): `Collection.onRowChange`, which every view listens with.
- [Stages](./stages.md): reading a view over staged rows.
- [Realms](./realms.md): `Realm.dispose`.
- [Error messages](../reference/errors.md): the view errors.
