# Block model

The block model is the layer between a block’s UI and its workflow. It defines the block’s state, controls when the workflow can run, computes outputs for the UI to display, and provides metadata like the block’s title and navigation sections. All of this is declared in a single builder chain exported from `model/src/index.ts`.

The two main primitives are `DataModelBuilder`, which defines the shape of the block’s state and how it migrates between versions, and `BlockModelV3`, which wires that state to the workflow and the UI. Both are imported from `@platforma-sdk/model`. Both also take the block’s [block kind](/sdk-block-kinds/) — the versioned contract for the params a block can be created from.

## Core concepts

A block stores all its state in a single `data` object — user selections, configuration, UI preferences. Several things are derived from `data`:

- **`args(data)`** derives the arguments the workflow receives. When the derived args change, the block’s Run button becomes active, letting the user start a new execution. Fields in `data` that are not included in the args return value can change freely without activating the Run button.
- **`argsIssues({ args, data })`** (optional) tells whether the block may run with those args. It returns a list of issues; an error keeps the Run button disabled, a warning does not.
- **`prerunArgs(data)`** (optional) derives separate arguments for the staging (pre-run) phase, allowing lightweight preview computations before a full run.
- **`prerunArgsIssues({ prerunArgs, data })`** (optional) tells whether the block may be staged with those prerun args, the way `argsIssues` does for Run.
- **`templateParams(data)`** projects the block’s state back to its kind’s params, so a project holding this block can be exported as a project template. Required — `done()` throws without it.
- **Outputs, title, sections, tags** are also computed from `data` and workflow results, providing the UI with display values and block metadata.

## Defining the data shape

`DataModelBuilder` defines the block’s data type, assigns it a version, and provides default values for new blocks.

```typescript
import { BlockModelV3, DataModelBuilder } from '@platforma-sdk/model';
import type { PlRef } from '@platforma-sdk/model';
import { kind } from '@platforma-open/<org>.<block>.kind';


type BlockData = {
  inputRef?: PlRef;
  species: string;
  chains: string[];
};


const dataModel = new DataModelBuilder({ kind })
  .from<BlockData>('v1')
  .init(({ params }) => ({
    species: params?.species ?? 'human',
    chains: params?.chains ?? ['TRB'],
  }));
```

- `from<T>(version)` — sets the data type and a version string
- `init(fn)` — factory for default values, used for new blocks and as a fallback when migrations fail
- `init(fn)` receives `{ params }` — the params a project template or a test supplied, `undefined` when the block was created through the UI. Every kind-declared field therefore needs a fallback default.

This is enough for a first release. When the data shape needs to change, add migrations.

## Data migrations

As the block above evolves, suppose we need to add a `preset` field. Rather than breaking existing saved blocks, we add a migration step. The original type becomes `BlockDataV1`, the new type becomes `BlockDataV2`, and a `BlockData` alias always points to the latest version:

```typescript
type BlockDataV1 = {
  inputRef?: PlRef;
  species: string;
  chains: string[];
};


type BlockDataV2 = {
  inputRef?: PlRef;
  species: string;
  chains: string[];
  preset: string;
};


type BlockData = BlockDataV2;


const dataModel = new DataModelBuilder({ kind })
  .from<BlockDataV1>('v1')
  .migrate<BlockDataV2>('v2', (v1) => ({ ...v1, preset: 'default' }))
  .init(() => ({
    species: 'human',
    chains: ['TRB'],
    preset: 'default',
  }));
```

When a block saved at `v1` is opened, the migration runs and produces `v2` data. New blocks start from `init()` directly.

Key points:

- Version keys are arbitrary strings
- Each step is typed: the migration function receives the previous version’s type and must return the next
- Migrations chain — a block saved at `v1` runs through all subsequent steps to reach the latest version
- If a migration throws, the block resets to `init()` defaults with a warning (the original data is preserved until the user commits)
- `new DataModelBuilder({ kind })` takes the block kind whatever the shape of the chain — with migrations, with `recover()`, or with neither

### Handling unforeseen versions

In rare cases — a development branch that wrote an unknown version, or data corruption — the block may encounter a version string not in its migration chain. `recover()` provides a safety net:

```typescript
const dataModel = new DataModelBuilder({ kind })
  .from<BlockDataV1>('v1')
  .recover((unknownData) => ({
    species: unknownData?.species ?? 'human',
    chains: Array.isArray(unknownData?.chains) ? unknownData.chains : ['TRB'],
  }))
  .migrate<BlockDataV2>('v2', (v1) => ({ ...v1, preset: 'default' }))
  .init(() => ({ species: 'human', chains: ['TRB'], preset: 'default' }));
```

