# Classes

> Read when modeling domain data. Declare a Model.Schema with box fields, derive values on it, write from its methods, decode it from the wire, and hand it the caller's own values, in a decode or an Effect program.

The Effect pages are for applications that already use Effect: see
[Schema-checked boxes](./boxes.md).

## Example

A model is a `Model.Schema`: a `Schema.Class` whose instances hold a realm
that its wire form never carries. A `$` field is a `Model.boxField` or a
[`Model.collectionField`](./collections.md), and its wire key drops the `$`;
any other field is plain, `readonly` data. A message's text is a box field
because an edit writes it. The sample decodes, makes, encodes, and restores a
`Message`.

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

class Message extends Model.Schema<Message>("Message")({
  id: Schema.String,
  roomId: Schema.String,
  author: Schema.String,
  // A box field: an edit writes it, and the wire key is "text".
  $text: Model.boxField(Schema.String.check(Schema.isMaxLength(2000))),
  sentAt: Schema.Number,
}) {
  readonly $preview = Computed.make(this.realm, (read) => `${this.author}: ${read(this.$text)}`);

  edit(text: string): void {
    Realm.update(this.realm, (_read, write) => {
      write(this.$text, text);
    });
  }
}

// Throws a DecodeError, holding the SchemaError, when the input does not fit.
const hello = Model.decode(
  app,
  Message,
)({ id: "m1", roomId: "general", author: "ada", text: "hi", sentAt: 1 });

hello.edit("hello");
const preview = Realm.untracked(app, (read) => read(hello.$preview)); // "ada: hello"

// From values in hand: $text's starting value under "text", checked.
const draft = Message.make({
  id: "m2",
  roomId: "general",
  author: "me",
  text: "on my way",
  sentAt: 2,
  realm: app,
});

// The wire fields alone, $text's current value under "text":
// { id: "m1", roomId: "general", author: "ada", text: "hello", sentAt: 1 }.
const wire = Realm.untracked(app, () => Schema.encodeSync(Message)(hello));

// The server's copy of an edit, restored into the held message: $text takes
// the new text, and a plain field that differs throws.
const applyEdit = (json: unknown): void => {
  Model.restore(app, Message)(hello, json);
};
```

A `Model.context` field holds the service of an Effect tag, such as a
formatter, and is never on the wire.

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

interface TimeFormat {
  readonly format: (at: number) => string;
}

// An Effect service: the field requires it, and the caller provides it.
class Times extends Context.Service<Times, TimeFormat>()("chat/Times") {}

// A notice from the server, shown with its time.
class Notice extends Model.Schema<Notice>("Notice")({
  $text: Model.boxField(Schema.String),
  sentAt: Schema.Number,
  times: Model.context(Times), // the caller's own value, never on the wire
}) {
  readonly $line = Computed.make(
    this.realm,
    (read) => `${this.times.format(this.sentAt)} ${read(this.$text)}`,
  );
}

const clock: TimeFormat = { format: (at) => new Date(at).toISOString().slice(11, 16) };
const notice = Model.decode(
  app,
  Notice,
  Context.make(Times, clock),
)({ text: "Maintenance at noon", sentAt: 0 });
```

## Rules

- Build an instance with `Model.decode` from wire data or `Message.make` from
  values in hand: both put its boxes in the given realm, which field
  initializers read as `this.realm`.
- A plain field is never written after decode: it is no box, so no `read`
  tracks it and a write reruns no reader. A value that changes is a `$` field.
- Derive a value with `Computed.make(this.realm, ...)` in a `$` property of
  the class body; a getter, or a method that takes `read`, is not cached.
- A context field's tag is a requirement of the decode: pass a `Context`
  holding it to `Model.decode`, or provide it in the Effect program.
- Encoding gives the wire fields alone and reads each `$` field as `read`
  does, so in a computed value it tracks and the value recomputes on a field
  write.

## Answers

| Call | Answers |
| --- | --- |
| `Model.Schema<Self>(identifier)(fields)` | A class whose `$` fields are boxes or collections, checked by its schema. It seals `extend`, `mapFields`, `makeOption`, and `makeEffect`. |
| `Model.boxField(schema)` | A box field of `schema`. |
| `Model.decode(realm, schema, context?)(input)` | The decoded value, or throws `DecodeError` whose `cause` is the `Schema.SchemaError`. |
| `Model.context(tag)` | A field holding the service of `tag`, never on the wire. |
| `Message.make({ ...values, realm })` | An instance from values in hand, each `$` field's value under its wire key, checked even under `{ disableChecks: true }`. |
| `Model.restore(realm, schema, context?)(held, input)` | Decodes `input` and restores it into `held` in place. Throws `DecodeError` as `Model.decode` does, and `sorus/restore-plain-field` when a plain field differs. |

## With Effect

`Schema.decodeUnknownEffect(Message)` decodes in a program, with `RealmService`
and each context tag as requirements: see [Programs](./programs.md).

## See also

- [Schema-checked boxes](./boxes.md): what a `$` field checks on a write.
- [Collection fields](./collections.md): rows by key, as a `$` field.
- [Snapshots](../state/snapshots.md): `read.snapshot` of a model, unencoded.
- [Error messages](../reference/errors.md): every message a model throws.
- [Hooks](../react/hooks.md): reading a model in a component.
