# Collections

> Read when state holds rows by key. Make a keyed collection, write and read rows, render one row per key, keep a value a row at a time, and choose between a collection and a box of an array.

## Example

A collection holds rows by key, a box for each key a reader reads, and one
box for the order of the keys, so a write to one row reruns the readers of
that row, not the readers of the list. The chat's messages are a collection
keyed by id.

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

interface Message {
  readonly id: string;
  readonly roomId: string;
  readonly author: string;
  readonly text: string;
  readonly sentAt: number;
}

const $messages = Collection.make(app, {
  keyOf: (message: Message) => message.id,
  // A refetch builds new objects; a message with the same text is kept.
  equals: (previous, next) => previous.text === next.text,
  name: "messages",
});
```

A list component reads `keys` and hands each row its key, so a change to one
message rerenders that row alone. `onRowChange` keeps a count a row at a time.

```tsx
import { Box, Collection, Realm } from "@frondruntime/sorus";
import { useValue } from "@frondruntime/sorus-react";
import { memo } from "react";
import { $messages, type Message } from "./messages.ts";
import { app } from "./realm.ts";

// A message from the socket replaces the one under its id, or comes last.
const receiveMessage = (message: Message) => {
  Realm.update(app, (_read, write) => {
    write.upsert($messages, message, { at: "end" });
  });
};

// A refetch makes these the rows. A message that `equals` finds unchanged is
// kept: what read its row does not rerun.
const receiveHistory = (messages: ReadonlyArray<Message>) => {
  Realm.update(app, (_read, write) => {
    write.replaceAll($messages, messages);
  });
};

// Rerenders when a message is added, removed, or moved; never for a message's
// own change.
function MessageList() {
  const ids = useValue($messages.keys);
  return (
    <ul>
      {ids.map((id) => (
        <MessageRow key={id} id={id} />
      ))}
    </ul>
  );
}

// Rerenders when the message under its id changes.
const MessageRow = memo(function MessageRow({ id }: { readonly id: string }) {
  const message = useValue($messages.row(id));
  return message === undefined ? null : (
    <li>
      {message.author}: {message.text}
    </li>
  );
});

// How many messages the user sent, kept a row at a time. It rolls back with
// the write that changed the row, and first hears each row held, as added.
const $sentByMe = Box.make(app, 0, { name: "sentByMe" });

const stopSentByMe = Collection.onRowChange($messages, (change, read, write) => {
  const mine = (message: Message | undefined) => (message?.author === "me" ? 1 : 0);
  const added = mine(change.after) - mine(change.before);
  if (added !== 0) write($sentByMe, read($sentByMe) + added);
});
```

## Rules

- Write a collection with `write.upsert`, `write.remove`, and
  `write.replaceAll`, inside an update. A failed update puts back the keys
  and every row.
- A row is never `undefined`: `row(key)` and `read.row` return `undefined`
  for a missing key, so `write.upsert` and `write.replaceAll` reject it,
  schema collections included.
- A held key's row is compared with `equals`, `Object.is` without one. A
  refetch builds new objects, so without `equals` it reruns the readers of
  every row.
- A list reads `keys` and gives each row component `row(key)`; `rows` reruns
  its reader on any row or order change.
- Where nothing tracks, read through `read.row($messages, key)`:
  `read($messages.row(key))` there makes a computed value and a box the
  collection keeps until the key is removed.
- Adding or removing a key copies the key order, about 15 µs at 1,000 rows,
  so many new rows go in through one `write.replaceAll`, not an `upsert` each.
- A list written or read a row at a time is a collection. A box of an array
  is written whole and every write reruns every reader; one written whole on
  each refetch goes through `Collection.reconcile`
  ([Collection fields](../effect/collections.md)).

## Answers

| Call | Answers |
| --- | --- |
| `Collection.make(realm, { keyOf, equals?, name? })` | An empty collection. `name` labels `<name>.keys` and `<name>.rows` in `Source.inspect` and errors. |
| `$messages.row(key)` | A computed value of that row, or `undefined`. |
| `$messages.keys`, `$messages.rows` | Computed values of the keys, and of every row, in order. |
| `read.row($messages, key)` | That row, or `undefined`; tracked in a tracked place, no box made elsewhere. |
| `write.upsert($messages, row, { at? })` | Replaces the row under its key in place, or adds it first, or last with `{ at: "end" }`. |
| `write.remove($messages, key)` | Removes the row under `key`; a missing key changes nothing. |
| `write.replaceAll($messages, rows)` | Makes `rows` the rows, in order, keeping each unchanged one. A repeated key throws. |
| `Collection.onRowChange($messages, (change, read, write) => ...)` | Calls the listener inside the update of each write that adds, replaces, or removes a row; `change` holds `key`, `before`, `after`. First reports every held row as added. Returns the function that removes it. |

## Indexes and sets

A sorted order, the keys of each group, and a total per group are
[views](./views.md). A set of keys is a collection keyed by the key itself,
so `read.row` tracks one key and a change to another reruns nothing. A value
per key that no view keeps is a collection a listener writes a row at a
time; a plain `Map` it fills is not undone with a failed write, a `Map` of
boxes is.

## With Effect

A collection whose rows a schema checks is a `Model.collectionField`: see
[Collection fields](../effect/collections.md).

## See also

- [Updates](./updates.md): the update every write runs in.
- [Views](./views.md): sorted orders, groups, and totals kept a row at a time.
- [Hooks](../react/hooks.md): every way a component reads.
- [Equality and hashing](../effect/equality.md): what `equals` counts as unchanged.