`recover()` receives the raw data and returns a value matching the type at that position in the chain. Here it returns `BlockDataV1`, and the subsequent migration to `v2` still applies. Use it as a defensive measure, not as a primary migration path.

> **Note:**
>
> For blocks migrating from the V1/V2 block model, use `upgradeLegacy()`. See the [migration guide](/sdk-migrating-to-v3/).

## Building the block model

`BlockModelV3.create({ dataModel, kind })` starts a builder chain that connects data to the workflow and UI.

```typescript
export const platforma = BlockModelV3.create({ dataModel, kind })
  .args((data) => ({
    inputRef: data.inputRef,
    species: data.species,
    chains: data.chains,
    preset: data.preset,
  }))
  .argsIssues(({ args }) =>
    args.inputRef === undefined ? [{ severity: 'error', message: 'Input is required' }] : [],
  )
  .templateParams((data) => ({
    inputRef: data.inputRef,
    species: data.species,
    chains: data.chains,
    preset: data.preset,
  }))
  .output('inputOptions', (ctx) =>
    ctx.resultPool.getOptions((spec) => isPColumnSpec(spec) && spec.name === 'pl7.app/vdj/sequence')
  )
  .sections(() => [{ type: 'link', href: '/', label: 'Main' }])
  .title(() => 'My Analysis Block')
  .done();
```

### args(fn)

**Required.** Derives workflow arguments from block data. When the return value changes, the Run button activates.

```typescript
.args((data) => ({
  inputRef: data.inputRef,
  species: data.species,
  chains: data.chains,
  preset: data.preset,
}))
```

