# Collection fields

> Read when a model holds rows by key, or when a schema-checked box of an array is refetched whole. Declare a Model.collectionField, decode it from a plain array, and reconcile a refetch.

## Example

A `Model.collectionField` is the core's [collection](../state/collections.md)
as a field of a `Model.Schema`, each row checked against the row schema and a
plain array on the wire. A room's thread holds the `Message` of
[Classes](./classes.md).

```ts
import { Computed, Model, Realm } from "@frondruntime/sorus-effect";
import { Schema } from "effect";
import { Message } from "./classes.ts";
import { app } from "./realm.ts";

class Thread extends Model.Schema<Thread>("Thread")({
  roomId: Schema.String,
  $messages: Model.collectionField(Message, { keyOf: (message) => message.id }),
}) {
  // Reads each message's $text: an edit to one reruns this.
  readonly $mentionsMe = Computed.make(
    this.realm,
    (read) =>
      read(this.$messages.rows).filter((message) => read(message.$text).includes("@me")).length,
    { name: "Thread.mentionsMe" },
  );

  add(message: Message): void {
    Realm.update(this.realm, (_read, write) => {
      write.upsert(this.$messages, message, { at: "end" });
    });
  }

  remove(id: string): void {
    Realm.update(this.realm, (_read, write) => {
      write.remove(this.$messages, id);
    });
  }
}

// On the wire, a collection is a plain array.
const thread = Model.decode(
  app,
  Thread,
)({
  roomId: "general",
  messages: [
    { id: "t1", roomId: "general", author: "ada", text: "hi @me", sentAt: 1 },
    { id: "t2", roomId: "general", author: "grace", text: "hello", sentAt: 2 },
  ],
});

const mentions = Realm.untracked(app, (read) => read(thread.$mentionsMe)); // 1
```

A `Box.schema` of an array refetched whole goes through `Collection.reconcile`,
so an unchanged item keeps its object.

```ts
import { Box, Collection, Computed, Model, Realm } from "@frondruntime/sorus-effect";
import { Schema } from "effect";
import { app } from "./realm.ts";

const Typist = Schema.Struct({ userId: Schema.String, since: Schema.Number });
const sameTypist = Schema.toEquivalence(Typist);
const $typing = Box.schema(app, Schema.Array(Typist), [], { name: "typing" });
const typistOf = Computed.fn(app, (read, userId: string) =>
  read($typing).find((typist) => typist.userId === userId),
);

const receiveTyping = (json: unknown) => {
  const next = Model.decode(app, Schema.Array(Typist))(json);
  Realm.update(app, (read, write) => {
    // An unchanged typist keeps its previous object, so typistOf for it
    // returns the same value and its readers do not rerun.
    write(
      $typing,
      Collection.reconcile(read($typing), next, {
        keyOf: (typist) => typist.userId,
        equals: sameTypist,
      }),
    );
  });
};
```

## Rules

- A `Model.collectionField` checks each row on `Model.decode`, `write.upsert`,
  and `write.replaceAll`; a rejected row throws and the update is undone.
- A repeated key fails `Model.decode` and `Collection.reconcile`, so no row
  is changed.
- A model row with a `$` field is a new instance after every `Model.decode`;
  `write.replaceAll`, `write.upsert`, and `Collection.reconcile` merge it into
  the held row, so only the readers of a changed box rerun
  ([Equality and hashing](./equality.md)).
- `Collection.reconcile` takes arrays: one refetched model is a list of one on
  each side, under any key.

## Answers

| Call | Answers |
| --- | --- |
| `Model.collectionField(schema, { keyOf, name? })` | A field of rows by key, each checked against `schema`. `name` names every instance's collection, as `Collection.make`'s does. |
| `Collection.reconcile(previous, next, { keyOf, equals? })` | `next` in its own order, with the previous object for each item whose key is held and which is equal; `previous` itself when nothing changed. `equals` defaults as [Equality and hashing](./equality.md) lists. |

## See also

- [Collections](../state/collections.md): reading and writing a collection, and a box of an array.
- [Classes](./classes.md): the model a collection field lives on.
- [Equality and hashing](./equality.md): what a row or item compares with, and when a merge runs.
- [Schema-checked boxes](./boxes.md): `Collection.schema` and `Box.schema`.
- [Live data](../guides/live-data.md): a refetch and a feed written into a collection field.
