Svelte

Contents

Svelte#

A struct the TypeScript generator emits is an interface, and a decoded value a plain object. Svelte 5’s $state makes a plain object reactive, but not a class instance inside it, such as the ModelMap a map field holds. Set svelte to also generate a .svelte.ts module of classes whose fields are $state:

[tool.model.typescript]
out = "src/lib/catalog.ts"
svelte = "src/lib/catalog.svelte.ts"

The Svelte module imports the TypeScript one, for its schemas and the Shape interfaces, so out is always generated with it. It needs svelte 5, and imports ModelMap from @omniblack/model-runtime/svelte (see the API reference).

Structs#

Each struct is a class of its name, with a $state property per field:

export class Story {
    title = $state<string>() as string;
    tags = $state<Array<string>>([]);
    byline = $state<Author | null>(null);

    constructor(shape?: base.StoryShape);
    static blank(): Story;
    static parse(input: unknown): Story;
    toJSON(): object;
}
  • Story.parse(input) decodes and validates input with the TypeScript module’s StorySchema, then builds a Story from it, throwing the same ValiError the schema does.

  • new Story(shape) builds one from a value that schema already decoded.

  • Story.blank() builds one not yet filled in, for a form to edit before it is valid: each list and map field empty, each other optional field null, and each other required field unset. new Story() does the same.

  • toJSON() gives the fields, since JSON.stringify cannot see $state ones. A field holding null is left out, as the TypeScript module leaves out a missing one, so a class writes what its schema decodes.

Every value inside is converted too: a struct field holds that struct’s class, a union its variant’s class, each list item and map value is converted in turn, and a map is the reactive ModelMap. A list is $state’s own deep proxy. So setting a field, and changing a list or map, notifies at any depth:

import { Story } from "$lib/catalog.svelte";

const story = Story.parse(data);
const count = $derived(story.tags.length);

story.tags.push("new"); // count is now one more
story.title = "Retitled"; // and anything reading story.title re-runs

An optional field starts null, and a list or map field empty. A required field has no value until the constructor sets it, which it does unless the instance is blank.

Unions#

Each variant is a class named as the TypeScript module’s variant interface, with its tag as a readonly property. An inlined struct variant extends its struct’s class; any other holds its value as a $state value. The union’s name is the type of its variants, and a constant with:

  • from(shape), the variant class holding a value the union’s schema decoded;

  • parse(input), which decodes input with that schema first.

Enums and routes are not in the Svelte module: import them from the TypeScript one.