# Fields and widgets

> How each Zod type in your schema becomes a control in the studio, and how hints, helpers and custom widgets change it.

Every field in a collection's schema becomes a control in the studio's editor. The type decides what's stored and how it's checked. A hint can choose a different control for the same type. Content files always hold plain values, so they stay readable without Vesper.

## From type to control

| In your schema | In the studio |
|---|---|
| `z.string()` | A one-line text field. `z.email()` and `z.url()` get email and web address fields. |
| `z.number()` | A number field that follows `min()`, `max()`, `int()` and `multipleOf()` |
| `z.boolean()` | A switch |
| `z.date()` or `z.coerce.date()` | A date picker. The file keeps a calendar date, such as `2026-10-17`. |
| `z.enum([...])` | Radio buttons for four options or fewer, otherwise a select |
| `z.array(z.string())` | A tag list: type a value and press Enter |
| `z.array(z.enum([...]))` | A multi-select |
| `z.object({ ... })` | A group of fields under its own heading. At the top of the form it's a section, set off by a line. |
| `z.array(z.object({ ... }))` | A list of items, each a row named by its content that opens in place. Drag a row by its handle to move it, open or closed. Each row's "…" menu moves, duplicates and removes it; Alt+↑ and Alt+↓ on a row move it too. A list of images has the same rows, with a thumbnail. |
| `z.discriminatedUnion('type', [ ... ])` | A choice of kind, then that kind's fields. See [Blocks](#blocks). |
| `z.array(z.discriminatedUnion('type', [ ... ]))` | Blocks: a list whose items are different kinds. See [Blocks](#blocks). |
| `reference('authors')` | A searchable list of that collection's entries. The file stores the entry's ID. |
| `z.array(reference('posts'))` | An ordered list of entries, with Move up, Move down and Remove |
| `image()` | An image picker. See [Images](/docs/content/images/). |

A few more rules:

- `.optional()` and `.default()` make a field optional, and a default fills in new entries.
- A list with `.max()` stops adding at that many, and says so under its Add button. Most fields are required, so the studio marks the ones that aren't: "(optional)" after the label.
- A union of string literals counts as an enum.
- `.refine()` keeps the field's control. The refinement still runs when the entry is saved.
- Fields appear in schema order. The first text field called `title`, `name`, `heading` or `label` becomes the page's heading in the editor.

Every save is checked against your schema. A problem shows under its field and in a summary at the top of the form.

## Raw YAML fields

When Vesper has no control for a type, it shows the value as a small YAML text box marked "Edited as YAML", instead of hiding it or guessing. That happens for:

- unions of different types, such as `z.union([z.string(), z.object({ ... })])`. A union of objects told apart by one key gets a control when it's written as `z.discriminatedUnion`: see [Blocks](#blocks)
- `.transform()` and `z.preprocess()`: the file holds something other than what the site reads, so editing the parsed value would write the wrong thing back
- records, tuples, `z.any()`, recursive schemas, and literals that aren't strings
- a schema that isn't a `z.object()` at the top level, whose whole frontmatter is then edited as YAML

The text is read the way Astro reads it, and what you type is kept while it's invalid. If a field shows as YAML and you'd rather it didn't, a simpler type usually gives it a real control.

## Blocks

A page builder is a list whose items are different kinds, told apart by one key. Write it as `z.discriminatedUnion`, with an object for each kind that holds the key as a literal:

```ts
const sections = z
  .array(
    z.discriminatedUnion('type', [
      z
        .object({
          type: z.literal('card_grid'),
          heading: z.string(),
          cards: z.array(z.object({ title: z.string(), body: z.string().optional() })),
        })
        .meta({ label: 'Card grid', description: 'Feature cards, numbered steps or a list.' }),
      z
        .object({
          type: z.literal('faq'),
          heading: z.string(),
          items: z.array(z.object({ question: z.string(), answer: z.string() })),
        })
        .meta({ label: 'FAQ', description: 'Questions and answers.' }),
      z
        .object({ type: z.literal('figure'), image: fields.image(image), caption: z.string().optional() })
        .meta({ label: 'Figure', description: 'One picture, with a caption.' }),
    ]),
  )
  .max(20)
  .default([]);
```

`fields.image()` takes the `image` helper from the collection's schema function, as on [Images](/docs/content/images/). The key can have any name, such as `type`, `kind` or `block`. In the file, each block is the key, then its fields:

```yaml
sections:
  - type: faq
    heading: Questions about cost
    items:
      - question: Are books included?
        answer: No.
```

In the studio:

- **Add** opens a menu of the kinds, each with its description. The new block opens, with focus in its first field. A list of one kind adds it straight away.
- **Each row** is named by its kind, then its own words: the kind's `summary` field, a title-like field, or its first text, as in "Card grid · This industry has rules". It opens in place, like any list item.
- **A row's "…" menu** has Add below, for a kind right after it, and Change to, for another kind. Change to keeps the fields both kinds have, under the same key and of the same kind. When something with content has no place in the new kind, the studio asks first and names it. Changing back before saving brings it back.
- **A kind the schema doesn't list**, such as one removed from the code, shows as "Unknown kind" with the block as YAML, and Change to offers every kind. The site's build would refuse it, so the save does too.

Each kind's `.meta()` takes `label` and `description` for the Add menu, and `summary` to name its rows. Without a label, the kind is its value in sentence case: `card_grid` is "Card grid".

On its own, outside a list, a discriminated union is a choice of kind, as radio buttons or a select labelled "Kind", followed by that kind's fields. An optional one adds "None". Changing the kind works as Change to does, and changing back brings the fields back.

Your site renders blocks itself, usually with a map from kind to component:

```astro
---
import CardGrid from '../components/CardGrid.astro';
import Faq from '../components/Faq.astro';
import Figure from '../components/Figure.astro';

const kinds = { card_grid: CardGrid, faq: Faq, figure: Figure };
---
{entry.data.sections.map((block) => {
  const Block = kinds[block.type];
  return <Block {...block} />;
})}
```

Blocks suit pages made of sections: every field has its own control, images get the image picker, and a template can place a block or read its fields. For components inside a stretch of writing, such as a callout in an article, use [Markdoc tags or MDX components](/docs/content/markdoc-and-mdx/) in the body.

## Hints with .meta()

```ts
summary: z.string().meta({
  widget: 'textarea',
  description: 'One or two sentences for search results and link previews.',
}),
```

| Key | What it does |
|---|---|
| `label` | The field's label. Without one, Vesper writes the key in sentence case: `publishedAt` becomes "Published at", `seoTitle` "SEO title". |
| `description` | Help text under the label |
| `widget` | The control to use instead of the one the type implies |
| `widgetOptions` | Settings for that control, such as `{ labels }` for an enum's options |
| `placeholder` | Sample text in an empty field. It's never a label. |
| `placement` | The editor tab the field is on: `'main'`, `'details'` or one you declare. See below. |
| `hidden` | Leaves the field out of the editor. Saves don't change its value. |
| `showWhen` | Shows the field only while a field beside it, in the same object, holds a value: `{ field: 'location', equals: 'Other' }`, or a list of values, `equals: ['Other', 'TBD']`. Hidden, it keeps its value. See [Fields that come and go](#fields-that-come-and-go). |
| `readOnly` | Shows the value, but editors can't change it |
| `autocomplete` | The browser's autofill hint, such as `email` |
| `summary` | On a list of objects, or its item object: the item field that names each row, such as `'question'`, or several, `['date', 'start', 'title']`, joined with " · ". Dates read "Mon, Sep 14", times as the editor's clock does, and selects by their labels; empty ones are left out. Without it, the first of `title`, `name`, `label`, `heading` and `text` names it. On a kind's object, the field after the kind's name in its rows. |

`.meta()` works before or after `.optional()` and `.default()`. Values must be plain data: a function in `widgetOptions` is dropped, with a warning.

The built-in widgets you can name are `text`, `textarea`, `markdown`, `email`, `url`, `slug`, `color`, `file`, `number`, `switch`, `date`, `datetime`, `time`, `select`, `radio`, `icon`, `tags`, `multiselect`, `group`, `union`, `repeater`, `reference`, `references`, `image`, `geo` and `raw`. A name that doesn't exist, or a widget that can't edit the field's type (`color` on a number), falls back to the control the type implies. Vesper warns in the terminal, naming the field and the widget.

## Fields that come and go

Some fields only matter when another has a certain value: a custom location when Location is "Other", a stream address for an online event. `showWhen` hides the field until then:

```ts
location: fields.select(['Main Stage', 'Building A', 'Other']).optional(),
customLocation: z
  .string()
  .optional()
  .meta({ showWhen: { field: 'location', equals: 'Other' } }),
```

- The condition names a field beside it, in the same object. In a list of objects, that's the same item's field.
- `equals` is a value, or a list of values any of which shows it: text, a number, `true` or `false`.
- Hiding never deletes. A value the field held stays in the file while it's hidden, and comes back when it shows again. Your pages decide whether to read it.
- Make such a field optional. A required field that's hidden would stop every save with nothing on screen to fix, so Vesper warns about one.
- When the field comes or goes, screen readers hear "Custom location is shown" or "… is hidden".
- A condition Vesper can't follow, such as one naming a field that isn't beside it, is ignored with a warning, and the field always shows.

## Field helpers

`vespercms/fields` has helpers for common fields. Each returns plain Zod from `astro/zod` with `.meta()` attached, so Astro checks it like any other schema. Paste the raw Zod instead and you get the same field: a test keeps the two equal.

```ts
import { z } from 'astro/zod';
import { fields } from 'vespercms/fields';

const schema = z.object({
  brandColor: fields.color({ palette: { Indigo: '#28335f', Pine: '#2f5d50' } }),
  website: fields.url(),
  startsAt: fields.datetime(),
});
```

| Helper | Raw Zod | Stored as |
|---|---|---|
| `fields.color({ palette?, alpha?, contrast? })` | `z.string().regex(/^#[0-9a-f]{6}$/i).meta({ widget: 'color' })` | `"#1a73e8"` |
| `fields.geo({ defaultCenter?, zoom? })` | `z.object({ lat: z.number().min(-90).max(90), lng: z.number().min(-180).max(180) }).meta({ widget: 'geo' })` | `{ lat, lng }` |
| `fields.slug({ from })` | `z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).meta({ widget: 'slug', widgetOptions: { from } })` | `"my-post"` |
| `fields.url()` | `z.url().meta({ widget: 'url' })` | `"https://…"` |
| `fields.email()` | `z.email().meta({ widget: 'email', autocomplete: 'email' })` | `"a@b.com"` |
| `fields.datetime()` | `z.coerce.date().meta({ widget: 'datetime' })` | ISO 8601, with an offset |
| `fields.time()` | `z.iso.time({ precision: -1 }).meta({ widget: 'time' })` | `"18:00"` |
| `fields.select(options)` | `z.enum([...]).meta({ widgetOptions: { labels } })` | `"value"` |
| `fields.icon(names)` | `z.enum([...]).meta({ widget: 'icon' })` | An icon's name, such as `"calendar-days"` |
| `fields.markdown({ inline? })` | `z.string().meta({ widget: 'markdown' })` | A Markdown string |
| `fields.file({ accept })` | `z.string().meta({ widget: 'file', widgetOptions: { accept } })` | A path, such as `/files/brochure.pdf` |
| `fields.image(image, { ratios? })` | See [Images](/docs/content/images/) | `{ src, alt, … }` |
| `fields.reference(collection)` | `z.string().meta({ vesper: { kind: 'reference', collection } })` | An entry's ID. For Markdoc tags' and MDX components' schemas; in `content.config.ts`, use Astro's `reference()`. |
| `fields.hideFromSearch()` | `z.boolean().default(false).meta({ label: 'Hide from site search', description, placement: 'details', search: 'hide' })` | `true` or `false` |

Options you pass go into `widgetOptions`, as they would in the raw form. What they do:

- `color()` with a `palette` shows the named swatches as radio buttons instead of a colour picker. `alpha` allows eight digits. `contrast: 'text'` (or `'large-text'`, `'graphic'`) checks the colour against your declared backgrounds: see [Accessibility](/docs/site/accessibility/).
- `slug({ from: 'title' })` follows that field on a new entry until someone edits the slug.
- `geo()` shows latitude and longitude fields. A map loads only when an editor asks for it with "Show on a map", and `defaultCenter` and `zoom` set where it starts.
- `datetime()` is entered in the site's time zone (`timeZone` in `vesper.config.ts`, otherwise each editor's own) and stored with that day's offset.
- `time()` is a time of day with no date, such as when doors open or a row of a schedule starts. The studio shows the browser's time picker, which reads the editor's own clock (6:00 PM in the US), and the file stores 24-hour `"18:00"`, which sorts as text. Format it for visitors on your pages.
- `markdown()` is a small editor for bold, italic, code, links, paragraphs and lists. With `inline: true` it leaves out paragraphs and lists.
- `select()` takes a list of values, an object of values and labels (`{ news: 'News' }`), or `[{ value, label }]`. The file stores the value.
- `icon()` offers [Lucide](https://lucide.dev/icons) icons by their names on that page, such as `icon(['leaf', 'calendar-days'])`. The studio shows a list you can search, with each icon beside its name, and the chosen icon in the field. The file stores the name, and your site draws the icon. Like `select()`, it also takes names with labels, `{ 'code-xml': 'Code' }`, and the list then shows the labels. Install the `lucide` package: Vesper takes the pictures of the icons you offer from it when it reads your schema, and only those reach the studio. A name Lucide doesn't have is still offered, by name alone, and Vesper warns in the terminal.
- `hideFromSearch()` keeps the entry's page out of the site's own search: see [Site search](/docs/site/search/).

## Tabs: Content, Details and your own

The editor shows the title as the page's heading, then tabs: Content holds the main fields and the body, and Details the secondary fields. With only main fields there are no tabs. A tab with a problem from the last save says so in its name, such as "Details (1 problem)", and a link in the error summary chooses the tab before it moves to the field. Details gets:

- slugs, dates and tags
- ordering and layout fields, such as `order`, `weight`, `layout` and `template`
- `draft`, SEO fields such as `seo`, `seoTitle` and `metaDescription`, and `canonical`, `noindex` and `aliases`

To move a field, set `.meta({ placement: 'main' })` or `'details'` on it, or set it per collection in `vesper.config.ts`, which wins:

```ts
// vesper.config.ts
collections: {
  events: { placement: { startsAt: 'main', endsAt: 'main' } },
},
```

A collection can have tabs of its own, between Content and Details. Declare them in `vesper.config.ts`, by id with their labels, in order, and place fields on them by id:

```ts
// vesper.config.ts
collections: {
  blog: {
    tabs: { seo: 'SEO' },
    placement: { seoTitle: 'seo', metaDescription: 'seo', ogImage: 'seo' },
  },
},
```

`.meta({ placement: 'seo' })` works too. A field placed on a tab nobody declared stays on Content, and Vesper warns in the terminal.

## Custom widgets

When no built-in control fits, write your own as a React component and register it in `vesper.config.ts`:

```ts
import { defineConfig } from 'vespercms/config';

export default defineConfig({
  widgets: {
    'store-hours': {
      component: () => import('./src/cms/StoreHours.tsx'),
      accepts: (field) => field.kind === 'array',
      match: (field) => field.path.at(-1) === 'hours',
    },
  },
});
```

- A field uses the widget when its `.meta({ widget: 'store-hours' })` names it, or when `match` returns true for it. `accepts` limits which fields it can edit.
- Vesper picks a control in this order: the widget a field names, then a custom widget whose `match` claims it, then the control its type implies, then a raw YAML field.
- The file's default export is the component. It receives `WidgetProps` (`import type { WidgetProps } from 'vespercms/config'`): `value`, `onChange`, `field`, `id`, `describedBy`, `invalid` and `disabled`.
- The editor draws the label, help text and errors. Your control takes `id`, passes `describedBy` and `invalid` on to `aria-describedby` and `aria-invalid`, works with the keyboard, and never validates: the schema does.
- Vesper compiles widget files as React, so your site needs no `@astrojs/react`. Start each file with `/** @jsxImportSource react */` so TypeScript checks it as React.
- If a widget fails to load, the field falls back to its built-in control, with a note.

## Collections in the studio

`vesper.config.ts` also says how each collection appears:

```ts
collections: {
  blog: { label: 'Blog posts', icon: 'newspaper', listFields: ['title', 'publishedAt'] },
  settings: { label: 'Site settings', singleton: true, icon: 'settings' },
},
```

- `label` is the collection's name in the studio. Without one, it's the collection's key in sentence case.
- `singleton: true` is for a collection with one entry, such as site settings. Home lists it on its own, and it opens straight into its editor.
- `listFields` names the fields the entry list shows beside each title. A select shows its label.
- `listSort` sorts the list as it opens: `listSort: { field: 'startsAt', direction: 'ascending' }` lists upcoming events soonest first. Without it, the first date among `listFields` sorts newest first.
- `orderBy: 'order'` puts the entries in a set order by a number field, such as services shown in the order you choose. The list is sorted by it, and editors drag an entry to a new place, move it with Alt+↑ and Alt+↓, or use Move up and Move down in its “…” menu. Each move writes the number into the entry's file, so sort by the same field on your pages.
- `icon` names a [Lucide](https://lucide.dev/icons) icon. Install the `lucide` package to use one.

Every option is on [vesper() and vesper.config.ts](/docs/reference/integration/).