Build the args even when the data is incomplete, and say whether the block may run in [`argsIssues()`](#argsissuesfn). Args that exist let the app see which columns the block references before it is ready to run, so the block gets its [links to other blocks](/sdk-p-columns-model/#links-to-other-blocks) while it is still being configured.

Throwing from `args()`, or returning `undefined`, still works: it means the block has no args at all, so the Run button stays disabled and the block has no links from its current args.

Fields excluded from the return value (like a graph scale preference) can change freely in `data` without activating the Run button.

### argsIssues(fn)

Optional. Tells whether the block may run with the args `args()` derived. It receives those args and the data they were built from, and returns a list of `ArgsIssue`s, `{ severity: 'error' | 'warning'; message: string }` (the type is exported from `@platforma-sdk/model`):

```typescript
.argsIssues(({ args, data }) => {
  const issues: ArgsIssue[] = [];
  if (args.inputRef === undefined) issues.push({ severity: 'error', message: 'Input is required' });
  if (data.chains.length === 0) issues.push({ severity: 'warning', message: 'No chains selected' });
  return issues;
})
```

- An `error` keeps the Run button disabled; a `warning` does not. An empty list means the block may run.
- The workflow only runs with args that have no errors, so it can rely on what `argsIssues` checks. This holds in every desktop app the block opens in: the SDK gives every block the feature flag `requiresArgsIssues`, and a desktop app that does not know the flag refuses to add, update or run the block.
- A throw from `argsIssues` counts as one error with the thrown message.
- It is not called when `args()` throws.
- It must be set after `.args()` — the builder throws otherwise — and setting `.args()` again drops it.

Without `argsIssues`, any args `args()` returns are runnable.

### prerunArgs(fn)

Optional. Defines separate arguments for the staging (pre-run) phase. If not defined, falls back to `args()` — but only when `argsIssues()` finds no errors; otherwise the block is skipped during staging. A block’s own `prerunArgs()` is not checked by `argsIssues()`; check it with [`prerunArgsIssues()`](#prerunargsissuesfn).

```typescript
.prerunArgs((data) => ({
  species: data.species,
  chains: data.chains,
}))
```

Pre-run results are available through `ctx.prerun` in output functions. If `prerunArgs()` throws, the block is skipped during staging.

### prerunArgsIssues(fn)

Optional. Tells whether the block may be staged with the args `prerunArgs()` derived. It receives those prerun args and the data they were built from, and returns a list of `ArgsIssue`s:

```typescript
.prerunArgs((data) => ({ species: data.species }))
.prerunArgsIssues(({ prerunArgs }) =>
  prerunArgs.species === undefined ? [{ severity: 'error', message: 'Species is required' }] : [],
)
```

- An `error` skips the block during staging; a `warning` does not.
- A throw from `prerunArgsIssues` counts as one error with the thrown message.
- It is not called when `prerunArgs()` throws or returns `undefined`; the block is skipped during staging anyway.
- It must be set after `.prerunArgs()` — the builder throws otherwise — and setting `.prerunArgs()` again drops it.

### templateParams(fn)

**Required.** Projects the block’s state back to its kind’s `BlockParams` — the inverse of `init`. It receives the same already-resolved `data` that `args()` gets. Its return type is the kind’s params, so a projection that drifts from the init contract fails to compile.

```typescript
.templateParams((data) => ({
  inputRef: data.inputRef,
  species: data.species,
  chains: data.chains,
  preset: data.preset,
}))
```

The SDK converts live references to their file form on the way out, so a block never handles the project-template representation, and never sees an unresolved reference on the way in.

View-only state — table layout, graph state, plot configuration — is deliberately left out. The projection describes the recipe, not what the user is looking at.

A block whose state genuinely cannot be reduced to params returns `{}` and says so explicitly. There is no way to decline.

Without it, `done()` throws:

```plaintext
templateParams() not set. Every block must project its state back to its kind's params…
```

See [block kinds](/sdk-block-kinds/) for the params contract this projects into, and [project templates](/sdk-project-templates/) for the file the projection ends up in.

### output(key, fn)

Defines named values computed from the block’s render context, accessible in the UI as `app.model.outputs.<key>`.

```typescript
.output('inputOptions', (ctx) =>
  ctx.resultPool.getOptions((spec) => isPColumnSpec(spec) && spec.name === 'pl7.app/vdj/sequence')
)
.output('resultTable', (ctx) => {
  const pCols = ctx.outputs?.resolve('results')?.getPColumns();
  if (!pCols) return undefined;
  return createPFrameForGraphs(ctx, pCols);
})
```

The render context provides:

| Property         | Type                      | Description                                                           |
| ---------------- | ------------------------- | --------------------------------------------------------------------- |
| `ctx.data`       | `Data`                    | Current block data                                                    |
| `ctx.args`       | `Args \| undefined`       | Derived args; `undefined` when `args()` throws or returns `undefined` |
| `ctx.activeArgs` | `Args \| undefined`       | Args from the currently running or last completed execution           |
| `ctx.outputs`    | `ResultPool \| undefined` | Workflow outputs from the main execution                              |
| `ctx.prerun`     | `ResultPool \| undefined` | Workflow outputs from the pre-run phase                               |
| `ctx.resultPool` | `ResultPool`              | Full result pool for querying upstream blocks                         |

`ctx.args` reflects the current derivation — it’s `undefined` when the args function throws or returns `undefined`. With `argsIssues`, `ctx.args` is set while the block is still incomplete, even when the block cannot run, so outputs must not assume a field the run check requires is present. `ctx.activeArgs` reflects what the workflow is actually running with (or last ran with), which may differ from `ctx.args` if the user has changed data since the last run.

### sections, title, subtitle, tags

Configure block appearance in the Platforma UI. All accept a function receiving the render context.

```typescript
.sections((ctx) => [
  { type: 'link', href: '/', label: 'Main', badge: ctx.args?.badgeText },
  { type: 'link', href: '/results', label: 'Results' },
])
.title(() => 'Clonotype Clustering')
.subtitle((ctx) => ctx.args?.customLabel || 'Default label')
.tags((ctx) => ['analysis', ...(ctx.args?.tagList || [])])
```

Since `ctx.args` can be `undefined`, use optional chaining when accessing args properties.

### done()

Closes the builder and returns the finalized model. Export it for use in the UI layer. It throws if `args()` was never set, and it throws if `templateParams()` was never set.

```typescript
export const platforma = BlockModelV3.create({ dataModel, kind })
  .args(...)
  .templateParams(...)
  .done();


export type BlockOutputs = InferOutputsType<typeof platforma>;
export type Href = InferHrefType<typeof platforma>;
```

## UI integration

### App setup

*ui/src/app.ts*

```typescript
import { defineApp } from '@platforma-sdk/ui-vue';
import { platforma } from '@myorg/my-block.model';
import MainPage from './MainPage.vue';


export const sdkPlugin = defineApp(platforma, () => ({
  routes: {
    '/': () => MainPage,
  },
}));


export const useApp = sdkPlugin.useApp;
```

### Using data and outputs in components

*ui/src/MainPage.vue*

```html
<script setup lang="ts">
import { useApp } from './app';
const app = useApp();
</script>


<template>
  <PlBlockPage>
    <PlTextField v-model="app.model.data.species" label="Species" />
    <PlDropdownRef
      v-model="app.model.data.inputRef"
      :options="app.model.outputs.inputOptions"
      label="Input"
    />
    <pre>{{ app.model.outputs.resultTable }}</pre>
  </PlBlockPage>
</template>
```

- **`app.model.data`** — all block state. Directly mutable and reactive; assigning a field triggers debounced persistence and args re-derivation.
- **`app.model.outputs`** — computed values from the model’s `.output()` definitions.

Source: https://docs.platforma.bio/sdk-model/
